Ported Python Editor APIs from GSF to CSL.
Support for SetupTools project type.
Contributed by Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
1.1 --- a/python.console/src/org/netbeans/modules/python/console/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
1.2 +++ b/python.console/src/org/netbeans/modules/python/console/Bundle.properties Sat Feb 28 17:25:32 2015 -0800
1.3 @@ -4,6 +4,6 @@
1.4 CTL_PythonConsoleTopComponent=PythonConsole Window
1.5 HINT_PyConsoleTopComponentTopComponent=This is a PyConsoleTopComponent window
1.6 HINT_PythonConsoleTopComponent=This is a PythonConsole window
1.7 -OpenIDE-Module-Name=python.console
1.8 +OpenIDE-Module-Name=Python Console
1.9 CTL_TermTopComponent=Python Console
1.10 HINT_TermTopComponent=This is a Python Console Window
2.1 --- a/python.console/src/org/netbeans/modules/python/console/PythonConsoleAction.java Sun Jan 04 13:11:53 2015 -0600
2.2 +++ b/python.console/src/org/netbeans/modules/python/console/PythonConsoleAction.java Sat Feb 28 17:25:32 2015 -0800
2.3 @@ -1,7 +1,3 @@
2.4 -/*
2.5 - * To change this template, choose Tools | Templates
2.6 - * and open the template in the editor.
2.7 - */
2.8 package org.netbeans.modules.python.console;
2.9
2.10 import java.awt.event.ActionEvent;
3.1 --- a/python.core/release/platform_info.py Sun Jan 04 13:11:53 2015 -0600
3.2 +++ b/python.core/release/platform_info.py Sat Feb 28 17:25:32 2015 -0800
3.3 @@ -4,20 +4,25 @@
3.4 import os
3.5
3.6 command = sys.executable
3.7 -version = sys.version.split()[0]
3.8 +major = sys.version_info[0]
3.9 +minor = sys.version_info[1]
3.10 +micro = sys.version_info[2]
3.11 +sourceLevel = str(major) + '.' + str(minor)
3.12 +version = sourceLevel + '.' + str(micro)
3.13 isJava = sys.platform.count("java")
3.14 if isJava :
3.15 print("platform.name="+ "Jython " + version)
3.16 else:
3.17 print("platform.name="+ "Python " + version)
3.18 -if command != None :
3.19 +print("platform.sourcelevel=" + sourceLevel)
3.20 +if command != None :
3.21 print("python.command="+ command.replace("\\", "\\\\"))
3.22 path = ""
3.23 for pathItem in sys.path:
3.24 path += pathItem + os.pathsep
3.25 print("python.path="+path.replace("\\", "\\\\"))
3.26
3.27 -if isJava :
3.28 +if isJava :
3.29 from java.lang import System
3.30 classpath = System.getProperty('java.class.path')
3.31 print(classpath)
4.1 --- a/python.core/src/org/netbeans/modules/python/api/PythonExecution.java Sun Jan 04 13:11:53 2015 -0600
4.2 +++ b/python.core/src/org/netbeans/modules/python/api/PythonExecution.java Sat Feb 28 17:25:32 2015 -0800
4.3 @@ -28,7 +28,7 @@
4.4 * @author Allan Davis
4.5 * @author Jean-Yves
4.6 */
4.7 -public class PythonExecution {
4.8 +public final class PythonExecution {
4.9 // execution commands
4.10 private String command;
4.11 private String workingDirectory;
5.1 --- a/python.core/src/org/netbeans/modules/python/api/PythonPlatform.java Sun Jan 04 13:11:53 2015 -0600
5.2 +++ b/python.core/src/org/netbeans/modules/python/api/PythonPlatform.java Sat Feb 28 17:25:32 2015 -0800
5.3 @@ -32,6 +32,7 @@
5.4 private String interpreterConsoleComand;
5.5 private String interpreterArgs;
5.6 private String homeUrl;
5.7 + private String sourceLevel;
5.8 private boolean dirty;
5.9 // When adding properties, be sure to update the persistence code in PythonPlatformManager
5.10
5.11 @@ -72,6 +73,15 @@
5.12 this.interpreterConsoleComand = interpreterConsoleComand;
5.13 }
5.14
5.15 + public String getSourceLevel() {
5.16 + return sourceLevel;
5.17 + }
5.18 +
5.19 + public void setSourceLevel(String sourceLevel) {
5.20 + checkDirty(this.sourceLevel, sourceLevel);
5.21 + this.sourceLevel = sourceLevel;
5.22 + }
5.23 +
5.24 public List<String> getJavaPath() {
5.25 return javaPath;
5.26 }
6.1 --- a/python.core/src/org/netbeans/modules/python/api/PythonPlatformManager.java Sun Jan 04 13:11:53 2015 -0600
6.2 +++ b/python.core/src/org/netbeans/modules/python/api/PythonPlatformManager.java Sat Feb 28 17:25:32 2015 -0800
6.3 @@ -19,6 +19,7 @@
6.4 import java.util.List;
6.5 import java.util.Map;
6.6 import java.util.Properties;
6.7 +import java.util.concurrent.ExecutionException;
6.8 import java.util.concurrent.Future;
6.9 import java.util.logging.Level;
6.10 import java.util.logging.Logger;
6.11 @@ -46,6 +47,7 @@
6.12 private static final String PLATFORM_INTEPRETER = ".interpreter"; // NOI18N
6.13 private static final String JAVA_LIB_DIR = "javalib"; // NOI18N
6.14 private static final String PLATFORM_NAME = "name"; // NOI18N
6.15 + private static final String SOURCE_LEVEL = "sourcelevel"; // NOI18N
6.16 private static final String INTERPRETER_ARGS = "args"; // NOI18N
6.17 private static final String CONSOLE_PATH = "console"; // NOI18N
6.18 private static final String PYTHON_LIB_DIR = "pythonlib"; // NOI18N
6.19 @@ -67,7 +69,8 @@
6.20 private PythonPlatform getBundledPlatform() {
6.21 PythonPlatform platform = new PythonPlatform(PLATFORM_ID_DEFAULT);
6.22
6.23 - File jythonInstall = InstalledFileLocator.getDefault().locate("jython-2.5.1", "org.jython", false); // NOI18N
6.24 + File jythonInstall = new File("C:\\jython2.5.1"); // NOI18N
6.25 +// File jythonInstall = InstalledFileLocator.getDefault().locate("jython-2.5.1", "org.jython", false); // NOI18N
6.26 if (!jythonInstall.exists()) {
6.27 return null;
6.28 }
6.29 @@ -99,7 +102,7 @@
6.30 } catch (IOException ex) {
6.31 Exceptions.printStackTrace(ex);
6.32 }
6.33 -
6.34 +
6.35 return platform;
6.36 }
6.37
6.38 @@ -137,6 +140,7 @@
6.39 String libDir = p.get(PLATFORM_PREFIX + idDot + PYTHON_LIB_DIR);
6.40 String javaPath = p.get(PLATFORM_PREFIX + idDot + JAVA_LIB_DIR);
6.41 String name = p.get(PLATFORM_PREFIX + idDot + PLATFORM_NAME);
6.42 + String sourceLevel = p.get(PLATFORM_PREFIX + idDot + SOURCE_LEVEL);
6.43 String interpreterArgs = p.get(PLATFORM_PREFIX + idDot + INTERPRETER_ARGS);
6.44 String interpreterConsolePath = p.get(PLATFORM_PREFIX + idDot + CONSOLE_PATH);
6.45
6.46 @@ -153,6 +157,9 @@
6.47 if (name != null && name.length() > 0) {
6.48 platform.setName(name);
6.49 }
6.50 + if (sourceLevel != null && !sourceLevel.isEmpty()) {
6.51 + platform.setSourceLevel(sourceLevel);
6.52 + }
6.53 if (libDir != null && libDir.length() > 0) {
6.54 platform.setPythonPath(libDir.split(File.pathSeparator));
6.55 }
6.56 @@ -178,7 +185,7 @@
6.57 defaultPlatform = deflt.getId();
6.58 platforms.put(defaultPlatform, deflt);
6.59 }
6.60 -
6.61 +
6.62 if (Util.isFirstPlatformTouch()) {
6.63 RequestProcessor.getDefault().post(new Runnable() {
6.64 public void run() {
6.65 @@ -186,7 +193,7 @@
6.66 autoDetect();
6.67 }
6.68 }
6.69 - });
6.70 + });
6.71 }
6.72 }
6.73 }
6.74 @@ -214,7 +221,7 @@
6.75 EditableProperties props = PropertyUtils.getGlobalProperties();
6.76 clearProperties(platform, props);
6.77 putPlatformProperties(platform, props);
6.78 - PropertyUtils.putGlobalProperties(props);
6.79 + PropertyUtils.putGlobalProperties(props);
6.80 return null;
6.81 }
6.82 });
6.83 @@ -234,6 +241,7 @@
6.84 props.remove(PLATFORM_PREFIX + idDot + PYTHON_LIB_DIR);
6.85 props.remove(PLATFORM_PREFIX + idDot + JAVA_LIB_DIR);
6.86 props.remove(PLATFORM_PREFIX + idDot + PLATFORM_NAME);
6.87 + props.remove(PLATFORM_PREFIX + idDot + SOURCE_LEVEL);
6.88 props.remove(PLATFORM_PREFIX + idDot + INTERPRETER_ARGS);
6.89 props.remove(PLATFORM_PREFIX + idDot + CONSOLE_PATH);
6.90 }
6.91 @@ -262,6 +270,9 @@
6.92 if (platform.getName() != null) {
6.93 props.setProperty(PLATFORM_PREFIX + idDot + PLATFORM_NAME, platform.getName());
6.94 }
6.95 + if (platform.getSourceLevel() != null) {
6.96 + props.setProperty(PLATFORM_PREFIX + idDot + SOURCE_LEVEL, platform.getSourceLevel());
6.97 + }
6.98 if (platform.getInterpreterArgs() != null) {
6.99 props.setProperty(PLATFORM_PREFIX + idDot + INTERPRETER_ARGS, platform.getInterpreterArgs());
6.100 }
6.101 @@ -338,16 +349,21 @@
6.102
6.103 firePlatformsChanged();
6.104 }
6.105 -
6.106 +
6.107 public PythonPlatform findPlatformProperties(String cmd, String id) throws PythonException{
6.108 PythonPlatform platform = null;
6.109 try{
6.110 PythonExecution pye = new PythonExecution();
6.111 - pye.setCommand(cmd);
6.112 + int split = cmd.indexOf(" ");
6.113 + pye.setCommand(split > 0 ? cmd.substring(0, split) : cmd);
6.114 pye.setDisplayName("Python Properties");
6.115 File info = InstalledFileLocator.getDefault().locate(
6.116 "platform_info.py", "org.netbeans.modules.python.core", false);
6.117 pye.setScript(info.getAbsolutePath());
6.118 + if(split > 0) {
6.119 + String cmdArgs = cmd.substring(split).trim();
6.120 + pye.setCommandArgs(cmdArgs);
6.121 + }
6.122 pye.setShowControls(false);
6.123 pye.setShowInput(false);
6.124 pye.setShowWindow(false);
6.125 @@ -377,6 +393,7 @@
6.126 platform.setInterpreterConsoleComand(command);
6.127 // @@@Jean-Yves end of fix
6.128 platform.setName(name);
6.129 + platform.setSourceLevel(prop.getProperty("platform.sourcelevel"));
6.130 String pathString = prop.getProperty("python.path");
6.131 if(pathString != null)
6.132 platform.setPythonPath(pathString.split(File.pathSeparator));
6.133 @@ -396,7 +413,11 @@
6.134 }catch(PythonException ex){
6.135 Exceptions.printStackTrace(ex);
6.136 throw ex;
6.137 - }catch(Exception ex){
6.138 + }catch(InterruptedException ex){
6.139 + Exceptions.printStackTrace(ex);
6.140 + } catch (ExecutionException ex) {
6.141 + Exceptions.printStackTrace(ex);
6.142 + } catch (IOException ex) {
6.143 Exceptions.printStackTrace(ex);
6.144 }
6.145 return platform;
6.146 @@ -484,7 +505,7 @@
6.147 }
6.148
6.149 }
6.150 -
6.151 +
6.152 private ArrayList<String> discoverJythonClasspath(String command){
6.153 ArrayList<String> temp = new ArrayList<String>();
6.154 //@@@jean-yves in some case bin is not there(jython 2.2.1 installer)
7.1 --- a/python.core/src/org/netbeans/modules/python/core/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
7.2 +++ b/python.core/src/org/netbeans/modules/python/core/Bundle.properties Sat Feb 28 17:25:32 2015 -0800
7.3 @@ -1,5 +1,5 @@
7.4 OpenIDE-Module-Display-Category=Python
7.5 -OpenIDE-Module-Name=python.core
7.6 +OpenIDE-Module-Name=Python Core
7.7 LBL_Python_loader_name=Python Files
7.8 LBL_PythonCompiled_loader_name=PythonCompiled Files
7.9 OpenIDE-Module-Short-Description=Core of Python Editor
8.1 --- a/python.debugger/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
8.2 +++ b/python.debugger/nbproject/project.xml Sat Feb 28 17:25:32 2015 -0800
8.3 @@ -24,6 +24,14 @@
8.4 </run-dependency>
8.5 </dependency>
8.6 <dependency>
8.7 + <code-name-base>org.netbeans.modules.editor.document</code-name-base>
8.8 + <build-prerequisite/>
8.9 + <compile-dependency/>
8.10 + <run-dependency>
8.11 + <specification-version>1.3</specification-version>
8.12 + </run-dependency>
8.13 + </dependency>
8.14 + <dependency>
8.15 <code-name-base>org.netbeans.modules.editor.lib</code-name-base>
8.16 <build-prerequisite/>
8.17 <compile-dependency/>
8.18 @@ -140,14 +148,6 @@
8.19 </run-dependency>
8.20 </dependency>
8.21 <dependency>
8.22 - <code-name-base>org.openide.util.ui</code-name-base>
8.23 - <build-prerequisite/>
8.24 - <compile-dependency/>
8.25 - <run-dependency>
8.26 - <specification-version>9.3</specification-version>
8.27 - </run-dependency>
8.28 - </dependency>
8.29 - <dependency>
8.30 <code-name-base>org.openide.util</code-name-base>
8.31 <build-prerequisite/>
8.32 <compile-dependency/>
8.33 @@ -164,6 +164,14 @@
8.34 </run-dependency>
8.35 </dependency>
8.36 <dependency>
8.37 + <code-name-base>org.openide.util.ui</code-name-base>
8.38 + <build-prerequisite/>
8.39 + <compile-dependency/>
8.40 + <run-dependency>
8.41 + <specification-version>9.3</specification-version>
8.42 + </run-dependency>
8.43 + </dependency>
8.44 + <dependency>
8.45 <code-name-base>org.openide.windows</code-name-base>
8.46 <build-prerequisite/>
8.47 <compile-dependency/>
8.48 @@ -189,6 +197,8 @@
8.49 <public-packages>
8.50 <package>org.netbeans.modules.python.debugger</package>
8.51 <package>org.netbeans.modules.python.debugger.actions</package>
8.52 + <package>org.netbeans.modules.python.debugger.backend</package>
8.53 + <package>org.netbeans.modules.python.debugger.spi</package>
8.54 </public-packages>
8.55 </data>
8.56 </configuration>
9.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
9.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/Bundle.properties Sat Feb 28 17:25:32 2015 -0800
9.3 @@ -3,6 +3,6 @@
9.4 TOOLTIP_DISABLED_BREAKPOINT=Disabled Breakpoint
9.5
9.6 OpenIDE-Module-Display-Category=Python
9.7 -OpenIDE-Module-Name=python.debugger
9.8 +OpenIDE-Module-Name=Python Debugger
9.9 OpenIDE-Module-Short-Description=Python Debugger
9.10 Toolbars/Debug=&Debug
10.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/Debuggee.java Sun Jan 04 13:11:53 2015 -0600
10.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/Debuggee.java Sat Feb 28 17:25:32 2015 -0800
10.3 @@ -46,7 +46,6 @@
10.4 import org.netbeans.modules.python.api.PythonPlatform;
10.5 import org.netbeans.modules.python.debugger.actions.JpyDbgView;
10.6 import org.netbeans.modules.python.debugger.spi.PythonSession;
10.7 -import org.netbeans.modules.python.debugger.spi.PythonSourceDebuggee;
10.8 import org.openide.filesystems.FileObject;
10.9 import org.openide.filesystems.FileUtil;
10.10 import org.openide.loaders.DataObject;
11.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/DebuggerPythonLogger.java Sun Jan 04 13:11:53 2015 -0600
11.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/DebuggerPythonLogger.java Sat Feb 28 17:25:32 2015 -0800
11.3 @@ -62,7 +62,6 @@
11.4 import java.util.Set;
11.5 import org.netbeans.modules.python.debugger.spi.PythonEvent;
11.6 import org.netbeans.modules.python.debugger.spi.PythonSession;
11.7 -import org.netbeans.modules.python.debugger.spi.PythonSourceDebuggee;
11.8
11.9 /**
11.10 * Debugger's tasking entry point class
12.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/PythonDebugger.java Sun Jan 04 13:11:53 2015 -0600
12.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/PythonDebugger.java Sat Feb 28 17:25:32 2015 -0800
12.3 @@ -56,7 +56,6 @@
12.4 import org.netbeans.modules.python.debugger.backend.PluginEvent;
12.5 import org.netbeans.modules.python.debugger.spi.PythonEvent;
12.6 import org.netbeans.modules.python.debugger.spi.PythonSession;
12.7 -import org.netbeans.modules.python.debugger.spi.PythonSourceDebuggee;
12.8 import org.netbeans.modules.python.debugger.spi.SessionsModel;
12.9 import org.netbeans.modules.python.debugger.gui.PythonDebugContainer;
12.10 import org.netbeans.modules.python.debugger.gui.PythonVariableTreeDataNode;
13.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
13.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/PythonSourceDebuggee.java Sat Feb 28 17:25:32 2015 -0800
13.3 @@ -0,0 +1,81 @@
13.4 +/*
13.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
13.6 + *
13.7 + * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
13.8 + *
13.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
13.10 + * Other names may be trademarks of their respective owners.
13.11 + *
13.12 + * The contents of this file are subject to the terms of either the GNU
13.13 + * General Public License Version 2 only ("GPL") or the Common
13.14 + * Development and Distribution License("CDDL") (collectively, the
13.15 + * "License"). You may not use this file except in compliance with the
13.16 + * License. You can obtain a copy of the License at
13.17 + * http://www.netbeans.org/cddl-gplv2.html
13.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
13.19 + * specific language governing permissions and limitations under the
13.20 + * License. When distributing the software, include this License Header
13.21 + * Notice in each file and include the License file at
13.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
13.23 + * particular file as subject to the "Classpath" exception as provided
13.24 + * by Oracle in the GPL Version 2 section of the License file that
13.25 + * accompanied this code. If applicable, add the following below the
13.26 + * License Header, with the fields enclosed by brackets [] replaced by
13.27 + * your own identifying information:
13.28 + * "Portions Copyrighted [year] [name of copyright owner]"
13.29 + *
13.30 + * If you wish your version of this file to be governed by only the CDDL
13.31 + * or only the GPL Version 2, indicate your decision by adding
13.32 + * "[Contributor] elects to include this software in this distribution
13.33 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
13.34 + * single choice of license, a recipient has the option to distribute
13.35 + * your version of this file under either the CDDL, the GPL Version 2 or
13.36 + * to extend the choice of license to its licensees as provided above.
13.37 + * However, if you add GPL Version 2 code and therefore, elected the GPL
13.38 + * Version 2 license, then the option applies only if the new code is
13.39 + * made subject to such option by the copyright holder.
13.40 + *
13.41 + * Contributor(s):
13.42 + *
13.43 + * Portions Copyrighted 2008 Sun Microsystems, Inc.
13.44 + */
13.45 +
13.46 +package org.netbeans.modules.python.debugger;
13.47 +
13.48 +import java.io.File ;
13.49 +import org.netbeans.modules.python.debugger.actions.JpyDbgView;
13.50 +import org.netbeans.modules.python.debugger.spi.PythonSession;
13.51 +import org.openide.filesystems.FileObject;
13.52 +
13.53 +/**
13.54 + * Node specialization for Python Sources debugging context
13.55 + * @author jean-yves Mengant
13.56 + */
13.57 +public interface PythonSourceDebuggee
13.58 +{
13.59 + /** Get the disk file for the python script.
13.60 + * @return the disk file, or null if none (but must be a file object)
13.61 + */
13.62 + File getFile ();
13.63 + /** Get the file object for the build script.
13.64 + * @return the file object, or null if none (but must be a disk file)
13.65 + */
13.66 + FileObject getFileObject ();
13.67 +
13.68 + /**
13.69 + bind a debug view object
13.70 + */
13.71 + public void setDebugView( JpyDbgView view ) ;
13.72 + public JpyDbgView getDebugView() ;
13.73 +
13.74 + /**
13.75 + execute current python shell action
13.76 + */
13.77 + //public void executePython()
13.78 + //throws PythonDebugException ;
13.79 +
13.80 + /** set current python session */
13.81 + public void setSession( PythonSession pythonSession ) ;
13.82 + public PythonSession getSession() ;
13.83 +
13.84 +}
14.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/actions/JpyDbgView.java Sun Jan 04 13:11:53 2015 -0600
14.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/actions/JpyDbgView.java Sat Feb 28 17:25:32 2015 -0800
14.3 @@ -47,7 +47,6 @@
14.4 import org.netbeans.modules.python.debugger.PythonDebugger;
14.5 import org.netbeans.modules.python.debugger.Utils;
14.6 import org.netbeans.modules.python.debugger.backend.PluginEvent;
14.7 -import org.netbeans.modules.python.debugger.backend.PluginEventListener;
14.8 import org.netbeans.modules.python.debugger.breakpoints.PythonBreakpoint;
14.9 import org.netbeans.modules.python.debugger.config.NetBeansFrontend;
14.10 import org.netbeans.modules.python.debugger.spi.PythonEvent;
15.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
15.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/actions/PluginEventListener.java Sat Feb 28 17:25:32 2015 -0800
15.3 @@ -0,0 +1,64 @@
15.4 +/*
15.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
15.6 + *
15.7 + * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
15.8 + *
15.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
15.10 + * Other names may be trademarks of their respective owners.
15.11 + *
15.12 + * The contents of this file are subject to the terms of either the GNU
15.13 + * General Public License Version 2 only ("GPL") or the Common
15.14 + * Development and Distribution License("CDDL") (collectively, the
15.15 + * "License"). You may not use this file except in compliance with the
15.16 + * License. You can obtain a copy of the License at
15.17 + * http://www.netbeans.org/cddl-gplv2.html
15.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
15.19 + * specific language governing permissions and limitations under the
15.20 + * License. When distributing the software, include this License Header
15.21 + * Notice in each file and include the License file at
15.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
15.23 + * particular file as subject to the "Classpath" exception as provided
15.24 + * by Oracle in the GPL Version 2 section of the License file that
15.25 + * accompanied this code. If applicable, add the following below the
15.26 + * License Header, with the fields enclosed by brackets [] replaced by
15.27 + * your own identifying information:
15.28 + * "Portions Copyrighted [year] [name of copyright owner]"
15.29 + *
15.30 + * If you wish your version of this file to be governed by only the CDDL
15.31 + * or only the GPL Version 2, indicate your decision by adding
15.32 + * "[Contributor] elects to include this software in this distribution
15.33 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
15.34 + * single choice of license, a recipient has the option to distribute
15.35 + * your version of this file under either the CDDL, the GPL Version 2 or
15.36 + * to extend the choice of license to its licensees as provided above.
15.37 + * However, if you add GPL Version 2 code and therefore, elected the GPL
15.38 + * Version 2 license, then the option applies only if the new code is
15.39 + * made subject to such option by the copyright holder.
15.40 + *
15.41 + * Contributor(s):
15.42 + *
15.43 + * Portions Copyrighted 2008 Sun Microsystems, Inc.
15.44 + */
15.45 +package org.netbeans.modules.python.debugger.actions;
15.46 +
15.47 +import org.netbeans.modules.python.debugger.backend.PluginEvent;
15.48 +import org.netbeans.modules.python.debugger.backend.PythonDebugException;
15.49 +
15.50 +/**
15.51 + *
15.52 + * used by pluggin implementors interfaces to get populated
15.53 + * With source debugging level instance
15.54 + *
15.55 + * @author jean-yves Mengant
15.56 + */
15.57 +public interface PluginEventListener {
15.58 +
15.59 + /**
15.60 + * populate debugging event to the UI plugin interface for
15.61 + * sources synchronization process
15.62 + * @param e
15.63 + * @throws PythonDebugException
15.64 + */
15.65 + public void newDebuggingEvent(PluginEvent e)
15.66 + throws PythonDebugException;
15.67 +}
16.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/backend/PluginEventListener.java Sun Jan 04 13:11:53 2015 -0600
16.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
16.3 @@ -1,61 +0,0 @@
16.4 -/*
16.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
16.6 - *
16.7 - * Copyright 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 - * If you wish your version of this file to be governed by only the CDDL
16.31 - * or only the GPL Version 2, indicate your decision by adding
16.32 - * "[Contributor] elects to include this software in this distribution
16.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
16.34 - * single choice of license, a recipient has the option to distribute
16.35 - * your version of this file under either the CDDL, the GPL Version 2 or
16.36 - * to extend the choice of license to its licensees as provided above.
16.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
16.38 - * Version 2 license, then the option applies only if the new code is
16.39 - * made subject to such option by the copyright holder.
16.40 - *
16.41 - * Contributor(s):
16.42 - *
16.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
16.44 - */
16.45 -package org.netbeans.modules.python.debugger.backend;
16.46 -
16.47 -/**
16.48 - *
16.49 - * used by pluggin implementors interfaces to get populated
16.50 - * With source debugging level instance
16.51 - *
16.52 - * @author jean-yves Mengant
16.53 - */
16.54 -public interface PluginEventListener {
16.55 -
16.56 - /**
16.57 - * populate debugging event to the UI plugin interface for
16.58 - * sources synchronization process
16.59 - * @param e
16.60 - * @throws PythonDebugException
16.61 - */
16.62 - public void newDebuggingEvent(PluginEvent e)
16.63 - throws PythonDebugException;
16.64 -}
17.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/gui/PythonDebugContainer.java Sun Jan 04 13:11:53 2015 -0600
17.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/gui/PythonDebugContainer.java Sat Feb 28 17:25:32 2015 -0800
17.3 @@ -71,7 +71,7 @@
17.4 import org.netbeans.modules.python.debugger.Utils;
17.5 import org.netbeans.modules.python.debugger.backend.DebuggerContextChangeListener;
17.6 import org.netbeans.modules.python.debugger.backend.PluginEvent;
17.7 -import org.netbeans.modules.python.debugger.backend.PluginEventListener;
17.8 +import org.netbeans.modules.python.debugger.actions.PluginEventListener;
17.9 import org.netbeans.modules.python.debugger.backend.PythonDebugClient;
17.10 import org.netbeans.modules.python.debugger.backend.PythonDebugEvent;
17.11 import org.netbeans.modules.python.debugger.backend.PythonDebugEventListener;
18.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/gui/WatchPanel.java Sun Jan 04 13:11:53 2015 -0600
18.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/gui/WatchPanel.java Sat Feb 28 17:25:32 2015 -0800
18.3 @@ -77,6 +77,7 @@
18.4 import java.io.IOException;
18.5 import javax.swing.text.StyledDocument;
18.6 import org.netbeans.editor.EditorUI;
18.7 +import org.netbeans.modules.python.api.PythonMIMEResolver;
18.8 import org.openide.ErrorManager;
18.9 import org.openide.cookies.EditorCookie;
18.10 import org.openide.text.NbDocument;
18.11 @@ -99,7 +100,7 @@
18.12 }
18.13
18.14 public static void setupContext(final JEditorPane editorPane, final ActionListener contextSetUp) {
18.15 - EditorKit kit = CloneableEditorSupport.getEditorKit("text/x-python");
18.16 + EditorKit kit = CloneableEditorSupport.getEditorKit(PythonMIMEResolver.PYTHON_MIME_TYPE);
18.17 editorPane.setEditorKit(kit);
18.18 DebuggerEngine en = DebuggerManager.getDebuggerManager ().getCurrentEngine();
18.19 if (EventQueue.isDispatchThread() && en != null) {
19.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/resources/python/nbpythondebug/jpydaemon.py Sun Jan 04 13:11:53 2015 -0600
19.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/resources/python/nbpythondebug/jpydaemon.py Sat Feb 28 17:25:32 2015 -0800
19.3 @@ -1483,9 +1483,8 @@
19.4 self.cmd = FREEZE
19.5 elif ( string.upper(verb) == "BP-"):
19.6 self.cmd = CLEAR_BP
19.7 - file , optarg = _utils.nextArg(arg)
19.8 - line , optarg = _utils.nextArg(optarg)
19.9 - self.clear_break( file, int(line) )
19.10 + arg , optarg = _utils.nextArg(arg) # split BP arguments
19.11 + self.clear_break( arg , int(optarg) )
19.12 self.cmd = FREEZE
19.13 elif ( string.upper(verb) == "KILL"):
19.14 self.cmd = QUIT
20.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/spi/PythonDebuggerTargetExecutor.java Sun Jan 04 13:11:53 2015 -0600
20.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/spi/PythonDebuggerTargetExecutor.java Sat Feb 28 17:25:32 2015 -0800
20.3 @@ -41,6 +41,7 @@
20.4 */
20.5 package org.netbeans.modules.python.debugger.spi;
20.6
20.7 +import org.netbeans.modules.python.debugger.PythonSourceDebuggee;
20.8 import org.openide.execution.ExecutorTask;
20.9 import java.io.IOException;
20.10 import java.io.OutputStream;
21.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/spi/PythonSourceDebuggee.java Sun Jan 04 13:11:53 2015 -0600
21.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
21.3 @@ -1,80 +0,0 @@
21.4 -/*
21.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
21.6 - *
21.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
21.8 - *
21.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
21.10 - * Other names may be trademarks of their respective owners.
21.11 - *
21.12 - * The contents of this file are subject to the terms of either the GNU
21.13 - * General Public License Version 2 only ("GPL") or the Common
21.14 - * Development and Distribution License("CDDL") (collectively, the
21.15 - * "License"). You may not use this file except in compliance with the
21.16 - * License. You can obtain a copy of the License at
21.17 - * http://www.netbeans.org/cddl-gplv2.html
21.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
21.19 - * specific language governing permissions and limitations under the
21.20 - * License. When distributing the software, include this License Header
21.21 - * Notice in each file and include the License file at
21.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
21.23 - * particular file as subject to the "Classpath" exception as provided
21.24 - * by Oracle in the GPL Version 2 section of the License file that
21.25 - * accompanied this code. If applicable, add the following below the
21.26 - * License Header, with the fields enclosed by brackets [] replaced by
21.27 - * your own identifying information:
21.28 - * "Portions Copyrighted [year] [name of copyright owner]"
21.29 - *
21.30 - * If you wish your version of this file to be governed by only the CDDL
21.31 - * or only the GPL Version 2, indicate your decision by adding
21.32 - * "[Contributor] elects to include this software in this distribution
21.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
21.34 - * single choice of license, a recipient has the option to distribute
21.35 - * your version of this file under either the CDDL, the GPL Version 2 or
21.36 - * to extend the choice of license to its licensees as provided above.
21.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
21.38 - * Version 2 license, then the option applies only if the new code is
21.39 - * made subject to such option by the copyright holder.
21.40 - *
21.41 - * Contributor(s):
21.42 - *
21.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
21.44 - */
21.45 -
21.46 -package org.netbeans.modules.python.debugger.spi;
21.47 -
21.48 -import java.io.File ;
21.49 -import org.netbeans.modules.python.debugger.actions.JpyDbgView;
21.50 -import org.openide.filesystems.FileObject;
21.51 -
21.52 -/**
21.53 - * Node specialization for Python Sources debugging context
21.54 - * @author jean-yves Mengant
21.55 - */
21.56 -public interface PythonSourceDebuggee
21.57 -{
21.58 - /** Get the disk file for the python script.
21.59 - * @return the disk file, or null if none (but must be a file object)
21.60 - */
21.61 - File getFile ();
21.62 - /** Get the file object for the build script.
21.63 - * @return the file object, or null if none (but must be a disk file)
21.64 - */
21.65 - FileObject getFileObject ();
21.66 -
21.67 - /**
21.68 - bind a debug view object
21.69 - */
21.70 - public void setDebugView( JpyDbgView view ) ;
21.71 - public JpyDbgView getDebugView() ;
21.72 -
21.73 - /**
21.74 - execute current python shell action
21.75 - */
21.76 - //public void executePython()
21.77 - //throws PythonDebugException ;
21.78 -
21.79 - /** set current python session */
21.80 - public void setSession( PythonSession pythonSession ) ;
21.81 - public PythonSession getSession() ;
21.82 -
21.83 -}
22.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/spi/TargetExecutor.java Sun Jan 04 13:11:53 2015 -0600
22.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/spi/TargetExecutor.java Sat Feb 28 17:25:32 2015 -0800
22.3 @@ -41,6 +41,7 @@
22.4 */
22.5 package org.netbeans.modules.python.debugger.spi;
22.6
22.7 +import org.netbeans.modules.python.debugger.PythonSourceDebuggee;
22.8 import org.openide.windows.InputOutput;
22.9 import org.openide.execution.ExecutorTask;
22.10 import org.openide.windows.IOProvider;
23.1 --- a/python.editor/build-python.xml Sun Jan 04 13:11:53 2015 -0600
23.2 +++ b/python.editor/build-python.xml Sat Feb 28 17:25:32 2015 -0800
23.3 @@ -87,7 +87,8 @@
23.4 </subant>
23.5 </target>
23.6
23.7 - <target name="everything" depends="gsf,python"/>
23.8 +<!-- <target name="everything" depends="gsf,python"/>-->
23.9 + <target name="everything" depends="python"/>
23.10
23.11 <target name="clean">
23.12 <ant dir="${nbroot}/nbbuild" target="init"/>
24.1 --- a/python.editor/build.xml Sun Jan 04 13:11:53 2015 -0600
24.2 +++ b/python.editor/build.xml Sat Feb 28 17:25:32 2015 -0800
24.3 @@ -6,12 +6,12 @@
24.4 <description>Builds, tests, and runs the project org.netbeans.modules.python.editor.</description>
24.5 <import file="../../nbbuild/templates/projectized.xml"/>
24.6
24.7 - <target name="jar" depends="init,compile,jar-prep" unless="is.jar.uptodate">
24.8 +<!-- <target name="jar" depends="init,compile,jar-prep" unless="is.jar.uptodate">
24.9 <taskdef name="gsfjar" classname="org.netbeans.modules.gsf.GsfJar" classpath="${nb_all}/contrib/gsf.api/anttask/gsfanttask.jar:${nbantext.jar}"/>
24.10 <gsfjar jarfile="${cluster}/${module.jar}" compress="${build.package.compress}" index="${build.package.index}" manifest="${manifest.mf}" stamp="${cluster}/.lastModified">
24.11 <fileset dir="${build.classes.dir}"/>
24.12 </gsfjar>
24.13 - </target>
24.14 + </target>-->
24.15
24.16 <target name="files-init" depends="projectized-common.files-init">
24.17 <!-- Override module.files definition performed by parent, used for NBMs etc. -->
25.1 --- a/python.editor/manifest.mf Sun Jan 04 13:11:53 2015 -0600
25.2 +++ b/python.editor/manifest.mf Sat Feb 28 17:25:32 2015 -0800
25.3 @@ -3,4 +3,5 @@
25.4 OpenIDE-Module-Layer: org/netbeans/modules/python/editor/layer.xml
25.5 OpenIDE-Module-Localizing-Bundle: org/netbeans/modules/python/editor/Bundle.properties
25.6 AutoUpdate-Show-In-Client: false
25.7 +OpenIDE-Module-Specification-Version: 1.0
25.8
26.1 --- a/python.editor/nbproject/project.properties Sun Jan 04 13:11:53 2015 -0600
26.2 +++ b/python.editor/nbproject/project.properties Sat Feb 28 17:25:32 2015 -0800
26.3 @@ -15,7 +15,7 @@
26.4 auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab=4
26.5 auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size=4
26.6 auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.text-limit-width=100
26.7 -javac.source=1.6
26.8 +javac.source=1.7
26.9 javac.compilerargs=-Xlint -Xlint:-serial
26.10 nbm.needs.restart=true
26.11 spec.version.base=1.8.1
27.1 --- a/python.editor/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
27.2 +++ b/python.editor/nbproject/project.xml Sat Feb 28 17:25:32 2015 -0800
27.3 @@ -15,6 +15,102 @@
27.4 </run-dependency>
27.5 </dependency>
27.6 <dependency>
27.7 + <code-name-base>org.eclipse.mylyn.wikitext.confluence.core</code-name-base>
27.8 + <build-prerequisite/>
27.9 + <compile-dependency/>
27.10 + <run-dependency>
27.11 + <specification-version>1.9.0</specification-version>
27.12 + </run-dependency>
27.13 + </dependency>
27.14 + <dependency>
27.15 + <code-name-base>org.eclipse.mylyn.wikitext.core</code-name-base>
27.16 + <build-prerequisite/>
27.17 + <compile-dependency/>
27.18 + <run-dependency>
27.19 + <specification-version>1.9.0</specification-version>
27.20 + </run-dependency>
27.21 + </dependency>
27.22 + <dependency>
27.23 + <code-name-base>org.eclipse.mylyn.wikitext.textile.core</code-name-base>
27.24 + <build-prerequisite/>
27.25 + <compile-dependency/>
27.26 + <run-dependency>
27.27 + <specification-version>1.9.0</specification-version>
27.28 + </run-dependency>
27.29 + </dependency>
27.30 + <dependency>
27.31 + <code-name-base>org.netbeans.api.annotations.common</code-name-base>
27.32 + <build-prerequisite/>
27.33 + <compile-dependency/>
27.34 + <run-dependency>
27.35 + <release-version>1</release-version>
27.36 + <specification-version>1.25</specification-version>
27.37 + </run-dependency>
27.38 + </dependency>
27.39 + <dependency>
27.40 + <code-name-base>org.netbeans.api.java.classpath</code-name-base>
27.41 + <build-prerequisite/>
27.42 + <compile-dependency/>
27.43 + <run-dependency>
27.44 + <release-version>1</release-version>
27.45 + <specification-version>1.48</specification-version>
27.46 + </run-dependency>
27.47 + </dependency>
27.48 + <dependency>
27.49 + <code-name-base>org.netbeans.api.progress</code-name-base>
27.50 + <build-prerequisite/>
27.51 + <compile-dependency/>
27.52 + <run-dependency>
27.53 + <release-version>1</release-version>
27.54 + <specification-version>1.38.1</specification-version>
27.55 + </run-dependency>
27.56 + </dependency>
27.57 + <dependency>
27.58 + <code-name-base>org.netbeans.core.multiview</code-name-base>
27.59 + <build-prerequisite/>
27.60 + <compile-dependency/>
27.61 + <run-dependency>
27.62 + <release-version>1</release-version>
27.63 + <specification-version>1.42</specification-version>
27.64 + </run-dependency>
27.65 + </dependency>
27.66 + <dependency>
27.67 + <code-name-base>org.netbeans.libs.lucene</code-name-base>
27.68 + <build-prerequisite/>
27.69 + <compile-dependency/>
27.70 + <run-dependency>
27.71 + <release-version>3</release-version>
27.72 + <specification-version>3.16.1</specification-version>
27.73 + </run-dependency>
27.74 + </dependency>
27.75 + <dependency>
27.76 + <code-name-base>org.netbeans.modules.csl.api</code-name-base>
27.77 + <build-prerequisite/>
27.78 + <compile-dependency/>
27.79 + <run-dependency>
27.80 + <release-version>2</release-version>
27.81 + <specification-version>2.49</specification-version>
27.82 + </run-dependency>
27.83 + </dependency>
27.84 + <dependency>
27.85 + <code-name-base>org.netbeans.modules.editor</code-name-base>
27.86 + <build-prerequisite/>
27.87 + <compile-dependency/>
27.88 + <run-dependency>
27.89 + <release-version>3</release-version>
27.90 + <specification-version>1.79.1.5.22.43</specification-version>
27.91 + </run-dependency>
27.92 + </dependency>
27.93 + <dependency>
27.94 + <code-name-base>org.netbeans.modules.editor.bracesmatching</code-name-base>
27.95 + <build-prerequisite/>
27.96 + <compile-dependency/>
27.97 + <run-dependency>
27.98 + <release-version>0</release-version>
27.99 + <specification-version>1.36</specification-version>
27.100 + </run-dependency>
27.101 + </dependency>
27.102 + <dependency>
27.103 <code-name-base>org.netbeans.modules.editor.codetemplates</code-name-base>
27.104 <build-prerequisite/>
27.105 <compile-dependency/>
27.106 @@ -33,6 +129,14 @@
27.107 </run-dependency>
27.108 </dependency>
27.109 <dependency>
27.110 + <code-name-base>org.netbeans.modules.editor.document</code-name-base>
27.111 + <build-prerequisite/>
27.112 + <compile-dependency/>
27.113 + <run-dependency>
27.114 + <specification-version>1.0</specification-version>
27.115 + </run-dependency>
27.116 + </dependency>
27.117 + <dependency>
27.118 <code-name-base>org.netbeans.modules.editor.indent</code-name-base>
27.119 <build-prerequisite/>
27.120 <compile-dependency/>
27.121 @@ -60,14 +164,6 @@
27.122 </run-dependency>
27.123 </dependency>
27.124 <dependency>
27.125 - <code-name-base>org.netbeans.modules.editor.document</code-name-base>
27.126 - <build-prerequisite/>
27.127 - <compile-dependency/>
27.128 - <run-dependency>
27.129 - <specification-version>1.0</specification-version>
27.130 - </run-dependency>
27.131 - </dependency>
27.132 - <dependency>
27.133 <code-name-base>org.netbeans.modules.editor.mimelookup</code-name-base>
27.134 <build-prerequisite/>
27.135 <compile-dependency/>
27.136 @@ -82,7 +178,15 @@
27.137 <compile-dependency/>
27.138 <run-dependency>
27.139 <release-version>1</release-version>
27.140 - <specification-version>1.21</specification-version>
27.141 + <specification-version>1.53.1</specification-version>
27.142 + </run-dependency>
27.143 + </dependency>
27.144 + <dependency>
27.145 + <code-name-base>org.netbeans.modules.editor.tools.storage</code-name-base>
27.146 + <build-prerequisite/>
27.147 + <compile-dependency/>
27.148 + <run-dependency>
27.149 + <specification-version>1.4.1</specification-version>
27.150 </run-dependency>
27.151 </dependency>
27.152 <dependency>
27.153 @@ -104,24 +208,6 @@
27.154 </run-dependency>
27.155 </dependency>
27.156 <dependency>
27.157 - <code-name-base>org.netbeans.modules.gsf</code-name-base>
27.158 - <build-prerequisite/>
27.159 - <compile-dependency/>
27.160 - <run-dependency>
27.161 - <release-version>2</release-version>
27.162 - <implementation-version/>
27.163 - </run-dependency>
27.164 - </dependency>
27.165 - <dependency>
27.166 - <code-name-base>org.netbeans.modules.gsf.api</code-name-base>
27.167 - <build-prerequisite/>
27.168 - <compile-dependency/>
27.169 - <run-dependency>
27.170 - <release-version>2</release-version>
27.171 - <specification-version>1.7</specification-version>
27.172 - </run-dependency>
27.173 - </dependency>
27.174 - <dependency>
27.175 <code-name-base>org.netbeans.modules.gsf.codecoverage</code-name-base>
27.176 <build-prerequisite/>
27.177 <compile-dependency/>
27.178 @@ -130,15 +216,6 @@
27.179 </run-dependency>
27.180 </dependency>
27.181 <dependency>
27.182 - <code-name-base>org.netbeans.modules.gsfpath.api</code-name-base>
27.183 - <build-prerequisite/>
27.184 - <compile-dependency/>
27.185 - <run-dependency>
27.186 - <release-version>1</release-version>
27.187 - <specification-version>0.30</specification-version>
27.188 - </run-dependency>
27.189 - </dependency>
27.190 - <dependency>
27.191 <code-name-base>org.netbeans.modules.lexer</code-name-base>
27.192 <build-prerequisite/>
27.193 <compile-dependency/>
27.194 @@ -166,6 +243,23 @@
27.195 </run-dependency>
27.196 </dependency>
27.197 <dependency>
27.198 + <code-name-base>org.netbeans.modules.parsing.api</code-name-base>
27.199 + <build-prerequisite/>
27.200 + <compile-dependency/>
27.201 + <run-dependency>
27.202 + <release-version>1</release-version>
27.203 + <specification-version>9.3</specification-version>
27.204 + </run-dependency>
27.205 + </dependency>
27.206 + <dependency>
27.207 + <code-name-base>org.netbeans.modules.parsing.indexing</code-name-base>
27.208 + <build-prerequisite/>
27.209 + <compile-dependency/>
27.210 + <run-dependency>
27.211 + <specification-version>9.3</specification-version>
27.212 + </run-dependency>
27.213 + </dependency>
27.214 + <dependency>
27.215 <code-name-base>org.netbeans.modules.projectapi</code-name-base>
27.216 <build-prerequisite/>
27.217 <compile-dependency/>
27.218 @@ -201,6 +295,14 @@
27.219 </run-dependency>
27.220 </dependency>
27.221 <dependency>
27.222 + <code-name-base>org.netbeans.modules.python.source</code-name-base>
27.223 + <build-prerequisite/>
27.224 + <compile-dependency/>
27.225 + <run-dependency>
27.226 + <specification-version>1.0</specification-version>
27.227 + </run-dependency>
27.228 + </dependency>
27.229 + <dependency>
27.230 <code-name-base>org.netbeans.modules.queries</code-name-base>
27.231 <build-prerequisite/>
27.232 <compile-dependency/>
27.233 @@ -274,14 +376,6 @@
27.234 </run-dependency>
27.235 </dependency>
27.236 <dependency>
27.237 - <code-name-base>org.openide.util.ui</code-name-base>
27.238 - <build-prerequisite/>
27.239 - <compile-dependency/>
27.240 - <run-dependency>
27.241 - <specification-version>9.3</specification-version>
27.242 - </run-dependency>
27.243 - </dependency>
27.244 - <dependency>
27.245 <code-name-base>org.openide.util</code-name-base>
27.246 <build-prerequisite/>
27.247 <compile-dependency/>
27.248 @@ -298,6 +392,14 @@
27.249 </run-dependency>
27.250 </dependency>
27.251 <dependency>
27.252 + <code-name-base>org.openide.util.ui</code-name-base>
27.253 + <build-prerequisite/>
27.254 + <compile-dependency/>
27.255 + <run-dependency>
27.256 + <specification-version>9.3</specification-version>
27.257 + </run-dependency>
27.258 + </dependency>
27.259 + <dependency>
27.260 <code-name-base>org.openide.windows</code-name-base>
27.261 <build-prerequisite/>
27.262 <compile-dependency/>
27.263 @@ -306,70 +408,13 @@
27.264 </run-dependency>
27.265 </dependency>
27.266 </module-dependencies>
27.267 - <test-dependencies>
27.268 - <test-type>
27.269 - <name>unit</name>
27.270 - <test-dependency>
27.271 - <code-name-base>org.netbeans.libs.junit4</code-name-base>
27.272 - <compile-dependency/>
27.273 - </test-dependency>
27.274 - <test-dependency>
27.275 - <code-name-base>org.netbeans.modules.editor.lib</code-name-base>
27.276 - <compile-dependency/>
27.277 - </test-dependency>
27.278 - <test-dependency>
27.279 - <code-name-base>org.netbeans.modules.editor.mimelookup</code-name-base>
27.280 - <recursive/>
27.281 - <compile-dependency/>
27.282 - <test/>
27.283 - </test-dependency>
27.284 - <test-dependency>
27.285 - <code-name-base>org.netbeans.modules.editor.mimelookup.impl</code-name-base>
27.286 - </test-dependency>
27.287 - <test-dependency>
27.288 - <code-name-base>org.netbeans.modules.editor.util</code-name-base>
27.289 - <recursive/>
27.290 - <compile-dependency/>
27.291 - </test-dependency>
27.292 - <test-dependency>
27.293 - <code-name-base>org.netbeans.modules.gsf</code-name-base>
27.294 - <recursive/>
27.295 - <compile-dependency/>
27.296 - <test/>
27.297 - </test-dependency>
27.298 - <test-dependency>
27.299 - <code-name-base>org.netbeans.modules.lexer</code-name-base>
27.300 - <compile-dependency/>
27.301 - <test/>
27.302 - </test-dependency>
27.303 - <test-dependency>
27.304 - <code-name-base>org.netbeans.modules.masterfs</code-name-base>
27.305 - </test-dependency>
27.306 - <test-dependency>
27.307 - <code-name-base>org.netbeans.modules.nbjunit</code-name-base>
27.308 - <recursive/>
27.309 - <compile-dependency/>
27.310 - </test-dependency>
27.311 - <test-dependency>
27.312 - <code-name-base>org.netbeans.modules.python.editor</code-name-base>
27.313 - <recursive/>
27.314 - <compile-dependency/>
27.315 - </test-dependency>
27.316 - <test-dependency>
27.317 - <code-name-base>org.netbeans.modules.python.project</code-name-base>
27.318 - <compile-dependency/>
27.319 - </test-dependency>
27.320 - <test-dependency>
27.321 - <code-name-base>org.openide.util</code-name-base>
27.322 - </test-dependency>
27.323 - </test-type>
27.324 - </test-dependencies>
27.325 <friend-packages>
27.326 <friend>org.netbeans.modules.python.project</friend>
27.327 + <friend>org.netbeans.modules.python.project2</friend>
27.328 <friend>org.netbeans.modules.python.testrunner</friend>
27.329 <package>org.netbeans.modules.python.editor</package>
27.330 + <package>org.netbeans.modules.python.editor.codecoverage</package>
27.331 <package>org.netbeans.modules.python.editor.lexer</package>
27.332 - <package>org.netbeans.modules.python.editor.codecoverage</package>
27.333 </friend-packages>
27.334 </data>
27.335 </configuration>
28.1 --- a/python.editor/src/org/netbeans/modules/python/actions/RunPyAction.java Sun Jan 04 13:11:53 2015 -0600
28.2 +++ b/python.editor/src/org/netbeans/modules/python/actions/RunPyAction.java Sat Feb 28 17:25:32 2015 -0800
28.3 @@ -5,14 +5,12 @@
28.4 package org.netbeans.modules.python.actions;
28.5
28.6 import java.io.File;
28.7 -import java.util.Properties;
28.8 import org.netbeans.modules.python.api.PythonExecution;
28.9 -import org.netbeans.modules.python.api.PythonOptions;
28.10 import org.netbeans.modules.python.api.PythonPlatform;
28.11 import org.netbeans.modules.python.api.PythonPlatformManager;
28.12 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
28.13 import org.netbeans.api.project.Project;
28.14 import org.netbeans.api.project.ui.OpenProjects;
28.15 +import org.netbeans.modules.python.api.PythonMIMEResolver;
28.16 import org.openide.filesystems.FileObject;
28.17 import org.openide.filesystems.FileUtil;
28.18 import org.openide.loaders.DataObject;
28.19 @@ -25,7 +23,7 @@
28.20 protected void performAction(Node[] activatedNodes) {
28.21 //listProperties();
28.22 DataObject gdo = activatedNodes[0].getLookup().lookup(DataObject.class);
28.23 - if (gdo.getPrimaryFile().getMIMEType().equals(PythonTokenId.PYTHON_MIME_TYPE)) {
28.24 + if (gdo.getPrimaryFile().getMIMEType().equals(PythonMIMEResolver.PYTHON_MIME_TYPE)) {
28.25
28.26 String path = gdo.getPrimaryFile().getParent().getPath();
28.27 //int pos = path.lastIndexOf("/");
28.28 @@ -67,7 +65,7 @@
28.29 boolean results = false; //super.enable(activatedNodes);
28.30 if (activatedNodes.length > 0) {
28.31 DataObject gdo = activatedNodes[0].getLookup().lookup(DataObject.class);
28.32 - results = gdo.getPrimaryFile().getMIMEType().equals(PythonTokenId.PYTHON_MIME_TYPE);
28.33 + results = gdo.getPrimaryFile().getMIMEType().equals(PythonMIMEResolver.PYTHON_MIME_TYPE);
28.34 }
28.35 return results;
28.36 }
29.1 --- a/python.editor/src/org/netbeans/modules/python/editor/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
29.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/Bundle.properties Sat Feb 28 17:25:32 2015 -0800
29.3 @@ -18,6 +18,8 @@
29.4 PythonLib=Python Library
29.5 In=in
29.6
29.7 +ChooseDecl=Go To Declaration
29.8 +
29.9 CTL_Hints_DisplayName=Hints
29.10 CTL_Hints_ToolTip=Hints And Warnings for Python Code
29.11 UnsafeIdentifierName=Only a-z, A-Z, digits and underscore are safe in Python names
30.1 --- a/python.editor/src/org/netbeans/modules/python/editor/DedentAction.java Sun Jan 04 13:11:53 2015 -0600
30.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/DedentAction.java Sat Feb 28 17:25:32 2015 -0800
30.3 @@ -48,8 +48,8 @@
30.4 import org.netbeans.editor.BaseDocument;
30.5 import org.netbeans.editor.Utilities;
30.6 import org.netbeans.lib.editor.util.swing.DocumentUtilities;
30.7 +import org.netbeans.modules.csl.spi.GsfUtilities;
30.8 import org.netbeans.modules.editor.indent.api.IndentUtils;
30.9 -import org.netbeans.modules.gsf.spi.GsfUtilities;
30.10 import org.openide.util.Exceptions;
30.11
30.12 /**
31.1 --- a/python.editor/src/org/netbeans/modules/python/editor/GoToSuperTypeAction.java Sun Jan 04 13:11:53 2015 -0600
31.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/GoToSuperTypeAction.java Sat Feb 28 17:25:32 2015 -0800
31.3 @@ -43,14 +43,27 @@
31.4 */
31.5 package org.netbeans.modules.python.editor;
31.6
31.7 +import java.awt.Component;
31.8 +import java.awt.Cursor;
31.9 +import java.awt.Image;
31.10 import java.awt.Point;
31.11 import java.awt.Rectangle;
31.12 import java.awt.Toolkit;
31.13 import java.awt.event.ActionEvent;
31.14 -import java.io.IOException;
31.15 +import java.awt.event.FocusEvent;
31.16 +import java.awt.event.FocusListener;
31.17 +import java.awt.event.KeyEvent;
31.18 +import java.awt.event.MouseEvent;
31.19 import java.util.ArrayList;
31.20 +import java.util.Collection;
31.21 import java.util.Collections;
31.22 import java.util.List;
31.23 +import javax.swing.DefaultListCellRenderer;
31.24 +import javax.swing.DefaultListModel;
31.25 +import javax.swing.ImageIcon;
31.26 +import javax.swing.JList;
31.27 +import javax.swing.JPanel;
31.28 +import javax.swing.ListModel;
31.29 import javax.swing.SwingUtilities;
31.30 import javax.swing.text.BadLocationException;
31.31 import javax.swing.text.Document;
31.32 @@ -58,19 +71,24 @@
31.33 import org.netbeans.api.editor.EditorRegistry;
31.34 import org.netbeans.editor.BaseAction;
31.35 import org.netbeans.editor.BaseDocument;
31.36 -import org.netbeans.modules.gsf.GsfHtmlFormatter;
31.37 -import org.netbeans.modules.gsf.api.CancellableTask;
31.38 -import org.netbeans.modules.gsf.api.CompilationInfo;
31.39 -import org.netbeans.modules.gsf.api.DeclarationFinder.AlternativeLocation;
31.40 -import org.netbeans.modules.gsf.api.DeclarationFinder.DeclarationLocation;
31.41 -import org.netbeans.modules.gsf.api.SourceModel;
31.42 -import org.netbeans.modules.gsf.api.SourceModelFactory;
31.43 -import org.netbeans.modules.gsf.spi.GsfUtilities;
31.44 -import org.netbeans.modules.gsfret.editor.hyperlink.DeclarationPopup;
31.45 -import org.netbeans.modules.gsfret.editor.hyperlink.GoToSupport;
31.46 -import org.netbeans.modules.gsfret.editor.hyperlink.PopupUtil;
31.47 +import org.netbeans.modules.csl.api.DeclarationFinder.AlternativeLocation;
31.48 +import org.netbeans.modules.csl.api.DeclarationFinder.DeclarationLocation;
31.49 +import org.netbeans.modules.csl.api.ElementHandle;
31.50 +import org.netbeans.modules.csl.api.ElementKind;
31.51 +import org.netbeans.modules.csl.api.HtmlFormatter;
31.52 +import org.netbeans.modules.csl.api.Modifier;
31.53 +import org.netbeans.modules.csl.api.UiUtils;
31.54 +import org.netbeans.modules.csl.spi.GsfUtilities;
31.55 +import org.netbeans.modules.parsing.api.ParserManager;
31.56 +import org.netbeans.modules.parsing.api.ResultIterator;
31.57 +import org.netbeans.modules.parsing.api.Source;
31.58 +import org.netbeans.modules.parsing.api.UserTask;
31.59 +import org.netbeans.modules.parsing.spi.ParseException;
31.60 +import org.netbeans.modules.python.editor.imports.PopupUtil;
31.61 +import org.openide.awt.StatusDisplayer;
31.62 import org.openide.filesystems.FileObject;
31.63 import org.openide.util.Exceptions;
31.64 +import org.openide.util.ImageUtilities;
31.65 import org.openide.util.NbBundle;
31.66
31.67 /**
31.68 @@ -109,21 +127,20 @@
31.69 // Move imports that I think may be unused to the end - or just comment them out?
31.70
31.71 // For imports: Gather imports from everywhere... move others into the same section
31.72 - CompilationInfo info = null;
31.73 + PythonParserResult info = null;
31.74
31.75 - SourceModel model = SourceModelFactory.getInstance().getModel(fo);
31.76 - if (model != null) {
31.77 - final CompilationInfo[] infoHolder = new CompilationInfo[1];
31.78 + Source source = Source.create(fo);
31.79 + if (source != null) {
31.80 + final PythonParserResult[] infoHolder = new PythonParserResult[1];
31.81 try {
31.82 - model.runUserActionTask(new CancellableTask<CompilationInfo>() {
31.83 - public void cancel() {
31.84 + ParserManager.parse(Collections.singleton(source), new UserTask() {
31.85 +
31.86 + @Override
31.87 + public void run(ResultIterator resultIterator) throws Exception {
31.88 + infoHolder[0] = (PythonParserResult) resultIterator.getParserResult();
31.89 }
31.90 -
31.91 - public void run(CompilationInfo info) throws Exception {
31.92 - infoHolder[0] = info;
31.93 - }
31.94 - }, false);
31.95 - } catch (IOException ex) {
31.96 + });
31.97 + } catch (ParseException ex) {
31.98 Exceptions.printStackTrace(ex);
31.99 }
31.100 info = infoHolder[0];
31.101 @@ -186,7 +203,7 @@
31.102 Point point = new Point(rectangle.x, rectangle.y + rectangle.height);
31.103 SwingUtilities.convertPointToScreen(point, target);
31.104
31.105 - String caption = NbBundle.getMessage(GoToSupport.class, "ChooseDecl");
31.106 + String caption = NbBundle.getMessage(GoToSuperTypeAction.class, "ChooseDecl");
31.107 PopupUtil.showPopup(new DeclarationPopup(caption, alternatives), caption, point.x, point.y, true, 0);
31.108
31.109 return true;
31.110 @@ -213,4 +230,439 @@
31.111
31.112 return null;
31.113 }
31.114 +
31.115 + /**
31.116 + * Copied from csl.api.core.
31.117 + */
31.118 + private static class GsfHtmlFormatter extends HtmlFormatter {
31.119 + protected boolean isDeprecated;
31.120 + protected boolean isParameter;
31.121 + protected boolean isType;
31.122 + protected boolean isName;
31.123 + protected boolean isEmphasis;
31.124 +
31.125 + protected StringBuilder sb = new StringBuilder();
31.126 +
31.127 + public GsfHtmlFormatter() {
31.128 + }
31.129 +
31.130 + public void reset() {
31.131 + textLength = 0;
31.132 + sb.setLength(0);
31.133 + }
31.134 +
31.135 + public void appendHtml(String html) {
31.136 + sb.append(html);
31.137 + // Not sure what to do about maxLength here... but presumably
31.138 + }
31.139 +
31.140 + public void appendText(String text, int fromInclusive, int toExclusive) {
31.141 + for (int i = fromInclusive; i < toExclusive; i++) {
31.142 + if (textLength >= maxLength) {
31.143 + if (textLength == maxLength) {
31.144 + sb.append("...");
31.145 + textLength += 3;
31.146 + }
31.147 + break;
31.148 + }
31.149 + char c = text.charAt(i);
31.150 +
31.151 + switch (c) {
31.152 + case '<':
31.153 + sb.append("<"); // NOI18N
31.154 +
31.155 + break;
31.156 +
31.157 + case '>': // Only ]]> is dangerous
31.158 + if ((i > 1) && (text.charAt(i - 2) == ']') && (text.charAt(i - 1) == ']')) {
31.159 + sb.append(">"); // NOI18N
31.160 + } else {
31.161 + sb.append(c);
31.162 + }
31.163 + break;
31.164 +
31.165 + case '&':
31.166 + sb.append("&"); // NOI18N
31.167 +
31.168 + break;
31.169 +
31.170 + default:
31.171 + sb.append(c);
31.172 + }
31.173 +
31.174 + textLength++;
31.175 + }
31.176 + }
31.177 +
31.178 + public void name(ElementKind kind, boolean start) {
31.179 + assert start != isName;
31.180 + isName = start;
31.181 +
31.182 + if (isName) {
31.183 + sb.append("<b>");
31.184 + } else {
31.185 + sb.append("</b>");
31.186 + }
31.187 + }
31.188 +
31.189 + public void parameters(boolean start) {
31.190 + assert start != isParameter;
31.191 + isParameter = start;
31.192 +
31.193 + if (isParameter) {
31.194 + sb.append("<font color=\"#808080\">");
31.195 + } else {
31.196 + sb.append("</font>");
31.197 + }
31.198 + }
31.199 +
31.200 + @Override
31.201 + public void active(boolean start) {
31.202 + emphasis(start);
31.203 + }
31.204 +
31.205 + public void type(boolean start) {
31.206 + assert start != isType;
31.207 + isType = start;
31.208 +
31.209 + if (isType) {
31.210 + sb.append("<font color=\"#808080\">");
31.211 + } else {
31.212 + sb.append("</font>");
31.213 + }
31.214 + }
31.215 +
31.216 + public void deprecated(boolean start) {
31.217 + assert start != isDeprecated;
31.218 + isDeprecated = start;
31.219 +
31.220 + if (isDeprecated) {
31.221 + sb.append("<s>");
31.222 + } else {
31.223 + sb.append("</s>");
31.224 + }
31.225 + }
31.226 +
31.227 + public String getText() {
31.228 + assert !isParameter && !isDeprecated && !isName && !isType;
31.229 +
31.230 + return sb.toString();
31.231 + }
31.232 +
31.233 + public void emphasis(boolean start) {
31.234 + assert start != isEmphasis;
31.235 + isEmphasis = start;
31.236 +
31.237 + if (isEmphasis) {
31.238 + sb.append("<b>");
31.239 + } else {
31.240 + sb.append("</b>");
31.241 + }
31.242 + }
31.243 + }
31.244 + private static class DeclarationPopup extends JPanel implements FocusListener {
31.245 +
31.246 + private String caption;
31.247 + private List<AlternativeLocation> declarations;
31.248 +
31.249 + /** Creates new form DeclarationPopup */
31.250 + public DeclarationPopup(String caption, List<AlternativeLocation> declarations) {
31.251 + this.caption = caption;
31.252 + this.declarations = declarations;
31.253 +
31.254 + initComponents();
31.255 +
31.256 + jList1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
31.257 +
31.258 + addFocusListener(this);
31.259 + }
31.260 +
31.261 + /** This method is called from within the constructor to
31.262 + * initialize the form.
31.263 + * WARNING: Do NOT modify this code. The content of this method is
31.264 + * always regenerated by the Form Editor.
31.265 + */
31.266 + // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
31.267 + private void initComponents() {
31.268 + java.awt.GridBagConstraints gridBagConstraints;
31.269 +
31.270 + jLabel1 = new javax.swing.JLabel();
31.271 + jScrollPane1 = new javax.swing.JScrollPane();
31.272 + jList1 = new javax.swing.JList();
31.273 +
31.274 + setFocusCycleRoot(true);
31.275 + setLayout(new java.awt.GridBagLayout());
31.276 +
31.277 + jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
31.278 + jLabel1.setText(caption
31.279 + );
31.280 + jLabel1.setFocusable(false);
31.281 + gridBagConstraints = new java.awt.GridBagConstraints();
31.282 + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
31.283 + add(jLabel1, gridBagConstraints);
31.284 +
31.285 + jList1.setModel(createListModel());
31.286 + jList1.setCellRenderer(new RendererImpl());
31.287 + jList1.setSelectedIndex(0);
31.288 + jList1.setVisibleRowCount(declarations.size()
31.289 + );
31.290 + jList1.addKeyListener(new java.awt.event.KeyAdapter() {
31.291 + public void keyPressed(java.awt.event.KeyEvent evt) {
31.292 + jList1KeyPressed(evt);
31.293 + }
31.294 + });
31.295 + jList1.addMouseListener(new java.awt.event.MouseAdapter() {
31.296 + public void mouseClicked(java.awt.event.MouseEvent evt) {
31.297 + jList1MouseClicked(evt);
31.298 + }
31.299 + });
31.300 + jScrollPane1.setViewportView(jList1);
31.301 +
31.302 + gridBagConstraints = new java.awt.GridBagConstraints();
31.303 + gridBagConstraints.gridx = 0;
31.304 + gridBagConstraints.gridy = 1;
31.305 + gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
31.306 + gridBagConstraints.weightx = 1.0;
31.307 + gridBagConstraints.weighty = 1.0;
31.308 + add(jScrollPane1, gridBagConstraints);
31.309 + }// </editor-fold>
31.310 +
31.311 + private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
31.312 + // TODO add your handling code here:
31.313 + if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() == 1) {
31.314 + openSelected();
31.315 + }
31.316 + }
31.317 +
31.318 + private void jList1KeyPressed(java.awt.event.KeyEvent evt) {
31.319 + // TODO add your handling code here:
31.320 + if (evt.getKeyCode() == KeyEvent.VK_ENTER && evt.getModifiers() == 0) {
31.321 + openSelected();
31.322 + }
31.323 + }
31.324 +
31.325 +
31.326 + // Variables declaration - do not modify
31.327 + private javax.swing.JLabel jLabel1;
31.328 + private javax.swing.JList jList1;
31.329 + private javax.swing.JScrollPane jScrollPane1;
31.330 + // End of variables declaration
31.331 +
31.332 + private void openSelected() {
31.333 + AlternativeLocation desc = (AlternativeLocation) jList1.getSelectedValue();
31.334 +
31.335 + if (desc != null) {
31.336 + DeclarationLocation location = desc.getLocation();
31.337 + if (location == DeclarationLocation.NONE) {
31.338 + StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage(DeclarationPopup.class, "InvalidLoc"));
31.339 + Toolkit.getDefaultToolkit().beep();
31.340 + } else {
31.341 + String invalid = location.getInvalidMessage();
31.342 + if (invalid != null) {
31.343 + // TODO - show in the editor as an error instead?
31.344 + StatusDisplayer.getDefault().setStatusText(invalid);
31.345 + Toolkit.getDefaultToolkit().beep();
31.346 + } else {
31.347 + FileObject fileObject = location.getFileObject();
31.348 + if (fileObject != null) {
31.349 + UiUtils.open(fileObject,location.getOffset());
31.350 + } else {
31.351 + Toolkit.getDefaultToolkit().beep();
31.352 + }
31.353 + }
31.354 + }
31.355 + }
31.356 +
31.357 + PopupUtil.hidePopup();
31.358 + }
31.359 +
31.360 + private ListModel createListModel() {
31.361 + DefaultListModel dlm = new DefaultListModel();
31.362 +
31.363 + for (AlternativeLocation el: declarations) {
31.364 + dlm.addElement(el);
31.365 + }
31.366 +
31.367 + return dlm;
31.368 + }
31.369 +
31.370 + private static class RendererImpl extends DefaultListCellRenderer {
31.371 + @Override
31.372 + public Component getListCellRendererComponent(
31.373 + JList list,
31.374 + Object value,
31.375 + int index,
31.376 + boolean isSelected,
31.377 + boolean cellHasFocus) {
31.378 + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
31.379 +
31.380 + if (value instanceof AlternativeLocation) {
31.381 + AlternativeLocation desc = (AlternativeLocation) value;
31.382 + ElementHandle e = desc.getElement();
31.383 + ImageIcon icon = Icons.getElementIcon(e.getKind(), e.getModifiers());
31.384 + setIcon(icon);
31.385 +
31.386 + GsfHtmlFormatter formatter = new GsfHtmlFormatter();
31.387 + String s = desc.getDisplayHtml(formatter);
31.388 + setText("<html>"+s);
31.389 + }
31.390 +
31.391 + return c;
31.392 + }
31.393 + }
31.394 +
31.395 + public void focusGained(FocusEvent arg0) {
31.396 + jList1.requestFocus();
31.397 + jList1.requestFocusInWindow();
31.398 + }
31.399 +
31.400 + public void focusLost(FocusEvent arg0) {
31.401 + }
31.402 +
31.403 + }
31.404 + private static class Icons {
31.405 + private static final String ICON_BASE = "org/netbeans/modules/csl/source/resources/icons/";
31.406 + private static final String GIF_EXTENSION = ".gif";
31.407 + private static final String PNG_EXTENSION = ".png";
31.408 + private static final String WAIT = ICON_BASE + "wait" + PNG_EXTENSION;
31.409 + //private static final Map<String, Icon> icons = new HashMap<String, Icon>();
31.410 +
31.411 + /** Creates a new instance of Icons */
31.412 + private Icons() {
31.413 + }
31.414 +
31.415 + // public static Icon getBusyIcon() {
31.416 + // Image img = Utilities.loadImage(WAIT);
31.417 + //
31.418 + // if (img == null) {
31.419 + // return null;
31.420 + // } else {
31.421 + // return new ImageIcon(img);
31.422 + // }
31.423 + // }
31.424 + //
31.425 + // public static Icon getMethodIcon() {
31.426 + // // TODO - consider modifiers
31.427 + // Image img =
31.428 + // Utilities.loadImage(ICON_BASE + "method" + "Public" + PNG_EXTENSION);
31.429 + //
31.430 + // if (img == null) {
31.431 + // return null;
31.432 + // } else {
31.433 + // return new ImageIcon(img);
31.434 + // }
31.435 + // }
31.436 + //
31.437 + // public static Icon getFieldIcon() {
31.438 + // // TODO - consider modifiers
31.439 + // Image img =
31.440 + // Utilities.loadImage(ICON_BASE + "field" + "Public" + PNG_EXTENSION);
31.441 + //
31.442 + // if (img == null) {
31.443 + // return null;
31.444 + // } else {
31.445 + // return new ImageIcon(img);
31.446 + // }
31.447 + // }
31.448 + //
31.449 + // public static Icon getClassIcon() {
31.450 + // Image img = Utilities.loadImage(ICON_BASE + "class" + PNG_EXTENSION);
31.451 + //
31.452 + // if (img == null) {
31.453 + // return null;
31.454 + // } else {
31.455 + // return new ImageIcon(img);
31.456 + // }
31.457 + // }
31.458 + //
31.459 + // public static Icon getModuleIcon() {
31.460 + // Image img =
31.461 + // Utilities.loadImage(ICON_BASE + "package" + GIF_EXTENSION);
31.462 + //
31.463 + // if (img == null) {
31.464 + // return null;
31.465 + // } else {
31.466 + // return new ImageIcon(img);
31.467 + // }
31.468 + // }
31.469 +
31.470 + public static ImageIcon getElementIcon( ElementKind elementKind, Collection<Modifier> modifiers ) {
31.471 +
31.472 + if ( modifiers == null ) {
31.473 + modifiers = Collections.<Modifier>emptyList();
31.474 + }
31.475 +
31.476 + Image img = null;
31.477 +
31.478 + switch( elementKind ) {
31.479 + case FILE:
31.480 + img = ImageUtilities.loadImage( ICON_BASE + "emptyfile-icon" + PNG_EXTENSION );
31.481 + break;
31.482 + case ERROR:
31.483 + img = ImageUtilities.loadImage( ICON_BASE + "error-glyph" + GIF_EXTENSION );
31.484 + break;
31.485 + case PACKAGE:
31.486 + case MODULE:
31.487 + img = ImageUtilities.loadImage( ICON_BASE + "package" + GIF_EXTENSION );
31.488 + break;
31.489 + case TEST:
31.490 + img = ImageUtilities.loadImage( ICON_BASE + "test" + PNG_EXTENSION );
31.491 + break;
31.492 + case CLASS:
31.493 + case INTERFACE:
31.494 + img = ImageUtilities.loadImage( ICON_BASE + "class" + PNG_EXTENSION );
31.495 + break;
31.496 + case TAG:
31.497 + img = ImageUtilities.loadImage( ICON_BASE + "html_element" + PNG_EXTENSION );
31.498 + break;
31.499 + case RULE:
31.500 + img = ImageUtilities.loadImage( ICON_BASE + "rule" + PNG_EXTENSION );
31.501 + break;
31.502 + case VARIABLE:
31.503 + case PROPERTY:
31.504 + case GLOBAL:
31.505 + case ATTRIBUTE:
31.506 + case FIELD:
31.507 + img = ImageUtilities.loadImage( getIconName( ICON_BASE + "field", PNG_EXTENSION, modifiers ) );
31.508 + break;
31.509 + case PARAMETER:
31.510 + case CONSTANT:
31.511 + img = ImageUtilities.loadImage(ICON_BASE + "constant" + PNG_EXTENSION );
31.512 + break;
31.513 + case CONSTRUCTOR:
31.514 + img = ImageUtilities.loadImage( getIconName( ICON_BASE + "constructor", PNG_EXTENSION, modifiers ) );
31.515 + break;
31.516 + case METHOD:
31.517 + img = ImageUtilities.loadImage( getIconName( ICON_BASE + "method", PNG_EXTENSION, modifiers ) );
31.518 + break;
31.519 + case DB:
31.520 + img = ImageUtilities.loadImage(ICON_BASE + "database" + GIF_EXTENSION);
31.521 + break;
31.522 + default:
31.523 + img = null;
31.524 + }
31.525 +
31.526 + return img == null ? null : new ImageIcon (img);
31.527 + }
31.528 +
31.529 + // Private Methods ---------------------------------------------------------
31.530 + private static String getIconName(String typeName, String extension, Collection<Modifier> modifiers) {
31.531 +
31.532 + StringBuffer fileName = new StringBuffer( typeName );
31.533 +
31.534 + if (modifiers.contains(Modifier.STATIC)) {
31.535 + fileName.append( "Static" );
31.536 + }
31.537 + if (modifiers.contains(Modifier.PROTECTED)) {
31.538 + return fileName.append( "Protected" ).append( extension ).toString();
31.539 + }
31.540 + if (modifiers.contains(Modifier.PRIVATE)) {
31.541 + return fileName.append( "Private" ).append( extension ).toString();
31.542 + }
31.543 + // Assume it's public
31.544 + return fileName.append( "Public" ).append( extension ).toString();
31.545 + //return fileName.append( "Package" ).append( extension ).toString();
31.546 + //return fileName.append(extension).toString();
31.547 + }
31.548 + }
31.549 }
32.1 --- a/python.editor/src/org/netbeans/modules/python/editor/IndentAction.java Sun Jan 04 13:11:53 2015 -0600
32.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/IndentAction.java Sat Feb 28 17:25:32 2015 -0800
32.3 @@ -48,8 +48,8 @@
32.4 import org.netbeans.editor.BaseKit;
32.5 import org.netbeans.editor.Utilities;
32.6 import org.netbeans.lib.editor.util.swing.DocumentUtilities;
32.7 +import org.netbeans.modules.csl.spi.GsfUtilities;
32.8 import org.netbeans.modules.editor.indent.api.IndentUtils;
32.9 -import org.netbeans.modules.gsf.spi.GsfUtilities;
32.10 import org.openide.util.Exceptions;
32.11
32.12 /**
33.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonAstTreeNode.java Sun Jan 04 13:11:53 2015 -0600
33.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonAstTreeNode.java Sat Feb 28 17:25:32 2015 -0800
33.3 @@ -30,19 +30,17 @@
33.4 */
33.5 package org.netbeans.modules.python.editor;
33.6
33.7 -import java.io.CharConversionException;
33.8 -import java.util.ArrayList;
33.9 -import java.util.Collections;
33.10 -import java.util.Enumeration;
33.11 -import java.util.List;
33.12 -import javax.swing.tree.TreeNode;
33.13 -import org.netbeans.modules.gsf.api.ParserResult.AstTreeNode;
33.14 -import org.openide.util.Exceptions;
33.15 -import org.openide.xml.XMLUtil;
33.16 -import org.python.antlr.PythonTree;
33.17 -import org.python.antlr.Visitor;
33.18 -import org.python.antlr.ast.Name;
33.19 -
33.20 +//import java.io.CharConversionException;
33.21 +//import java.util.ArrayList;
33.22 +//import java.util.Collections;
33.23 +//import java.util.Enumeration;
33.24 +//import java.util.List;
33.25 +//import org.openide.util.Exceptions;
33.26 +//import org.openide.xml.XMLUtil;
33.27 +//import org.python.antlr.PythonTree;
33.28 +//import org.python.antlr.Visitor;
33.29 +//import org.python.antlr.ast.Name;
33.30 +/* Unused?
33.31 class PythonAstTreeNode implements AstTreeNode {
33.32 private List<PythonAstTreeNode> children;
33.33 private final PythonTree node;
33.34 @@ -179,3 +177,4 @@
33.35 return null;
33.36 }
33.37 }
33.38 +*/
33.39 \ No newline at end of file
34.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonAstUtils.java Sun Jan 04 13:11:53 2015 -0600
34.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonAstUtils.java Sat Feb 28 17:25:32 2015 -0800
34.3 @@ -30,7 +30,6 @@
34.4 */
34.5 package org.netbeans.modules.python.editor;
34.6
34.7 -import java.io.IOException;
34.8 import java.util.ArrayList;
34.9 import java.util.Collections;
34.10 import java.util.HashSet;
34.11 @@ -48,17 +47,19 @@
34.12 import org.netbeans.editor.BaseDocument;
34.13 import org.netbeans.editor.Finder;
34.14 import org.netbeans.editor.FinderFactory;
34.15 +import org.netbeans.modules.csl.api.ElementKind;
34.16 +import org.netbeans.modules.csl.api.OffsetRange;
34.17 +import org.netbeans.modules.csl.api.StructureItem;
34.18 +import org.netbeans.modules.csl.spi.GsfUtilities;
34.19 +import org.netbeans.modules.csl.spi.ParserResult;
34.20 +import org.netbeans.modules.parsing.api.ParserManager;
34.21 +import org.netbeans.modules.parsing.api.ResultIterator;
34.22 +import org.netbeans.modules.parsing.api.Source;
34.23 +import org.netbeans.modules.parsing.api.UserTask;
34.24 +import org.netbeans.modules.parsing.spi.ParseException;
34.25 import org.netbeans.modules.python.editor.elements.IndexedElement;
34.26 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
34.27 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
34.28 -import org.netbeans.modules.gsf.api.CancellableTask;
34.29 -import org.netbeans.modules.gsf.api.CompilationInfo;
34.30 -import org.netbeans.modules.gsf.api.ElementKind;
34.31 -import org.netbeans.modules.gsf.api.OffsetRange;
34.32 -import org.netbeans.modules.gsf.api.ParserResult;
34.33 -import org.netbeans.modules.gsf.api.SourceModel;
34.34 -import org.netbeans.modules.gsf.api.SourceModelFactory;
34.35 -import org.netbeans.modules.gsf.api.TranslatedSource;
34.36 import org.netbeans.modules.python.editor.lexer.PythonCommentTokenId;
34.37 import org.netbeans.modules.python.editor.scopes.ScopeInfo;
34.38 import org.netbeans.modules.python.editor.scopes.SymbolTable;
34.39 @@ -92,62 +93,38 @@
34.40 // This is just a utility class, no instances expected so private constructor
34.41 }
34.42
34.43 - public static int getAstOffset(CompilationInfo info, int lexOffset) {
34.44 - ParserResult result = info.getEmbeddedResult(PythonTokenId.PYTHON_MIME_TYPE, 0);
34.45 + public static int getAstOffset(ParserResult result, int lexOffset) {
34.46 if (result != null) {
34.47 - TranslatedSource ts = result.getTranslatedSource();
34.48 - if (ts != null) {
34.49 - return ts.getAstOffset(lexOffset);
34.50 - }
34.51 + return result.getSnapshot().getEmbeddedOffset(lexOffset);
34.52 }
34.53
34.54 return lexOffset;
34.55 }
34.56
34.57 - public static OffsetRange getAstOffsets(CompilationInfo info, OffsetRange lexicalRange) {
34.58 - ParserResult result = info.getEmbeddedResult(PythonTokenId.PYTHON_MIME_TYPE, 0);
34.59 + public static OffsetRange getAstOffsets(ParserResult result, OffsetRange lexicalRange) {
34.60 if (result != null) {
34.61 - TranslatedSource ts = result.getTranslatedSource();
34.62 - if (ts != null) {
34.63 - int rangeStart = lexicalRange.getStart();
34.64 - int start = ts.getAstOffset(rangeStart);
34.65 - if (start == rangeStart) {
34.66 - return lexicalRange;
34.67 - } else if (start == -1) {
34.68 - return OffsetRange.NONE;
34.69 - } else {
34.70 - // Assumes the translated range maintains size
34.71 - return new OffsetRange(start, start + lexicalRange.getLength());
34.72 - }
34.73 + int rangeStart = lexicalRange.getStart();
34.74 + int start = result.getSnapshot().getEmbeddedOffset(rangeStart);
34.75 + if (start == rangeStart) {
34.76 + return lexicalRange;
34.77 + } else if (start == -1) {
34.78 + return OffsetRange.NONE;
34.79 + } else {
34.80 + // Assumes the translated range maintains size
34.81 + return new OffsetRange(start, start + lexicalRange.getLength());
34.82 }
34.83 }
34.84 return lexicalRange;
34.85 }
34.86
34.87 - public static PythonTree getRoot(CompilationInfo info) {
34.88 - return getRoot(info, PythonTokenId.PYTHON_MIME_TYPE);
34.89 - }
34.90 -
34.91 - public static PythonParserResult getParseResult(CompilationInfo info) {
34.92 - ParserResult result = info.getEmbeddedResult(PythonTokenId.PYTHON_MIME_TYPE, 0);
34.93 -
34.94 - if (result == null) {
34.95 + public static PythonParserResult getParseResult(ParserResult result) {
34.96 + if(result == null || !(result instanceof PythonParserResult)) {
34.97 return null;
34.98 } else {
34.99 return ((PythonParserResult)result);
34.100 }
34.101 }
34.102
34.103 - public static PythonTree getRoot(CompilationInfo info, String mimeType) {
34.104 - ParserResult result = info.getEmbeddedResult(mimeType, 0);
34.105 -
34.106 - if (result == null) {
34.107 - return null;
34.108 - }
34.109 -
34.110 - return getRoot(result);
34.111 - }
34.112 -
34.113 public static PythonTree getRoot(ParserResult r) {
34.114 assert r instanceof PythonParserResult;
34.115
34.116 @@ -160,7 +137,7 @@
34.117 * Return a range that matches the given node's source buffer range
34.118 */
34.119 @SuppressWarnings("unchecked")
34.120 - public static OffsetRange getNameRange(CompilationInfo info, PythonTree node) {
34.121 + public static OffsetRange getNameRange(PythonParserResult info, PythonTree node) {
34.122 // final int type = node.getType();
34.123 // switch (type) {
34.124 // case Token.FUNCTION: {
34.125 @@ -218,7 +195,7 @@
34.126 // but if you have additional comments etc. that won't work right, so
34.127 // in this case, go and look at the actual document
34.128 if (info != null) {
34.129 - BaseDocument doc = (BaseDocument)info.getDocument();
34.130 + BaseDocument doc = GsfUtilities.getDocument(info.getSnapshot().getSource().getFileObject(), false);
34.131 if (doc != null) {
34.132 int lexOffset = PythonLexerUtils.getLexerOffset(info, defStart);
34.133 int limitOffset = PythonLexerUtils.getLexerOffset(info, def.getCharStopIndex());
34.134 @@ -592,36 +569,33 @@
34.135 return null;
34.136 }
34.137
34.138 - public static PythonTree getForeignNode(final IndexedElement o, CompilationInfo[] compilationInfoRet) {
34.139 + public static PythonTree getForeignNode(final IndexedElement o, PythonParserResult[] parserResultRet) {
34.140 FileObject fo = o.getFileObject();
34.141
34.142 if (fo == null) {
34.143 return null;
34.144 }
34.145 -
34.146 - SourceModel model = SourceModelFactory.getInstance().getModel(fo);
34.147 - if (model == null) {
34.148 +
34.149 + Source source = Source.create(fo);
34.150 + if(source == null) {
34.151 return null;
34.152 }
34.153 - final CompilationInfo[] infoHolder = new CompilationInfo[1];
34.154 + final PythonParserResult[] resultHolder = new PythonParserResult[1];
34.155 try {
34.156 - model.runUserActionTask(new CancellableTask<CompilationInfo>() {
34.157 - public void cancel() {
34.158 + ParserManager.parse(Collections.singleton(source), new UserTask() {
34.159 +
34.160 + @Override
34.161 + public void run(ResultIterator resultIterator) throws Exception {
34.162 + resultHolder[0] = (PythonParserResult) resultIterator.getParserResult();
34.163 }
34.164 -
34.165 - public void run(CompilationInfo info) throws Exception {
34.166 - infoHolder[0] = info;
34.167 - }
34.168 - //}, true);
34.169 - }, false); // XXX REMOVE THIS REMOVE THIS REMOVE THIS!
34.170 - } catch (IOException ex) {
34.171 + });
34.172 + } catch (ParseException ex) {
34.173 Exceptions.printStackTrace(ex);
34.174 - return null;
34.175 }
34.176
34.177 - CompilationInfo info = infoHolder[0];
34.178 - if (compilationInfoRet != null) {
34.179 - compilationInfoRet[0] = info;
34.180 + PythonParserResult info = resultHolder[0];
34.181 + if (parserResultRet != null) {
34.182 + parserResultRet[0] = info;
34.183 }
34.184 PythonParserResult result = getParseResult(info);
34.185 if (result == null) {
34.186 @@ -667,7 +641,7 @@
34.187 // }
34.188
34.189 ElementKind kind = o.getKind();
34.190 - List<PythonStructureItem> items = result.getStructure().getElements();
34.191 + List<PythonStructureItem> items = PythonStructureScanner.analyze(info).getElements();
34.192 if (items != null) {
34.193 return find(items, signature, kind);
34.194 } else {
34.195 @@ -675,21 +649,20 @@
34.196 }
34.197 }
34.198
34.199 - private static PythonTree find(List<PythonStructureItem> items, String signature, ElementKind kind) {
34.200 - for (PythonStructureItem item : items) {
34.201 + private static PythonTree find(List<? extends StructureItem> items, String signature, ElementKind kind) {
34.202 + for (StructureItem item : items) {
34.203 ElementKind childKind = item.getKind();
34.204 if (childKind == kind &&
34.205 - signature.equals(item.getSignature())) {
34.206 - return item.getNode();
34.207 + item instanceof PythonStructureItem &&
34.208 + signature.equals(((PythonStructureItem)item).getSignature())) {
34.209 + return ((PythonStructureItem)item).getNode();
34.210 }
34.211 - if (childKind == ElementKind.CLASS && signature.indexOf(item.getName()) != -1) {
34.212 + if (childKind == ElementKind.CLASS && signature.contains(item.getName())) {
34.213 @SuppressWarnings("unchecked")
34.214 - List<PythonStructureItem> children = (List<PythonStructureItem>)item.getNestedItems();
34.215 - if (children != null) {
34.216 - PythonTree result = find(children, signature, kind);
34.217 - if (result != null) {
34.218 - return result;
34.219 - }
34.220 + List<? extends StructureItem> children = item.getNestedItems();
34.221 + PythonTree result = find(children, signature, kind);
34.222 + if (result != null) {
34.223 + return result;
34.224 }
34.225 }
34.226 }
34.227 @@ -697,7 +670,7 @@
34.228 return null;
34.229 }
34.230
34.231 - public static Set<OffsetRange> getAllOffsets(CompilationInfo info, AstPath path, int lexOffset, String name, boolean abortOnFree) {
34.232 + public static Set<OffsetRange> getAllOffsets(PythonParserResult info, AstPath path, int lexOffset, String name, boolean abortOnFree) {
34.233 if (path == null) {
34.234 path = AstPath.get(PythonAstUtils.getRoot(info), lexOffset);
34.235 }
34.236 @@ -708,7 +681,7 @@
34.237 return null;
34.238 }
34.239 Set<OffsetRange> offsets = new HashSet<OffsetRange>();
34.240 - Document doc = info.getDocument();
34.241 + Document doc = GsfUtilities.getDocument(info.getSnapshot().getSource().getFileObject(), false);
34.242 if (doc == null) {
34.243 return Collections.emptySet();
34.244 }
34.245 @@ -787,7 +760,7 @@
34.246 }
34.247 }
34.248
34.249 - public static Set<OffsetRange> getLocalVarOffsets(CompilationInfo info, int lexOffset) {
34.250 + public static Set<OffsetRange> getLocalVarOffsets(PythonParserResult info, int lexOffset) {
34.251 int astOffset = getAstOffset(info, lexOffset);
34.252 if (astOffset != -1) {
34.253 PythonTree root = getRoot(info);
34.254 @@ -806,7 +779,7 @@
34.255 return Collections.emptySet();
34.256 }
34.257
34.258 - public static Set<OffsetRange> getLocalVarOffsets(CompilationInfo info, PythonTree scope, String name) {
34.259 + public static Set<OffsetRange> getLocalVarOffsets(PythonParserResult info, PythonTree scope, String name) {
34.260 LocalVarVisitor visitor = new LocalVarVisitor(info, name, false, true);
34.261 try {
34.262 visitor.visit(scope);
34.263 @@ -817,7 +790,7 @@
34.264 }
34.265 }
34.266
34.267 - public static List<Name> getLocalVarNodes(CompilationInfo info, PythonTree scope, String name) {
34.268 + public static List<Name> getLocalVarNodes(PythonParserResult info, PythonTree scope, String name) {
34.269 LocalVarVisitor visitor = new LocalVarVisitor(info, name, true, false);
34.270 try {
34.271 visitor.visit(scope);
34.272 @@ -828,7 +801,7 @@
34.273 }
34.274 }
34.275
34.276 - public static List<Name> getLocalVarAssignNodes(CompilationInfo info, PythonTree scope, String name) {
34.277 + public static List<Name> getLocalVarAssignNodes(PythonParserResult info, PythonTree scope, String name) {
34.278 LocalVarAssignVisitor visitor = new LocalVarAssignVisitor(info, name, true, false);
34.279 try {
34.280 visitor.visit(scope);
34.281 @@ -843,12 +816,12 @@
34.282 private List<Name> vars = new ArrayList<Name>();
34.283 private Set<OffsetRange> offsets = new HashSet<OffsetRange>();
34.284 private String name;
34.285 - private CompilationInfo info;
34.286 + private PythonParserResult info;
34.287 private boolean collectNames;
34.288 private boolean collectOffsets;
34.289 private PythonTree parent;
34.290
34.291 - private LocalVarVisitor(CompilationInfo info, String name, boolean collectNames, boolean collectOffsets) {
34.292 + private LocalVarVisitor(PythonParserResult info, String name, boolean collectNames, boolean collectOffsets) {
34.293 this.info = info;
34.294 this.name = name;
34.295 this.collectNames = collectNames;
34.296 @@ -899,12 +872,12 @@
34.297 private List<Name> vars = new ArrayList<Name>();
34.298 private Set<OffsetRange> offsets = new HashSet<OffsetRange>();
34.299 private String name;
34.300 - private CompilationInfo info;
34.301 + private PythonParserResult info;
34.302 private boolean collectNames;
34.303 private boolean collectOffsets;
34.304 private PythonTree parent;
34.305
34.306 - private LocalVarAssignVisitor(CompilationInfo info, String name, boolean collectNames, boolean collectOffsets) {
34.307 + private LocalVarAssignVisitor(PythonParserResult info, String name, boolean collectNames, boolean collectOffsets) {
34.308 this.info = info;
34.309 this.name = name;
34.310 this.collectNames = collectNames;
35.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
35.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonBracesMatcherFactory.java Sat Feb 28 17:25:32 2015 -0800
35.3 @@ -0,0 +1,52 @@
35.4 +/*
35.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
35.6 + *
35.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
35.8 + *
35.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
35.10 + * Other names may be trademarks of their respective owners.
35.11 + *
35.12 + * The contents of this file are subject to the terms of either the GNU
35.13 + * General Public License Version 2 only ("GPL") or the Common
35.14 + * Development and Distribution License("CDDL") (collectively, the
35.15 + * "License"). You may not use this file except in compliance with the
35.16 + * License. You can obtain a copy of the License at
35.17 + * http://www.netbeans.org/cddl-gplv2.html
35.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
35.19 + * specific language governing permissions and limitations under the
35.20 + * License. When distributing the software, include this License Header
35.21 + * Notice in each file and include the License file at
35.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
35.23 + * particular file as subject to the "Classpath" exception as provided
35.24 + * by Oracle in the GPL Version 2 section of the License file that
35.25 + * accompanied this code. If applicable, add the following below the
35.26 + * License Header, with the fields enclosed by brackets [] replaced by
35.27 + * your own identifying information:
35.28 + * "Portions Copyrighted [year] [name of copyright owner]"
35.29 + *
35.30 + * Contributor(s):
35.31 + *
35.32 + * Portions Copyrighted 2007 Sun Microsystems, Inc.
35.33 + */
35.34 +package org.netbeans.modules.python.editor;
35.35 +
35.36 +import org.netbeans.api.editor.mimelookup.MimeRegistration;
35.37 +import org.netbeans.modules.python.api.PythonMIMEResolver;
35.38 +import org.netbeans.spi.editor.bracesmatching.BracesMatcher;
35.39 +import org.netbeans.spi.editor.bracesmatching.BracesMatcherFactory;
35.40 +import org.netbeans.spi.editor.bracesmatching.MatcherContext;
35.41 +import org.netbeans.spi.editor.bracesmatching.support.BracesMatcherSupport;
35.42 +
35.43 +/**
35.44 + *
35.45 + * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
35.46 + */
35.47 +@MimeRegistration(mimeType = PythonMIMEResolver.PYTHON_MIME_TYPE, service = BracesMatcherFactory.class)
35.48 +public class PythonBracesMatcherFactory implements BracesMatcherFactory {
35.49 +
35.50 + @Override
35.51 + public BracesMatcher createMatcher(MatcherContext mc) {
35.52 + return BracesMatcherSupport.defaultMatcher(mc, -1, -1);
35.53 + }
35.54 +
35.55 +}
36.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonCodeCompleter.java Sun Jan 04 13:11:53 2015 -0600
36.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonCodeCompleter.java Sat Feb 28 17:25:32 2015 -0800
36.3 @@ -45,7 +45,6 @@
36.4 import javax.swing.text.JTextComponent;
36.5 import org.netbeans.api.editor.EditorRegistry;
36.6 import org.netbeans.api.editor.completion.Completion;
36.7 -import org.netbeans.modules.gsf.api.Index;
36.8 import org.netbeans.modules.python.editor.elements.Element;
36.9 import org.netbeans.modules.python.editor.elements.IndexedElement;
36.10 import org.netbeans.modules.python.editor.elements.IndexedMethod;
36.11 @@ -58,23 +57,23 @@
36.12 import org.netbeans.api.lexer.TokenSequence;
36.13 import org.netbeans.editor.BaseDocument;
36.14 import org.netbeans.editor.Utilities;
36.15 +import org.netbeans.modules.csl.api.CodeCompletionContext;
36.16 +import org.netbeans.modules.csl.api.CodeCompletionHandler;
36.17 +import org.netbeans.modules.csl.api.CodeCompletionResult;
36.18 +import org.netbeans.modules.csl.api.CompletionProposal;
36.19 +import org.netbeans.modules.csl.api.ElementHandle;
36.20 +import org.netbeans.modules.csl.api.ElementKind;
36.21 +import org.netbeans.modules.csl.api.HtmlFormatter;
36.22 +import org.netbeans.modules.csl.api.Modifier;
36.23 +import org.netbeans.modules.csl.api.OffsetRange;
36.24 +import org.netbeans.modules.csl.api.ParameterInfo;
36.25 +import org.netbeans.modules.csl.spi.DefaultCompletionProposal;
36.26 +import org.netbeans.modules.csl.spi.DefaultCompletionResult;
36.27 +import org.netbeans.modules.csl.spi.GsfUtilities;
36.28 +import org.netbeans.modules.csl.spi.ParserResult;
36.29 import org.netbeans.modules.editor.indent.api.IndentUtils;
36.30 -import org.netbeans.modules.gsf.api.CodeCompletionContext;
36.31 -import org.netbeans.modules.gsf.api.CodeCompletionHandler;
36.32 -import org.netbeans.modules.gsf.api.CodeCompletionResult;
36.33 -import org.netbeans.modules.gsf.api.CompilationInfo;
36.34 -import org.netbeans.modules.gsf.api.CompletionProposal;
36.35 -import org.netbeans.modules.gsf.api.ElementHandle;
36.36 -import org.netbeans.modules.gsf.api.ElementKind;
36.37 -import org.netbeans.modules.gsf.api.HtmlFormatter;
36.38 -import org.netbeans.modules.gsf.api.Modifier;
36.39 -import org.netbeans.modules.gsf.api.NameKind;
36.40 -import org.netbeans.modules.gsf.api.OffsetRange;
36.41 -import org.netbeans.modules.gsf.api.ParameterInfo;
36.42 -import org.netbeans.modules.gsf.api.SourceModelFactory;
36.43 -import org.netbeans.modules.gsf.spi.DefaultCompletionProposal;
36.44 -import org.netbeans.modules.gsf.spi.DefaultCompletionResult;
36.45 -import org.netbeans.modules.gsf.spi.GsfUtilities;
36.46 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
36.47 +import org.netbeans.modules.python.api.PythonMIMEResolver;
36.48 import org.netbeans.modules.python.editor.PythonParser.Sanitize;
36.49 import org.netbeans.modules.python.editor.elements.IndexedPackage;
36.50 import org.netbeans.modules.python.editor.imports.ImportManager;
36.51 @@ -83,7 +82,6 @@
36.52 import org.netbeans.modules.python.editor.options.CodeStyle;
36.53 import org.netbeans.modules.python.editor.scopes.SymbolTable;
36.54 import org.openide.filesystems.FileObject;
36.55 -import org.openide.filesystems.FileStateInvalidException;
36.56 import org.openide.util.Exceptions;
36.57 import org.openide.util.ImageUtilities;
36.58 import org.openide.util.NbBundle;
36.59 @@ -130,23 +128,13 @@
36.60 "\\xhh", "Character with hex value hh",};
36.61
36.62 public CodeCompletionResult complete(CodeCompletionContext context) {
36.63 - CompilationInfo info = context.getInfo();
36.64 + ParserResult result = context.getParserResult();
36.65 int lexOffset = context.getCaretOffset();
36.66 String prefix = context.getPrefix();
36.67 - NameKind kind = context.getNameKind();
36.68 QueryType queryType = context.getQueryType();
36.69 this.caseSensitive = context.isCaseSensitive();
36.70
36.71 - // Temporary: case insensitive matches don't work very well for JavaScript
36.72 - if (kind == NameKind.CASE_INSENSITIVE_PREFIX) {
36.73 - kind = NameKind.PREFIX;
36.74 - }
36.75 -
36.76 - if (prefix == null) {
36.77 - prefix = "";
36.78 - }
36.79 -
36.80 - final Document document = info.getDocument();
36.81 + final Document document = result.getSnapshot().getSource().getDocument(false);
36.82 if (document == null) {
36.83 return CodeCompletionResult.NONE;
36.84 }
36.85 @@ -155,16 +143,16 @@
36.86 List<CompletionProposal> proposals = new ArrayList<CompletionProposal>();
36.87 DefaultCompletionResult completionResult = new PythonCompletionResult(context, proposals);
36.88
36.89 - PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
36.90 + PythonParserResult parseResult = PythonAstUtils.getParseResult(result);
36.91 doc.readLock(); // Read-lock due to Token hierarchy use
36.92 try {
36.93 PythonTree root = parseResult != null ? parseResult.getRoot() : null;
36.94 - final int astOffset = PythonAstUtils.getAstOffset(info, lexOffset);
36.95 + final int astOffset = PythonAstUtils.getAstOffset(result, lexOffset);
36.96 if (astOffset == -1) {
36.97 return CodeCompletionResult.NONE;
36.98 }
36.99 final TokenHierarchy<Document> th = TokenHierarchy.get(document);
36.100 - final FileObject fileObject = info.getFileObject();
36.101 + final FileObject fileObject = result.getSnapshot().getSource().getFileObject();
36.102 //Call call = Call.getCallType(doc, th, lexOffset);
36.103
36.104 // Carry completion context around since this logic is split across lots of methods
36.105 @@ -175,22 +163,19 @@
36.106 request.result = parseResult;
36.107 request.lexOffset = lexOffset;
36.108 request.astOffset = astOffset;
36.109 - request.index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
36.110 + request.index = PythonIndex.get(fileObject);
36.111 request.doc = doc;
36.112 - request.info = info;
36.113 + if(prefix == null) {
36.114 + prefix = "";
36.115 + }
36.116 request.prefix = prefix;
36.117 request.th = th;
36.118 - request.kind = kind;
36.119 + request.kind = context.isPrefixMatch()?QuerySupport.Kind.PREFIX:QuerySupport.Kind.EXACT;
36.120 request.queryType = queryType;
36.121 request.fileObject = fileObject;
36.122 - request.anchor = lexOffset - prefix.length();
36.123 + request.anchor = lexOffset - request.prefix.length();
36.124 //request.call = call;
36.125 -
36.126 - try {
36.127 - request.searchUrl = request.fileObject.getURL().toExternalForm();
36.128 - } catch (FileStateInvalidException ex) {
36.129 - Exceptions.printStackTrace(ex);
36.130 - }
36.131 + request.searchUrl = request.fileObject.toURL().toExternalForm();
36.132 if (request.searchUrl == null) {
36.133 request.searchUrl = "";
36.134 }
36.135 @@ -284,7 +269,7 @@
36.136 // function, so I have to account for that.
36.137 FunctionDef def = (FunctionDef)path.leaf();
36.138 OffsetRange astRange = PythonAstUtils.getRange(def);
36.139 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(info, astRange);
36.140 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(parseResult, astRange);
36.141 if (lexRange != OffsetRange.NONE) {
36.142 OffsetRange narrowed = PythonLexerUtils.narrow(doc, lexRange, true);
36.143 if (!narrowed.containsInclusive(lexOffset)) {
36.144 @@ -360,7 +345,7 @@
36.145 return completionResult;
36.146 }
36.147
36.148 - public String document(CompilationInfo info, ElementHandle element) {
36.149 + public String document(ParserResult info, ElementHandle element) {
36.150 if (element instanceof CommentElement) {
36.151 // Text is packaged as the name
36.152 String rst = element.getName();
36.153 @@ -405,75 +390,72 @@
36.154 if (last != null) {
36.155 FileObject fo = GsfUtilities.findFileObject(last);
36.156 if (fo != null) {
36.157 - Index gsfIndex = SourceModelFactory.getInstance().getIndex(fo, PythonTokenId.PYTHON_MIME_TYPE);
36.158 - if (gsfIndex != null) {
36.159 - PythonIndex index = PythonIndex.get(gsfIndex, fo);
36.160 - boolean isMember = link.startsWith("meth:") || link.startsWith("attr:");
36.161 - if (isMember || link.startsWith("func:") || link.startsWith("data:")) { // NOI18N
36.162 - String name = link.substring(link.indexOf(':') + 1);
36.163 - int paren = name.indexOf('(');
36.164 - if (paren != -1) {
36.165 - name = name.substring(0, paren);
36.166 + PythonIndex index = PythonIndex.get(fo);
36.167 + boolean isMember = link.startsWith("meth:") || link.startsWith("attr:");
36.168 + if (isMember || link.startsWith("func:") || link.startsWith("data:")) { // NOI18N
36.169 + String name = link.substring(link.indexOf(':') + 1);
36.170 + int paren = name.indexOf('(');
36.171 + if (paren != -1) {
36.172 + name = name.substring(0, paren);
36.173 + }
36.174 + int dot = name.indexOf('.');
36.175 + String cls = null;
36.176 + if (dot != -1) {
36.177 + cls = name.substring(0, dot);
36.178 + name = name.substring(dot + 1);
36.179 + }
36.180 + Set<IndexedElement> elements;
36.181 + if (isMember) {
36.182 + elements = index.getAllMembers(name, QuerySupport.Kind.EXACT, null, false);
36.183 + } else {
36.184 + elements = index.getAllElements(name, QuerySupport.Kind.EXACT, null, false);
36.185 + }
36.186 + if (elements.size() == 0) {
36.187 + if (isMember) {
36.188 + elements = index.getAllElements(name, QuerySupport.Kind.EXACT, null, false);
36.189 + } else {
36.190 + elements = index.getAllMembers(name, QuerySupport.Kind.EXACT, null, false);
36.191 }
36.192 - int dot = name.indexOf('.');
36.193 - String cls = null;
36.194 - if (dot != -1) {
36.195 - cls = name.substring(0, dot);
36.196 - name = name.substring(dot + 1);
36.197 - }
36.198 - Set<IndexedElement> elements;
36.199 - if (isMember) {
36.200 - elements = index.getAllMembers(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, null, false);
36.201 - } else {
36.202 - elements = index.getAllElements(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, null, false);
36.203 - }
36.204 - if (elements.size() == 0) {
36.205 - if (isMember) {
36.206 - elements = index.getAllElements(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, null, false);
36.207 - } else {
36.208 - elements = index.getAllMembers(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, null, false);
36.209 + }
36.210 + if (elements.size() > 0) {
36.211 + if (cls != null && cls.length() > 0) {
36.212 + for (IndexedElement element : elements) {
36.213 + if (element.getIn() != null && element.getIn().equals(cls)) {
36.214 + return element;
36.215 + }
36.216 }
36.217 }
36.218 - if (elements.size() > 0) {
36.219 - if (cls != null && cls.length() > 0) {
36.220 - for (IndexedElement element : elements) {
36.221 - if (element.getIn() != null && element.getIn().equals(cls)) {
36.222 - return element;
36.223 - }
36.224 + // Pick the same one as the original element, if any
36.225 + if (originalHandle instanceof IndexedElement) {
36.226 + String oldUrl = ((IndexedElement)originalHandle).getFilenameUrl();
36.227 + for (IndexedElement element : elements) {
36.228 + if (oldUrl.equals(element.getFilenameUrl())) {
36.229 + return element;
36.230 }
36.231 }
36.232 - // Pick the same one as the original element, if any
36.233 - if (originalHandle instanceof IndexedElement) {
36.234 - String oldUrl = ((IndexedElement)originalHandle).getFilenameUrl();
36.235 - for (IndexedElement element : elements) {
36.236 - if (oldUrl.equals(element.getFilenameUrl())) {
36.237 - return element;
36.238 - }
36.239 + }
36.240 + return elements.iterator().next();
36.241 + }
36.242 + } else if (link.startsWith("class:") || link.startsWith("exc:")) { // NOI18N
36.243 + String name = link.substring(link.indexOf(':') + 1);
36.244 + int paren = name.indexOf('(');
36.245 + if (paren != -1) {
36.246 + name = name.substring(0, paren);
36.247 + }
36.248 + Set<IndexedElement> classes = index.getClasses(name, QuerySupport.Kind.EXACT, null, false);
36.249 + if (classes.size() > 0) {
36.250 + // Pick the same one as the original element, if any
36.251 + if (originalHandle instanceof IndexedElement) {
36.252 + String oldUrl = ((IndexedElement)originalHandle).getFilenameUrl();
36.253 + for (IndexedElement cls : classes) {
36.254 + if (oldUrl.equals(cls.getFilenameUrl())) {
36.255 + return cls;
36.256 }
36.257 }
36.258 - return elements.iterator().next();
36.259 }
36.260 - } else if (link.startsWith("class:") || link.startsWith("exc:")) { // NOI18N
36.261 - String name = link.substring(link.indexOf(':') + 1);
36.262 - int paren = name.indexOf('(');
36.263 - if (paren != -1) {
36.264 - name = name.substring(0, paren);
36.265 - }
36.266 - Set<IndexedElement> classes = index.getClasses(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, null, false);
36.267 - if (classes.size() > 0) {
36.268 - // Pick the same one as the original element, if any
36.269 - if (originalHandle instanceof IndexedElement) {
36.270 - String oldUrl = ((IndexedElement)originalHandle).getFilenameUrl();
36.271 - for (IndexedElement cls : classes) {
36.272 - if (oldUrl.equals(cls.getFilenameUrl())) {
36.273 - return cls;
36.274 - }
36.275 - }
36.276 - }
36.277 - return classes.iterator().next();
36.278 - }
36.279 - } // TODO: Attributes
36.280 - }
36.281 + return classes.iterator().next();
36.282 + }
36.283 + } // TODO: Attributes
36.284 }
36.285 }
36.286
36.287 @@ -481,9 +463,9 @@
36.288 }
36.289
36.290 @SuppressWarnings("unchecked")
36.291 - public String getPrefix(CompilationInfo info, int lexOffset, boolean upToOffset) {
36.292 + public String getPrefix(ParserResult info, int lexOffset, boolean upToOffset) {
36.293 try {
36.294 - BaseDocument doc = (BaseDocument)info.getDocument();
36.295 + BaseDocument doc = (BaseDocument)info.getSnapshot().getSource().getDocument(false);
36.296 if (doc == null) {
36.297 return null;
36.298 }
36.299 @@ -585,7 +567,7 @@
36.300 return QueryType.NONE;
36.301 }
36.302
36.303 - public String resolveTemplateVariable(String variable, CompilationInfo info, int caretOffset, String name, Map parameters) {
36.304 + public String resolveTemplateVariable(String variable, ParserResult info, int caretOffset, String name, Map parameters) {
36.305 PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
36.306 if (parseResult != null) {
36.307 // HACK: The caret offset we're passed in is bogus. It -isn't- the code template
36.308 @@ -604,7 +586,7 @@
36.309 }
36.310
36.311 if ("initialindent".equals(variable)) { // NOI18N
36.312 - Document doc = info.getDocument();
36.313 + Document doc = info.getSnapshot().getSource().getDocument(false);
36.314 try {
36.315 int lineStart = IndentUtils.lineStartOffset(doc, Math.min(caretOffset, doc.getLength()));
36.316 int initial = IndentUtils.lineIndent(doc, lineStart);
36.317 @@ -614,23 +596,25 @@
36.318 return null;
36.319 }
36.320 } else if ("indent".equals(variable)) { // NOI18N
36.321 - Document doc = info.getDocument();
36.322 + Document doc = info.getSnapshot().getSource().getDocument(false);
36.323 return IndentUtils.createIndentString(doc, IndentUtils.indentLevelSize(doc));
36.324 }
36.325 return null;
36.326 }
36.327
36.328 - public Set<String> getApplicableTemplates(CompilationInfo info, int selectionBegin, int selectionEnd) {
36.329 + @Override
36.330 + public Set<String> getApplicableTemplates(Document info, int selectionBegin, int selectionEnd) {
36.331 return Collections.emptySet();
36.332 }
36.333
36.334 - public ParameterInfo parameters(CompilationInfo info, int lexOffset,
36.335 + @Override
36.336 + public ParameterInfo parameters(ParserResult info, int lexOffset,
36.337 CompletionProposal proposal) {
36.338 IndexedMethod[] methodHolder = new IndexedMethod[1];
36.339 int[] paramIndexHolder = new int[1];
36.340 int[] anchorOffsetHolder = new int[1];
36.341 int astOffset = PythonAstUtils.getAstOffset(info, lexOffset);
36.342 - if (!computeMethodCall(info, lexOffset, astOffset,
36.343 + if (!computeMethodCall((PythonParserResult) info, lexOffset, astOffset,
36.344 methodHolder, paramIndexHolder, anchorOffsetHolder, null)) {
36.345
36.346 return ParameterInfo.NONE;
36.347 @@ -642,7 +626,7 @@
36.348 }
36.349 int index = paramIndexHolder[0];
36.350 int astAnchorOffset = anchorOffsetHolder[0];
36.351 - int anchorOffset = PythonLexerUtils.getLexerOffset(info, astAnchorOffset);
36.352 + int anchorOffset = PythonLexerUtils.getLexerOffset((PythonParserResult) info, astAnchorOffset);
36.353
36.354 // TODO: Make sure the caret offset is inside the arguments portion
36.355 // (parameter hints shouldn't work on the method call name itself
36.356 @@ -676,8 +660,7 @@
36.357 PythonIndex index = request.index;
36.358 String className = classDef.getInternalName();
36.359 String prefix = request.prefix;
36.360 - NameKind kind = request.kind;
36.361 - Set<IndexedElement> methods = index.getInheritedElements(className, prefix, kind);
36.362 + Set<IndexedElement> methods = index.getInheritedElements(className, prefix, request.kind);
36.363
36.364 String searchUrl = request.searchUrl;
36.365 for (IndexedElement element : methods) {
36.366 @@ -821,7 +804,7 @@
36.367
36.368 // User defined and library classes
36.369 PythonIndex index = request.index;
36.370 - Set<IndexedElement> elements = index.getClasses(prefix, request.kind, PythonIndex.ALL_SCOPE, request.result, false);
36.371 + Set<IndexedElement> elements = index.getClasses(prefix, request.kind, request.result, false);
36.372 for (IndexedElement element : elements) {
36.373 if (element.isNoDoc()) {
36.374 continue;
36.375 @@ -857,7 +840,7 @@
36.376
36.377 String prefix = request.prefix;
36.378 int lexOffset = request.lexOffset;
36.379 - NameKind kind = request.kind;
36.380 + QuerySupport.Kind kind = request.kind;
36.381
36.382 TokenSequence<? extends PythonTokenId> ts = PythonLexerUtils.getPositionedSequence(request.doc, lexOffset);
36.383 if (ts == null) {
36.384 @@ -907,7 +890,7 @@
36.385 } else {
36.386 prefix = library;
36.387 }
36.388 - if (kind == NameKind.PREFIX || kind == NameKind.CASE_INSENSITIVE_PREFIX) {
36.389 + if (kind == QuerySupport.Kind.PREFIX || kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX) {
36.390 anchor = libraryStart;
36.391 int length = lexOffset - libraryStart;
36.392 if (length >= 0 && length < prefix.length()) {
36.393 @@ -989,7 +972,7 @@
36.394 }
36.395 }
36.396 Set<IndexedElement> symbols = index.getImportedElements(prefix, request.kind,
36.397 - PythonIndex.ALL_SCOPE, Collections.<String>singleton(library), null);
36.398 + Collections.<String>singleton(library), null);
36.399 for (IndexedElement symbol : symbols) {
36.400 if (!symbol.isPublic()) {
36.401 continue;
36.402 @@ -1046,7 +1029,7 @@
36.403
36.404 return true;
36.405 } else if (id == PythonTokenId.RAISE || id == PythonTokenId.EXCEPT) {
36.406 - Set<IndexedElement> classes = index.getExceptions(prefix, kind, PythonIndex.ALL_SCOPE);
36.407 + Set<IndexedElement> classes = index.getExceptions(prefix, kind);
36.408 for (IndexedElement clz : classes) {
36.409 if (clz.isNoDoc()) {
36.410 continue;
36.411 @@ -1094,9 +1077,9 @@
36.412 }
36.413
36.414 private boolean completeLocal(List<CompletionProposal> proposals, CompletionRequest request) {
36.415 - CompilationInfo info = request.info;
36.416 + PythonParserResult info = request.result;
36.417 String prefix = request.prefix;
36.418 - NameKind kind = request.kind;
36.419 + QuerySupport.Kind kind = request.kind;
36.420 org.netbeans.modules.python.editor.lexer.Call call = request.call;
36.421
36.422 // Only call local and inherited methods if we don't have an LHS, such as Foo::
36.423 @@ -1205,7 +1188,7 @@
36.424 TokenHierarchy<Document> th = request.th;
36.425 BaseDocument doc = request.doc;
36.426 AstPath path = request.path;
36.427 - NameKind kind = request.kind;
36.428 + QuerySupport.Kind kind = request.kind;
36.429 FileObject fileObject = request.fileObject;
36.430 PythonTree node = request.node;
36.431
36.432 @@ -1242,7 +1225,7 @@
36.433 if (method != null) {
36.434 // TODO - if the lhs is "foo.bar." I need to split this
36.435 // up and do it a bit more cleverly
36.436 - PythonTypeAnalyzer analyzer = new PythonTypeAnalyzer(request.info, index, method, node, astOffset, lexOffset, fileObject);
36.437 + PythonTypeAnalyzer analyzer = new PythonTypeAnalyzer(request.result, index, method, node, astOffset, lexOffset, fileObject);
36.438 type = analyzer.getType(lhs);
36.439
36.440 if (type == null) {
36.441 @@ -1384,10 +1367,10 @@
36.442 moduleName = lhs;
36.443 }
36.444 if (moduleCompletion) {
36.445 - Set<IndexedElement> modules = index.getModules(moduleName, NameKind.EXACT_NAME);
36.446 + Set<IndexedElement> modules = index.getModules(moduleName, QuerySupport.Kind.EXACT);
36.447 if (modules.size() > 0) {
36.448 Set<IndexedElement> symbols = index.getImportedElements(prefix, request.kind,
36.449 - PythonIndex.ALL_SCOPE, Collections.<String>singleton(moduleName), null);
36.450 + Collections.<String>singleton(moduleName), null);
36.451 if (symbols.size() > 0) {
36.452 if (elements != null && elements.size() > 0) {
36.453 symbols.addAll(elements);
36.454 @@ -1426,7 +1409,7 @@
36.455 // Try just the method call (e.g. across all classes). This is ignoring the
36.456 // left hand side because we can't resolve it.
36.457 if ((elements.isEmpty())) {
36.458 - elements = index.getAllMembers(prefix, kind, PythonIndex.ALL_SCOPE, request.result, false);
36.459 + elements = index.getAllMembers(prefix, kind, request.result, false);
36.460
36.461 if (addSpecifyTypeItem) {
36.462 // Add a special code completion item to TELL us the type
36.463 @@ -1460,10 +1443,10 @@
36.464 private boolean completeClasses(List<CompletionProposal> proposals, CompletionRequest request) {
36.465 PythonIndex index = request.index;
36.466 String prefix = request.prefix;
36.467 - NameKind kind = request.kind;
36.468 + QuerySupport.Kind kind = request.kind;
36.469 String searchUrl = request.searchUrl;
36.470
36.471 - Set<IndexedElement> classes = index.getClasses(prefix, kind, PythonIndex.ALL_SCOPE, request.result, false);
36.472 + Set<IndexedElement> classes = index.getClasses(prefix, kind, request.result, false);
36.473 for (IndexedElement clz : classes) {
36.474 if (clz.isNoDoc()) {
36.475 continue;
36.476 @@ -1484,11 +1467,11 @@
36.477 private boolean completeMethods(List<CompletionProposal> proposals, CompletionRequest request) {
36.478 PythonIndex index = request.index;
36.479 String prefix = request.prefix;
36.480 - NameKind kind = request.kind;
36.481 + QuerySupport.Kind kind = request.kind;
36.482
36.483 - Set<IndexedElement> elements = index.getAllElements(prefix, kind, PythonIndex.ALL_SCOPE, request.result, false);
36.484 + Set<IndexedElement> elements = index.getAllElements(prefix, kind, request.result, false);
36.485 if (request.call.getLhs() != null || elements.size() == 0) {
36.486 - Set<IndexedElement> members = index.getAllMembers(prefix, kind, PythonIndex.ALL_SCOPE, request.result, false);
36.487 + Set<IndexedElement> members = index.getAllMembers(prefix, kind, request.result, false);
36.488 if (members.size() > 0) {
36.489 elements.addAll(members);
36.490 }
36.491 @@ -1514,10 +1497,10 @@
36.492 private boolean completeDecorators(List<CompletionProposal> proposals, CompletionRequest request) throws BadLocationException {
36.493 PythonIndex index = request.index;
36.494 String prefix = request.prefix;
36.495 - NameKind kind = request.kind;
36.496 + QuerySupport.Kind kind = request.kind;
36.497
36.498 boolean found = false;
36.499 - Set<IndexedElement> elements = index.getAllElements(prefix, kind, PythonIndex.ALL_SCOPE, request.result, false);
36.500 + Set<IndexedElement> elements = index.getAllElements(prefix, kind, request.result, false);
36.501 for (IndexedElement element : elements) {
36.502 if (element.isNoDoc()) {
36.503 continue;
36.504 @@ -1598,7 +1581,7 @@
36.505 Set<IndexedMethod>[] alternatesHolder = new Set[1];
36.506 int[] paramIndexHolder = new int[1];
36.507 int[] anchorOffsetHolder = new int[1];
36.508 - CompilationInfo info = request.info;
36.509 + PythonParserResult info = request.result;
36.510 int lexOffset = request.lexOffset;
36.511 int astOffset = request.astOffset;
36.512
36.513 @@ -1642,7 +1625,7 @@
36.514 * The argument index is returned in parameterIndexHolder[0] and the method being
36.515 * called in methodHolder[0].
36.516 */
36.517 - static boolean computeMethodCall(CompilationInfo info, int lexOffset, int astOffset,
36.518 + static boolean computeMethodCall(PythonParserResult info, int lexOffset, int astOffset,
36.519 IndexedMethod[] methodHolder, int[] parameterIndexHolder, int[] anchorOffsetHolder,
36.520 Set<IndexedMethod>[] alternativesHolder) {
36.521 try {
36.522 @@ -1662,7 +1645,7 @@
36.523 int originalAstOffset = astOffset;
36.524
36.525 // Adjust offset to the left
36.526 - BaseDocument doc = (BaseDocument)info.getDocument();
36.527 + BaseDocument doc = (BaseDocument) info.getSnapshot().getSource().getDocument(false);
36.528 if (doc == null) {
36.529 return false;
36.530 }
36.531 @@ -1778,7 +1761,7 @@
36.532 callMethod = null;
36.533 return false;
36.534 } else if (targetMethod == null) {
36.535 - targetMethod = new PythonDeclarationFinder().findMethodDeclaration(info, call, path,
36.536 + targetMethod = new PythonDeclarationFinder().findMethodDeclaration((PythonParserResult) info, call, path,
36.537 alternativesHolder);
36.538 if (targetMethod == null) {
36.539 return false;
36.540 @@ -1826,7 +1809,6 @@
36.541 private static class CompletionRequest {
36.542 private DefaultCompletionResult completionResult;
36.543 private TokenHierarchy<Document> th;
36.544 - private CompilationInfo info;
36.545 private AstPath path;
36.546 private PythonTree node;
36.547 private PythonTree root;
36.548 @@ -1836,7 +1818,7 @@
36.549 private BaseDocument doc;
36.550 private String prefix;
36.551 private PythonIndex index;
36.552 - private NameKind kind;
36.553 + private QuerySupport.Kind kind;
36.554 private PythonParserResult result;
36.555 private QueryType queryType;
36.556 private FileObject fileObject;
36.557 @@ -2280,6 +2262,11 @@
36.558 anchor = request.anchor;
36.559 }
36.560
36.561 + @Override
36.562 + public OffsetRange getOffsetRange(ParserResult pr) {
36.563 + return null;
36.564 + }
36.565 +
36.566 void setHandle(ElementHandle handle) {
36.567 this.handle = handle;
36.568 }
36.569 @@ -2376,7 +2363,7 @@
36.570 }
36.571
36.572 public String getMimeType() {
36.573 - return PythonTokenId.PYTHON_MIME_TYPE;
36.574 + return PythonMIMEResolver.PYTHON_MIME_TYPE;
36.575 }
36.576
36.577 public String getIn() {
36.578 @@ -2407,6 +2394,11 @@
36.579 this.lexOffset = lexOffset;
36.580 }
36.581
36.582 + @Override
36.583 + public OffsetRange getOffsetRange(ParserResult pr) {
36.584 + return null;
36.585 + }
36.586 +
36.587 public String getVariableName() {
36.588 return call.getLhs();
36.589 }
36.590 @@ -2471,7 +2463,7 @@
36.591 }
36.592
36.593 public String getMimeType() {
36.594 - return PythonTokenId.PYTHON_MIME_TYPE;
36.595 + return PythonMIMEResolver.PYTHON_MIME_TYPE;
36.596 }
36.597
36.598 public String getIn() {
36.599 @@ -2581,19 +2573,19 @@
36.600 boolean packageImport = !cs.preferSymbolImports();
36.601 // TODO - if you're already applying this import on a LHS for an imported
36.602 // symbol, handle that
36.603 - new ImportManager(context.getInfo()).ensureImported(module, symbol, packageImport, false, false);
36.604 + new ImportManager((PythonParserResult) context.getParserResult()).ensureImported(module, symbol, packageImport, false, false);
36.605
36.606 } else if (call == null || call.getLhs() == null) {
36.607 if (pythonItem.getElement() instanceof IndexedElement) {
36.608 CodeStyle cs = CodeStyle.getDefault(pythonItem.request.doc);
36.609
36.610 final IndexedElement elem = (IndexedElement)pythonItem.getElement();
36.611 - FileObject requestFile = context.getInfo().getFileObject();
36.612 + FileObject requestFile = context.getParserResult().getSnapshot().getSource().getFileObject();
36.613 FileObject elementFile = elem.getFileObject();
36.614 if (elementFile != requestFile) {
36.615 String module = elem.getModule();
36.616 if (requestFile != null) {
36.617 - String searchModule = PythonUtils.getModuleName(requestFile, null);
36.618 + String searchModule = PythonUtils.getModuleName(requestFile);
36.619 if (searchModule.equals(module)) {
36.620 return;
36.621 }
36.622 @@ -2603,7 +2595,7 @@
36.623 boolean packageImport = !cs.preferSymbolImports();
36.624 // TODO - if you're already applying this import on a LHS for an imported
36.625 // symbol, handle that
36.626 - new ImportManager(context.getInfo()).ensureImported(module, symbol, packageImport, false, false);
36.627 + new ImportManager((PythonParserResult) context.getParserResult()).ensureImported(module, symbol, packageImport, false, false);
36.628 }
36.629 }
36.630 }
37.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonDeclarationFinder.java Sun Jan 04 13:11:53 2015 -0600
37.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonDeclarationFinder.java Sat Feb 28 17:25:32 2015 -0800
37.3 @@ -38,8 +38,6 @@
37.4 import java.util.Set;
37.5 import javax.swing.text.BadLocationException;
37.6 import javax.swing.text.Document;
37.7 -import org.netbeans.modules.gsf.api.Index;
37.8 -import org.netbeans.modules.gsf.api.SourceModelFactory;
37.9 import org.netbeans.modules.python.editor.elements.IndexedElement;
37.10 import org.netbeans.modules.python.editor.elements.IndexedMethod;
37.11 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
37.12 @@ -51,12 +49,14 @@
37.13 import org.netbeans.api.lexer.TokenSequence;
37.14 import org.netbeans.editor.BaseDocument;
37.15 import org.netbeans.editor.Utilities;
37.16 -import org.netbeans.modules.gsf.api.CompilationInfo;
37.17 -import org.netbeans.modules.gsf.api.DeclarationFinder;
37.18 -import org.netbeans.modules.gsf.api.ElementHandle;
37.19 -import org.netbeans.modules.gsf.api.HtmlFormatter;
37.20 -import org.netbeans.modules.gsf.api.NameKind;
37.21 -import org.netbeans.modules.gsf.api.OffsetRange;
37.22 +import org.netbeans.modules.csl.api.DeclarationFinder;
37.23 +import org.netbeans.modules.csl.api.DeclarationFinder.AlternativeLocation;
37.24 +import org.netbeans.modules.csl.api.DeclarationFinder.DeclarationLocation;
37.25 +import org.netbeans.modules.csl.api.ElementHandle;
37.26 +import org.netbeans.modules.csl.api.HtmlFormatter;
37.27 +import org.netbeans.modules.csl.api.OffsetRange;
37.28 +import org.netbeans.modules.csl.spi.ParserResult;
37.29 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
37.30 import org.netbeans.modules.python.editor.lexer.PythonLexer;
37.31 import org.netbeans.modules.python.editor.scopes.SymbolTable;
37.32 import org.netbeans.modules.python.editor.scopes.SymInfo;
37.33 @@ -157,7 +157,7 @@
37.34 return OffsetRange.NONE;
37.35 }
37.36
37.37 - private DeclarationLocation findImport(CompilationInfo info, int lexOffset, BaseDocument doc) {
37.38 + private DeclarationLocation findImport(PythonParserResult info, int lexOffset, BaseDocument doc) {
37.39 TokenSequence<? extends PythonTokenId> ts = PythonLexerUtils.getPositionedSequence(doc, lexOffset);
37.40 if (ts == null) {
37.41 return DeclarationLocation.NONE;
37.42 @@ -253,21 +253,21 @@
37.43 return DeclarationLocation.NONE;
37.44 }
37.45
37.46 - private DeclarationLocation findImport(CompilationInfo info, String moduleName, String symbol) {
37.47 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
37.48 + private DeclarationLocation findImport(PythonParserResult info, String moduleName, String symbol) {
37.49 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
37.50
37.51 Set<IndexedElement> elements = null;
37.52
37.53 if (moduleName != null && symbol != null) {
37.54 - elements = index.getImportedElements(symbol, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, Collections.<String>singleton(moduleName), null);
37.55 + elements = index.getImportedElements(symbol, QuerySupport.Kind.EXACT, Collections.<String>singleton(moduleName), null);
37.56 }
37.57
37.58 if (symbol != null && (elements == null || elements.size() == 0)) {
37.59 - elements = index.getInheritedElements(null, symbol, NameKind.EXACT_NAME);
37.60 + elements = index.getInheritedElements(null, symbol, QuerySupport.Kind.EXACT);
37.61 }
37.62
37.63 if (elements == null || elements.size() == 0) {
37.64 - elements = index.getModules(moduleName, NameKind.EXACT_NAME);
37.65 + elements = index.getModules(moduleName, QuerySupport.Kind.EXACT);
37.66 }
37.67
37.68 if (elements != null && elements.size() > 0) {
37.69 @@ -316,7 +316,7 @@
37.70 }
37.71
37.72 @SuppressWarnings("empty-statement")
37.73 - private DeclarationLocation findUrl(CompilationInfo info, Document doc, int lexOffset) {
37.74 + private DeclarationLocation findUrl(PythonParserResult info, Document doc, int lexOffset) {
37.75 TokenSequence<?> ts = PythonLexerUtils.getPythonSequence((BaseDocument)doc, lexOffset);
37.76
37.77 if (ts == null) {
37.78 @@ -367,9 +367,10 @@
37.79 return DeclarationLocation.NONE;
37.80 }
37.81
37.82 - public DeclarationLocation findDeclaration(CompilationInfo info, int lexOffset) {
37.83 + @Override
37.84 + public DeclarationLocation findDeclaration(ParserResult info, int lexOffset) {
37.85
37.86 - final Document document = info.getDocument();
37.87 + final Document document = info.getSnapshot().getSource().getDocument(false);
37.88 if (document == null) {
37.89 return DeclarationLocation.NONE;
37.90 }
37.91 @@ -393,12 +394,12 @@
37.92 }
37.93
37.94 // See if it's an import
37.95 - DeclarationLocation imp = findImport(info, lexOffset, doc);
37.96 + DeclarationLocation imp = findImport(parseResult, lexOffset, doc);
37.97 if (imp != DeclarationLocation.NONE) {
37.98 return imp;
37.99 }
37.100
37.101 - DeclarationLocation url = findUrl(info, doc, lexOffset);
37.102 + DeclarationLocation url = findUrl(parseResult, doc, lexOffset);
37.103 if (url != DeclarationLocation.NONE) {
37.104 return url;
37.105 }
37.106 @@ -406,6 +407,8 @@
37.107 final TokenHierarchy<Document> th = TokenHierarchy.get(document);
37.108 org.netbeans.modules.python.editor.lexer.Call call =
37.109 org.netbeans.modules.python.editor.lexer.Call.getCallType(doc, th, lexOffset);
37.110 +
37.111 + FileObject fileObject = info.getSnapshot().getSource().getFileObject();
37.112
37.113 // Search for local variables
37.114 if (root != null && call.getLhs() == null) {
37.115 @@ -418,13 +421,13 @@
37.116 SymInfo sym = symbolTable.findDeclaration(scope, name, true);
37.117 if (sym != null) {
37.118 if (sym.isFree()) {
37.119 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
37.120 + PythonIndex index = PythonIndex.get(fileObject);
37.121
37.122 List<Import> imports = symbolTable.getImports();
37.123 List<ImportFrom> importsFrom = symbolTable.getImportsFrom();
37.124 - Set<IndexedElement> elements = index.getImportedElements(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, imports, importsFrom);
37.125 + Set<IndexedElement> elements = index.getImportedElements(name, QuerySupport.Kind.EXACT, parseResult, imports, importsFrom);
37.126 if (elements != null && elements.size() > 0) {
37.127 - return getDeclaration(info, null /*name*/, elements,
37.128 + return getDeclaration(parseResult, null /*name*/, elements,
37.129 path, node, index, astOffset, lexOffset);
37.130 }
37.131 // Must be defined by one of the imported symbols
37.132 @@ -443,7 +446,7 @@
37.133 break;
37.134 } else if (at.getInternalName().equals(name)) {
37.135 // We found our library - just show it
37.136 - return findImport(info, name, null);
37.137 + return findImport(parseResult, name, null);
37.138 }
37.139 }
37.140 }
37.141 @@ -457,7 +460,7 @@
37.142 break;
37.143 } else if (at.getInternalName().equals(name)) {
37.144 // We found our library - just show it
37.145 - return findImport(info, impNode.getInternalModule(), name);
37.146 + return findImport(parseResult, impNode.getInternalModule(), name);
37.147 }
37.148 }
37.149 }
37.150 @@ -465,22 +468,22 @@
37.151 }
37.152
37.153 if (sym.isUnresolved()) {
37.154 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
37.155 + PythonIndex index = PythonIndex.get(fileObject);
37.156
37.157 List<Import> imports = symbolTable.getImports();
37.158 List<ImportFrom> importsFrom = symbolTable.getImportsFrom();
37.159 - Set<IndexedElement> elements = index.getImportedElements(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, imports, importsFrom);
37.160 + Set<IndexedElement> elements = index.getImportedElements(name, QuerySupport.Kind.EXACT, parseResult, imports, importsFrom);
37.161 if (elements != null && elements.size() > 0) {
37.162 - return getDeclaration(info, null /*name*/, elements,
37.163 + return getDeclaration(parseResult, null /*name*/, elements,
37.164 path, node, index, astOffset, lexOffset);
37.165 }
37.166 } else {
37.167 OffsetRange astRange = PythonAstUtils.getNameRange(null, declNode);
37.168 - int lexerOffset = PythonLexerUtils.getLexerOffset(info, astRange.getStart());
37.169 + int lexerOffset = PythonLexerUtils.getLexerOffset(parseResult, astRange.getStart());
37.170 if (lexerOffset == -1) {
37.171 lexerOffset = 0;
37.172 }
37.173 - return new DeclarationLocation(info.getFileObject(), lexerOffset);
37.174 + return new DeclarationLocation(fileObject, lexerOffset);
37.175 }
37.176 }
37.177 }
37.178 @@ -510,11 +513,11 @@
37.179 }
37.180
37.181 if (name != null) {
37.182 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
37.183 + PythonIndex index = PythonIndex.get(fileObject);
37.184 // Add methods in the class (without an FQN)
37.185 - Set<IndexedElement> elements = index.getInheritedElements(type, name, NameKind.EXACT_NAME);
37.186 + Set<IndexedElement> elements = index.getInheritedElements(type, name, QuerySupport.Kind.EXACT);
37.187 if (elements != null && elements.size() > 0) {
37.188 - return getDeclaration(info, null /*name*/, elements,
37.189 + return getDeclaration(parseResult, null /*name*/, elements,
37.190 path, node, index, astOffset, lexOffset);
37.191 }
37.192 }
37.193 @@ -530,32 +533,32 @@
37.194 }
37.195 }
37.196 if (prefix != null) {
37.197 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
37.198 + PythonIndex index = PythonIndex.get(fileObject);
37.199
37.200 Set<? extends IndexedElement> elements = null;
37.201 if (prefix.length() > 0 && Character.isUpperCase(prefix.charAt(0))) {
37.202 - elements = index.getClasses(prefix, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, parseResult, true);
37.203 + elements = index.getClasses(prefix, QuerySupport.Kind.EXACT, parseResult, true);
37.204 }
37.205
37.206 if (elements == null || elements.size() == 0) {
37.207 elements = index.getAllElements(prefix,
37.208 - NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, parseResult, true);
37.209 + QuerySupport.Kind.EXACT, parseResult, true);
37.210 }
37.211
37.212 if (elements == null || elements.size() == 0) {
37.213 elements = index.getAllMembers(prefix,
37.214 - NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, parseResult, true);
37.215 + QuerySupport.Kind.EXACT, parseResult, true);
37.216 }
37.217
37.218 if (elements != null && elements.size() > 0) {
37.219 - return getDeclaration(info, null /*name*/, elements,
37.220 + return getDeclaration(parseResult, null /*name*/, elements,
37.221 path, node, index, astOffset, lexOffset);
37.222 }
37.223
37.224 // TODO - classes
37.225 //WORKING HERE
37.226 // if (elements == null || elements.size() == 0) {
37.227 -// elements = index.getClasses(prefix, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, parseResult, true);
37.228 +// elements = index.getClasses(prefix, QuerySupport.Kind.EXACT, PythonIndex.ALL_SCOPE, parseResult, true);
37.229 // }
37.230 // if (elements != null && elements.size() > 0) {
37.231 // String name = null; // unused!
37.232 @@ -570,9 +573,9 @@
37.233 return DeclarationLocation.NONE;
37.234 }
37.235
37.236 - private DeclarationLocation getDeclaration(CompilationInfo info, String name, Set<? extends IndexedElement> methods,
37.237 + private DeclarationLocation getDeclaration(PythonParserResult info, String name, Set<? extends IndexedElement> methods,
37.238 AstPath path, PythonTree closest, PythonIndex index, int astOffset, int lexOffset) {
37.239 - BaseDocument doc = (BaseDocument)info.getDocument();
37.240 + BaseDocument doc = (BaseDocument)info.getSnapshot().getSource().getDocument(false);
37.241 if (doc == null) {
37.242 return DeclarationLocation.NONE;
37.243 }
37.244 @@ -584,8 +587,8 @@
37.245 return getDeclarationLocation(info, candidate, methods);
37.246 }
37.247
37.248 - private DeclarationLocation getDeclarationLocation(CompilationInfo info, IndexedElement candidate, Set<? extends IndexedElement> methods) {
37.249 - BaseDocument doc = (BaseDocument)info.getDocument();
37.250 + private DeclarationLocation getDeclarationLocation(PythonParserResult info, IndexedElement candidate, Set<? extends IndexedElement> methods) {
37.251 + BaseDocument doc = (BaseDocument)info.getSnapshot().getSource().getDocument(false);
37.252 if (doc == null) {
37.253 return DeclarationLocation.NONE;
37.254 }
37.255 @@ -632,7 +635,7 @@
37.256 return DeclarationLocation.NONE;
37.257 }
37.258
37.259 - private IndexedElement findBestMatch(CompilationInfo info, String name, Set<? extends IndexedElement> methodSet,
37.260 + private IndexedElement findBestMatch(PythonParserResult info, String name, Set<? extends IndexedElement> methodSet,
37.261 BaseDocument doc, int astOffset, int lexOffset, AstPath path, PythonTree call, PythonIndex index) {
37.262 // Make sure that the best fit method actually has a corresponding valid source location
37.263 // and parse tree
37.264 @@ -665,7 +668,7 @@
37.265 return null;
37.266 }
37.267
37.268 - private IndexedElement findBestMatchHelper(CompilationInfo info, String name, Set<IndexedElement> elements,
37.269 + private IndexedElement findBestMatchHelper(PythonParserResult info, String name, Set<IndexedElement> elements,
37.270 BaseDocument doc, int astOffset, int lexOffset, AstPath path, PythonTree callNode, PythonIndex index) {
37.271
37.272 Set<IndexedElement> candidates = new HashSet<IndexedElement>();
37.273 @@ -677,25 +680,21 @@
37.274 }
37.275
37.276 // 1. Prefer matches in the current file
37.277 - try {
37.278 - String searchUrl = info.getFileObject().getURL().toExternalForm();
37.279 - candidates = new HashSet<IndexedElement>();
37.280 + String searchUrl = info.getSnapshot().getSource().getFileObject().toURL().toExternalForm();
37.281 + candidates = new HashSet<IndexedElement>();
37.282
37.283 - for (IndexedElement element : elements) {
37.284 - String url = element.getFilenameUrl();
37.285 + for (IndexedElement element : elements) {
37.286 + String url = element.getFilenameUrl();
37.287
37.288 - if (url.equals(searchUrl)) {
37.289 - candidates.add(element);
37.290 - }
37.291 + if (url.equals(searchUrl)) {
37.292 + candidates.add(element);
37.293 }
37.294 + }
37.295
37.296 - if (candidates.size() == 1) {
37.297 - return candidates.iterator().next();
37.298 - } else if (!candidates.isEmpty()) {
37.299 - elements = candidates;
37.300 - }
37.301 - } catch (FileStateInvalidException ex) {
37.302 - Exceptions.printStackTrace(ex);
37.303 + if (candidates.size() == 1) {
37.304 + return candidates.iterator().next();
37.305 + } else if (!candidates.isEmpty()) {
37.306 + elements = candidates;
37.307 }
37.308
37.309
37.310 @@ -772,7 +771,7 @@
37.311 return elements.iterator().next();
37.312 }
37.313
37.314 - public DeclarationLocation getSuperImplementations(CompilationInfo info, int lexOffset) {
37.315 + public DeclarationLocation getSuperImplementations(PythonParserResult info, int lexOffset) {
37.316 // Figure out if we're on a method, and if so, locate the nearest
37.317 // method it is overriding.
37.318 // Otherwise, if we're on a class (anywhere, not just definition),
37.319 @@ -799,7 +798,7 @@
37.320 }
37.321
37.322 Set<IndexedElement> elements = null;
37.323 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
37.324 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
37.325 if (findClass) {
37.326 elements = index.getSuperClasses(name);
37.327 } else {
37.328 @@ -828,9 +827,9 @@
37.329 return DeclarationLocation.NONE;
37.330 }
37.331
37.332 - public IndexedMethod findMethodDeclaration(CompilationInfo info, org.python.antlr.ast.Call call, AstPath path, Set<IndexedMethod>[] alternativesHolder) {
37.333 + public IndexedMethod findMethodDeclaration(PythonParserResult info, org.python.antlr.ast.Call call, AstPath path, Set<IndexedMethod>[] alternativesHolder) {
37.334 PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
37.335 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
37.336 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
37.337 Set<IndexedElement> functions = null;
37.338
37.339 // TODO - do more accurate lookup of types here!
37.340 @@ -844,9 +843,9 @@
37.341
37.342 if (call.getInternalFunc() instanceof Attribute) {
37.343 // Method/member access
37.344 - functions = index.getAllMembers(callName, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, parseResult, false);
37.345 + functions = index.getAllMembers(callName, QuerySupport.Kind.EXACT, parseResult, false);
37.346 } else {
37.347 - functions = index.getAllElements(callName, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, parseResult, false);
37.348 + functions = index.getAllElements(callName, QuerySupport.Kind.EXACT, parseResult, false);
37.349 }
37.350
37.351 if (functions != null && functions.size() > 0) {
37.352 @@ -860,7 +859,7 @@
37.353 int astOffset = call.getCharStartIndex();
37.354 int lexOffset = PythonLexerUtils.getLexerOffset(info, astOffset);
37.355 IndexedElement candidate =
37.356 - findBestMatch(info, callName, eligible, (BaseDocument)info.getDocument(),
37.357 + findBestMatch(info, callName, eligible, (BaseDocument)info.getSnapshot().getSource().getDocument(false),
37.358 astOffset, lexOffset, path, call, index);
37.359 assert candidate instanceof IndexedMethod; // Filtered into earlier already
37.360 return (IndexedMethod)candidate;
37.361 @@ -882,16 +881,11 @@
37.362 return DeclarationLocation.NONE;
37.363 }
37.364
37.365 - Index gsfIndex = SourceModelFactory.getInstance().getIndex(fileInProject, PythonTokenId.PYTHON_MIME_TYPE);
37.366 - if (gsfIndex == null) {
37.367 - return DeclarationLocation.NONE;
37.368 - }
37.369 -
37.370 String className = testString.substring(0, methodIndex);
37.371 String methodName = testString.substring(methodIndex+1);
37.372
37.373 - PythonIndex index = PythonIndex.get(gsfIndex, fileInProject);
37.374 - Set<IndexedElement> elements = index.getAllMembers(methodName, NameKind.EXACT_NAME, PythonIndex.SOURCE_SCOPE, null, true);
37.375 + PythonIndex index = PythonIndex.get(fileInProject);
37.376 + Set<IndexedElement> elements = index.getAllMembers(methodName, QuerySupport.Kind.EXACT, null, true);
37.377 // Look for one that matches our class name
37.378 if (elements.size() > 0) {
37.379 IndexedElement candidate = null;
38.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonFormatter.java Sun Jan 04 13:11:53 2015 -0600
38.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonFormatter.java Sat Feb 28 17:25:32 2015 -0800
38.3 @@ -58,15 +58,14 @@
38.4 import org.netbeans.api.lexer.TokenUtilities;
38.5 import org.netbeans.editor.BaseDocument;
38.6 import org.netbeans.editor.Utilities;
38.7 +import org.netbeans.modules.csl.api.EditList;
38.8 +import org.netbeans.modules.csl.api.Formatter;
38.9 +import org.netbeans.modules.csl.spi.GsfUtilities;
38.10 +import org.netbeans.modules.csl.spi.ParserResult;
38.11 import org.netbeans.modules.editor.indent.api.IndentUtils;
38.12 import org.netbeans.modules.editor.indent.spi.Context;
38.13 -import org.netbeans.modules.gsf.api.CompilationInfo;
38.14 -import org.netbeans.modules.gsf.api.EditList;
38.15 -import org.netbeans.modules.gsf.api.Formatter;
38.16 -import org.netbeans.modules.gsf.spi.GsfUtilities;
38.17 import org.netbeans.modules.python.editor.imports.ImportManager;
38.18 import org.netbeans.modules.python.editor.options.CodeStyle;
38.19 -import org.netbeans.napi.gsfret.source.SourceUtils;
38.20 import org.openide.util.Exceptions;
38.21
38.22 /**
38.23 @@ -98,7 +97,8 @@
38.24 this.codeStyle = codeStyle;
38.25 }
38.26
38.27 - public void reformat(Context context, CompilationInfo compilationInfo) {
38.28 + @Override
38.29 + public void reformat(Context context, ParserResult compilationInfo) {
38.30
38.31 // No AST pretty printing yet
38.32 // I should offer to go and do space insert/removal around commas, parentheses, etc.
38.33 @@ -107,10 +107,10 @@
38.34 int startOffset = context.startOffset();
38.35 int endOffset = context.endOffset();
38.36
38.37 - reformat(context, document, startOffset, endOffset, compilationInfo);
38.38 + reformat(context, document, startOffset, endOffset, (PythonParserResult) compilationInfo);
38.39 }
38.40
38.41 - public void reformat(final Context context, Document document, int startOffset, int endOffset, CompilationInfo info) {
38.42 + public void reformat(final Context context, Document document, int startOffset, int endOffset, PythonParserResult info) {
38.43 if (codeStyle == null) {
38.44 codeStyle = CodeStyle.getDefault(context.document());
38.45 }
38.46 @@ -127,9 +127,9 @@
38.47 }
38.48
38.49 public boolean needsParserResult() {
38.50 - if (SourceUtils.isScanInProgress()) {
38.51 - return false;
38.52 - }
38.53 +// if (SourceUtils.isScanInProgress()) {
38.54 +// return false;
38.55 +// }
38.56
38.57 // If we're going to format imports, then yes, we need the parser result
38.58 JTextComponent target = EditorRegistry.lastFocusedComponent();
38.59 @@ -425,7 +425,7 @@
38.60 return Utilities.getRowFirstNonWhite(doc, offset) == offset;
38.61 }
38.62
38.63 - private void cleanup(Document document, CompilationInfo info, int startOffset, int endOffset) {
38.64 + private void cleanup(Document document, PythonParserResult info, int startOffset, int endOffset) {
38.65 BaseDocument doc = (BaseDocument)document;
38.66 final EditList edits = new EditList(doc);
38.67 try {
39.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonHintOptions.java Sun Jan 04 13:11:53 2015 -0600
39.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonHintOptions.java Sat Feb 28 17:25:32 2015 -0800
39.3 @@ -30,9 +30,10 @@
39.4 */
39.5 package org.netbeans.modules.python.editor;
39.6
39.7 +import org.netbeans.modules.csl.api.HintsProvider;
39.8 +import org.netbeans.modules.csl.api.HintsProvider.HintsManager;
39.9 +import org.netbeans.modules.python.api.PythonMIMEResolver;
39.10 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
39.11 -import org.netbeans.modules.gsf.api.HintsProvider;
39.12 -import org.netbeans.modules.gsf.api.HintsProvider.HintsManager;
39.13 import org.netbeans.spi.options.AdvancedOption;
39.14 import org.netbeans.spi.options.OptionsPanelController;
39.15 import org.openide.util.NbBundle;
39.16 @@ -43,17 +44,20 @@
39.17 public class PythonHintOptions extends AdvancedOption {
39.18 OptionsPanelController panelController;
39.19
39.20 + @Override
39.21 public String getDisplayName() {
39.22 return NbBundle.getMessage(PythonHintOptions.class, "CTL_Hints_DisplayName"); // NOI18N
39.23 }
39.24
39.25 + @Override
39.26 public String getTooltip() {
39.27 return NbBundle.getMessage(PythonHintOptions.class, "CTL_Hints_ToolTip"); // NOI18N
39.28 }
39.29
39.30 + @Override
39.31 public synchronized OptionsPanelController create() {
39.32 if (panelController == null) {
39.33 - HintsManager manager = HintsProvider.Factory.getManager(PythonTokenId.PYTHON_MIME_TYPE);
39.34 + HintsManager manager = HintsProvider.HintsManager.getManagerForMimeType(PythonMIMEResolver.PYTHON_MIME_TYPE);
39.35 assert manager != null;
39.36 panelController = manager.getOptionsController();
39.37 }
40.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonIndex.java Sun Jan 04 13:11:53 2015 -0600
40.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonIndex.java Sat Feb 28 17:25:32 2015 -0800
40.3 @@ -36,6 +36,7 @@
40.4 import java.net.URL;
40.5 import java.util.ArrayList;
40.6 import java.util.Arrays;
40.7 +import java.util.Collection;
40.8 import java.util.Collections;
40.9 import java.util.EnumSet;
40.10 import java.util.HashMap;
40.11 @@ -44,12 +45,20 @@
40.12 import java.util.List;
40.13 import java.util.Map;
40.14 import java.util.Set;
40.15 +import java.util.WeakHashMap;
40.16 +import java.util.logging.Level;
40.17 +import java.util.logging.Logger;
40.18 +import org.netbeans.api.project.Project;
40.19 +import org.netbeans.modules.csl.api.ElementKind;
40.20 +import org.netbeans.modules.parsing.spi.indexing.PathRecognizer;
40.21 +import org.netbeans.modules.parsing.spi.indexing.support.IndexResult;
40.22 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
40.23 +import static org.netbeans.modules.parsing.spi.indexing.support.QuerySupport.Kind.CAMEL_CASE;
40.24 +import static org.netbeans.modules.parsing.spi.indexing.support.QuerySupport.Kind.CASE_INSENSITIVE_PREFIX;
40.25 +import static org.netbeans.modules.parsing.spi.indexing.support.QuerySupport.Kind.CASE_INSENSITIVE_REGEXP;
40.26 +import static org.netbeans.modules.parsing.spi.indexing.support.QuerySupport.Kind.PREFIX;
40.27 +import static org.netbeans.modules.parsing.spi.indexing.support.QuerySupport.Kind.REGEXP;
40.28 import org.netbeans.modules.python.editor.elements.IndexedElement;
40.29 -import org.netbeans.modules.gsf.api.ElementKind;
40.30 -import org.netbeans.modules.gsf.api.Index;
40.31 -import org.netbeans.modules.gsf.api.Index.SearchResult;
40.32 -import org.netbeans.modules.gsf.api.Index.SearchScope;
40.33 -import org.netbeans.modules.gsf.api.NameKind;
40.34 import org.netbeans.modules.python.api.PythonPlatform;
40.35 import org.netbeans.modules.python.api.PythonPlatformManager;
40.36 import org.netbeans.modules.python.editor.elements.IndexedPackage;
40.37 @@ -59,6 +68,7 @@
40.38 import org.openide.filesystems.URLMapper;
40.39 import org.openide.modules.InstalledFileLocator;
40.40 import org.openide.util.Exceptions;
40.41 +import org.openide.util.Lookup;
40.42 import org.python.antlr.ast.Import;
40.43 import org.python.antlr.ast.ImportFrom;
40.44 import org.python.antlr.ast.alias;
40.45 @@ -69,19 +79,24 @@
40.46 * @author Tor Norbye
40.47 */
40.48 public class PythonIndex {
40.49 - public static final Set<SearchScope> ALL_SCOPE = EnumSet.allOf(SearchScope.class);
40.50 - public static final Set<SearchScope> SOURCE_SCOPE = EnumSet.of(SearchScope.SOURCE);
40.51 +// public static final Set<SearchScope> ALL_SCOPE = EnumSet.allOf(SearchScope.class);
40.52 +// public static final Set<SearchScope> SOURCE_SCOPE = EnumSet.of(SearchScope.SOURCE);
40.53 static final String CLUSTER_URL = "cluster:"; // NOI18N
40.54 static final String PYTHONHOME_URL = "python:"; // NOI18N
40.55 private static final String STUB_MISSING = "stub_missing"; // NOI18N
40.56 - private final Index index;
40.57 - private final FileObject context;
40.58
40.59 // The "functions" module is always imported by the interpreter, and ditto
40.60 // for exceptions, constants, etc.
40.61 public static Set<String> BUILTIN_MODULES = new HashSet<String>();
40.62
40.63
40.64 + private static final Logger LOG = Logger.getLogger(PythonIndex.class.getName());
40.65 + public static final String OBJECT = "object"; // NOI18N
40.66 + static Map<String, Set<String>> wildcardImports = new HashMap<String, Set<String>>();
40.67 + static Set<String> systemModules;
40.68 + // TODO - make weak?
40.69 + static Set<String> availableClasses;
40.70 + private static String clusterUrl = null;
40.71 static {
40.72 //BUILTIN_MODULES.add("objects"); // NOI18N -- just links to the others
40.73 BUILTIN_MODULES.add("stdtypes"); // NOI18N
40.74 @@ -91,25 +106,179 @@
40.75 BUILTIN_MODULES.add("constants"); // NOI18N
40.76 }
40.77
40.78 - /** Creates a new instance of PythonIndex */
40.79 - private PythonIndex(Index index, FileObject context) {
40.80 - this.index = index;
40.81 - this.context = context;
40.82 + public static PythonIndex get(Collection<FileObject> roots) {
40.83 + // XXX no cache - is it needed?
40.84 + LOG.log(Level.FINE, "PythonIndex for roots: {0}", roots); //NOI18N
40.85 + return new PythonIndex(QuerySupportFactory.get(roots), false);
40.86 + }
40.87 +
40.88 + public static PythonIndex get(Project project) {
40.89 + Set<String> sourceIds = new HashSet<String>();
40.90 + Set<String> libraryIds = new HashSet<String>();
40.91 + Collection<? extends PathRecognizer> lookupAll = Lookup.getDefault().lookupAll(PathRecognizer.class);
40.92 + for (PathRecognizer pathRecognizer : lookupAll) {
40.93 + Set<String> source = pathRecognizer.getSourcePathIds();
40.94 + if (source != null) {
40.95 + sourceIds.addAll(source);
40.96 + }
40.97 + Set<String> library = pathRecognizer.getLibraryPathIds();
40.98 + if (library != null) {
40.99 + libraryIds.addAll(library);
40.100 + }
40.101 + }
40.102 +
40.103 + final Collection<FileObject> findRoots = QuerySupport.findRoots(project,
40.104 + sourceIds,
40.105 + libraryIds,
40.106 + Collections.<String>emptySet());
40.107 + return PythonIndex.get(findRoots);
40.108 + }
40.109 +
40.110 + private static final WeakHashMap<FileObject, PythonIndex> INDEX_CACHE = new WeakHashMap<FileObject, PythonIndex>();
40.111 + public static PythonIndex get(FileObject fo) {
40.112 + PythonIndex index = INDEX_CACHE.get(fo);
40.113 + if (index == null) {
40.114 + LOG.log(Level.FINE, "Creating PythonIndex for FileObject: {0}", fo); //NOI18N
40.115 + index = new PythonIndex(QuerySupportFactory.get(fo), true);
40.116 + INDEX_CACHE.put(fo, index);
40.117 + }
40.118 + return index;
40.119 }
40.120
40.121 - public static PythonIndex get(Index index) {
40.122 - return new PythonIndex(index, null);
40.123 + public static boolean isBuiltinModule(String module) {
40.124 + return BUILTIN_MODULES.contains(module) || STUB_MISSING.equals(module);
40.125 }
40.126
40.127 - public static PythonIndex get(Index index, FileObject context) {
40.128 - return new PythonIndex(index, context);
40.129 + // For testing only
40.130 + public static void setClusterUrl(String url) {
40.131 + clusterUrl = url;
40.132 }
40.133
40.134 - private boolean search(String key, String name, NameKind kind, Set<SearchResult> result,
40.135 - Set<SearchScope> scope, Set<String> terms) {
40.136 + static String getPreindexUrl(String url) {
40.137 + // TODO - look up the correct platform to use!
40.138 + final PythonPlatformManager manager = PythonPlatformManager.getInstance();
40.139 + final String platformName = manager.getDefaultPlatform();
40.140 + PythonPlatform platform = manager.getPlatform(platformName);
40.141 + if (platform != null) {
40.142 + String s = platform.getHomeUrl();
40.143 + if (s != null) {
40.144 + if (url.startsWith(s)) {
40.145 + url = PYTHONHOME_URL + url.substring(s.length());
40.146 + return url;
40.147 + }
40.148 + }
40.149 + }
40.150 +
40.151 + String s = getClusterUrl();
40.152 +
40.153 + if (url.startsWith(s)) {
40.154 + return CLUSTER_URL + url.substring(s.length());
40.155 + }
40.156 +
40.157 + if (url.startsWith("jar:file:")) { // NOI18N
40.158 + String sub = url.substring(4);
40.159 + if (sub.startsWith(s)) {
40.160 + return CLUSTER_URL + sub.substring(s.length());
40.161 + }
40.162 + }
40.163 +
40.164 + return url;
40.165 + }
40.166 +
40.167 +/** Get the FileObject corresponding to a URL returned from the index */
40.168 + public static FileObject getFileObject(String url) {
40.169 + return getFileObject(url, null);
40.170 + }
40.171 +
40.172 + public static FileObject getFileObject(String url, FileObject context) {
40.173 try {
40.174 - index.search(key, name, kind, scope, result, terms);
40.175 + if (url.startsWith(PYTHONHOME_URL)) {
40.176 + Iterator<String> it = null;
40.177 +
40.178 + // TODO - look up the right platform for the given project
40.179 + //if (context != null) {
40.180 + // Project project = FileOwnerQuery.getOwner(context);
40.181 + // if (project != null) {
40.182 + // PythonPlatform platform = PythonPlatform.platformFor(project);
40.183 + // if (platform != null) {
40.184 + // it = Collections.singleton(platform).iterator();
40.185 + // }
40.186 + // }
40.187 + //}
40.188 +
40.189 + PythonPlatformManager manager = PythonPlatformManager.getInstance();
40.190 + if (it == null) {
40.191 + it = manager.getPlatformList().iterator();
40.192 + }
40.193 + while (it.hasNext()) {
40.194 + String name = it.next();
40.195 + PythonPlatform platform = manager.getPlatform(name);
40.196 + if (platform != null) {
40.197 + String u = platform.getHomeUrl();
40.198 + if (u != null) {
40.199 + try {
40.200 + u = u + url.substring(PYTHONHOME_URL.length());
40.201 + FileObject fo = URLMapper.findFileObject(new URL(u));
40.202 + if (fo != null) {
40.203 + return fo;
40.204 + }
40.205 + } catch (MalformedURLException mue) {
40.206 + Exceptions.printStackTrace(mue);
40.207 + }
40.208 + }
40.209 + }
40.210 + }
40.211 +
40.212 + return null;
40.213 + } else if (url.startsWith(CLUSTER_URL)) {
40.214 + url = getClusterUrl() + url.substring(CLUSTER_URL.length()); // NOI18N
40.215 + if (url.indexOf(".egg!/") != -1) { // NOI18N
40.216 + url = "jar:" + url; // NOI18N
40.217 + }
40.218 + }
40.219 +
40.220 + return URLMapper.findFileObject(new URL(url));
40.221 + } catch (IOException ex) {
40.222 + Exceptions.printStackTrace(ex);
40.223 + }
40.224 +
40.225 + return null;
40.226 + }
40.227 +
40.228 + static String getClusterUrl() {
40.229 + if (clusterUrl == null) {
40.230 + File f =
40.231 + InstalledFileLocator.getDefault().locate("modules/org-netbeans-modules-python-editor.jar", null, false); // NOI18N
40.232 +
40.233 + if (f == null) {
40.234 + throw new RuntimeException("Can't find cluster");
40.235 + }
40.236 +
40.237 + f = new File(f.getParentFile().getParentFile().getAbsolutePath());
40.238 +
40.239 + try {
40.240 + f = f.getCanonicalFile();
40.241 + clusterUrl = f.toURI().toURL().toExternalForm();
40.242 + } catch (IOException ioe) {
40.243 + Exceptions.printStackTrace(ioe);
40.244 + }
40.245 + }
40.246
40.247 + return clusterUrl;
40.248 + }
40.249 +
40.250 + private final QuerySupport index;
40.251 + private final boolean updateCache;
40.252 +
40.253 + /** Creates a new instance of PythonIndex */
40.254 + private PythonIndex(QuerySupport index, boolean updateCache) {
40.255 + this.index = index;
40.256 + this.updateCache = updateCache;
40.257 + }
40.258 +
40.259 + private boolean search(String fieldName, String fieldValue, QuerySupport.Kind kind, Set<? super IndexResult> result, final String... fieldsToLoad) {
40.260 + try {
40.261 + result.addAll(index.query(fieldName, fieldValue, kind, fieldsToLoad));
40.262 return true;
40.263 } catch (IOException ioe) {
40.264 Exceptions.printStackTrace(ioe);
40.265 @@ -120,8 +289,8 @@
40.266 }
40.267 }
40.268
40.269 - public Set<IndexedElement> getModules(String name, final NameKind kind) {
40.270 - final Set<SearchResult> result = new HashSet<SearchResult>();
40.271 + public Set<IndexedElement> getModules(String name, final QuerySupport.Kind kind) {
40.272 + final Set<IndexResult> result = new HashSet<IndexResult>();
40.273
40.274 // if (!isValid()) {
40.275 // LOGGER.fine(String.format("LuceneIndex[%s] is invalid!\n", this.toString()));
40.276 @@ -130,32 +299,30 @@
40.277
40.278 // TODO - handle case insensitive searches etc?
40.279 String field = PythonIndexer.FIELD_MODULE_NAME;
40.280 - Set<String> terms = new HashSet<String>(5);
40.281 - terms.add(PythonIndexer.FIELD_MODULE_ATTR_NAME);
40.282 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
40.283
40.284 - search(field, name, kind, result, ALL_SCOPE, terms);
40.285 + search(field, name, kind, result, PythonIndexer.FIELD_MODULE_ATTR_NAME, PythonIndexer.FIELD_MODULE_NAME);
40.286
40.287 final Set<IndexedElement> modules = new HashSet<IndexedElement>();
40.288
40.289 - for (SearchResult map : result) {
40.290 - String url = map.getPersistentUrl();
40.291 + for (IndexResult map : result) {
40.292 + URL url = map.getUrl();
40.293 if (url == null) {
40.294 continue;
40.295 }
40.296 + String path = url.toExternalForm();
40.297 String module = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
40.298 if (STUB_MISSING.equals(module)) {
40.299 continue;
40.300 }
40.301
40.302 - IndexedElement element = new IndexedElement(module, ElementKind.MODULE, url, null, null, null);
40.303 + IndexedElement element = new IndexedElement(module, ElementKind.MODULE, path, null, null, null);
40.304
40.305 String attrs = map.getValue(PythonIndexer.FIELD_MODULE_ATTR_NAME);
40.306 if (attrs != null && attrs.indexOf('D') != -1) {
40.307 element.setFlags(IndexedElement.DEPRECATED);
40.308 }
40.309
40.310 - String rhs = url.substring(url.lastIndexOf('/') + 1);
40.311 + String rhs = path.substring(path.lastIndexOf('/') + 1);
40.312 element.setRhs(rhs);
40.313 modules.add(element);
40.314 }
40.315 @@ -163,15 +330,15 @@
40.316 return modules;
40.317 }
40.318
40.319 - public Set<IndexedPackage> getPackages(String name, final NameKind kind) {
40.320 - final Set<SearchResult> result = new HashSet<SearchResult>();
40.321 + public Set<IndexedPackage> getPackages(String name, final QuerySupport.Kind kind) {
40.322 + final Set<IndexResult> result = new HashSet<IndexResult>();
40.323
40.324 String field = PythonIndexer.FIELD_MODULE_NAME;
40.325 - search(field, name, kind, result, ALL_SCOPE, Collections.singleton(PythonIndexer.FIELD_MODULE_NAME));
40.326 + search(field, name, kind, result, PythonIndexer.FIELD_MODULE_NAME);
40.327
40.328 final Set<IndexedPackage> packages = new HashSet<IndexedPackage>();
40.329
40.330 - for (SearchResult map : result) {
40.331 + for (IndexResult map : result) {
40.332 String module = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
40.333
40.334 String pkgName = null;
40.335 @@ -199,7 +366,7 @@
40.336 }
40.337
40.338 if (pkgName != null) {
40.339 - String url = map.getPersistentUrl();
40.340 + String url = map.getUrl().toExternalForm();
40.341 IndexedPackage element = new IndexedPackage(pkgName, pkg, url, nextNextDot != -1);
40.342 element.setRhs("");
40.343 packages.add(element);
40.344 @@ -208,10 +375,9 @@
40.345
40.346 return packages;
40.347 }
40.348 -
40.349 - public Set<IndexedElement> getClasses(String name, final NameKind kind, Set<SearchScope> scope,
40.350 - PythonParserResult context, boolean includeDuplicates) {
40.351 - final Set<SearchResult> result = new HashSet<SearchResult>();
40.352 +
40.353 + public Set<IndexedElement> getClasses(String name, final QuerySupport.Kind kind, PythonParserResult context, boolean includeDuplicates) {
40.354 + final Set<IndexResult> result = new HashSet<IndexResult>();
40.355
40.356 // if (!isValid()) {
40.357 // LOGGER.fine(String.format("LuceneIndex[%s] is invalid!\n", this.toString()));
40.358 @@ -220,42 +386,37 @@
40.359 String field;
40.360
40.361 switch (kind) {
40.362 - case EXACT_NAME:
40.363 - case PREFIX:
40.364 - case CAMEL_CASE:
40.365 - case REGEXP:
40.366 - field = PythonIndexer.FIELD_CLASS_NAME;
40.367 -
40.368 - break;
40.369 -
40.370 - case CASE_INSENSITIVE_PREFIX:
40.371 - case CASE_INSENSITIVE_REGEXP:
40.372 - field = PythonIndexer.FIELD_CASE_INSENSITIVE_CLASS_NAME;
40.373 -
40.374 - break;
40.375 -
40.376 - default:
40.377 - throw new UnsupportedOperationException(kind.toString());
40.378 + case EXACT:
40.379 + case PREFIX:
40.380 + case CAMEL_CASE:
40.381 + case REGEXP:
40.382 + field = PythonIndexer.FIELD_CLASS_NAME;
40.383 +
40.384 + break;
40.385 +
40.386 + case CASE_INSENSITIVE_PREFIX:
40.387 + case CASE_INSENSITIVE_REGEXP:
40.388 + field = PythonIndexer.FIELD_CASE_INSENSITIVE_CLASS_NAME;
40.389 +
40.390 + break;
40.391 +
40.392 + default:
40.393 + throw new UnsupportedOperationException(kind.toString());
40.394 }
40.395
40.396 - Set<String> terms = new HashSet<String>(5);
40.397 - terms.add(PythonIndexer.FIELD_IN);
40.398 - terms.add(PythonIndexer.FIELD_CLASS_ATTR_NAME);
40.399 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
40.400 -
40.401 - search(field, name, kind, result, scope, terms);
40.402 + search(field, name, kind, result, PythonIndexer.FIELD_IN, PythonIndexer.FIELD_CLASS_ATTR_NAME, PythonIndexer.FIELD_CLASS_NAME);
40.403
40.404 Set<String> uniqueClasses = includeDuplicates ? null : new HashSet<String>();
40.405
40.406 final Set<IndexedElement> classes = new HashSet<IndexedElement>();
40.407
40.408 - for (SearchResult map : result) {
40.409 + for (IndexResult map : result) {
40.410 String clz = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
40.411 if (clz == null) {
40.412 // A module without classes
40.413 continue;
40.414 }
40.415 - String url = map.getPersistentUrl();
40.416 + String url = map.getUrl().toExternalForm();
40.417 String module = map.getValue(PythonIndexer.FIELD_IN);
40.418 boolean isBuiltin = isBuiltinModule(module);
40.419
40.420 @@ -290,7 +451,7 @@
40.421 // * @todo Use arglist arity comparison to reject methods that are not overrides...
40.422 // */
40.423 // public IndexedMethod getOverridingMethod(String className, String methodName) {
40.424 -// Set<IndexedElement> methods = getInheritedElements(className, methodName, NameKind.EXACT_NAME);
40.425 +// Set<IndexedElement> methods = getInheritedElements(className, methodName, QuerySupport.Kind.EXACT);
40.426 //
40.427 // // TODO - this is only returning ONE match, not the most distant one. I really need to
40.428 // // produce a PythonIndex method for this which can walk in there and do a decent job!
40.429 @@ -308,7 +469,7 @@
40.430 // }
40.431 /** Get the super implementation of the given method */
40.432 public Set<IndexedElement> getOverridingMethods(String className, String function) {
40.433 - Set<IndexedElement> methods = getInheritedElements(className, function, NameKind.EXACT_NAME, true);
40.434 + Set<IndexedElement> methods = getInheritedElements(className, function, QuerySupport.Kind.EXACT, true);
40.435
40.436 // TODO - remove all methods that are in the same file
40.437 if (methods.size() > 0) {
40.438 @@ -339,16 +500,12 @@
40.439
40.440 /** Get the super class of the given class */
40.441 public Set<IndexedElement> getSuperClasses(String className) {
40.442 - final Set<SearchResult> result = new HashSet<SearchResult>();
40.443 - Set<String> terms = new HashSet<String>(5);
40.444 -// terms.add(PythonIndexer.FIELD_IN);
40.445 - terms.add(PythonIndexer.FIELD_EXTENDS_NAME);
40.446 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
40.447 + final Set<IndexResult> result = new HashSet<IndexResult>();
40.448
40.449 - search(PythonIndexer.FIELD_CLASS_NAME, className, NameKind.EXACT_NAME, result, ALL_SCOPE, terms);
40.450 + search(PythonIndexer.FIELD_CLASS_NAME, className, QuerySupport.Kind.EXACT, result, PythonIndexer.FIELD_EXTENDS_NAME, PythonIndexer.FIELD_CLASS_NAME);
40.451
40.452 Set<String> classNames = new HashSet<String>();
40.453 - for (SearchResult map : result) {
40.454 + for (IndexResult map : result) {
40.455 String[] extendsClasses = map.getValues(PythonIndexer.FIELD_EXTENDS_NAME);
40.456 if (extendsClasses != null && extendsClasses.length > 0) {
40.457 for (String clzName : extendsClasses) {
40.458 @@ -357,18 +514,16 @@
40.459 }
40.460 }
40.461
40.462 - terms = new HashSet<String>(5);
40.463 - terms.add(PythonIndexer.FIELD_IN);
40.464 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
40.465 + String[] terms = { PythonIndexer.FIELD_IN, PythonIndexer.FIELD_CLASS_NAME };
40.466
40.467 Set<IndexedElement> superClasses = new HashSet<IndexedElement>();
40.468
40.469 for (String superClz : classNames) {
40.470 result.clear();
40.471 - search(PythonIndexer.FIELD_CLASS_NAME, superClz, NameKind.EXACT_NAME, result, ALL_SCOPE, terms);
40.472 - for (SearchResult map : result) {
40.473 + search(PythonIndexer.FIELD_CLASS_NAME, superClz, QuerySupport.Kind.EXACT, result, terms);
40.474 + for (IndexResult map : result) {
40.475 assert superClz.equals(map.getValue(PythonIndexer.FIELD_CLASS_NAME));
40.476 - String url = map.getPersistentUrl();
40.477 + String url = map.getUrl().toExternalForm();
40.478 String module = map.getValue(PythonIndexer.FIELD_IN);
40.479 IndexedElement clz = new IndexedElement(superClz, ElementKind.CLASS, url, module, null, null);
40.480 superClasses.add(clz);
40.481 @@ -381,15 +536,15 @@
40.482 /**
40.483 * Get the set of inherited (through super classes and mixins) for the given fully qualified class name.
40.484 * @param classFqn FQN: module1::module2::moduleN::class
40.485 - * @param prefix If kind is NameKind.PREFIX/CASE_INSENSITIVE_PREFIX, a prefix to filter methods by. Else,
40.486 - * if kind is NameKind.EXACT_NAME filter methods by the exact name.
40.487 + * @param prefix If kind is QuerySupport.Kind.PREFIX/CASE_INSENSITIVE_PREFIX, a prefix to filter methods by. Else,
40.488 + * if kind is QuerySupport.Kind.EXACT filter methods by the exact name.
40.489 * @param kind Whether the prefix field should be taken as a prefix or a whole name
40.490 */
40.491 - public Set<IndexedElement> getInheritedElements(String classFqn, String prefix, NameKind kind) {
40.492 + public Set<IndexedElement> getInheritedElements(String classFqn, String prefix, QuerySupport.Kind kind) {
40.493 return getInheritedElements(classFqn, prefix, kind, false);
40.494 }
40.495
40.496 - public Set<IndexedElement> getInheritedElements(String classFqn, String prefix, NameKind kind, boolean includeOverrides) {
40.497 + public Set<IndexedElement> getInheritedElements(String classFqn, String prefix, QuerySupport.Kind kind, boolean includeOverrides) {
40.498 boolean haveRedirected = false;
40.499
40.500 if (classFqn == null) {
40.501 @@ -421,15 +576,11 @@
40.502 return elements;
40.503 }
40.504
40.505 - public static final String OBJECT = "object"; // NOI18N
40.506 -
40.507 /** Return whether the specific class referenced (classFqn) was found or not. This is
40.508 * not the same as returning whether any classes were added since it may add
40.509 * additional methods from parents (Object/Class).
40.510 */
40.511 - private boolean addMethodsFromClass(String prefix, NameKind kind, String classFqn,
40.512 - Set<IndexedElement> elements, Set<String> seenSignatures, Set<String> scannedClasses,
40.513 - boolean haveRedirected, boolean inheriting, boolean includeOverrides, int depth) {
40.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) {
40.515 // Prevent problems with circular includes or redundant includes
40.516 if (scannedClasses.contains(classFqn)) {
40.517 return false;
40.518 @@ -439,16 +590,15 @@
40.519
40.520 String searchField = PythonIndexer.FIELD_CLASS_NAME;
40.521
40.522 - Set<SearchResult> result = new HashSet<SearchResult>();
40.523 + Set<IndexResult> result = new HashSet<IndexResult>();
40.524
40.525 - Set<String> terms = new HashSet<String>(5);
40.526 - terms.add(PythonIndexer.FIELD_IN);
40.527 - terms.add(PythonIndexer.FIELD_EXTENDS_NAME);
40.528 - terms.add(PythonIndexer.FIELD_MEMBER);
40.529 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
40.530 -
40.531 -
40.532 - search(searchField, classFqn, NameKind.EXACT_NAME, result, ALL_SCOPE, terms);
40.533 + String[] terms = {PythonIndexer.FIELD_IN,
40.534 + PythonIndexer.FIELD_EXTENDS_NAME,
40.535 + PythonIndexer.FIELD_MEMBER,
40.536 + PythonIndexer.FIELD_CLASS_NAME};
40.537 +
40.538 +
40.539 + search(searchField, classFqn, QuerySupport.Kind.EXACT, result, terms);
40.540
40.541 boolean foundIt = result.size() > 0;
40.542
40.543 @@ -467,10 +617,10 @@
40.544 }
40.545 int prefixLength = prefix.length();
40.546
40.547 - for (SearchResult map : result) {
40.548 + for (IndexResult map : result) {
40.549 assert map != null;
40.550
40.551 - String url = map.getPersistentUrl();
40.552 + String url = map.getUrl().toExternalForm();
40.553 String clz = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
40.554 String module = map.getValue(PythonIndexer.FIELD_IN);
40.555
40.556 @@ -493,16 +643,16 @@
40.557 // Prevent duplicates when method is redefined
40.558 if (includeOverrides || !seenSignatures.contains(signature)) {
40.559 if (signature.startsWith(prefix)) {
40.560 - if (kind == NameKind.EXACT_NAME) {
40.561 + if (kind == QuerySupport.Kind.EXACT) {
40.562 if (signature.charAt(prefixLength) != ';') {
40.563 continue;
40.564 }
40.565 - } else if (kind == NameKind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, prefix, 0, prefix.length())) {
40.566 + } else if (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, prefix, 0, prefix.length())) {
40.567 continue;
40.568 } else {
40.569 // REGEXP, CAMELCASE filtering etc. not supported here
40.570 - assert (kind == NameKind.PREFIX) ||
40.571 - (kind == NameKind.CASE_INSENSITIVE_PREFIX);
40.572 + assert (kind == QuerySupport.Kind.PREFIX) ||
40.573 + (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX);
40.574 }
40.575
40.576 if (!includeOverrides) {
40.577 @@ -558,36 +708,31 @@
40.578
40.579 return foundIt;
40.580 }
40.581 -
40.582 - public Set<IndexedElement> getAllMembers(String name, NameKind kind, Set<SearchScope> scope,
40.583 - PythonParserResult context, boolean includeDuplicates) {
40.584 - final Set<SearchResult> result = new HashSet<SearchResult>();
40.585 +
40.586 +
40.587 + public Set<IndexedElement> getAllMembers(String name, QuerySupport.Kind kind, PythonParserResult context, boolean includeDuplicates) {
40.588 + final Set<IndexResult> result = new HashSet<IndexResult>();
40.589 // TODO - handle case sensitivity better...
40.590 String field = PythonIndexer.FIELD_MEMBER;
40.591 - NameKind originalKind = kind;
40.592 - if (kind == NameKind.EXACT_NAME) {
40.593 + QuerySupport.Kind originalKind = kind;
40.594 + if (kind == QuerySupport.Kind.EXACT) {
40.595 // I can't do exact searches on methods because the method
40.596 // entries include signatures etc. So turn this into a prefix
40.597 // search and then compare chopped off signatures with the name
40.598 - kind = NameKind.PREFIX;
40.599 + kind = QuerySupport.Kind.PREFIX;
40.600 }
40.601
40.602 String searchUrl = null;
40.603 if (context != null) {
40.604 - try {
40.605 - searchUrl = context.getFile().getFileObject().getURL().toExternalForm();
40.606 - } catch (FileStateInvalidException ex) {
40.607 - Exceptions.printStackTrace(ex);
40.608 - }
40.609 + searchUrl = context.getSnapshot().getSource().getFileObject().toURL().toExternalForm();
40.610 }
40.611
40.612 - Set<String> terms = new HashSet<String>(5);
40.613 - terms.add(PythonIndexer.FIELD_IN);
40.614 - terms.add(PythonIndexer.FIELD_EXTENDS_NAME);
40.615 - terms.add(PythonIndexer.FIELD_MEMBER);
40.616 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
40.617 + String[] terms = {PythonIndexer.FIELD_IN,
40.618 + PythonIndexer.FIELD_EXTENDS_NAME,
40.619 + PythonIndexer.FIELD_MEMBER,
40.620 + PythonIndexer.FIELD_CLASS_NAME};
40.621
40.622 - search(field, name, kind, result, scope, terms);
40.623 + search(field, name, kind, result, terms);
40.624
40.625 // Set<String> uniqueClasses = null;
40.626 // if (includeDuplicates) {
40.627 @@ -599,25 +744,25 @@
40.628 final Set<IndexedElement> members = new HashSet<IndexedElement>();
40.629 int nameLength = name.length();
40.630
40.631 - for (SearchResult map : result) {
40.632 + for (IndexResult map : result) {
40.633 String[] signatures = map.getValues(PythonIndexer.FIELD_MEMBER);
40.634 if (signatures != null && signatures.length > 0) {
40.635 - String url = map.getPersistentUrl();
40.636 + String url = map.getUrl().toExternalForm();
40.637 String clz = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
40.638 String module = map.getValue(PythonIndexer.FIELD_IN);
40.639 boolean inherited = searchUrl == null || !searchUrl.equals(url);
40.640
40.641 for (String signature : signatures) {
40.642 - if (originalKind == NameKind.EXACT_NAME) {
40.643 + if (originalKind == QuerySupport.Kind.EXACT) {
40.644 if (signature.charAt(nameLength) != ';') {
40.645 continue;
40.646 }
40.647 - } else if (originalKind == NameKind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, name, 0, name.length())) {
40.648 + } else if (originalKind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, name, 0, name.length())) {
40.649 continue;
40.650 } else {
40.651 // REGEXP, CAMELCASE filtering etc. not supported here
40.652 - assert (originalKind == NameKind.PREFIX) ||
40.653 - (originalKind == NameKind.CASE_INSENSITIVE_PREFIX);
40.654 + assert (originalKind == QuerySupport.Kind.PREFIX) ||
40.655 + (originalKind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX);
40.656 }
40.657
40.658 IndexedElement element = IndexedElement.create(signature, module, url, clz);
40.659 @@ -629,56 +774,50 @@
40.660
40.661 return members;
40.662 }
40.663 -
40.664 - public Set<IndexedElement> getAllElements(String name, NameKind kind, Set<SearchScope> scope,
40.665 - PythonParserResult context, boolean includeDuplicates) {
40.666 - final Set<SearchResult> result = new HashSet<SearchResult>();
40.667 +
40.668 + public Set<IndexedElement> getAllElements(String name, QuerySupport.Kind kind, PythonParserResult context, boolean includeDuplicates) {
40.669 + final Set<IndexResult> result = new HashSet<IndexResult>();
40.670 // TODO - handle case sensitivity better...
40.671 String field = PythonIndexer.FIELD_ITEM;
40.672 - NameKind originalKind = kind;
40.673 - if (kind == NameKind.EXACT_NAME) {
40.674 + QuerySupport.Kind originalKind = kind;
40.675 + if (kind == QuerySupport.Kind.EXACT) {
40.676 // I can't do exact searches on methods because the method
40.677 // entries include signatures etc. So turn this into a prefix
40.678 // search and then compare chopped off signatures with the name
40.679 - kind = NameKind.PREFIX;
40.680 + kind = QuerySupport.Kind.PREFIX;
40.681 }
40.682
40.683 String searchUrl = null;
40.684 if (context != null) {
40.685 - try {
40.686 - searchUrl = context.getFile().getFileObject().getURL().toExternalForm();
40.687 - } catch (FileStateInvalidException ex) {
40.688 - Exceptions.printStackTrace(ex);
40.689 - }
40.690 + searchUrl = context.getSnapshot().getSource().getFileObject().toURL().toExternalForm();
40.691 }
40.692
40.693 - Set<String> terms = new HashSet<String>(5);
40.694 - terms.add(PythonIndexer.FIELD_ITEM);
40.695 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
40.696 + String[] terms = { PythonIndexer.FIELD_ITEM,
40.697 + PythonIndexer.FIELD_MODULE_NAME };
40.698
40.699 - search(field, name, kind, result, scope, terms);
40.700 + search(field, name, kind, result, terms);
40.701
40.702 final Set<IndexedElement> elements = new HashSet<IndexedElement>();
40.703 int nameLength = name.length();
40.704
40.705 - for (SearchResult map : result) {
40.706 + for (IndexResult map : result) {
40.707 String[] signatures = map.getValues(PythonIndexer.FIELD_ITEM);
40.708 if (signatures != null && signatures.length > 0) {
40.709 - String url = map.getPersistentUrl();
40.710 + String url = map.getUrl().toExternalForm();
40.711 String module = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
40.712 boolean inherited = searchUrl == null || !searchUrl.equals(url);
40.713
40.714 for (String signature : signatures) {
40.715 - if (originalKind == NameKind.EXACT_NAME) {
40.716 + if (originalKind == QuerySupport.Kind.EXACT) {
40.717 if (signature.charAt(nameLength) != ';') {
40.718 continue;
40.719 }
40.720 - } else if (originalKind == NameKind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, name, 0, name.length())) {
40.721 + } else if (originalKind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, name, 0, name.length())) {
40.722 continue;
40.723 } else {
40.724 // REGEXP, CAMELCASE filtering etc. not supported here
40.725 - assert (originalKind == NameKind.PREFIX) ||
40.726 - (originalKind == NameKind.CASE_INSENSITIVE_PREFIX);
40.727 + assert (originalKind == QuerySupport.Kind.PREFIX) ||
40.728 + (originalKind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX);
40.729 }
40.730
40.731 IndexedElement element = IndexedElement.create(signature, module, url, null);
40.732 @@ -704,20 +843,19 @@
40.733
40.734 Set<String> symbols = new HashSet<String>(250);
40.735
40.736 - Set<String> terms = new HashSet<String>(5);
40.737 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
40.738 - terms.add(PythonIndexer.FIELD_ITEM);
40.739 + String[] terms = { PythonIndexer.FIELD_MODULE_NAME,
40.740 + PythonIndexer.FIELD_ITEM };
40.741
40.742 // Look up all symbols
40.743 for (String module : modules) {
40.744 - final Set<SearchResult> result = new HashSet<SearchResult>();
40.745 + final Set<IndexResult> result = new HashSet<IndexResult>();
40.746 // TODO - handle case sensitivity better...
40.747 String field = PythonIndexer.FIELD_MODULE_NAME;
40.748 - NameKind kind = NameKind.EXACT_NAME;
40.749 + QuerySupport.Kind kind = QuerySupport.Kind.EXACT;
40.750
40.751 - search(field, module, kind, result, ALL_SCOPE, terms);
40.752 + search(field, module, kind, result, terms);
40.753
40.754 - for (SearchResult map : result) {
40.755 + for (IndexResult map : result) {
40.756 String[] signatures = map.getValues(PythonIndexer.FIELD_ITEM);
40.757 if (signatures != null) {
40.758 for (String signature : signatures) {
40.759 @@ -798,17 +936,13 @@
40.760 return symbols;
40.761 }
40.762
40.763 - public static boolean isBuiltinModule(String module) {
40.764 - return BUILTIN_MODULES.contains(module) || STUB_MISSING.equals(module);
40.765 - }
40.766 -
40.767 @SuppressWarnings("unchecked")
40.768 public Set<String> getImportsFor(String ident, boolean includeSymbol) {
40.769 Set<String> modules = new HashSet<String>(10);
40.770
40.771 - final Set<SearchResult> result = new HashSet<SearchResult>();
40.772 - search(PythonIndexer.FIELD_MODULE_NAME, ident, NameKind.EXACT_NAME, result, ALL_SCOPE, Collections.singleton(PythonIndexer.FIELD_MODULE_NAME));
40.773 - for (SearchResult map : result) {
40.774 + final Set<IndexResult> result = new HashSet<IndexResult>();
40.775 + search(PythonIndexer.FIELD_MODULE_NAME, ident, QuerySupport.Kind.EXACT, result, PythonIndexer.FIELD_MODULE_NAME);
40.776 + for (IndexResult map : result) {
40.777 String module = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
40.778 if (module != null) {
40.779 // TODO - record more information about this, such as the FQN
40.780 @@ -819,18 +953,17 @@
40.781
40.782 // TODO - handle case sensitivity better...
40.783 String field = PythonIndexer.FIELD_ITEM;
40.784 - NameKind kind = NameKind.PREFIX; // We're storing encoded signatures so not exact matches
40.785 + QuerySupport.Kind kind = QuerySupport.Kind.PREFIX; // We're storing encoded signatures so not exact matches
40.786
40.787 - Set<String> terms = new HashSet<String>(5);
40.788 - terms.add(PythonIndexer.FIELD_ITEM);
40.789 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
40.790 + String[] terms = { PythonIndexer.FIELD_ITEM,
40.791 + PythonIndexer.FIELD_MODULE_NAME };
40.792
40.793 result.clear();
40.794 - search(field, ident, kind, result, ALL_SCOPE, terms);
40.795 + search(field, ident, kind, result, terms);
40.796 String match = ident + ";";
40.797
40.798 MapSearch:
40.799 - for (SearchResult map : result) {
40.800 + for (IndexResult map : result) {
40.801 String module = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
40.802 if (module == null) {
40.803 continue;
40.804 @@ -883,13 +1016,12 @@
40.805
40.806 return modules;
40.807 }
40.808 -
40.809 - public Set<IndexedElement> getImportedElements(String prefix, NameKind kind, Set<SearchScope> scope,
40.810 - List<Import> imports, List<ImportFrom> importsFrom) {
40.811 +
40.812 + public Set<IndexedElement> getImportedElements(String prefix, QuerySupport.Kind kind, PythonParserResult context, List<Import> imports, List<ImportFrom> importsFrom) {
40.813 // TODO - separate methods from variables?? E.g. if you have method Foo() and class Foo
40.814 // coming from different places
40.815 -
40.816 -
40.817 +
40.818 +
40.819 // Set<String> imported = new HashSet<String>();
40.820 //
40.821 Set<IndexedElement> elements = new HashSet<IndexedElement>();
40.822 @@ -934,7 +1066,7 @@
40.823 // // Create variable items for the locally imported symbols
40.824 // for (String name : imported) {
40.825 // if (name.startsWith(prefix)) {
40.826 -// if (kind == NameKind.EXACT_NAME) {
40.827 +// if (kind == QuerySupport.Kind.EXACT) {
40.828 // // Ensure that the method is not longer than the prefix
40.829 // if ((name.length() > prefix.length()) &&
40.830 // (name.charAt(prefix.length()) != '(') &&
40.831 @@ -943,8 +1075,8 @@
40.832 // }
40.833 // } else {
40.834 // // REGEXP, CAMELCASE filtering etc. not supported here
40.835 -// assert (kind == NameKind.PREFIX) ||
40.836 -// (kind == NameKind.CASE_INSENSITIVE_PREFIX);
40.837 +// assert (kind == QuerySupport.Kind.PREFIX) ||
40.838 +// (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX);
40.839 // }
40.840 // String url = null;
40.841 // ElementKind elementKind = ElementKind.VARIABLE;
40.842 @@ -962,18 +1094,16 @@
40.843 // Always include the current file as imported
40.844 String moduleName = null;
40.845 if (context != null) {
40.846 - moduleName = context.getName();
40.847 + moduleName = PythonUtils.getModuleName(context.getSnapshot().getSource().getFileObject());
40.848 modules.add(moduleName);
40.849 }
40.850
40.851 modules.addAll(BUILTIN_MODULES);
40.852
40.853 - addImportedElements(prefix, kind, scope, modules, elements, null);
40.854 + addImportedElements(prefix, kind, modules, elements, null);
40.855
40.856 return elements;
40.857 }
40.858 - static Map<String, Set<String>> wildcardImports = new HashMap<String, Set<String>>();
40.859 -
40.860 public Set<String> getImportedFromWildcards(List<ImportFrom> importsFrom) {
40.861 Set<String> symbols = new HashSet<String>(100);
40.862
40.863 @@ -992,9 +1122,7 @@
40.864 }
40.865 }
40.866
40.867 - Set<String> terms = new HashSet<String>(5);
40.868 - terms.add(PythonIndexer.FIELD_ITEM);
40.869 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
40.870 + String[] terms = { PythonIndexer.FIELD_ITEM, PythonIndexer.FIELD_MODULE_NAME };
40.871
40.872 // Look up all symbols
40.873 for (String module : modules) {
40.874 @@ -1012,12 +1140,12 @@
40.875 }
40.876
40.877
40.878 - final Set<SearchResult> result = new HashSet<SearchResult>();
40.879 + final Set<IndexResult> result = new HashSet<IndexResult>();
40.880 // TODO - handle case sensitivity better...
40.881
40.882 - search(PythonIndexer.FIELD_MODULE_NAME, module, NameKind.EXACT_NAME, result, ALL_SCOPE, terms);
40.883 + search(PythonIndexer.FIELD_MODULE_NAME, module, QuerySupport.Kind.EXACT, result, terms);
40.884
40.885 - for (SearchResult map : result) {
40.886 + for (IndexResult map : result) {
40.887 String[] items = map.getValues(PythonIndexer.FIELD_ITEM);
40.888 if (items != null) {
40.889 for (String signature : items) {
40.890 @@ -1044,35 +1172,32 @@
40.891
40.892 return symbols;
40.893 }
40.894 -
40.895 - public Set<IndexedElement> getImportedElements(String prefix, NameKind kind, Set<SearchScope> scope,
40.896 - Set<String> modules, Set<String> systemModuleHolder) {
40.897 +
40.898 + public Set<IndexedElement> getImportedElements(String prefix, QuerySupport.Kind kind, Set<String> modules, Set<String> systemModuleHolder) {
40.899 Set<IndexedElement> elements = new HashSet<IndexedElement>();
40.900
40.901 - addImportedElements(prefix, kind, scope, modules, elements, systemModuleHolder);
40.902 + addImportedElements(prefix, kind, modules, elements, systemModuleHolder);
40.903
40.904 return elements;
40.905 }
40.906 - static Set<String> systemModules;
40.907
40.908 public boolean isSystemModule(String module) {
40.909 if (systemModules == null) {
40.910 systemModules = new HashSet<String>(800); // measured: 623
40.911 - Set<String> terms = new HashSet<String>(5);
40.912 - terms.add(PythonIndexer.FIELD_MODULE_ATTR_NAME);
40.913 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
40.914 - final Set<SearchResult> result = new HashSet<SearchResult>();
40.915 + String[] terms = { PythonIndexer.FIELD_MODULE_ATTR_NAME,
40.916 + PythonIndexer.FIELD_MODULE_NAME };
40.917 + final Set<IndexResult> result = new HashSet<IndexResult>();
40.918
40.919 // This doesn't work because the attrs field isn't searchable:
40.920 - //search(PythonIndexer.FIELD_MODULE_ATTR_NAME, "S", NameKind.PREFIX, result, ALL_SCOPE, terms);
40.921 - //for (SearchResult map : result) {
40.922 + //search(PythonIndexer.FIELD_MODULE_ATTR_NAME, "S", QuerySupport.Kind.PREFIX, result, ALL_SCOPE, terms);
40.923 + //for (IndexResult map : result) {
40.924 // assert map.getValue(PythonIndexer.FIELD_MODULE_ATTR_NAME).indexOf("S") != -1;
40.925 // systemModules.add(map.getValue(PythonIndexer.FIELD_MODULE_NAME));
40.926 //}
40.927
40.928 - search(PythonIndexer.FIELD_MODULE_NAME, "", NameKind.PREFIX, result, ALL_SCOPE, terms);
40.929 + search(PythonIndexer.FIELD_MODULE_NAME, "", QuerySupport.Kind.PREFIX, result, terms);
40.930
40.931 - for (SearchResult map : result) {
40.932 + for (IndexResult map : result) {
40.933 String attrs = map.getValue(PythonIndexer.FIELD_MODULE_ATTR_NAME);
40.934 if (attrs != null && attrs.indexOf('S') != -1) {
40.935 String mod = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
40.936 @@ -1084,19 +1209,14 @@
40.937 return systemModules.contains(module);
40.938 }
40.939
40.940 - // TODO - make weak?
40.941 - static Set<String> availableClasses;
40.942 -
40.943 public boolean isLowercaseClassName(String clz) {
40.944 if (availableClasses == null) {
40.945 availableClasses = new HashSet<String>(300); // measured: 193
40.946 - Set<String> terms = new HashSet<String>(5);
40.947 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
40.948 - final Set<SearchResult> result = new HashSet<SearchResult>();
40.949 + final Set<IndexResult> result = new HashSet<IndexResult>();
40.950
40.951 - search(PythonIndexer.FIELD_CLASS_NAME, "", NameKind.PREFIX, result, ALL_SCOPE, terms);
40.952 + search(PythonIndexer.FIELD_CLASS_NAME, "", QuerySupport.Kind.PREFIX, result, PythonIndexer.FIELD_CLASS_NAME);
40.953
40.954 - for (SearchResult map : result) {
40.955 + for (IndexResult map : result) {
40.956 String c = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
40.957 if (c != null && !Character.isUpperCase(c.charAt(0))) {
40.958 availableClasses.add(c);
40.959 @@ -1106,28 +1226,26 @@
40.960
40.961 return availableClasses.contains(clz);
40.962 }
40.963 -
40.964 - public void addImportedElements(String prefix, NameKind kind, Set<SearchScope> scope,
40.965 - Set<String> modules, Set<IndexedElement> elements, Set<String> systemModuleHolder) {
40.966 -
40.967 - Set<String> terms = new HashSet<String>(5);
40.968 - terms.add(PythonIndexer.FIELD_ITEM);
40.969 - terms.add(PythonIndexer.FIELD_MODULE_ATTR_NAME);
40.970 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
40.971 +
40.972 + public void addImportedElements(String prefix, QuerySupport.Kind kind, Set<String> modules, Set<IndexedElement> elements, Set<String> systemModuleHolder) {
40.973 +
40.974 + String[] terms = { PythonIndexer.FIELD_ITEM,
40.975 + PythonIndexer.FIELD_MODULE_ATTR_NAME,
40.976 + PythonIndexer.FIELD_MODULE_NAME };
40.977
40.978 // Look up all symbols
40.979 for (String module : modules) {
40.980 boolean isBuiltin = isBuiltinModule(module);
40.981 boolean isSystem = isBuiltin;
40.982
40.983 - final Set<SearchResult> result = new HashSet<SearchResult>();
40.984 + final Set<IndexResult> result = new HashSet<IndexResult>();
40.985 // TODO - handle case sensitivity better...
40.986
40.987 - search(PythonIndexer.FIELD_MODULE_NAME, module, NameKind.EXACT_NAME, result, scope, terms);
40.988 + search(PythonIndexer.FIELD_MODULE_NAME, module, QuerySupport.Kind.EXACT, result, terms);
40.989 int prefixLength = prefix.length();
40.990
40.991 - for (SearchResult map : result) {
40.992 - String url = map.getPersistentUrl();
40.993 + for (IndexResult map : result) {
40.994 + String url = map.getUrl().toExternalForm();
40.995 String[] items = map.getValues(PythonIndexer.FIELD_ITEM);
40.996 if (items != null) {
40.997 String attrs = map.getValue(PythonIndexer.FIELD_MODULE_ATTR_NAME);
40.998 @@ -1136,16 +1254,16 @@
40.999 }
40.1000 for (String signature : items) {
40.1001 if (signature.startsWith(prefix)) {
40.1002 - if (kind == NameKind.EXACT_NAME) {
40.1003 + if (kind == QuerySupport.Kind.EXACT) {
40.1004 if (signature.charAt(prefixLength) != ';') {
40.1005 continue;
40.1006 }
40.1007 - } else if (kind == NameKind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, prefix, 0, prefix.length())) {
40.1008 + } else if (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, prefix, 0, prefix.length())) {
40.1009 continue;
40.1010 } else {
40.1011 // REGEXP, CAMELCASE filtering etc. not supported here
40.1012 - assert (kind == NameKind.PREFIX) ||
40.1013 - (kind == NameKind.CASE_INSENSITIVE_PREFIX);
40.1014 + assert (kind == QuerySupport.Kind.PREFIX) ||
40.1015 + (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX);
40.1016 }
40.1017
40.1018 IndexedElement element = IndexedElement.create(signature, module, url, null);
40.1019 @@ -1170,17 +1288,16 @@
40.1020 }
40.1021 }
40.1022
40.1023 - public Set<IndexedElement> getExceptions(String prefix, NameKind kind, Set<SearchScope> scope) {
40.1024 - final Set<SearchResult> result = new HashSet<SearchResult>();
40.1025 - Set<String> terms = new HashSet<String>();
40.1026 - terms.add(PythonIndexer.FIELD_EXTENDS_NAME);
40.1027 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
40.1028 - terms.add(PythonIndexer.FIELD_CLASS_ATTR_NAME);
40.1029 - terms.add(PythonIndexer.FIELD_IN);
40.1030 - search(PythonIndexer.FIELD_EXTENDS_NAME, "", NameKind.PREFIX, result, scope, terms); // NOI18N
40.1031 + public Set<IndexedElement> getExceptions(String prefix, QuerySupport.Kind kind) {
40.1032 + final Set<IndexResult> result = new HashSet<IndexResult>();
40.1033 + String[] terms = { PythonIndexer.FIELD_EXTENDS_NAME,
40.1034 + PythonIndexer.FIELD_CLASS_NAME,
40.1035 + PythonIndexer.FIELD_CLASS_ATTR_NAME,
40.1036 + PythonIndexer.FIELD_IN };
40.1037 + search(PythonIndexer.FIELD_EXTENDS_NAME, "", QuerySupport.Kind.PREFIX, result, terms); // NOI18N
40.1038 Map<String, String> extendsMap = new HashMap<String, String>(100);
40.1039 // First iteration: Compute inheritance hierarchy
40.1040 - for (SearchResult map : result) {
40.1041 + for (IndexResult map : result) {
40.1042
40.1043 String superClass = map.getValue(PythonIndexer.FIELD_EXTENDS_NAME);
40.1044 if (superClass != null) {
40.1045 @@ -1231,21 +1348,21 @@
40.1046
40.1047 // Next add elements for all the exceptions
40.1048 final Set<IndexedElement> classes = new HashSet<IndexedElement>();
40.1049 - for (SearchResult map : result) {
40.1050 + for (IndexResult map : result) {
40.1051 String clz = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
40.1052 if (clz == null || !exceptionClasses.contains(clz)) {
40.1053 continue;
40.1054 }
40.1055
40.1056 - if ((kind == NameKind.PREFIX) && !clz.startsWith(prefix)) {
40.1057 + if ((kind == QuerySupport.Kind.PREFIX) && !clz.startsWith(prefix)) {
40.1058 continue;
40.1059 - } else if (kind == NameKind.CASE_INSENSITIVE_PREFIX && !clz.regionMatches(true, 0, prefix, 0, prefix.length())) {
40.1060 + } else if (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX && !clz.regionMatches(true, 0, prefix, 0, prefix.length())) {
40.1061 continue;
40.1062 - } else if (kind == NameKind.EXACT_NAME && !clz.equals(prefix)) {
40.1063 + } else if (kind == QuerySupport.Kind.EXACT && !clz.equals(prefix)) {
40.1064 continue;
40.1065 }
40.1066
40.1067 - String url = map.getPersistentUrl();
40.1068 + String url = map.getUrl().toExternalForm();
40.1069 String module = map.getValue(PythonIndexer.FIELD_IN);
40.1070 IndexedElement element = new IndexedElement(clz, ElementKind.CLASS, url, module, null, null);
40.1071 String attrs = map.getValue(PythonIndexer.FIELD_CLASS_ATTR_NAME);
40.1072 @@ -1299,9 +1416,8 @@
40.1073
40.1074 return classes;
40.1075 }
40.1076 -
40.1077 - private boolean addSubclasses(String classFqn,
40.1078 - Set<IndexedElement> classes, Set<String> seenClasses, Set<String> scannedClasses, boolean directOnly) {
40.1079 +
40.1080 + private boolean addSubclasses(String classFqn, Set<IndexedElement> classes, Set<String> seenClasses, Set<String> scannedClasses, boolean directOnly) {
40.1081 // Prevent problems with circular includes or redundant includes
40.1082 if (scannedClasses.contains(classFqn)) {
40.1083 return false;
40.1084 @@ -1311,15 +1427,14 @@
40.1085
40.1086 String searchField = PythonIndexer.FIELD_EXTENDS_NAME;
40.1087
40.1088 - Set<SearchResult> result = new HashSet<SearchResult>();
40.1089 + Set<IndexResult> result = new HashSet<IndexResult>();
40.1090
40.1091 - Set<String> terms = new HashSet<String>(5);
40.1092 - terms.add(PythonIndexer.FIELD_IN);
40.1093 - terms.add(PythonIndexer.FIELD_EXTENDS_NAME);
40.1094 - terms.add(PythonIndexer.FIELD_CLASS_ATTR_NAME);
40.1095 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
40.1096 + String[] terms = { PythonIndexer.FIELD_IN,
40.1097 + PythonIndexer.FIELD_EXTENDS_NAME,
40.1098 + PythonIndexer.FIELD_CLASS_ATTR_NAME,
40.1099 + PythonIndexer.FIELD_CLASS_NAME };
40.1100
40.1101 - search(searchField, classFqn, NameKind.EXACT_NAME, result, ALL_SCOPE, terms);
40.1102 + search(searchField, classFqn, QuerySupport.Kind.EXACT, result, terms);
40.1103
40.1104 boolean foundIt = result.size() > 0;
40.1105
40.1106 @@ -1328,10 +1443,10 @@
40.1107 return foundIt;
40.1108 }
40.1109
40.1110 - for (SearchResult map : result) {
40.1111 + for (IndexResult map : result) {
40.1112 String className = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
40.1113 if (className != null && !seenClasses.contains(className)) {
40.1114 - String url = map.getPersistentUrl();
40.1115 + String url = map.getUrl().toExternalForm();
40.1116 String module = map.getValue(PythonIndexer.FIELD_IN);
40.1117 IndexedElement clz = new IndexedElement(className, ElementKind.CLASS, url, module, null, null);
40.1118 String attrs = map.getValue(PythonIndexer.FIELD_CLASS_ATTR_NAME);
40.1119 @@ -1351,123 +1466,4 @@
40.1120
40.1121 return foundIt;
40.1122 }
40.1123 - private static String clusterUrl = null;
40.1124 -
40.1125 - // For testing only
40.1126 - public static void setClusterUrl(String url) {
40.1127 - clusterUrl = url;
40.1128 - }
40.1129 -
40.1130 - static String getPreindexUrl(String url) {
40.1131 - // TODO - look up the correct platform to use!
40.1132 - final PythonPlatformManager manager = PythonPlatformManager.getInstance();
40.1133 - final String platformName = manager.getDefaultPlatform();
40.1134 - PythonPlatform platform = manager.getPlatform(platformName);
40.1135 - if (platform != null) {
40.1136 - String s = platform.getHomeUrl();
40.1137 - if (s != null) {
40.1138 - if (url.startsWith(s)) {
40.1139 - url = PYTHONHOME_URL + url.substring(s.length());
40.1140 - return url;
40.1141 - }
40.1142 - }
40.1143 - }
40.1144 -
40.1145 - String s = getClusterUrl();
40.1146 -
40.1147 - if (url.startsWith(s)) {
40.1148 - return CLUSTER_URL + url.substring(s.length());
40.1149 - }
40.1150 -
40.1151 - if (url.startsWith("jar:file:")) { // NOI18N
40.1152 - String sub = url.substring(4);
40.1153 - if (sub.startsWith(s)) {
40.1154 - return CLUSTER_URL + sub.substring(s.length());
40.1155 - }
40.1156 - }
40.1157 -
40.1158 - return url;
40.1159 - }
40.1160 -
40.1161 - /** Get the FileObject corresponding to a URL returned from the index */
40.1162 - public static FileObject getFileObject(String url) {
40.1163 - return getFileObject(url, null);
40.1164 - }
40.1165 -
40.1166 - public static FileObject getFileObject(String url, FileObject context) {
40.1167 - try {
40.1168 - if (url.startsWith(PYTHONHOME_URL)) {
40.1169 - Iterator<String> it = null;
40.1170 -
40.1171 - // TODO - look up the right platform for the given project
40.1172 - //if (context != null) {
40.1173 - // Project project = FileOwnerQuery.getOwner(context);
40.1174 - // if (project != null) {
40.1175 - // PythonPlatform platform = PythonPlatform.platformFor(project);
40.1176 - // if (platform != null) {
40.1177 - // it = Collections.singleton(platform).iterator();
40.1178 - // }
40.1179 - // }
40.1180 - //}
40.1181 -
40.1182 - PythonPlatformManager manager = PythonPlatformManager.getInstance();
40.1183 - if (it == null) {
40.1184 - it = manager.getPlatformList().iterator();
40.1185 - }
40.1186 - while (it.hasNext()) {
40.1187 - String name = it.next();
40.1188 - PythonPlatform platform = manager.getPlatform(name);
40.1189 - if (platform != null) {
40.1190 - String u = platform.getHomeUrl();
40.1191 - if (u != null) {
40.1192 - try {
40.1193 - u = u + url.substring(PYTHONHOME_URL.length());
40.1194 - FileObject fo = URLMapper.findFileObject(new URL(u));
40.1195 - if (fo != null) {
40.1196 - return fo;
40.1197 - }
40.1198 - } catch (MalformedURLException mue) {
40.1199 - Exceptions.printStackTrace(mue);
40.1200 - }
40.1201 - }
40.1202 - }
40.1203 - }
40.1204 -
40.1205 - return null;
40.1206 - } else if (url.startsWith(CLUSTER_URL)) {
40.1207 - url = getClusterUrl() + url.substring(CLUSTER_URL.length()); // NOI18N
40.1208 - if (url.indexOf(".egg!/") != -1) { // NOI18N
40.1209 - url = "jar:" + url; // NOI18N
40.1210 - }
40.1211 - }
40.1212 -
40.1213 - return URLMapper.findFileObject(new URL(url));
40.1214 - } catch (IOException ex) {
40.1215 - Exceptions.printStackTrace(ex);
40.1216 - }
40.1217 -
40.1218 - return null;
40.1219 - }
40.1220 -
40.1221 - static String getClusterUrl() {
40.1222 - if (clusterUrl == null) {
40.1223 - File f =
40.1224 - InstalledFileLocator.getDefault().locate("modules/org-netbeans-modules-python-editor.jar", null, false); // NOI18N
40.1225 -
40.1226 - if (f == null) {
40.1227 - throw new RuntimeException("Can't find cluster");
40.1228 - }
40.1229 -
40.1230 - f = new File(f.getParentFile().getParentFile().getAbsolutePath());
40.1231 -
40.1232 - try {
40.1233 - f = f.getCanonicalFile();
40.1234 - clusterUrl = f.toURI().toURL().toExternalForm();
40.1235 - } catch (IOException ioe) {
40.1236 - Exceptions.printStackTrace(ioe);
40.1237 - }
40.1238 - }
40.1239 -
40.1240 - return clusterUrl;
40.1241 - }
40.1242 }
41.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonIndexSearcher.java Sun Jan 04 13:11:53 2015 -0600
41.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonIndexSearcher.java Sat Feb 28 17:25:32 2015 -0800
41.3 @@ -31,7 +31,6 @@
41.4 package org.netbeans.modules.python.editor;
41.5
41.6 import java.awt.Toolkit;
41.7 -import java.util.EnumSet;
41.8 import java.util.HashSet;
41.9 import java.util.Set;
41.10 import java.util.logging.Logger;
41.11 @@ -42,13 +41,12 @@
41.12 import org.netbeans.api.project.Project;
41.13 import org.netbeans.api.project.ProjectInformation;
41.14 import org.netbeans.api.project.ProjectUtils;
41.15 -import org.netbeans.modules.gsf.api.CompilationInfo;
41.16 -import org.netbeans.modules.gsf.api.ElementHandle;
41.17 -import org.netbeans.modules.gsf.api.Index;
41.18 -import org.netbeans.modules.gsf.api.Index.SearchScope;
41.19 -import org.netbeans.modules.gsf.api.IndexSearcher;
41.20 -import org.netbeans.modules.gsf.api.NameKind;
41.21 -import org.netbeans.modules.gsf.spi.GsfUtilities;
41.22 +import org.netbeans.modules.csl.api.ElementHandle;
41.23 +import org.netbeans.modules.csl.api.IndexSearcher;
41.24 +import org.netbeans.modules.csl.api.IndexSearcher.Descriptor;
41.25 +import org.netbeans.modules.csl.api.IndexSearcher.Helper;
41.26 +import org.netbeans.modules.csl.spi.GsfUtilities;
41.27 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
41.28 import org.openide.filesystems.FileObject;
41.29 import org.openide.util.ImageUtilities;
41.30 import org.python.antlr.PythonTree;
41.31 @@ -58,18 +56,20 @@
41.32 * @author Tor Norbye
41.33 */
41.34 public class PythonIndexSearcher implements IndexSearcher {
41.35 - public Set<? extends Descriptor> getTypes(Index gsfIndex, String textForQuery, NameKind kind, EnumSet<SearchScope> scope, Helper helper) {
41.36 - PythonIndex index = PythonIndex.get(gsfIndex);
41.37 +
41.38 + @Override
41.39 + public Set<? extends Descriptor> getTypes(Project prjct, String textForQuery, QuerySupport.Kind kind, Helper helper) {
41.40 + PythonIndex index = PythonIndex.get(prjct);
41.41 Set<PythonSymbol> result = new HashSet<PythonSymbol>();
41.42 Set<? extends IndexedElement> elements;
41.43
41.44 // TODO - do some filtering if you use ./#
41.45 // int dot = textForQuery.lastIndexOf('.');
41.46 - // if (dot != -1 && (kind == NameKind.PREFIX || kind == NameKind.CASE_INSENSITIVE_PREFIX)) {
41.47 + // if (dot != -1 && (kind == QuerySupport.Kind.PREFIX || kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX)) {
41.48 // String prefix = textForQuery.substring(dot+1);
41.49 // String in = textForQuery.substring(0, dot);
41.50
41.51 - elements = index.getClasses(textForQuery, kind, scope, null, true);
41.52 + elements = index.getClasses(textForQuery, kind, null, true);
41.53 for (IndexedElement element : elements) {
41.54 result.add(new PythonSymbol(element, helper));
41.55 }
41.56 @@ -77,22 +77,23 @@
41.57 return result;
41.58 }
41.59
41.60 - public Set<? extends Descriptor> getSymbols(Index gsfIndex, String textForQuery, NameKind kind, EnumSet<SearchScope> scope, Helper helper) {
41.61 - PythonIndex index = PythonIndex.get(gsfIndex);
41.62 + @Override
41.63 + public Set<? extends Descriptor> getSymbols(Project prjct, String textForQuery, QuerySupport.Kind kind, Helper helper) {
41.64 + PythonIndex index = PythonIndex.get(prjct);
41.65 Set<PythonSymbol> result = new HashSet<PythonSymbol>();
41.66 Set<? extends IndexedElement> elements;
41.67
41.68 // TODO - do some filtering if you use ./#
41.69 // int dot = textForQuery.lastIndexOf('.');
41.70 - // if (dot != -1 && (kind == NameKind.PREFIX || kind == NameKind.CASE_INSENSITIVE_PREFIX)) {
41.71 + // if (dot != -1 && (kind == QuerySupport.Kind.PREFIX || kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX)) {
41.72 // String prefix = textForQuery.substring(dot+1);
41.73 // String in = textForQuery.substring(0, dot);
41.74
41.75 - elements = index.getAllMembers(textForQuery, kind, scope, null, true);
41.76 + elements = index.getAllMembers(textForQuery, kind, null, true);
41.77 for (IndexedElement element : elements) {
41.78 result.add(new PythonSymbol(element, helper));
41.79 }
41.80 - elements = index.getClasses(textForQuery, kind, scope, null, true);
41.81 + elements = index.getClasses(textForQuery, kind, null, true);
41.82 for (IndexedElement element : elements) {
41.83 result.add(new PythonSymbol(element, helper));
41.84 }
41.85 @@ -187,12 +188,12 @@
41.86
41.87 @Override
41.88 public void open() {
41.89 - CompilationInfo[] infoRet = new CompilationInfo[1];
41.90 - PythonTree node = PythonAstUtils.getForeignNode(element, infoRet);
41.91 + PythonParserResult[] parserResultRet = new PythonParserResult[1];
41.92 + PythonTree node = PythonAstUtils.getForeignNode(element, parserResultRet);
41.93
41.94 if (node != null) {
41.95 int astOffset = PythonAstUtils.getRange(node).getStart();
41.96 - int lexOffset = PythonLexerUtils.getLexerOffset(infoRet[0], astOffset);
41.97 + int lexOffset = PythonLexerUtils.getLexerOffset(parserResultRet[0], astOffset);
41.98 if (lexOffset == -1) {
41.99 lexOffset = 0;
41.100 }
42.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonIndexer.java Sun Jan 04 13:11:53 2015 -0600
42.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonIndexer.java Sat Feb 28 17:25:32 2015 -0800
42.3 @@ -39,20 +39,21 @@
42.4 import java.util.HashMap;
42.5 import java.util.List;
42.6 import java.util.Map;
42.7 +import java.util.logging.Level;
42.8 +import java.util.logging.Logger;
42.9 import java.util.regex.Matcher;
42.10 import java.util.regex.Pattern;
42.11 import javax.swing.text.BadLocationException;
42.12 import org.netbeans.editor.BaseDocument;
42.13 -import org.netbeans.modules.gsf.api.IndexDocument;
42.14 -import org.netbeans.modules.gsf.api.IndexDocumentFactory;
42.15 -import org.netbeans.modules.gsf.api.Indexer;
42.16 -import org.netbeans.modules.gsf.api.Parser.Job;
42.17 -import org.netbeans.modules.gsf.api.ParserFile;
42.18 -import org.netbeans.modules.gsf.api.ParserResult;
42.19 -import org.netbeans.modules.gsf.api.SourceFileReader;
42.20 -import org.netbeans.modules.gsf.spi.DefaultParseListener;
42.21 -import org.netbeans.modules.gsf.spi.DefaultParserFile;
42.22 -import org.netbeans.modules.gsf.spi.GsfUtilities;
42.23 +import org.netbeans.modules.csl.spi.GsfUtilities;
42.24 +import org.netbeans.modules.csl.spi.ParserResult;
42.25 +import org.netbeans.modules.parsing.api.Snapshot;
42.26 +import org.netbeans.modules.parsing.spi.Parser;
42.27 +import org.netbeans.modules.parsing.spi.indexing.Context;
42.28 +import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexer;
42.29 +import org.netbeans.modules.parsing.spi.indexing.Indexable;
42.30 +import org.netbeans.modules.parsing.spi.indexing.support.IndexDocument;
42.31 +import org.netbeans.modules.parsing.spi.indexing.support.IndexingSupport;
42.32 import org.netbeans.modules.python.api.PythonPlatform;
42.33 import org.netbeans.modules.python.api.PythonPlatformManager;
42.34 import org.netbeans.modules.python.editor.elements.IndexedElement;
42.35 @@ -90,7 +91,9 @@
42.36 * Here I need to pick up all 3 signatures!
42.37 * @author Tor Norbye
42.38 */
42.39 -public class PythonIndexer implements Indexer {
42.40 +public class PythonIndexer extends EmbeddingIndexer {
42.41 + public static final String NAME = "PythonIndexer";
42.42 + public static final int VERSION = 1;
42.43 public static boolean PREINDEXING = Boolean.getBoolean("gsf.preindexing"); // NOI18N
42.44 public static final String FIELD_MEMBER = "member"; //NOI18N
42.45 public static final String FIELD_MODULE_NAME = "module"; //NOI18N
42.46 @@ -104,13 +107,35 @@
42.47 private FileObject prevParent;
42.48 private boolean prevResult;
42.49
42.50 - public boolean isIndexable(ParserFile file) {
42.51 - String extension = file.getExtension();
42.52 + public static boolean isIndexable(Indexable indexable, Snapshot snapshot) {
42.53 + FileObject fo = snapshot.getSource().getFileObject();
42.54 + String extension = fo.getExt();
42.55 + if ("py".equals(extension)) { // NOI18N
42.56 + return true;
42.57 + }
42.58 +
42.59 + if ("rst".equals(extension)) { // NOI18N
42.60 + // Index restructured text if it looks like it contains Python library
42.61 + // definitions
42.62 + return true;
42.63 + }
42.64 +
42.65 + if ("egg".equals(extension)) { // NOI18N
42.66 + return true;
42.67 + }
42.68 +
42.69 + return false;
42.70 + }
42.71 +
42.72 +
42.73 + public boolean isIndexable(Snapshot file) {
42.74 + FileObject fo = file.getSource().getFileObject();
42.75 + String extension = fo.getExt();
42.76 if ("py".equals(extension)) { // NOI18N
42.77
42.78 // Skip "test" folders under lib... Lots of weird files there
42.79 // and we don't want to pollute the index with them
42.80 - File parent = file.getFile().getParentFile();
42.81 + FileObject parent = fo.getParent();
42.82
42.83 if (parent != null && parent.getName().equals("test")) { // NOI18N
42.84 // Make sure it's really a lib folder, we want to include the
42.85 @@ -118,10 +143,6 @@
42.86
42.87 // Avoid double-indexing files that have multiple versions - e.g. foo.js and foo-min.js
42.88 // or foo.uncompressed
42.89 - FileObject fo = file.getFileObject();
42.90 - if (fo == null) {
42.91 - return true;
42.92 - }
42.93 FileObject parentFo = fo.getParent();
42.94 if (prevParent == parentFo) {
42.95 return prevResult;
42.96 @@ -159,22 +180,36 @@
42.97 return false;
42.98 }
42.99
42.100 - public List<IndexDocument> index(ParserResult result, IndexDocumentFactory factory) throws IOException {
42.101 + @Override
42.102 + protected void index(Indexable indexable, Parser.Result result, Context context) {
42.103 PythonParserResult parseResult = (PythonParserResult)result;
42.104 if (parseResult == null) {
42.105 - return Collections.emptyList();
42.106 + return;
42.107 }
42.108 - String extension = result.getFile().getNameExt();
42.109 +
42.110 + IndexingSupport support;
42.111 + try {
42.112 + support = IndexingSupport.getInstance(context);
42.113 + } catch (IOException ioe) {
42.114 + LOG.log(Level.WARNING, null, ioe);
42.115 + return;
42.116 + }
42.117 +
42.118 + support.removeDocuments(indexable);
42.119 +
42.120 + FileObject fileObject = result.getSnapshot().getSource().getFileObject();
42.121 + String extension = fileObject.getNameExt();
42.122
42.123 if (extension.endsWith(".rst")) { // NOI18N
42.124 - return scanRst(result.getFile().getFileObject(), factory, null);
42.125 + scanRst(fileObject, indexable, support, null);
42.126 } else if (extension.endsWith(".egg")) { // NOI18N
42.127 - return scanEgg(result, factory);
42.128 + scanEgg(fileObject, indexable, parseResult, support);
42.129 } else {
42.130 // Normal python file
42.131 - return new IndexTask(parseResult, factory).scan();
42.132 + new IndexTask(parseResult, support).scan();
42.133 }
42.134 }
42.135 + private static final Logger LOG = Logger.getLogger(PythonIndexer.class.getName());
42.136
42.137 public boolean acceptQueryPath(String url) {
42.138 return url.indexOf("jsstubs") == -1; // NOI18N
42.139 @@ -224,20 +259,20 @@
42.140
42.141 private static class IndexTask {
42.142 private PythonParserResult result;
42.143 - private ParserFile file;
42.144 - private IndexDocumentFactory factory;
42.145 + private FileObject file;
42.146 + private IndexingSupport support;
42.147 private List<IndexDocument> documents = new ArrayList<IndexDocument>();
42.148 private String url;
42.149 private String module;
42.150 private SymbolTable symbolTable;
42.151 private String overrideUrl;
42.152
42.153 - private IndexTask(PythonParserResult result, IndexDocumentFactory factory) {
42.154 + private IndexTask(PythonParserResult result, IndexingSupport support) {
42.155 this.result = result;
42.156 - this.file = result.getFile();
42.157 - this.factory = factory;
42.158 + this.file = result.getSnapshot().getSource().getFileObject();
42.159 + this.support = support;
42.160
42.161 - module = PythonUtils.getModuleName(null, file);
42.162 + module = PythonUtils.getModuleName(file);
42.163 //PythonTree root = PythonAstUtils.getRoot(result);
42.164 //if (root instanceof Module) {
42.165 // Str moduleDoc = PythonAstUtils.getDocumentationNode(root);
42.166 @@ -247,24 +282,18 @@
42.167 //}
42.168 }
42.169
42.170 - private IndexTask(PythonParserResult result, IndexDocumentFactory factory, String overrideUrl) {
42.171 - this(result, factory);
42.172 + private IndexTask(PythonParserResult result, IndexingSupport support, String overrideUrl) {
42.173 + this(result, support);
42.174 this.overrideUrl = overrideUrl;
42.175 }
42.176
42.177 public List<IndexDocument> scan() {
42.178 - FileObject fileObject = file.getFileObject();
42.179 - try {
42.180 - url = fileObject.getURL().toExternalForm();
42.181 -
42.182 - // Make relative URLs for urls in the libraries
42.183 - url = PythonIndex.getPreindexUrl(url);
42.184 - } catch (IOException ioe) {
42.185 - Exceptions.printStackTrace(ioe);
42.186 - }
42.187 + url = file.toURL().toExternalForm();
42.188 + // Make relative URLs for urls in the libraries
42.189 + url = PythonIndex.getPreindexUrl(url);
42.190
42.191 IndexDocument doc = createDocument();
42.192 - doc.addPair(FIELD_MODULE_NAME, module, true);
42.193 + doc.addPair(FIELD_MODULE_NAME, module, true, true);
42.194
42.195 String moduleAttrs = null;
42.196 if (url.startsWith(PythonIndex.CLUSTER_URL) || url.startsWith(PythonIndex.PYTHONHOME_URL)) {
42.197 @@ -283,7 +312,7 @@
42.198 }
42.199 }
42.200 if (moduleAttrs != null) {
42.201 - doc.addPair(FIELD_MODULE_ATTR_NAME, moduleAttrs, false); // NOI18N
42.202 + doc.addPair(FIELD_MODULE_ATTR_NAME, moduleAttrs, false, true);
42.203 }
42.204
42.205 PythonTree root = PythonAstUtils.getRoot(result);
42.206 @@ -306,7 +335,7 @@
42.207 StringBuilder sig = new StringBuilder();
42.208 sig.append(name);
42.209 appendFlags(sig, 'C', sym, 0);
42.210 - doc.addPair(FIELD_ITEM, sig.toString(), true);
42.211 + doc.addPair(FIELD_ITEM, sig.toString(), true, true);
42.212
42.213 if (sym.node instanceof ClassDef) {
42.214 assert sym.node instanceof ClassDef : sym.node;
42.215 @@ -323,24 +352,24 @@
42.216 assert sym.node instanceof FunctionDef : sym.node;
42.217 FunctionDef def = (FunctionDef)sym.node;
42.218 String sig = computeFunctionSig(name, def, sym);
42.219 - doc.addPair(FIELD_ITEM, sig, true);
42.220 + doc.addPair(FIELD_ITEM, sig, true, true);
42.221 } else if (sym.isImported()) {
42.222 if (!"*".equals(name)) { // NOI18N
42.223 StringBuilder sig = new StringBuilder();
42.224 sig.append(name);
42.225 appendFlags(sig, 'I', sym, 0);
42.226 - doc.addPair(FIELD_ITEM, sig.toString(), true);
42.227 + doc.addPair(FIELD_ITEM, sig.toString(), true, true);
42.228 }
42.229 } else if (sym.isGeneratorExp()) {
42.230 StringBuilder sig = new StringBuilder();
42.231 sig.append(name);
42.232 appendFlags(sig, 'G', sym, 0);
42.233 - doc.addPair(FIELD_ITEM, sig.toString(), true);
42.234 + doc.addPair(FIELD_ITEM, sig.toString(), true, true);
42.235 } else if (sym.isData()) {
42.236 StringBuilder sig = new StringBuilder();
42.237 sig.append(name);
42.238 appendFlags(sig, 'D', sym, 0);
42.239 - doc.addPair(FIELD_ITEM, sig.toString(), true);
42.240 + doc.addPair(FIELD_ITEM, sig.toString(), true, true);
42.241 } else {
42.242 // XXX what the heck is this??
42.243 }
42.244 @@ -351,7 +380,7 @@
42.245
42.246 private void indexClass(String className, SymInfo classSym, ClassDef clz) {
42.247 IndexDocument classDocument = createDocument();
42.248 - classDocument.addPair(FIELD_IN, module, true);
42.249 + classDocument.addPair(FIELD_IN, module, true, true);
42.250
42.251 // Superclass
42.252 List<expr> bases = clz.getInternalBases();
42.253 @@ -359,18 +388,18 @@
42.254 for (expr base : bases) {
42.255 String extendsName = PythonAstUtils.getExprName(base);
42.256 if (extendsName != null) {
42.257 - classDocument.addPair(FIELD_EXTENDS_NAME, extendsName, true);
42.258 + classDocument.addPair(FIELD_EXTENDS_NAME, extendsName, true, true);
42.259 }
42.260 }
42.261 }
42.262
42.263 - classDocument.addPair(FIELD_CLASS_NAME, className, true);
42.264 + classDocument.addPair(FIELD_CLASS_NAME, className, true, true);
42.265
42.266 if (classSym.isPrivate()) {
42.267 // TODO - store Documented, Deprecated, DocOnly, etc.
42.268 - classDocument.addPair(FIELD_CLASS_ATTR_NAME, IndexedElement.encode(IndexedElement.PRIVATE), false);
42.269 + classDocument.addPair(FIELD_CLASS_ATTR_NAME, IndexedElement.encode(IndexedElement.PRIVATE), false, true);
42.270 }
42.271 - classDocument.addPair(FIELD_CASE_INSENSITIVE_CLASS_NAME, className.toLowerCase(), true);
42.272 + classDocument.addPair(FIELD_CASE_INSENSITIVE_CLASS_NAME, className.toLowerCase(), true, true);
42.273
42.274 //Str doc = PythonAstUtils.getDocumentationNode(clz);
42.275 //if (doc != null) {
42.276 @@ -397,7 +426,7 @@
42.277 StringBuilder sig = new StringBuilder();
42.278 sig.append(name);
42.279 appendFlags(sig, 'C', sym, 0);
42.280 - classDocument.addPair(FIELD_ITEM, sig.toString(), true);
42.281 + classDocument.addPair(FIELD_ITEM, sig.toString(), true, true);
42.282
42.283 } else if (sym.isFunction() && sym.node instanceof FunctionDef) {
42.284 if (sym.node instanceof Name) {
42.285 @@ -405,17 +434,17 @@
42.286 }
42.287 FunctionDef def = (FunctionDef)sym.node;
42.288 String sig = computeFunctionSig(name, def, sym);
42.289 - classDocument.addPair(FIELD_MEMBER, sig, true);
42.290 + classDocument.addPair(FIELD_MEMBER, sig, true, true);
42.291 } else if (sym.isData()) {
42.292 StringBuilder sig = new StringBuilder();
42.293 sig.append(name);
42.294 appendFlags(sig, 'D', sym, 0);
42.295 - classDocument.addPair(FIELD_MEMBER, sig.toString(), true);
42.296 + classDocument.addPair(FIELD_MEMBER, sig.toString(), true, true);
42.297 } else if (sym.isMember()) {
42.298 StringBuilder sig = new StringBuilder();
42.299 sig.append(name);
42.300 appendFlags(sig, 'A', sym, 0);
42.301 - classDocument.addPair(FIELD_MEMBER, sig.toString(), true);
42.302 + classDocument.addPair(FIELD_MEMBER, sig.toString(), true, true);
42.303 } else if (!sym.isBound()) {
42.304 continue;
42.305 } else {
42.306 @@ -434,7 +463,7 @@
42.307 StringBuilder sig = new StringBuilder();
42.308 sig.append(name);
42.309 appendFlags(sig, 'C', sym, 0);
42.310 - classDocument.addPair(FIELD_ITEM, sig.toString(), true);
42.311 + classDocument.addPair(FIELD_ITEM, sig.toString(), true, true);
42.312
42.313 } else if (sym.isFunction() && sym.node instanceof FunctionDef) {
42.314 if (sym.node instanceof Name) {
42.315 @@ -442,17 +471,17 @@
42.316 }
42.317 FunctionDef def = (FunctionDef)sym.node;
42.318 String sig = computeFunctionSig(name, def, sym);
42.319 - classDocument.addPair(FIELD_MEMBER, sig, true);
42.320 + classDocument.addPair(FIELD_MEMBER, sig, true, true);
42.321 } else if (sym.isData()) {
42.322 StringBuilder sig = new StringBuilder();
42.323 sig.append(name);
42.324 appendFlags(sig, 'D', sym, 0);
42.325 - classDocument.addPair(FIELD_MEMBER, sig.toString(), true);
42.326 + classDocument.addPair(FIELD_MEMBER, sig.toString(), true, true);
42.327 } else if (sym.isMember()) {
42.328 StringBuilder sig = new StringBuilder();
42.329 sig.append(name);
42.330 appendFlags(sig, 'A', sym, 0);
42.331 - classDocument.addPair(FIELD_MEMBER, sig.toString(), true);
42.332 + classDocument.addPair(FIELD_MEMBER, sig.toString(), true, true);
42.333 } else if (!sym.isBound()) {
42.334 continue;
42.335 } else {
42.336 @@ -466,7 +495,7 @@
42.337
42.338 // TODO - what about nested functions?
42.339 private IndexDocument createDocument() {
42.340 - IndexDocument doc = factory.createDocument(DEFAULT_DOC_SIZE, overrideUrl);
42.341 + IndexDocument doc = support.createDocument(file);
42.342 documents.add(doc);
42.343
42.344 return doc;
42.345 @@ -637,11 +666,11 @@
42.346 }
42.347 }
42.348
42.349 - private List<IndexDocument> scanRst(FileObject fo, IndexDocumentFactory factory, String overrideUrl) {
42.350 + private List<IndexDocument> scanRst(FileObject fo, Indexable indexable, IndexingSupport support, String overrideUrl) {
42.351 List<CachedIndexDocument> documents = new ArrayList<CachedIndexDocument>();
42.352
42.353 List<IndexDocument> docs = new ArrayList<IndexDocument>();
42.354 -
42.355 +
42.356 if (fo != null) {
42.357 String module = fo.getNameExt();
42.358 assert module.endsWith(".rst"); // NOI18N
42.359 @@ -1079,10 +1108,11 @@
42.360 // because I want to modify the documents after adding documents and pairs.
42.361 for (CachedIndexDocument cid : documents) {
42.362 List<CachedIndexDocumentEntry> entries = cid.entries;
42.363 - IndexDocument indexedDoc = factory.createDocument(entries.size(), overrideUrl);
42.364 + IndexDocument indexedDoc = support.createDocument(indexable);
42.365 +// IndexDocument indexedDoc = support.createDocument(entries.size(), overrideUrl);
42.366 docs.add(indexedDoc);
42.367 for (CachedIndexDocumentEntry entry : entries) {
42.368 - indexedDoc.addPair(entry.key, entry.value, entry.index);
42.369 + indexedDoc.addPair(entry.key, entry.value, true, true); // XXX indexable and stored ???
42.370 }
42.371 }
42.372 }
42.373 @@ -1274,22 +1304,19 @@
42.374 }
42.375 }
42.376
42.377 - private List<IndexDocument> scanEgg(ParserResult result, IndexDocumentFactory factory) {
42.378 + private List<IndexDocument> scanEgg(FileObject fo, Indexable indexable, ParserResult result, IndexingSupport support) {
42.379 List<IndexDocument> documents = new ArrayList<IndexDocument>();
42.380
42.381 - FileObject fo = result.getFile().getFileObject();
42.382 if (fo == null) {
42.383 return documents;
42.384 }
42.385
42.386 try {
42.387 - String s = fo.getURL().toExternalForm() + "!"; // NOI18N
42.388 + String s = fo.toURL().toExternalForm() + "!"; // NOI18N
42.389 URL u = new URL("jar:" + s); // NOI18N
42.390 FileObject root = URLMapper.findFileObject(u);
42.391 String rootUrl = PythonIndex.getPreindexUrl(u.toExternalForm());
42.392 - indexScriptDocRecursively(factory, documents, root, rootUrl);
42.393 - } catch (FileStateInvalidException ex) {
42.394 - Exceptions.printStackTrace(ex);
42.395 + indexScriptDocRecursively(support, documents, root, rootUrl);
42.396 } catch (MalformedURLException ex) {
42.397 Exceptions.printStackTrace(ex);
42.398 }
42.399 @@ -1301,46 +1328,46 @@
42.400 * Method which recursively indexes directory trees, such as the yui/ folder
42.401 * for example
42.402 */
42.403 - private void indexScriptDocRecursively(IndexDocumentFactory factory, List<IndexDocument> documents, final FileObject fo, String url) {
42.404 + private void indexScriptDocRecursively(IndexingSupport support, List<IndexDocument> documents, final FileObject fo, String url) {
42.405 if (fo.isFolder()) {
42.406 for (FileObject c : fo.getChildren()) {
42.407 - indexScriptDocRecursively(factory, documents, c, url + "/" + c.getNameExt()); // NOI18N
42.408 + indexScriptDocRecursively(support, documents, c, url + "/" + c.getNameExt()); // NOI18N
42.409 }
42.410 return;
42.411 }
42.412
42.413 String ext = fo.getExt();
42.414
42.415 - if ("py".equals(ext)) { // NOI18N
42.416 - DefaultParseListener listener = new DefaultParseListener();
42.417 - List<ParserFile> files = Collections.<ParserFile>singletonList(new DefaultParserFile(fo, null, false));
42.418 - SourceFileReader reader = new SourceFileReader() {
42.419 - public CharSequence read(ParserFile file) throws IOException {
42.420 - BaseDocument doc = GsfUtilities.getDocument(fo, true);
42.421 - if (doc != null) {
42.422 - try {
42.423 - return doc.getText(0, doc.getLength());
42.424 - } catch (BadLocationException ex) {
42.425 - Exceptions.printStackTrace(ex);
42.426 - }
42.427 - }
42.428 -
42.429 - return "";
42.430 - }
42.431 -
42.432 - public int getCaretOffset(ParserFile file) {
42.433 - return -1;
42.434 - }
42.435 - };
42.436 - Job job = new Job(files, listener, reader, null);
42.437 - new PythonParser().parseFiles(job);
42.438 - ParserResult parserResult = listener.getParserResult();
42.439 - if (parserResult != null && parserResult.isValid()) {
42.440 - documents.addAll(new IndexTask((PythonParserResult)parserResult, factory, url).scan());
42.441 - }
42.442 - } else if ("rst".equals(ext)) { // NOI18N
42.443 - documents.addAll(scanRst(fo, factory, url));
42.444 - }
42.445 +// if ("py".equals(ext)) { // NOI18N
42.446 +// DefaultParseListener listener = new DefaultParseListener();
42.447 +// List<ParserFile> files = Collections.<ParserFile>singletonList(new DefaultParserFile(fo, null, false));
42.448 +// SourceFileReader reader = new SourceFileReader() {
42.449 +// public CharSequence read(ParserFile file) throws IOException {
42.450 +// BaseDocument doc = GsfUtilities.getDocument(fo, true);
42.451 +// if (doc != null) {
42.452 +// try {
42.453 +// return doc.getText(0, doc.getLength());
42.454 +// } catch (BadLocationException ex) {
42.455 +// Exceptions.printStackTrace(ex);
42.456 +// }
42.457 +// }
42.458 +//
42.459 +// return "";
42.460 +// }
42.461 +//
42.462 +// public int getCaretOffset(ParserFile file) {
42.463 +// return -1;
42.464 +// }
42.465 +// };
42.466 +// Job job = new Job(files, listener, reader, null);
42.467 +// new PythonParser().parseFiles(job);
42.468 +// ParserResult parserResult = listener.getParserResult();
42.469 +// if (parserResult != null && parserResult.isValid()) {
42.470 +// documents.addAll(new IndexTask((PythonParserResult)parserResult, support, url).scan());
42.471 +// }
42.472 +// } else if ("rst".equals(ext)) { // NOI18N
42.473 +// documents.addAll(scanRst(fo, support, url));
42.474 +// }
42.475 }
42.476
42.477 private FileObject getLibDir() {
43.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
43.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonIndexerFactory.java Sat Feb 28 17:25:32 2015 -0800
43.3 @@ -0,0 +1,47 @@
43.4 +/*
43.5 + * To change this license header, choose License Headers in Project Properties.
43.6 + * To change this template file, choose Tools | Templates
43.7 + * and open the template in the editor.
43.8 + */
43.9 +package org.netbeans.modules.python.editor;
43.10 +
43.11 +import org.netbeans.modules.parsing.api.Snapshot;
43.12 +import org.netbeans.modules.parsing.spi.indexing.Context;
43.13 +import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexer;
43.14 +import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexerFactory;
43.15 +import org.netbeans.modules.parsing.spi.indexing.Indexable;
43.16 +
43.17 +/**
43.18 + *
43.19 + * @author Ralph Benjamin Ruijs
43.20 + */
43.21 +public class PythonIndexerFactory extends EmbeddingIndexerFactory {
43.22 +
43.23 + @Override
43.24 + public EmbeddingIndexer createIndexer(Indexable indexable, Snapshot snapshot) {
43.25 + if(PythonIndexer.isIndexable(indexable, snapshot)) {
43.26 + return new PythonIndexer();
43.27 + }
43.28 + return null;
43.29 + }
43.30 +
43.31 + @Override
43.32 + public void filesDeleted(Iterable<? extends Indexable> indexables, Context context) {
43.33 +// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
43.34 + }
43.35 +
43.36 + @Override
43.37 + public void filesDirty(Iterable<? extends Indexable> arg0, Context arg1) {
43.38 +// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
43.39 + }
43.40 +
43.41 + @Override
43.42 + public String getIndexerName() {
43.43 + return PythonIndexer.NAME;
43.44 + }
43.45 +
43.46 + @Override
43.47 + public int getIndexVersion() {
43.48 + return PythonIndexer.VERSION;
43.49 + }
43.50 +}
44.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonInstantRename.java Sun Jan 04 13:11:53 2015 -0600
44.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonInstantRename.java Sat Feb 28 17:25:32 2015 -0800
44.3 @@ -36,9 +36,9 @@
44.4 import org.netbeans.api.lexer.Token;
44.5 import org.netbeans.api.lexer.TokenSequence;
44.6 import org.netbeans.editor.BaseDocument;
44.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
44.8 -import org.netbeans.modules.gsf.api.InstantRenamer;
44.9 -import org.netbeans.modules.gsf.api.OffsetRange;
44.10 +import org.netbeans.modules.csl.api.InstantRenamer;
44.11 +import org.netbeans.modules.csl.api.OffsetRange;
44.12 +import org.netbeans.modules.csl.spi.ParserResult;
44.13 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
44.14 import org.netbeans.modules.python.editor.lexer.PythonCommentTokenId;
44.15 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
44.16 @@ -54,7 +54,8 @@
44.17 * @author Tor Norbye
44.18 */
44.19 public class PythonInstantRename implements InstantRenamer {
44.20 - public boolean isRenameAllowed(CompilationInfo info, int caretOffset, String[] explanationRetValue) {
44.21 +
44.22 + public boolean isRenameAllowed(ParserResult info, int caretOffset, String[] explanationRetValue) {
44.23 if (findVarName(info, caretOffset) != null) {
44.24 return true;
44.25 }
44.26 @@ -79,8 +80,8 @@
44.27 return false;
44.28 }
44.29
44.30 - private TokenSequence<PythonCommentTokenId> findVarName(CompilationInfo info, int caretOffset) {
44.31 - Document document = info.getDocument();
44.32 + private TokenSequence<PythonCommentTokenId> findVarName(ParserResult info, int caretOffset) {
44.33 + Document document = info.getSnapshot().getSource().getDocument(false);
44.34 if (document != null) {
44.35 BaseDocument doc = (BaseDocument)document;
44.36 TokenSequence<? extends PythonTokenId> ts = PythonLexerUtils.getPositionedSequence(doc, caretOffset);
44.37 @@ -106,12 +107,12 @@
44.38 return null;
44.39 }
44.40
44.41 - public Set<OffsetRange> getRenameRegions(CompilationInfo info, int caretOffset) {
44.42 + public Set<OffsetRange> getRenameRegions(ParserResult info, int caretOffset) {
44.43 TokenSequence<PythonCommentTokenId> embedded = findVarName(info, caretOffset);
44.44 if (embedded != null) {
44.45 Token<PythonCommentTokenId> token = embedded.token();
44.46 String name = token.text().toString();
44.47 - Set<OffsetRange> offsets = PythonAstUtils.getAllOffsets(info, null, caretOffset, name, true);
44.48 + Set<OffsetRange> offsets = PythonAstUtils.getAllOffsets((PythonParserResult) info, null, caretOffset, name, true);
44.49 if (offsets != null) {
44.50 return offsets;
44.51 }
44.52 @@ -127,7 +128,7 @@
44.53 String name = null;
44.54 if (leaf instanceof Name) {
44.55 name = ((Name)leaf).getInternalId();
44.56 - Set<OffsetRange> offsets = PythonAstUtils.getAllOffsets(info, path, caretOffset, name, true);
44.57 + Set<OffsetRange> offsets = PythonAstUtils.getAllOffsets((PythonParserResult) info, path, caretOffset, name, true);
44.58 if (offsets != null) {
44.59 return offsets;
44.60 }
45.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonKeystrokeHandler.java Sun Jan 04 13:11:53 2015 -0600
45.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonKeystrokeHandler.java Sat Feb 28 17:25:32 2015 -0800
45.3 @@ -44,12 +44,13 @@
45.4 import org.netbeans.api.lexer.TokenSequence;
45.5 import org.netbeans.editor.BaseDocument;
45.6 import org.netbeans.editor.Utilities;
45.7 +import org.netbeans.modules.csl.api.EditorOptions;
45.8 +import org.netbeans.modules.csl.api.KeystrokeHandler;
45.9 +import org.netbeans.modules.csl.api.OffsetRange;
45.10 +import org.netbeans.modules.csl.spi.GsfUtilities;
45.11 +import org.netbeans.modules.csl.spi.ParserResult;
45.12 import org.netbeans.modules.editor.indent.api.IndentUtils;
45.13 -import org.netbeans.modules.gsf.api.CompilationInfo;
45.14 -import org.netbeans.modules.gsf.api.EditorOptions;
45.15 -import org.netbeans.modules.gsf.api.KeystrokeHandler;
45.16 -import org.netbeans.modules.gsf.api.OffsetRange;
45.17 -import org.netbeans.modules.gsf.spi.GsfUtilities;
45.18 +import org.netbeans.modules.python.api.PythonMIMEResolver;
45.19 import org.openide.util.Exceptions;
45.20 import org.python.antlr.PythonTree;
45.21
45.22 @@ -260,7 +261,7 @@
45.23 // The editor options code is calling methods on BaseOptions instead of looking in the settings map :(
45.24 //Boolean b = ((Boolean)Settings.getValue(doc.getKitClass(), SettingsNames.PAIR_CHARACTERS_COMPLETION));
45.25 //return b == null || b.booleanValue();
45.26 - EditorOptions options = EditorOptions.get(PythonTokenId.PYTHON_MIME_TYPE);
45.27 + EditorOptions options = EditorOptions.get(PythonMIMEResolver.PYTHON_MIME_TYPE);
45.28 if (options != null) {
45.29 return options.getMatchBrackets();
45.30 }
45.31 @@ -1259,7 +1260,7 @@
45.32 }
45.33 }
45.34
45.35 - public List<OffsetRange> findLogicalRanges(CompilationInfo info, int caretOffset) {
45.36 + public List<OffsetRange> findLogicalRanges(ParserResult info, int caretOffset) {
45.37 PythonTree root = PythonAstUtils.getRoot(info);
45.38 if (root != null) {
45.39 List<OffsetRange> ranges = new ArrayList<OffsetRange>();
45.40 @@ -1267,7 +1268,7 @@
45.41 OffsetRange prevRange = OffsetRange.NONE;
45.42 for (PythonTree node : path) {
45.43 OffsetRange astRange = PythonAstUtils.getRange(node);
45.44 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(info, astRange);
45.45 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets((PythonParserResult) info, astRange);
45.46 if (lexRange != OffsetRange.NONE) {
45.47 if (prevRange == OffsetRange.NONE ||
45.48 prevRange.getStart() > lexRange.getStart() ||
45.49 @@ -1278,7 +1279,7 @@
45.50 }
45.51 }
45.52
45.53 - int docLength = info.getDocument().getLength();
45.54 + int docLength = info.getSnapshot().getSource().getDocument(false).getLength();
45.55 if (prevRange == OffsetRange.NONE || prevRange.getStart() > 0 ||
45.56 prevRange.getEnd() < docLength) {
45.57 ranges.add(new OffsetRange(0, docLength));
46.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonLanguage.java Sun Jan 04 13:11:53 2015 -0600
46.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonLanguage.java Sat Feb 28 17:25:32 2015 -0800
46.3 @@ -31,24 +31,24 @@
46.4 package org.netbeans.modules.python.editor;
46.5
46.6 import java.io.File;
46.7 -import java.util.Collection;
46.8 -import java.util.Collections;
46.9 import org.netbeans.modules.python.editor.hints.PythonHintsProvider;
46.10 import org.netbeans.api.lexer.Language;
46.11 +import org.netbeans.modules.csl.api.CodeCompletionHandler;
46.12 +import org.netbeans.modules.csl.api.DeclarationFinder;
46.13 +import org.netbeans.modules.csl.api.Formatter;
46.14 +import org.netbeans.modules.csl.api.HintsProvider;
46.15 +import org.netbeans.modules.csl.api.IndexSearcher;
46.16 +import org.netbeans.modules.csl.api.InstantRenamer;
46.17 +import org.netbeans.modules.csl.api.KeystrokeHandler;
46.18 +import org.netbeans.modules.csl.api.OccurrencesFinder;
46.19 +import org.netbeans.modules.csl.api.SemanticAnalyzer;
46.20 +import org.netbeans.modules.csl.api.StructureScanner;
46.21 +import org.netbeans.modules.csl.spi.DefaultLanguageConfig;
46.22 +import org.netbeans.modules.csl.spi.LanguageRegistration;
46.23 +import org.netbeans.modules.parsing.spi.Parser;
46.24 +import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexerFactory;
46.25 +import org.netbeans.modules.python.api.PythonMIMEResolver;
46.26 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
46.27 -import org.netbeans.modules.gsf.api.CodeCompletionHandler;
46.28 -import org.netbeans.modules.gsf.api.DeclarationFinder;
46.29 -import org.netbeans.modules.gsf.api.Formatter;
46.30 -import org.netbeans.modules.gsf.api.HintsProvider;
46.31 -import org.netbeans.modules.gsf.api.IndexSearcher;
46.32 -import org.netbeans.modules.gsf.api.Indexer;
46.33 -import org.netbeans.modules.gsf.api.InstantRenamer;
46.34 -import org.netbeans.modules.gsf.api.KeystrokeHandler;
46.35 -import org.netbeans.modules.gsf.api.OccurrencesFinder;
46.36 -import org.netbeans.modules.gsf.api.Parser;
46.37 -import org.netbeans.modules.gsf.api.SemanticAnalyzer;
46.38 -import org.netbeans.modules.gsf.api.StructureScanner;
46.39 -import org.netbeans.modules.gsf.spi.DefaultLanguageConfig;
46.40 import org.openide.filesystems.FileObject;
46.41 import org.openide.filesystems.FileUtil;
46.42 import org.openide.modules.InstalledFileLocator;
46.43 @@ -58,6 +58,7 @@
46.44 * @author alley
46.45 * @author Tor Norbye
46.46 */
46.47 +@LanguageRegistration(mimeType=PythonMIMEResolver.PYTHON_MIME_TYPE)
46.48 public class PythonLanguage extends DefaultLanguageConfig {
46.49 private static FileObject jsStubsFO;
46.50
46.51 @@ -74,10 +75,12 @@
46.52 c == '_';
46.53 }
46.54
46.55 + @Override
46.56 public Language getLexerLanguage() {
46.57 return PythonTokenId.language();
46.58 }
46.59
46.60 + @Override
46.61 public String getDisplayName() {
46.62 return "Python";
46.63 }
46.64 @@ -107,7 +110,7 @@
46.65 public SemanticAnalyzer getSemanticAnalyzer() {
46.66 return new PythonSemanticHighlighter();
46.67 }
46.68 -
46.69 +
46.70 @Override
46.71 public KeystrokeHandler getKeystrokeHandler() {
46.72 return new PythonKeystrokeHandler();
46.73 @@ -134,8 +137,8 @@
46.74 }
46.75
46.76 @Override
46.77 - public Indexer getIndexer() {
46.78 - return new PythonIndexer();
46.79 + public EmbeddingIndexerFactory getIndexerFactory() {
46.80 + return new PythonIndexerFactory();
46.81 }
46.82
46.83 @Override
46.84 @@ -168,12 +171,6 @@
46.85 return new PythonFormatter();
46.86 }
46.87
46.88 - @Override
46.89 - public Collection<FileObject> getCoreLibraries() {
46.90 - return Collections.singletonList(getPythonStubs());
46.91 - }
46.92 -
46.93 -
46.94 // TODO - add classpath recognizer for these ? No, don't need go to declaration inside these files...
46.95 public static FileObject getPythonStubs() {
46.96 if (jsStubsFO == null) {
47.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonOccurrencesMarker.java Sun Jan 04 13:11:53 2015 -0600
47.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonOccurrencesMarker.java Sat Feb 28 17:25:32 2015 -0800
47.3 @@ -43,10 +43,13 @@
47.4 import org.netbeans.api.lexer.TokenSequence;
47.5 import org.netbeans.editor.BaseDocument;
47.6 import org.netbeans.editor.Utilities;
47.7 -import org.netbeans.modules.gsf.api.ColoringAttributes;
47.8 -import org.netbeans.modules.gsf.api.CompilationInfo;
47.9 -import org.netbeans.modules.gsf.api.OccurrencesFinder;
47.10 -import org.netbeans.modules.gsf.api.OffsetRange;
47.11 +import org.netbeans.modules.csl.api.ColoringAttributes;
47.12 +import org.netbeans.modules.csl.api.OccurrencesFinder;
47.13 +import org.netbeans.modules.csl.api.OffsetRange;
47.14 +import org.netbeans.modules.csl.spi.ParserResult;
47.15 +import org.netbeans.modules.parsing.spi.Parser.Result;
47.16 +import org.netbeans.modules.parsing.spi.Scheduler;
47.17 +import org.netbeans.modules.parsing.spi.SchedulerEvent;
47.18 import org.netbeans.modules.python.editor.lexer.PythonCommentTokenId;
47.19 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
47.20 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
47.21 @@ -69,7 +72,7 @@
47.22 *
47.23 * @author Tor Norbye
47.24 */
47.25 -public class PythonOccurrencesMarker implements OccurrencesFinder {
47.26 +public class PythonOccurrencesMarker extends OccurrencesFinder<PythonParserResult> {
47.27 private boolean cancelled;
47.28 private int caretPosition;
47.29 private Map<OffsetRange, ColoringAttributes> occurrences;
47.30 @@ -99,23 +102,30 @@
47.31 this.caretPosition = position;
47.32 }
47.33
47.34 - public void run(CompilationInfo info) {
47.35 + @Override
47.36 + public int getPriority() {
47.37 + return 0;
47.38 + }
47.39 +
47.40 + @Override
47.41 + public Class<? extends Scheduler> getSchedulerClass() {
47.42 + return Scheduler.CURSOR_SENSITIVE_TASK_SCHEDULER;
47.43 + }
47.44 +
47.45 + @Override
47.46 + public void run(PythonParserResult info, SchedulerEvent event) {
47.47 resume();
47.48
47.49 if (isCancelled()) {
47.50 return;
47.51 }
47.52
47.53 - PythonParserResult ppr = PythonAstUtils.getParseResult(info);
47.54 - if (ppr == null) {
47.55 - return;
47.56 - }
47.57 - PythonTree root = PythonAstUtils.getRoot(ppr);
47.58 + PythonTree root = PythonAstUtils.getRoot(info);
47.59 if (root == null) {
47.60 return;
47.61 }
47.62
47.63 - int astOffset = PythonAstUtils.getAstOffset(info, caretPosition);
47.64 + int astOffset = PythonAstUtils.getAstOffset((ParserResult) info, caretPosition);
47.65 if (astOffset == -1) {
47.66 return;
47.67 }
47.68 @@ -126,13 +136,13 @@
47.69 return;
47.70 }
47.71 PythonTree closest = path.leaf();
47.72 - OffsetRange blankRange = ppr.getSanitizedRange();
47.73 + OffsetRange blankRange = info.getSanitizedRange();
47.74
47.75 if (blankRange.containsInclusive(astOffset)) {
47.76 closest = null;
47.77 }
47.78
47.79 - Document document = info.getDocument();
47.80 + Document document = info.getSnapshot().getSource().getDocument(false);
47.81 if (document == null) {
47.82 return;
47.83 }
47.84 @@ -155,7 +165,7 @@
47.85 if (id == PythonCommentTokenId.VARNAME) {
47.86 String name = token.text().toString();
47.87
47.88 - offsets = findNames(ppr, path, name, info, offsets);
47.89 + offsets = findNames(info, path, name, offsets);
47.90
47.91 int start = embedded.offset();
47.92 offsets.add(new OffsetRange(start, start + name.length()));
47.93 @@ -184,13 +194,13 @@
47.94 //addNodes(scopeNode != null ? scopeNode : root, name, highlights);
47.95 //closest = null;
47.96 String name = ((Name)closest).getInternalId();
47.97 - offsets = findNames(ppr, path, name, info, offsets);
47.98 + offsets = findNames(info, path, name, offsets);
47.99 } else if (closest instanceof Attribute) {
47.100 Attribute attr = (Attribute)closest;
47.101 offsets = findSameAttributes(info, root, attr);
47.102 } else if (closest instanceof Import || closest instanceof ImportFrom) {
47.103 // Try to find occurrences of an imported symbol
47.104 - offsets = findNameFromImport(caretPosition, ppr, path, info, offsets);
47.105 + offsets = findNameFromImport(caretPosition, info, path, offsets);
47.106 } else if ((closest instanceof FunctionDef || closest instanceof ClassDef) &&
47.107 PythonAstUtils.getNameRange(null, closest).containsInclusive(astOffset)) {
47.108 String name;
47.109 @@ -200,7 +210,7 @@
47.110 assert closest instanceof ClassDef;
47.111 name = ((ClassDef)closest).getInternalName();
47.112 }
47.113 - offsets = findNames(ppr, path, name, info, offsets);
47.114 + offsets = findNames(info, path, name, offsets);
47.115
47.116 if (offsets == null || offsets.size() == 0) {
47.117 if (closest instanceof FunctionDef) {
47.118 @@ -236,7 +246,7 @@
47.119 }
47.120 }
47.121 if (nearest != null) {
47.122 - OffsetRange range = PythonAstUtils.getNameRange(info, nearest);
47.123 + OffsetRange range = PythonAstUtils.getNameRange((PythonParserResult) info, nearest);
47.124 if (!range.containsInclusive(astOffset)) {
47.125 nearest = null;
47.126 }
47.127 @@ -300,9 +310,9 @@
47.128 private final FunctionDef def;
47.129 private final String name;
47.130 private final Set<OffsetRange> ranges = new HashSet<OffsetRange>();
47.131 - private final CompilationInfo info;
47.132 + private final PythonParserResult info;
47.133
47.134 - CallVisitor(CompilationInfo info, FunctionDef def, Call call) {
47.135 + CallVisitor(PythonParserResult info, FunctionDef def, Call call) {
47.136 this.info = info;
47.137 this.def = def;
47.138 this.call = call;
47.139 @@ -343,8 +353,8 @@
47.140 }
47.141 }
47.142
47.143 - private Set<OffsetRange> findNameFromImport(int lexOffset, PythonParserResult ppr, AstPath path, CompilationInfo info, Set<OffsetRange> offsets) {
47.144 - BaseDocument doc = (BaseDocument)info.getDocument();
47.145 + private Set<OffsetRange> findNameFromImport(int lexOffset, PythonParserResult ppr, AstPath path, Set<OffsetRange> offsets) {
47.146 + BaseDocument doc = (BaseDocument)ppr.getSnapshot().getSource().getDocument(false);
47.147 try {
47.148 doc.readLock();
47.149 String identifier = Utilities.getIdentifier(doc, lexOffset);
47.150 @@ -358,7 +368,7 @@
47.151 // TODO - determine if you're hovering over a whole module name instead of an imported
47.152 // symbol, and if so, work a bit harder...
47.153 if (identifier.length() > 0) {
47.154 - return findNames(ppr, path, identifier, info, offsets);
47.155 + return findNames(ppr, path, identifier, offsets);
47.156 }
47.157 } catch (BadLocationException ex) {
47.158 Exceptions.printStackTrace(ex);
47.159 @@ -369,12 +379,12 @@
47.160 return null;
47.161 }
47.162
47.163 - private Set<OffsetRange> findNames(PythonParserResult ppr, AstPath path, String name, CompilationInfo info, Set<OffsetRange> offsets) {
47.164 + private Set<OffsetRange> findNames(PythonParserResult ppr, AstPath path, String name, Set<OffsetRange> offsets) {
47.165 //offsets = PythonAstUtils.getLocalVarOffsets(info, scope, name);
47.166 - return PythonAstUtils.getAllOffsets(info, path, caretPosition, name, false);
47.167 + return PythonAstUtils.getAllOffsets(ppr, path, caretPosition, name, false);
47.168 }
47.169
47.170 - private Set<OffsetRange> findSameAttributes(CompilationInfo info, PythonTree root, Attribute attr) {
47.171 + private Set<OffsetRange> findSameAttributes(PythonParserResult info, PythonTree root, Attribute attr) {
47.172 List<PythonTree> result = new ArrayList<PythonTree>();
47.173 PythonAstUtils.addNodesByType(root, new Class[]{Attribute.class}, result);
47.174
47.175 @@ -397,7 +407,7 @@
47.176 OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(info, astRange);
47.177 if (name != null && (node instanceof Import || node instanceof ImportFrom)) {
47.178 // Try to find the exact spot
47.179 - lexRange = PythonLexerUtils.getImportNameOffset((BaseDocument)info.getDocument(), lexRange, node, name);
47.180 + lexRange = PythonLexerUtils.getImportNameOffset((BaseDocument)info.getSnapshot().getSource().getDocument(false), lexRange, node, name);
47.181 }
47.182 if (lexRange != OffsetRange.NONE) {
47.183 offsets.add(lexRange);
48.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonParser.java Sun Jan 04 13:11:53 2015 -0600
48.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonParser.java Sat Feb 28 17:25:32 2015 -0800
48.3 @@ -34,10 +34,20 @@
48.4 import java.io.InputStreamReader;
48.5 import java.util.ArrayList;
48.6 import java.util.List;
48.7 -import java.util.Properties;
48.8 import java.util.logging.Level;
48.9 import java.util.logging.Logger;
48.10 +import javax.swing.event.ChangeListener;
48.11 import javax.swing.text.BadLocationException;
48.12 +import org.netbeans.modules.csl.api.Severity;
48.13 +import org.netbeans.modules.csl.spi.DefaultError;
48.14 +import org.netbeans.modules.csl.api.Error;
48.15 +import org.netbeans.modules.csl.api.OffsetRange;
48.16 +import org.netbeans.modules.csl.spi.GsfUtilities;
48.17 +import org.netbeans.modules.parsing.api.Snapshot;
48.18 +import org.netbeans.modules.parsing.api.Task;
48.19 +import org.netbeans.modules.parsing.spi.Parser;
48.20 +import org.netbeans.modules.parsing.spi.SourceModificationEvent;
48.21 +import org.openide.filesystems.FileObject;
48.22 import org.python.antlr.runtime.ANTLRStringStream;
48.23 import org.python.antlr.runtime.BaseRecognizer;
48.24 import org.python.antlr.runtime.BitSet;
48.25 @@ -47,19 +57,7 @@
48.26 import org.python.antlr.runtime.Lexer;
48.27 import org.python.antlr.runtime.MismatchedTokenException;
48.28 import org.python.antlr.runtime.RecognitionException;
48.29 -import org.netbeans.modules.gsf.api.Error;
48.30 -import org.netbeans.modules.gsf.api.OffsetRange;
48.31 -import org.netbeans.modules.gsf.api.Parser;
48.32 -import org.netbeans.modules.gsf.api.PositionManager;
48.33
48.34 -import org.netbeans.modules.gsf.api.ParseEvent;
48.35 -import org.netbeans.modules.gsf.api.ParseListener;
48.36 -import org.netbeans.modules.gsf.api.ParserFile;
48.37 -import org.netbeans.modules.gsf.api.Severity;
48.38 -import org.netbeans.modules.gsf.api.SourceFileReader;
48.39 -import org.netbeans.modules.gsf.api.TranslatedSource;
48.40 -import org.netbeans.modules.gsf.spi.DefaultError;
48.41 -import org.netbeans.modules.gsf.spi.GsfUtilities;
48.42 import org.openide.filesystems.FileUtil;
48.43 import org.openide.util.Exceptions;
48.44 import org.python.antlr.BaseParser;
48.45 @@ -82,13 +80,15 @@
48.46 * @author Frank Wierzbicki
48.47 * @author Tor Norbye
48.48 */
48.49 -public class PythonParser implements Parser {
48.50 +public class PythonParser extends Parser {
48.51 /** For unit tests such that they can make sure we didn't have a parser abort */
48.52 static Throwable runtimeException;
48.53
48.54 static {
48.55 org.python.core.PySystemState.initialize();
48.56 }
48.57 +
48.58 + private Result lastResult;
48.59
48.60 public mod file_input(CharStream charStream, String fileName) throws RecognitionException {
48.61 ListErrorHandler eh = new ListErrorHandler();
48.62 @@ -107,12 +107,41 @@
48.63 return tree;
48.64 }
48.65
48.66 + @Override
48.67 + public void addChangeListener(ChangeListener changeListener) {}
48.68 +
48.69 + @Override
48.70 + public void removeChangeListener(ChangeListener changeListener) {}
48.71 +
48.72 public PythonTree parse(InputStream istream, String fileName) throws Exception {
48.73 InputStreamReader reader = new InputStreamReader(istream, "ISO-8859-1");
48.74 return file_input(new ANTLRReaderStream(reader), fileName);
48.75 }
48.76 +
48.77 + @Override
48.78 + public final Result getResult(Task task) throws org.netbeans.modules.parsing.spi.ParseException {
48.79 + return lastResult;
48.80 + }
48.81 +
48.82 + private static final Logger LOG = Logger.getLogger(PythonParser.class.getName());
48.83
48.84 - public PythonParserResult parse(final Context context, Sanitize sanitizing) throws Exception {
48.85 + @Override
48.86 + public void parse(Snapshot snapshot, Task task, SourceModificationEvent event) throws org.netbeans.modules.parsing.spi.ParseException {
48.87 + Context context = new Context();
48.88 + context.snapshot = snapshot;
48.89 + context.event = event;
48.90 + context.task = task;
48.91 + context.caretOffset = GsfUtilities.getLastKnownCaretOffset(snapshot, event);
48.92 + context.source = snapshot.getText().toString();
48.93 + context.file = snapshot.getSource().getFileObject();
48.94 + /* Let's not sanitize ;-) Would be great if we could have a more robust parser
48.95 + if (context.caretOffset != -1) {
48.96 + context.sanitized = Sanitize.EDITED_DOT;
48.97 + }
48.98 + */
48.99 + lastResult = parse(context, context.sanitized);
48.100 + }
48.101 + public PythonParserResult parse(final Context context, Sanitize sanitizing) {
48.102 boolean sanitizedSource = false;
48.103 String sourceCode = context.source;
48.104 if (!((sanitizing == Sanitize.NONE) || (sanitizing == Sanitize.NEVER))) {
48.105 @@ -134,7 +163,7 @@
48.106 }
48.107
48.108 final List<Error> errors = new ArrayList<Error>();
48.109 - final ParserFile file = context.file;
48.110 + final FileObject file = context.file;
48.111 try {
48.112 String fileName = file.getNameExt();
48.113 // TODO - sniff file headers etc. Frank's comment:
48.114 @@ -151,7 +180,7 @@
48.115 ListErrorHandler errorHandler = new ListErrorHandler() {
48.116 @Override
48.117 public void error(String message, PythonTree t) {
48.118 - errors.add(new DefaultError(null, message, null, file.getFileObject(), t.getCharStartIndex(), t.getCharStopIndex(), Severity.ERROR));
48.119 + errors.add(new DefaultError(null, message, null, file, t.getCharStartIndex(), t.getCharStopIndex(), Severity.ERROR));
48.120 super.error(message, t);
48.121 }
48.122
48.123 @@ -191,7 +220,7 @@
48.124 }
48.125 int start = lineOffset;//t.getCharStartIndex();
48.126 int stop = lineOffset;//t.getCharStopIndex();
48.127 - errors.add(new DefaultError(null, message, null, file.getFileObject(), start, stop, Severity.ERROR));
48.128 + errors.add(new DefaultError(null, message, null, file, start, stop, Severity.ERROR));
48.129 }
48.130 return super.recoverFromMismatchedToken(br, input, ttype, follow);
48.131 }
48.132 @@ -255,7 +284,7 @@
48.133 end = start;
48.134 }
48.135
48.136 - errors.add(new DefaultError(null, message, null, file.getFileObject(), start, end, Severity.ERROR));
48.137 + errors.add(new DefaultError(null, message, null, file, start, end, Severity.ERROR));
48.138
48.139 super.reportError(br, re);
48.140 }
48.141 @@ -267,16 +296,14 @@
48.142 CommonTokenStream tokens = new CommonTokenStream(lexer);
48.143 tokens.discardOffChannelTokens(true);
48.144 PythonTokenSource indentedSource = new PythonTokenSource(tokens, fileName);
48.145 - tokens = new CommonTokenStream(indentedSource);
48.146 - org.python.antlr.PythonParser parser = new org.python.antlr.PythonParser(tokens);
48.147 + CommonTokenStream indentedTokens = new CommonTokenStream(indentedSource);
48.148 + org.python.antlr.PythonParser parser = new org.python.antlr.PythonParser(indentedTokens);
48.149 parser.setTreeAdaptor(new PythonTreeAdaptor());
48.150 parser.setErrorHandler(errorHandler);
48.151 org.python.antlr.PythonParser.file_input_return r = parser.file_input();
48.152 PythonTree t = (PythonTree)r.getTree();
48.153 - PythonParserResult result = createParseResult(t, file, true);
48.154 - for (Error error : errors) {
48.155 - result.addError(error);
48.156 - }
48.157 + PythonParserResult result = new PythonParserResult(t, context.snapshot);
48.158 + result.setErrors(errors);
48.159
48.160 result.setSanitized(context.sanitized, context.sanitizedRange, context.sanitizedContents);
48.161 result.setSource(sourceCode);
48.162 @@ -294,8 +321,8 @@
48.163 if (desc == null) {
48.164 desc = pe.getMessage();
48.165 }
48.166 - DefaultError error = new DefaultError(null /*key*/, desc, null, file.getFileObject(), offset, offset, Severity.ERROR);
48.167 - PythonParserResult parserResult = createParseResult(null, file, false);
48.168 + DefaultError error = new DefaultError(null /*key*/, desc, null, file, offset, offset, Severity.ERROR);
48.169 + PythonParserResult parserResult = new PythonParserResult(null, context.snapshot);
48.170 parserResult.addError(error);
48.171 for (Error e : errors) {
48.172 parserResult.addError(e);
48.173 @@ -308,23 +335,24 @@
48.174 }
48.175 } catch (NullPointerException e) {
48.176 String fileName = "";
48.177 - if (file.getFileObject() != null) {
48.178 - fileName = FileUtil.getFileDisplayName(file.getFileObject());
48.179 + if (file != null) {
48.180 + fileName = FileUtil.getFileDisplayName(file);
48.181 }
48.182 - Exceptions.attachMessage(e, "Was parsing " + fileName);
48.183 - return createParseResult(null, file, false);
48.184 + e = Exceptions.attachMessage(e, "Was parsing " + fileName);
48.185 + Exceptions.printStackTrace(e);
48.186 + return new PythonParserResult(null, context.snapshot);
48.187 } catch (Throwable t) {
48.188 runtimeException = t;
48.189 StackTraceElement[] stackTrace = t.getStackTrace();
48.190 - if (stackTrace != null && stackTrace.length > 0 && stackTrace[0].getClassName().equals("org.python.antlr.runtime.tree.RewriteRuleElementStream")) {
48.191 + if (stackTrace != null && stackTrace.length > 0 && stackTrace[0].getClassName().startsWith("org.python.antlr")) {//.runtime.tree.RewriteRuleElementStream")) {
48.192 // This is issue 150921
48.193 // Don't bug user about it -- we already know
48.194 Logger.getLogger(this.getClass().getName()).log(Level.FINE, "Encountered issue #150921", t);
48.195 } else {
48.196 - Exceptions.attachMessage(t, "Was parsing " + FileUtil.getFileDisplayName(file.getFileObject()));
48.197 + t = Exceptions.attachMessage(t, "Was parsing " + FileUtil.getFileDisplayName(file));
48.198 Exceptions.printStackTrace(t);
48.199 }
48.200 - return createParseResult(null, file, false);
48.201 + return new PythonParserResult(null, context.snapshot);
48.202 }
48.203 }
48.204
48.205 @@ -336,63 +364,13 @@
48.206 }
48.207 }
48.208
48.209 - public void parseFiles(Job job) {
48.210 - ParseListener listener = job.listener;
48.211 - SourceFileReader reader = job.reader;
48.212 -
48.213 - for (ParserFile file : job.files) {
48.214 - ParseEvent beginEvent = new ParseEvent(ParseEvent.Kind.PARSE, file, null);
48.215 - listener.started(beginEvent);
48.216 -
48.217 - PythonParserResult result = null;
48.218 -
48.219 - try {
48.220 - // RST files aren't really Python but I want to index them so
48.221 - // fake up a parser result I can use
48.222 - String nameExt = file.getNameExt();
48.223 - if (nameExt != null && nameExt.endsWith(".rst")) { // NOI18N
48.224 - result = createParseResult(null, file, false);
48.225 - } else if (nameExt != null && nameExt.endsWith(".egg")) { // NOI18N
48.226 - // .Egg files aren't really python but we need the indexer to get
48.227 - // a chance - GSF will only call it if it maps to a Python parser result
48.228 - result = createParseResult(null, file, false);
48.229 - } else {
48.230 - CharSequence buffer = reader.read(file);
48.231 - String source = asString(buffer);
48.232 -
48.233 - int caretOffset = reader.getCaretOffset(file);
48.234 - if (caretOffset != -1 && job.translatedSource != null) {
48.235 - caretOffset = job.translatedSource.getAstOffset(caretOffset);
48.236 - }
48.237 - Context context = new Context(file, listener, source, caretOffset, job.translatedSource, job);
48.238 -
48.239 - result = parse(context, Sanitize.NONE);
48.240 - result.setSource(source);
48.241 - }
48.242 - } catch (Exception ioe) {
48.243 - listener.exception(ioe);
48.244 - }
48.245 -
48.246 - ParseEvent doneEvent = new ParseEvent(ParseEvent.Kind.PARSE, file, result);
48.247 - listener.finished(doneEvent);
48.248 - }
48.249 - }
48.250 -
48.251 - public PositionManager getPositionManager() {
48.252 - return new PythonPositionManager();
48.253 - }
48.254 -
48.255 - private PythonParserResult createParseResult(PythonTree rootNode, ParserFile file, boolean isValid) {
48.256 - return new PythonParserResult(rootNode, this, file, isValid);
48.257 - }
48.258
48.259 @SuppressWarnings("fallthrough")
48.260 - private PythonParserResult sanitize(final Context context,
48.261 - final Sanitize sanitizing) throws Exception {
48.262 + private PythonParserResult sanitize(final Context context, final Sanitize sanitizing) {
48.263
48.264 switch (sanitizing) {
48.265 case NEVER:
48.266 - return createParseResult(null, context.file, false);
48.267 + return new PythonParserResult(null, context.snapshot);
48.268
48.269 case NONE:
48.270 if (context.caretOffset != -1) {
48.271 @@ -433,7 +411,7 @@
48.272 case EDITED_LINE:
48.273 default:
48.274 // We're out of tricks - just return the failed parse result
48.275 - return createParseResult(null, context.file, false);
48.276 + return new PythonParserResult(null, context.snapshot);
48.277 }
48.278 }
48.279
48.280 @@ -641,10 +619,10 @@
48.281 EDITED_LINE,
48.282 }
48.283
48.284 - /** Parsing context */
48.285 + /** Sanitize context */
48.286 public static class Context {
48.287 - private final ParserFile file;
48.288 - private ParseListener listener;
48.289 + private FileObject file;
48.290 +// private ParseListener listener;
48.291 private int errorOffset;
48.292 private String source;
48.293 private String sanitizedSource;
48.294 @@ -652,42 +630,45 @@
48.295 private String sanitizedContents;
48.296 private int caretOffset;
48.297 private Sanitize sanitized = Sanitize.NONE;
48.298 - private TranslatedSource translatedSource;
48.299 - private Parser.Job job;
48.300 -
48.301 - public Context(ParserFile parserFile, ParseListener listener, String source, int caretOffset, TranslatedSource translatedSource, Parser.Job job) {
48.302 - this.file = parserFile;
48.303 - this.listener = listener;
48.304 - this.source = source;
48.305 - this.caretOffset = caretOffset;
48.306 - this.translatedSource = translatedSource;
48.307 - this.job = job;
48.308 -
48.309 -
48.310 - if (caretOffset != -1) {
48.311 - sanitized = Sanitize.EDITED_DOT;
48.312 - }
48.313 - }
48.314 -
48.315 - @Override
48.316 - public String toString() {
48.317 - return "PythonParser.Context(" + file.toString() + ")"; // NOI18N
48.318 - }
48.319 -
48.320 - public OffsetRange getSanitizedRange() {
48.321 - return sanitizedRange;
48.322 - }
48.323 -
48.324 - public Sanitize getSanitized() {
48.325 - return sanitized;
48.326 - }
48.327 -
48.328 - public String getSanitizedSource() {
48.329 - return sanitizedSource;
48.330 - }
48.331 -
48.332 - public int getErrorOffset() {
48.333 - return errorOffset;
48.334 - }
48.335 +// private TranslatedSource translatedSource;
48.336 +// private Parser.Job job;
48.337 + private Snapshot snapshot;
48.338 + private Task task;
48.339 + private SourceModificationEvent event;
48.340 +//
48.341 +// public Context(ParserFile parserFile, ParseListener listener, String source, int caretOffset, TranslatedSource translatedSource, Parser.Job job) {
48.342 +// this.file = parserFile;
48.343 +// this.listener = listener;
48.344 +// this.source = source;
48.345 +// this.caretOffset = caretOffset;
48.346 +// this.translatedSource = translatedSource;
48.347 +// this.job = job;
48.348 +//
48.349 +//
48.350 +// if (caretOffset != -1) {
48.351 +// sanitized = Sanitize.EDITED_DOT;
48.352 +// }
48.353 +// }
48.354 +//
48.355 +// @Override
48.356 +// public String toString() {
48.357 +// return "PythonParser.Context(" + file.toString() + ")"; // NOI18N
48.358 +// }
48.359 +//
48.360 +// public OffsetRange getSanitizedRange() {
48.361 +// return sanitizedRange;
48.362 +// }
48.363 +//
48.364 +// public Sanitize getSanitized() {
48.365 +// return sanitized;
48.366 +// }
48.367 +//
48.368 +// public String getSanitizedSource() {
48.369 +// return sanitizedSource;
48.370 +// }
48.371 +//
48.372 +// public int getErrorOffset() {
48.373 +// return errorOffset;
48.374 +// }
48.375 }
48.376 }
49.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonParserResult.java Sun Jan 04 13:11:53 2015 -0600
49.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonParserResult.java Sat Feb 28 17:25:32 2015 -0800
49.3 @@ -30,23 +30,16 @@
49.4 */
49.5 package org.netbeans.modules.python.editor;
49.6
49.7 -import java.io.IOException;
49.8 -import java.util.Collection;
49.9 import java.util.Collections;
49.10 +import java.util.LinkedList;
49.11 import java.util.List;
49.12 -import javax.swing.text.Document;
49.13 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
49.14 -import org.netbeans.modules.gsf.api.CompilationInfo;
49.15 -import org.netbeans.modules.gsf.api.Error;
49.16 -import org.netbeans.modules.gsf.api.Index;
49.17 -import org.netbeans.modules.gsf.api.OffsetRange;
49.18 -import org.netbeans.modules.gsf.api.ParserFile;
49.19 -import org.netbeans.modules.gsf.api.ParserResult;
49.20 -import org.netbeans.modules.gsf.api.annotations.NonNull;
49.21 -import org.netbeans.modules.gsf.spi.GsfUtilities;
49.22 +import org.netbeans.api.annotations.common.NonNull;
49.23 +import org.netbeans.modules.csl.api.Error;
49.24 +import org.netbeans.modules.csl.api.OffsetRange;
49.25 +import org.netbeans.modules.csl.spi.ParserResult;
49.26 +import org.netbeans.modules.parsing.api.Snapshot;
49.27 import org.netbeans.modules.python.editor.PythonParser.Sanitize;
49.28 import org.netbeans.modules.python.editor.scopes.SymbolTable;
49.29 -import org.openide.util.Exceptions;
49.30 import org.python.antlr.PythonTree;
49.31
49.32 /**
49.33 @@ -57,6 +50,7 @@
49.34 */
49.35 public class PythonParserResult extends ParserResult {
49.36 private PythonTree root;
49.37 + private List<Error> errors;
49.38 private OffsetRange sanitizedRange = OffsetRange.NONE;
49.39 private String source;
49.40 private String sanitizedContents;
49.41 @@ -65,9 +59,10 @@
49.42 private SymbolTable symbolTable;
49.43 private int codeTemplateOffset = -1;
49.44
49.45 - public PythonParserResult(PythonTree tree, PythonParser parser, ParserFile file, boolean isValid) {
49.46 - super(parser, file, PythonTokenId.PYTHON_MIME_TYPE, isValid);
49.47 + public PythonParserResult(PythonTree tree, @NonNull Snapshot snapshot) {
49.48 + super(snapshot);
49.49 this.root = tree;
49.50 + this.errors = new LinkedList<Error>();
49.51 }
49.52
49.53 public PythonTree getRoot() {
49.54 @@ -75,10 +70,19 @@
49.55 }
49.56
49.57 @Override
49.58 - public AstTreeNode getAst() {
49.59 - return PythonAstTreeNode.get(root);
49.60 + public List<? extends Error> getDiagnostics() {
49.61 + return errors;
49.62 }
49.63
49.64 + @Override
49.65 + protected void invalidate() {
49.66 + }
49.67 +
49.68 + public void setErrors(List<? extends Error> errors) {
49.69 + this.errors.clear();
49.70 + this.errors.addAll(errors);
49.71 + }
49.72 +
49.73 /**
49.74 * Set the range of source that was sanitized, if any.
49.75 */
49.76 @@ -107,7 +111,7 @@
49.77
49.78 public SymbolTable getSymbolTable() {
49.79 if (symbolTable == null) {
49.80 - symbolTable = new SymbolTable(root, file.getFileObject());
49.81 + symbolTable = new SymbolTable(root, getSnapshot().getSource().getFileObject());
49.82 }
49.83
49.84 return symbolTable;
49.85 @@ -125,68 +129,6 @@
49.86 this.source = source;
49.87 }
49.88
49.89 - void setStructure(@NonNull PythonStructureScanner.AnalysisResult result) {
49.90 - this.analysisResult = result;
49.91 - }
49.92 -
49.93 - @NonNull
49.94 - public PythonStructureScanner.AnalysisResult getStructure() {
49.95 - if (analysisResult == null) {
49.96 - CompilationInfo info = getInfo();
49.97 - if (info == null) {
49.98 - try {
49.99 - info = new CompilationInfo(getFile().getFileObject()) {
49.100 - private Document doc;
49.101 -
49.102 - @Override
49.103 - public Collection<? extends ParserResult> getEmbeddedResults(String mimeType) {
49.104 - if (mimeType.equals(PythonTokenId.PYTHON_MIME_TYPE)) {
49.105 - return Collections.singleton(PythonParserResult.this);
49.106 - }
49.107 - return null;
49.108 - }
49.109 -
49.110 - @Override
49.111 - public ParserResult getEmbeddedResult(String mimeType, int offset) {
49.112 - if (mimeType.equals(PythonTokenId.PYTHON_MIME_TYPE)) {
49.113 - return PythonParserResult.this;
49.114 - }
49.115 - return null;
49.116 - }
49.117 -
49.118 - @Override
49.119 - public String getText() {
49.120 - return getSource();
49.121 - }
49.122 -
49.123 - @Override
49.124 - public Index getIndex(String mimeType) {
49.125 - return null;
49.126 - }
49.127 -
49.128 - @Override
49.129 - public List<Error> getErrors() {
49.130 - return Collections.emptyList();
49.131 - }
49.132 -
49.133 - @Override
49.134 - public Document getDocument() {
49.135 - if (doc == null) {
49.136 - doc = GsfUtilities.getDocument(getFileObject(), true);
49.137 - }
49.138 -
49.139 - return doc;
49.140 - }
49.141 - };
49.142 - } catch (IOException ioe) {
49.143 - Exceptions.printStackTrace(ioe);
49.144 - }
49.145 - }
49.146 - analysisResult = PythonStructureScanner.analyze(info);
49.147 - }
49.148 - return analysisResult;
49.149 - }
49.150 -
49.151 /**
49.152 * @return the codeTemplateOffset
49.153 */
49.154 @@ -200,4 +142,12 @@
49.155 public void setCodeTemplateOffset(int codeTemplateOffset) {
49.156 this.codeTemplateOffset = codeTemplateOffset;
49.157 }
49.158 +
49.159 + public void addError(Error e) {
49.160 + errors.add(e);
49.161 + }
49.162 +
49.163 + public boolean isValid() {
49.164 + return errors.isEmpty();
49.165 + }
49.166 }
50.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonPositionManager.java Sun Jan 04 13:11:53 2015 -0600
50.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
50.3 @@ -1,42 +0,0 @@
50.4 -/*
50.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
50.6 - *
50.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
50.8 - *
50.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
50.10 - * Other names may be trademarks of their respective owners.
50.11 - *
50.12 - * The contents of this file are subject to the terms of either the GNU
50.13 - * General Public License Version 2 only ("GPL") or the Common
50.14 - * Development and Distribution License("CDDL") (collectively, the
50.15 - * "License"). You may not use this file except in compliance with the
50.16 - * License. You can obtain a copy of the License at
50.17 - * http://www.netbeans.org/cddl-gplv2.html
50.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
50.19 - * specific language governing permissions and limitations under the
50.20 - * License. When distributing the software, include this License Header
50.21 - * Notice in each file and include the License file at
50.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
50.23 - * particular file as subject to the "Classpath" exception as provided
50.24 - * by Oracle in the GPL Version 2 section of the License file that
50.25 - * accompanied this code. If applicable, add the following below the
50.26 - * License Header, with the fields enclosed by brackets [] replaced by
50.27 - * your own identifying information:
50.28 - * "Portions Copyrighted [year] [name of copyright owner]"
50.29 - *
50.30 - * Contributor(s):
50.31 - *
50.32 - * Portions Copyrighted 2007 Sun Microsystems, Inc.
50.33 - */
50.34 -package org.netbeans.modules.python.editor;
50.35 -
50.36 -import org.netbeans.modules.gsf.api.CompilationInfo;
50.37 -import org.netbeans.modules.gsf.api.ElementHandle;
50.38 -import org.netbeans.modules.gsf.api.OffsetRange;
50.39 -import org.netbeans.modules.gsf.api.PositionManager;
50.40 -
50.41 -class PythonPositionManager implements PositionManager {
50.42 - public OffsetRange getOffsetRange(CompilationInfo info, ElementHandle object) {
50.43 - return OffsetRange.NONE;
50.44 - }
50.45 -}
51.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonSemanticHighlighter.java Sun Jan 04 13:11:53 2015 -0600
51.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonSemanticHighlighter.java Sat Feb 28 17:25:32 2015 -0800
51.3 @@ -34,12 +34,16 @@
51.4 import java.util.HashMap;
51.5 import java.util.Map;
51.6 import java.util.Set;
51.7 -import org.netbeans.modules.gsf.api.ColoringAttributes;
51.8 -import org.netbeans.modules.gsf.api.CompilationInfo;
51.9 -import org.netbeans.modules.gsf.api.OffsetRange;
51.10 -import org.netbeans.modules.gsf.api.SemanticAnalyzer;
51.11 +import org.netbeans.modules.csl.api.ColoringAttributes;
51.12 +import org.netbeans.modules.csl.api.OffsetRange;
51.13 +import org.netbeans.modules.csl.api.SemanticAnalyzer;
51.14 +import org.netbeans.modules.csl.spi.ParserResult;
51.15 +import org.netbeans.modules.parsing.spi.Parser.Result;
51.16 +import org.netbeans.modules.parsing.spi.Scheduler;
51.17 +import org.netbeans.modules.parsing.spi.SchedulerEvent;
51.18 import org.netbeans.modules.python.editor.scopes.ScopeInfo;
51.19 import org.netbeans.modules.python.editor.scopes.SymbolTable;
51.20 +import org.openide.util.Exceptions;
51.21 import org.python.antlr.PythonTree;
51.22 import org.python.antlr.Visitor;
51.23 import org.python.antlr.ast.ClassDef;
51.24 @@ -52,7 +56,7 @@
51.25 *
51.26 * @author Tor Norbye
51.27 */
51.28 -public class PythonSemanticHighlighter implements SemanticAnalyzer {
51.29 +public class PythonSemanticHighlighter extends SemanticAnalyzer<PythonParserResult> {
51.30 private boolean cancelled;
51.31 private Map<OffsetRange, Set<ColoringAttributes>> semanticHighlights;
51.32
51.33 @@ -72,34 +76,47 @@
51.34 cancelled = true;
51.35 }
51.36
51.37 - public void run(CompilationInfo info) throws Exception {
51.38 + @Override
51.39 + public int getPriority() {
51.40 + return 0;
51.41 + }
51.42 +
51.43 + @Override
51.44 + public Class<? extends Scheduler> getSchedulerClass() {
51.45 + return Scheduler.EDITOR_SENSITIVE_TASK_SCHEDULER;
51.46 + }
51.47 +
51.48 + public void run(PythonParserResult pr, SchedulerEvent event) {
51.49 resume();
51.50
51.51 if (isCancelled()) {
51.52 return;
51.53 }
51.54
51.55 - PythonTree root = PythonAstUtils.getRoot(info);
51.56 + PythonTree root = PythonAstUtils.getRoot(pr);
51.57 if (root == null) {
51.58 return;
51.59 }
51.60
51.61 - PythonParserResult pr = PythonAstUtils.getParseResult(info);
51.62 SymbolTable symbolTable = pr.getSymbolTable();
51.63
51.64 - SemanticVisitor visitor = new SemanticVisitor(info, symbolTable);
51.65 - visitor.visit(root);
51.66 + SemanticVisitor visitor = new SemanticVisitor(pr, symbolTable);
51.67 + try {
51.68 + visitor.visit(root);
51.69 + } catch (Exception ex) {
51.70 + Exceptions.printStackTrace(ex);
51.71 + }
51.72 semanticHighlights = visitor.getHighlights();
51.73 }
51.74
51.75 private static class SemanticVisitor extends Visitor {
51.76 - private final CompilationInfo info;
51.77 + private final PythonParserResult info;
51.78 private Map<OffsetRange, Set<ColoringAttributes>> highlights =
51.79 new HashMap<OffsetRange, Set<ColoringAttributes>>(100);
51.80 private final SymbolTable symbolTable;
51.81 private ScopeInfo scope;
51.82
51.83 - SemanticVisitor(CompilationInfo info, SymbolTable symbolTable) {
51.84 + SemanticVisitor(PythonParserResult info, SymbolTable symbolTable) {
51.85 this.info = info;
51.86 this.symbolTable = symbolTable;
51.87 }
52.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonStructureItem.java Sun Jan 04 13:11:53 2015 -0600
52.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonStructureItem.java Sat Feb 28 17:25:32 2015 -0800
52.3 @@ -34,21 +34,33 @@
52.4 import java.util.Collections;
52.5 import java.util.List;
52.6 import javax.swing.ImageIcon;
52.7 +import org.netbeans.modules.csl.api.ElementHandle;
52.8 +import org.netbeans.modules.csl.api.ElementKind;
52.9 +import org.netbeans.modules.csl.api.HtmlFormatter;
52.10 +import org.netbeans.modules.csl.api.Modifier;
52.11 +import org.netbeans.modules.csl.api.StructureItem;
52.12 import org.netbeans.modules.python.editor.elements.AstElement;
52.13 -import org.netbeans.modules.gsf.api.ElementHandle;
52.14 -import org.netbeans.modules.gsf.api.ElementKind;
52.15 -import org.netbeans.modules.gsf.api.HtmlFormatter;
52.16 -import org.netbeans.modules.gsf.api.Modifier;
52.17 -import org.netbeans.modules.gsf.api.StructureItem;
52.18 import org.netbeans.modules.python.editor.scopes.SymbolTable;
52.19 import org.openide.util.ImageUtilities;
52.20 import org.python.antlr.PythonTree;
52.21 +import org.python.antlr.ast.ClassDef;
52.22 import org.python.antlr.ast.FunctionDef;
52.23
52.24 public final class PythonStructureItem extends AstElement implements StructureItem {
52.25 private List<PythonStructureItem> children;
52.26 private PythonStructureItem parent;
52.27
52.28 + public PythonStructureItem(SymbolTable scopes, ClassDef def) {
52.29 + this(scopes, def, def.getInternalName(), ElementKind.CLASS);
52.30 + }
52.31 +
52.32 + public PythonStructureItem(SymbolTable scopes, FunctionDef def) {
52.33 + this(scopes, def, def.getInternalName(), ElementKind.METHOD);
52.34 + if ("__init__".equals(name)) { // NOI18N
52.35 + kind = ElementKind.CONSTRUCTOR;
52.36 + }
52.37 + }
52.38 +
52.39 public PythonStructureItem(SymbolTable scopes, PythonTree node, String name, ElementKind kind) {
52.40 super(scopes, node, name, kind);
52.41 this.node = node;
53.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonStructureScanner.java Sun Jan 04 13:11:53 2015 -0600
53.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonStructureScanner.java Sat Feb 28 17:25:32 2015 -0800
53.3 @@ -39,11 +39,13 @@
53.4 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
53.5 import org.netbeans.editor.BaseDocument;
53.6 import org.netbeans.editor.Utilities;
53.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
53.8 -import org.netbeans.modules.gsf.api.ElementKind;
53.9 -import org.netbeans.modules.gsf.api.OffsetRange;
53.10 -import org.netbeans.modules.gsf.api.StructureItem;
53.11 -import org.netbeans.modules.gsf.api.StructureScanner;
53.12 +import org.netbeans.modules.csl.api.ElementKind;
53.13 +import org.netbeans.modules.csl.api.OffsetRange;
53.14 +import org.netbeans.modules.csl.api.StructureItem;
53.15 +import org.netbeans.modules.csl.api.StructureScanner;
53.16 +import org.netbeans.modules.csl.api.StructureScanner.Configuration;
53.17 +import org.netbeans.modules.csl.spi.GsfUtilities;
53.18 +import org.netbeans.modules.csl.spi.ParserResult;
53.19 import org.netbeans.modules.python.editor.scopes.ScopeInfo;
53.20 import org.netbeans.modules.python.editor.scopes.SymInfo;
53.21 import org.netbeans.modules.python.editor.scopes.SymbolTable;
53.22 @@ -61,24 +63,8 @@
53.23 * @author Tor Norbye
53.24 */
53.25 public class PythonStructureScanner implements StructureScanner {
53.26 - public static PythonStructureItem create(SymbolTable scopes, ClassDef def) {
53.27 - PythonStructureItem item = new PythonStructureItem(scopes, def, def.getInternalName(), ElementKind.CLASS);
53.28 -
53.29 - return item;
53.30 - }
53.31 -
53.32 - public static PythonStructureItem create(SymbolTable scopes, FunctionDef def) {
53.33 - String name = def.getInternalName();
53.34 - ElementKind kind = ElementKind.METHOD;
53.35 - if ("__init__".equals(name)) { // NOI18N
53.36 - kind = ElementKind.CONSTRUCTOR;
53.37 - }
53.38 - PythonStructureItem item = new PythonStructureItem(scopes, def, name, kind);
53.39 -
53.40 - return item;
53.41 - }
53.42 -
53.43 - public static AnalysisResult analyze(CompilationInfo info) {
53.44 +
53.45 + public static AnalysisResult analyze(PythonParserResult info) {
53.46 AnalysisResult analysisResult = new AnalysisResult();
53.47
53.48 PythonTree root = PythonAstUtils.getRoot(info);
53.49 @@ -96,16 +82,24 @@
53.50 return analysisResult;
53.51 }
53.52
53.53 - public List<? extends StructureItem> scan(CompilationInfo info) {
53.54 + @Override
53.55 + public List<? extends StructureItem> scan(ParserResult info) {
53.56 PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
53.57 if (parseResult == null) {
53.58 return Collections.emptyList();
53.59 }
53.60
53.61 - return parseResult.getStructure().getElements();
53.62 + return getStructure(parseResult).getElements();
53.63 + }
53.64 +
53.65 + public PythonStructureScanner.AnalysisResult getStructure(PythonParserResult result) {
53.66 + // TODO Cache ! (Used to be in PythonParserResult
53.67 + AnalysisResult analysisResult = PythonStructureScanner.analyze(result);
53.68 + return analysisResult;
53.69 }
53.70
53.71 - public Map<String, List<OffsetRange>> folds(CompilationInfo info) {
53.72 + @Override
53.73 + public Map<String, List<OffsetRange>> folds(ParserResult info) {
53.74 PythonParserResult result = PythonAstUtils.getParseResult(info);
53.75 PythonTree root = PythonAstUtils.getRoot(result);
53.76 if (root == null) {
53.77 @@ -119,11 +113,11 @@
53.78 //List<?extends AstElement> elements = ar.getElements();
53.79 //List<StructureItem> itemList = new ArrayList<StructureItem>(elements.size());
53.80
53.81 - BaseDocument doc = (BaseDocument)info.getDocument();
53.82 + BaseDocument doc = GsfUtilities.getDocument(result.getSnapshot().getSource().getFileObject(), false);
53.83 if (doc != null) {
53.84 try {
53.85 doc.readLock(); // For Utilities.getRowEnd() access
53.86 - FoldVisitor visitor = new FoldVisitor(info, doc);
53.87 + FoldVisitor visitor = new FoldVisitor((PythonParserResult) info, doc);
53.88 visitor.visit(root);
53.89 List<OffsetRange> codeBlocks = visitor.getCodeBlocks();
53.90
53.91 @@ -140,18 +134,18 @@
53.92 return Collections.emptyMap();
53.93 }
53.94
53.95 + @Override
53.96 public Configuration getConfiguration() {
53.97 - return null;
53.98 + return new Configuration(true, true, -1);
53.99 }
53.100
53.101 private static class FoldVisitor extends Visitor {
53.102 private List<OffsetRange> codeBlocks = new ArrayList<OffsetRange>();
53.103 - private CompilationInfo info;
53.104 + private PythonParserResult info;
53.105 private BaseDocument doc;
53.106
53.107 - private FoldVisitor(CompilationInfo info, BaseDocument doc) {
53.108 + private FoldVisitor(PythonParserResult info, BaseDocument doc) {
53.109 this.info = info;
53.110 -
53.111 this.doc = doc;
53.112 }
53.113
53.114 @@ -211,7 +205,7 @@
53.115
53.116 @Override
53.117 public Object visitClassDef(ClassDef def) throws Exception {
53.118 - PythonStructureItem item = new PythonStructureItem(scopes, def, def.getInternalName(), ElementKind.CLASS);
53.119 + PythonStructureItem item = new PythonStructureItem(scopes, def);
53.120 add(item);
53.121
53.122 ScopeInfo scope = scopes.getScopeInfo(def);
53.123 @@ -237,7 +231,7 @@
53.124
53.125 @Override
53.126 public Object visitFunctionDef(FunctionDef def) throws Exception {
53.127 - PythonStructureItem item = create(scopes, def);
53.128 + PythonStructureItem item = new PythonStructureItem(scopes, def);
53.129
53.130 add(item);
53.131 stack.add(item);
54.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonTypeAnalyzer.java Sun Jan 04 13:11:53 2015 -0600
54.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonTypeAnalyzer.java Sat Feb 28 17:25:32 2015 -0800
54.3 @@ -38,8 +38,7 @@
54.4 import org.netbeans.api.lexer.TokenHierarchy;
54.5 import org.netbeans.api.lexer.TokenSequence;
54.6 import org.netbeans.editor.BaseDocument;
54.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
54.8 -import org.netbeans.modules.gsf.api.OffsetRange;
54.9 +import org.netbeans.modules.csl.api.OffsetRange;
54.10 import org.netbeans.modules.python.editor.lexer.PythonCommentTokenId;
54.11 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
54.12 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
54.13 @@ -117,12 +116,12 @@
54.14 /** PythonTree we are looking for; */
54.15 private PythonTree target;
54.16 private final FileObject fileObject;
54.17 - private final CompilationInfo info;
54.18 + private final PythonParserResult info;
54.19 private long startTime;
54.20
54.21 /** Creates a new instance of JsTypeAnalyzer for a given position.
54.22 * The {@link #analyze} method will do the rest. */
54.23 - public PythonTypeAnalyzer(CompilationInfo info, PythonIndex index, PythonTree root, PythonTree target, int astOffset, int lexOffset, FileObject fileObject) {
54.24 + public PythonTypeAnalyzer(PythonParserResult info, PythonIndex index, PythonTree root, PythonTree target, int astOffset, int lexOffset, FileObject fileObject) {
54.25 this.info = info;
54.26 this.index = index;
54.27 this.root = root;
54.28 @@ -722,7 +721,7 @@
54.29
54.30 if (info != null && root != null) {
54.31 // Look for type annotations
54.32 - BaseDocument doc = (BaseDocument)info.getDocument();
54.33 + BaseDocument doc = (BaseDocument) info.getSnapshot().getSource().getDocument(false);
54.34 if (doc != null) {
54.35 // Look for type declarations that can apply to this variable
54.36 OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(info, PythonAstUtils.getRange(root));
55.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonUtils.java Sun Jan 04 13:11:53 2015 -0600
55.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonUtils.java Sat Feb 28 17:25:32 2015 -0800
55.3 @@ -33,20 +33,19 @@
55.4 import java.util.Comparator;
55.5 import java.util.List;
55.6 import javax.swing.text.Document;
55.7 +import org.netbeans.api.annotations.common.NonNull;
55.8 import org.netbeans.api.project.FileOwnerQuery;
55.9 import org.netbeans.api.project.Project;
55.10 +import org.netbeans.api.project.ProjectUtils;
55.11 import org.netbeans.api.project.SourceGroup;
55.12 import org.netbeans.api.project.Sources;
55.13 import org.netbeans.lib.editor.codetemplates.api.CodeTemplate;
55.14 import org.netbeans.lib.editor.codetemplates.api.CodeTemplateManager;
55.15 -import org.netbeans.modules.gsf.api.ParserFile;
55.16 +import org.netbeans.modules.python.api.PythonMIMEResolver;
55.17 import org.netbeans.modules.python.api.PythonPlatform;
55.18 import org.netbeans.modules.python.api.PythonPlatformManager;
55.19 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
55.20 import org.openide.filesystems.FileObject;
55.21 -import org.openide.filesystems.FileStateInvalidException;
55.22 import org.openide.filesystems.FileUtil;
55.23 -import org.openide.util.Exceptions;
55.24 import org.openide.util.NbBundle;
55.25 import org.python.antlr.PythonTree;
55.26 import org.python.antlr.ast.Attribute;
55.27 @@ -59,13 +58,13 @@
55.28 public class PythonUtils {
55.29 public static boolean canContainPython(FileObject f) {
55.30 String mimeType = f.getMIMEType();
55.31 - return PythonTokenId.PYTHON_MIME_TYPE.equals(mimeType);
55.32 + return PythonMIMEResolver.PYTHON_MIME_TYPE.equals(mimeType);
55.33 // TODO: "text/x-yaml".equals(mimeType) || // NOI18N
55.34 // RubyInstallation.RHTML_MIME_TYPE.equals(mimeType);
55.35 }
55.36
55.37 public static boolean isPythonFile(FileObject f) {
55.38 - return PythonTokenId.PYTHON_MIME_TYPE.equals(f.getMIMEType());
55.39 + return PythonMIMEResolver.PYTHON_MIME_TYPE.equals(f.getMIMEType());
55.40 }
55.41
55.42 public static boolean isRstFile(FileObject f) {
55.43 @@ -75,7 +74,7 @@
55.44 public static boolean isPythonDocument(Document doc) {
55.45 String mimeType = (String)doc.getProperty("mimeType"); // NOI18N
55.46
55.47 - return PythonTokenId.PYTHON_MIME_TYPE.equals(mimeType);
55.48 + return PythonMIMEResolver.PYTHON_MIME_TYPE.equals(mimeType);
55.49 }
55.50 public static final String DOT__INIT__ = ".__init__"; // NOI18N
55.51
55.52 @@ -95,100 +94,83 @@
55.53 * @param projectRelativeName If non null, the path from the project root down to this file
55.54 * @return A string for the full package module name
55.55 */
55.56 - public static String getModuleName(FileObject fo, ParserFile file) {
55.57 - assert fo != null || file != null;
55.58 + public static String getModuleName(@NonNull FileObject fo) {
55.59
55.60 // TODO - use PythonPlatform's library roots!
55.61
55.62 - String module = null;
55.63 - if (file != null) {
55.64 - module = file.getNameExt();
55.65 - fo = file.getFileObject();
55.66 - } else {
55.67 - module = fo.getName();
55.68 + String module = fo.getName();
55.69 +
55.70 + // First see if we're on the load path for the platform, and if so,
55.71 + // use that as the base
55.72 + // TODO - look up platform for the current search context instead of all platforms!!
55.73 + if (fo.getParent() != prevParent) {
55.74 + prevRootUrl = null;
55.75 + prevParent = fo.getParent();
55.76 }
55.77
55.78 - if (fo != null) {
55.79 - // First see if we're on the load path for the platform, and if so,
55.80 - // use that as the base
55.81 - // TODO - look up platform for the current search context instead of all platforms!!
55.82 - try {
55.83 - if (fo.getParent() != prevParent) {
55.84 - prevRootUrl = null;
55.85 - prevParent = fo.getParent();
55.86 - }
55.87 + String url = fo.toURL().toExternalForm();
55.88 + if (prevRootUrl == null) {
55.89 + boolean found = false;
55.90 + PythonPlatformManager manager = PythonPlatformManager.getInstance();
55.91
55.92 - String url = fo.getURL().toExternalForm();
55.93 - if (prevRootUrl == null) {
55.94 - boolean found = false;
55.95 - PythonPlatformManager manager = PythonPlatformManager.getInstance();
55.96 -
55.97 - PlatformSearch:
55.98 - for (String name : manager.getPlatformList()) {
55.99 - PythonPlatform platform = manager.getPlatform(name);
55.100 - if (platform != null) {
55.101 - List<FileObject> unique = platform.getUniqueLibraryRoots();
55.102 - for (FileObject root : unique) {
55.103 - if (FileUtil.isParentOf(root, fo)) {
55.104 - for (FileObject r : platform.getLibraryRoots()) {
55.105 - if (FileUtil.isParentOf(r, fo)) {
55.106 - // See if the folder itself contains
55.107 - // an __init__.py file - if it does,
55.108 - // then include the directory itself
55.109 - // in the package name.
55.110 - if (r.getFileObject("__init__.py") != null) { // NOI18N
55.111 - r = r.getParent();
55.112 - }
55.113 -
55.114 - prevRootUrl = r.getURL().toExternalForm();
55.115 - found = true;
55.116 - break PlatformSearch;
55.117 - }
55.118 - }
55.119 - break PlatformSearch;
55.120 - }
55.121 - }
55.122 - }
55.123 - }
55.124 -
55.125 - if (!found) {
55.126 - Project project = FileOwnerQuery.getOwner(fo);
55.127 - if (project != null) {
55.128 - Sources source = project.getLookup().lookup(Sources.class);
55.129 - // Look up the source path
55.130 - SourceGroup[] sourceGroups = source.getSourceGroups(SOURCES_TYPE_PYTHON);
55.131 - for (SourceGroup group : sourceGroups) {
55.132 - FileObject folder = group.getRootFolder();
55.133 - if (FileUtil.isParentOf(folder, fo)) {
55.134 + PlatformSearch:
55.135 + for (String name : manager.getPlatformList()) {
55.136 + PythonPlatform platform = manager.getPlatform(name);
55.137 + if (platform != null) {
55.138 + List<FileObject> unique = platform.getUniqueLibraryRoots();
55.139 + for (FileObject root : unique) {
55.140 + if (FileUtil.isParentOf(root, fo)) {
55.141 + for (FileObject r : platform.getLibraryRoots()) {
55.142 + if (FileUtil.isParentOf(r, fo)) {
55.143 // See if the folder itself contains
55.144 // an __init__.py file - if it does,
55.145 // then include the directory itself
55.146 // in the package name.
55.147 - if (folder.getFileObject("__init__.py") != null) { // NOI18N
55.148 - folder = folder.getParent();
55.149 + if (r.getFileObject("__init__.py") != null) { // NOI18N
55.150 + r = r.getParent();
55.151 }
55.152
55.153 - prevRootUrl = folder.getURL().toExternalForm();
55.154 - break;
55.155 + prevRootUrl = r.toURL().toExternalForm();
55.156 + found = true;
55.157 + break PlatformSearch;
55.158 }
55.159 }
55.160 + break PlatformSearch;
55.161 }
55.162 }
55.163 }
55.164 + }
55.165
55.166 - if (prevRootUrl != null) {
55.167 - module = url.substring(prevRootUrl.length());
55.168 - if (module.startsWith("/")) {
55.169 - module = module.substring(1);
55.170 + if (!found) {
55.171 + Project project = FileOwnerQuery.getOwner(fo);
55.172 + if (project != null) {
55.173 + Sources source = ProjectUtils.getSources(project);
55.174 + // Look up the source path
55.175 + SourceGroup[] sourceGroups = source.getSourceGroups(SOURCES_TYPE_PYTHON);
55.176 + for (SourceGroup group : sourceGroups) {
55.177 + FileObject folder = group.getRootFolder();
55.178 + if (FileUtil.isParentOf(folder, fo)) {
55.179 + // See if the folder itself contains
55.180 + // an __init__.py file - if it does,
55.181 + // then include the directory itself
55.182 + // in the package name.
55.183 + if (folder.getFileObject("__init__.py") != null) { // NOI18N
55.184 + folder = folder.getParent();
55.185 + }
55.186 +
55.187 + prevRootUrl = folder.toURL().toExternalForm();
55.188 + break;
55.189 + }
55.190 }
55.191 - } else if (file != null && file.getRelativePath() != null) {
55.192 - module = file.getRelativePath();
55.193 }
55.194 - } catch (FileStateInvalidException ex) {
55.195 - Exceptions.printStackTrace(ex);
55.196 }
55.197 - } else if (file != null && file.getRelativePath() != null) {
55.198 - module = file.getRelativePath();
55.199 + }
55.200 +
55.201 + if (prevRootUrl != null) {
55.202 + module = url.substring(prevRootUrl.length());
55.203 + if (module.startsWith("/")) {
55.204 + module = module.substring(1);
55.205 + }
55.206 }
55.207
55.208 // Strip off .y extension
56.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
56.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/QuerySupportFactory.java Sat Feb 28 17:25:32 2015 -0800
56.3 @@ -0,0 +1,74 @@
56.4 +/*
56.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
56.6 + *
56.7 + * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
56.8 + *
56.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
56.10 + * Other names may be trademarks of their respective owners.
56.11 + *
56.12 + * The contents of this file are subject to the terms of either the GNU
56.13 + * General Public License Version 2 only ("GPL") or the Common
56.14 + * Development and Distribution License("CDDL") (collectively, the
56.15 + * "License"). You may not use this file except in compliance with the
56.16 + * License. You can obtain a copy of the License at
56.17 + * http://www.netbeans.org/cddl-gplv2.html
56.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
56.19 + * specific language governing permissions and limitations under the
56.20 + * License. When distributing the software, include this License Header
56.21 + * Notice in each file and include the License file at
56.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
56.23 + * particular file as subject to the "Classpath" exception as provided
56.24 + * by Oracle in the GPL Version 2 section of the License file that
56.25 + * accompanied this code. If applicable, add the following below the
56.26 + * License Header, with the fields enclosed by brackets [] replaced by
56.27 + * your own identifying information:
56.28 + * "Portions Copyrighted [year] [name of copyright owner]"
56.29 + *
56.30 + * If you wish your version of this file to be governed by only the CDDL
56.31 + * or only the GPL Version 2, indicate your decision by adding
56.32 + * "[Contributor] elects to include this software in this distribution
56.33 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
56.34 + * single choice of license, a recipient has the option to distribute
56.35 + * your version of this file under either the CDDL, the GPL Version 2 or
56.36 + * to extend the choice of license to its licensees as provided above.
56.37 + * However, if you add GPL Version 2 code and therefore, elected the GPL
56.38 + * Version 2 license, then the option applies only if the new code is
56.39 + * made subject to such option by the copyright holder.
56.40 + *
56.41 + * Contributor(s):
56.42 + *
56.43 + * Portions Copyrighted 2012 Sun Microsystems, Inc.
56.44 + */
56.45 +package org.netbeans.modules.python.editor;
56.46 +
56.47 +import java.io.IOException;
56.48 +import java.util.Collection;
56.49 +import java.util.Collections;
56.50 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
56.51 +import org.openide.filesystems.FileObject;
56.52 +import org.openide.util.Exceptions;
56.53 +
56.54 +/**
56.55 + *
56.56 + * @author Petr Pisl
56.57 + */
56.58 +public class QuerySupportFactory {
56.59 +
56.60 + public static QuerySupport get(final Collection<FileObject> roots) {
56.61 + try {
56.62 + return QuerySupport.forRoots(PythonIndexer.NAME,
56.63 + PythonIndexer.VERSION,
56.64 + roots.toArray(new FileObject[roots.size()]));
56.65 + } catch (IOException ex) {
56.66 + Exceptions.printStackTrace(ex);
56.67 + }
56.68 + return null;
56.69 + }
56.70 +
56.71 + public static QuerySupport get(final FileObject source) {
56.72 + return get(QuerySupport.findRoots(source,
56.73 + null,
56.74 + null,
56.75 + Collections.<String>emptySet()));
56.76 + }
56.77 +}
57.1 --- a/python.editor/src/org/netbeans/modules/python/editor/RstFormatter.java Sun Jan 04 13:11:53 2015 -0600
57.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/RstFormatter.java Sat Feb 28 17:25:32 2015 -0800
57.3 @@ -57,10 +57,11 @@
57.4 import org.netbeans.api.lexer.TokenHierarchy;
57.5 import org.netbeans.api.lexer.TokenSequence;
57.6 import org.netbeans.editor.BaseDocument;
57.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
57.8 -import org.netbeans.modules.gsf.api.ElementHandle;
57.9 -import org.netbeans.modules.gsf.api.ElementKind;
57.10 -import org.netbeans.modules.gsf.spi.GsfUtilities;
57.11 +import org.netbeans.modules.csl.api.ElementHandle;
57.12 +import org.netbeans.modules.csl.api.ElementKind;
57.13 +import org.netbeans.modules.csl.spi.GsfUtilities;
57.14 +import org.netbeans.modules.csl.spi.ParserResult;
57.15 +import org.netbeans.modules.python.api.PythonMIMEResolver;
57.16 import org.netbeans.modules.python.editor.elements.Element;
57.17 import org.netbeans.modules.python.editor.elements.IndexedElement;
57.18 import org.netbeans.modules.python.editor.elements.IndexedMethod;
57.19 @@ -186,7 +187,7 @@
57.20 } else if (marker.equals("keyword")) { // NOI18N
57.21 sb.append("<code style=\""); // NOI18N
57.22
57.23 - MimePath mimePath = MimePath.parse(PythonTokenId.PYTHON_MIME_TYPE);
57.24 + MimePath mimePath = MimePath.parse(PythonMIMEResolver.PYTHON_MIME_TYPE);
57.25 Lookup lookup = MimeLookup.getLookup(mimePath);
57.26 FontColorSettings fcs = lookup.lookup(FontColorSettings.class);
57.27
57.28 @@ -1001,7 +1002,7 @@
57.29 return -1;
57.30 }
57.31
57.32 - public static String document(CompilationInfo info, ElementHandle element) {
57.33 + public static String document(ParserResult info, ElementHandle element) {
57.34 if (element instanceof IndexedElement) {
57.35 IndexedElement indexedElement = (IndexedElement)element;
57.36
57.37 @@ -1024,7 +1025,7 @@
57.38 return null;
57.39 }
57.40
57.41 - public static String document(CompilationInfo info, PythonTree node, IndexedElement element) {
57.42 + public static String document(ParserResult info, PythonTree node, IndexedElement element) {
57.43 if (node != null) {
57.44 String doc = PythonAstUtils.getDocumentation(node);
57.45 if (doc != null) {
57.46 @@ -1124,7 +1125,7 @@
57.47 }
57.48
57.49 Language<?> language = PythonTokenId.language();
57.50 - String mimeType = PythonTokenId.PYTHON_MIME_TYPE;
57.51 + String mimeType = PythonMIMEResolver.PYTHON_MIME_TYPE;
57.52 // TODO - handle YAML and other languages I can see in the documentation...
57.53 /*if (python.indexOf(" <%") != -1) { // NOI18N
57.54 mimeType = "application/x-httpd-eruby"; // RHTML
58.1 --- a/python.editor/src/org/netbeans/modules/python/editor/codecoverage/PythonCoverageProvider.java Sun Jan 04 13:11:53 2015 -0600
58.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/codecoverage/PythonCoverageProvider.java Sat Feb 28 17:25:32 2015 -0800
58.3 @@ -65,14 +65,15 @@
58.4 import org.netbeans.api.project.Project;
58.5 import org.netbeans.editor.BaseDocument;
58.6 import org.netbeans.editor.Utilities;
58.7 +import org.netbeans.modules.csl.spi.GsfUtilities;
58.8 import org.netbeans.modules.gsf.codecoverage.api.CoverageManager;
58.9 import org.netbeans.modules.gsf.codecoverage.api.CoverageProvider;
58.10 import org.netbeans.modules.gsf.codecoverage.api.CoverageProviderHelper;
58.11 import org.netbeans.modules.gsf.codecoverage.api.CoverageType;
58.12 import org.netbeans.modules.gsf.codecoverage.api.FileCoverageDetails;
58.13 import org.netbeans.modules.gsf.codecoverage.api.FileCoverageSummary;
58.14 -import org.netbeans.modules.gsf.spi.GsfUtilities;
58.15 import org.netbeans.modules.python.api.PythonExecution;
58.16 +import org.netbeans.modules.python.api.PythonMIMEResolver;
58.17 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
58.18 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
58.19 import org.openide.filesystems.FileObject;
58.20 @@ -96,7 +97,7 @@
58.21 private Map<String, String> fullNames;
58.22 private long timestamp;
58.23 private Project project;
58.24 - private Set<String> mimeTypes = Collections.singleton(PythonTokenId.PYTHON_MIME_TYPE);
58.25 + private Set<String> mimeTypes = Collections.singleton(PythonMIMEResolver.PYTHON_MIME_TYPE);
58.26 private Boolean enabled;
58.27 private Boolean aggregating;
58.28
59.1 --- a/python.editor/src/org/netbeans/modules/python/editor/elements/AstElement.java Sun Jan 04 13:11:53 2015 -0600
59.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/elements/AstElement.java Sat Feb 28 17:25:32 2015 -0800
59.3 @@ -31,10 +31,13 @@
59.4 package org.netbeans.modules.python.editor.elements;
59.5
59.6 import java.util.Set;
59.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
59.8 -import org.netbeans.modules.gsf.api.ElementKind;
59.9 -import org.netbeans.modules.gsf.api.Modifier;
59.10 +import org.netbeans.modules.csl.api.ElementKind;
59.11 +import org.netbeans.modules.csl.api.Modifier;
59.12 +import org.netbeans.modules.csl.api.OffsetRange;
59.13 +import org.netbeans.modules.csl.spi.ParserResult;
59.14 import org.netbeans.modules.python.editor.PythonAstUtils;
59.15 +import org.netbeans.modules.python.editor.PythonParserResult;
59.16 +import org.netbeans.modules.python.editor.PythonStructureItem;
59.17 import org.netbeans.modules.python.editor.PythonStructureScanner;
59.18 import org.netbeans.modules.python.editor.scopes.SymbolTable;
59.19 import org.python.antlr.PythonTree;
59.20 @@ -64,13 +67,13 @@
59.21 this.kind = kind;
59.22 }
59.23
59.24 - public static AstElement create(CompilationInfo info, PythonTree node) {
59.25 - SymbolTable scopes = PythonAstUtils.getParseResult(info).getSymbolTable();
59.26 + public static AstElement create(PythonParserResult result, PythonTree node) {
59.27 + SymbolTable scopes = result.getSymbolTable();
59.28
59.29 if (node instanceof FunctionDef) {
59.30 - return PythonStructureScanner.create(scopes, (FunctionDef)node);
59.31 + return new PythonStructureItem(scopes, (FunctionDef)node);
59.32 } else if (node instanceof ClassDef) {
59.33 - return PythonStructureScanner.create(scopes, (ClassDef)node);
59.34 + return new PythonStructureItem(scopes, (ClassDef)node);
59.35 } else if (node instanceof Call) {
59.36 String name = PythonAstUtils.getCallName((Call)node);
59.37 return new AstElement(scopes, node, name, ElementKind.METHOD);
60.1 --- a/python.editor/src/org/netbeans/modules/python/editor/elements/Element.java Sun Jan 04 13:11:53 2015 -0600
60.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/elements/Element.java Sat Feb 28 17:25:32 2015 -0800
60.3 @@ -32,10 +32,12 @@
60.4
60.5 import java.util.Collections;
60.6 import java.util.Set;
60.7 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
60.8 -import org.netbeans.modules.gsf.api.ElementHandle;
60.9 -import org.netbeans.modules.gsf.api.ElementKind;
60.10 -import org.netbeans.modules.gsf.api.Modifier;
60.11 +import org.netbeans.modules.csl.api.ElementHandle;
60.12 +import org.netbeans.modules.csl.api.ElementKind;
60.13 +import org.netbeans.modules.csl.api.Modifier;
60.14 +import org.netbeans.modules.csl.api.OffsetRange;
60.15 +import org.netbeans.modules.csl.spi.ParserResult;
60.16 +import org.netbeans.modules.python.api.PythonMIMEResolver;
60.17 import org.openide.filesystems.FileObject;
60.18
60.19 /**
60.20 @@ -43,27 +45,40 @@
60.21 * @author Tor Norbye
60.22 */
60.23 public abstract class Element implements ElementHandle {
60.24 + @Override
60.25 public abstract String getName();
60.26
60.27 + @Override
60.28 public abstract ElementKind getKind();
60.29
60.30 + @Override
60.31 public String getMimeType() {
60.32 - return PythonTokenId.PYTHON_MIME_TYPE;
60.33 + return PythonMIMEResolver.PYTHON_MIME_TYPE;
60.34 }
60.35
60.36 + @Override
60.37 public boolean signatureEquals(ElementHandle handle) {
60.38 // XXX TODO
60.39 return false;
60.40 }
60.41
60.42 + @Override
60.43 + public OffsetRange getOffsetRange(ParserResult pr) {
60.44 + // XXX TODO
60.45 + return null;
60.46 + }
60.47 +
60.48 + @Override
60.49 public FileObject getFileObject() {
60.50 return null;
60.51 }
60.52
60.53 + @Override
60.54 public Set<Modifier> getModifiers() {
60.55 return Collections.emptySet();
60.56 }
60.57
60.58 + @Override
60.59 public String getIn() {
60.60 return null;
60.61 }
61.1 --- a/python.editor/src/org/netbeans/modules/python/editor/elements/IndexedElement.java Sun Jan 04 13:11:53 2015 -0600
61.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/elements/IndexedElement.java Sat Feb 28 17:25:32 2015 -0800
61.3 @@ -33,9 +33,11 @@
61.4 import java.util.Collections;
61.5 import java.util.EnumSet;
61.6 import java.util.Set;
61.7 +import org.netbeans.modules.csl.api.ElementKind;
61.8 +import org.netbeans.modules.csl.api.Modifier;
61.9 +import org.netbeans.modules.csl.api.OffsetRange;
61.10 +import org.netbeans.modules.csl.spi.ParserResult;
61.11 import org.netbeans.modules.python.editor.PythonIndex;
61.12 -import org.netbeans.modules.gsf.api.ElementKind;
61.13 -import org.netbeans.modules.gsf.api.Modifier;
61.14 import org.netbeans.modules.python.editor.PythonAstUtils;
61.15 import org.openide.filesystems.FileObject;
61.16 import org.python.antlr.PythonTree;
62.1 --- a/python.editor/src/org/netbeans/modules/python/editor/elements/IndexedMethod.java Sun Jan 04 13:11:53 2015 -0600
62.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/elements/IndexedMethod.java Sat Feb 28 17:25:32 2015 -0800
62.3 @@ -30,7 +30,7 @@
62.4 */
62.5 package org.netbeans.modules.python.editor.elements;
62.6
62.7 -import org.netbeans.modules.gsf.api.ElementKind;
62.8 +import org.netbeans.modules.csl.api.ElementKind;
62.9
62.10 /**
62.11 *
63.1 --- a/python.editor/src/org/netbeans/modules/python/editor/elements/IndexedPackage.java Sun Jan 04 13:11:53 2015 -0600
63.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/elements/IndexedPackage.java Sat Feb 28 17:25:32 2015 -0800
63.3 @@ -43,8 +43,8 @@
63.4
63.5 import java.util.Collections;
63.6 import java.util.Set;
63.7 -import org.netbeans.modules.gsf.api.ElementKind;
63.8 -import org.netbeans.modules.gsf.api.Modifier;
63.9 +import org.netbeans.modules.csl.api.ElementKind;
63.10 +import org.netbeans.modules.csl.api.Modifier;
63.11
63.12 /**
63.13 *
64.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
64.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/file/PyDataObject.java Sat Feb 28 17:25:32 2015 -0800
64.3 @@ -0,0 +1,132 @@
64.4 +package org.netbeans.modules.python.editor.file;
64.5 +
64.6 +import java.io.IOException;
64.7 +import org.netbeans.core.spi.multiview.MultiViewElement;
64.8 +import org.netbeans.core.spi.multiview.text.MultiViewEditorElement;
64.9 +import org.netbeans.modules.python.api.PythonMIMEResolver;
64.10 +import org.openide.awt.ActionID;
64.11 +import org.openide.awt.ActionReference;
64.12 +import org.openide.awt.ActionReferences;
64.13 +import org.openide.filesystems.FileObject;
64.14 +import org.openide.filesystems.MIMEResolver;
64.15 +import org.openide.loaders.DataObject;
64.16 +import org.openide.loaders.DataObjectExistsException;
64.17 +import org.openide.loaders.MultiDataObject;
64.18 +import org.openide.loaders.MultiFileLoader;
64.19 +import org.openide.util.Lookup;
64.20 +import org.openide.util.NbBundle.Messages;
64.21 +import org.openide.windows.TopComponent;
64.22 +
64.23 +@Messages({
64.24 + "LBL_Py_LOADER=Files of Py"
64.25 +})
64.26 +@MIMEResolver.ExtensionRegistration(
64.27 + displayName = "#LBL_Py_LOADER",
64.28 + mimeType = PythonMIMEResolver.PYTHON_MIME_TYPE,
64.29 + extension = {"py"}
64.30 +)
64.31 +@DataObject.Registration(
64.32 + mimeType = PythonMIMEResolver.PYTHON_MIME_TYPE,
64.33 + iconBase = "org/netbeans/modules/python/editor/resources/pyNode25.png",
64.34 + displayName = "#LBL_Py_LOADER",
64.35 + position = 300
64.36 +)
64.37 +@ActionReferences({
64.38 + @ActionReference(
64.39 + path = "Loaders/text/x-python/Actions",
64.40 + id = @ActionID(category = "System", id = "org.openide.actions.OpenAction"),
64.41 + position = 100,
64.42 + separatorAfter = 200
64.43 + ),
64.44 + @ActionReference(
64.45 + path = "Loaders/text/x-python/Actions",
64.46 + id = @ActionID(category = "Edit", id = "org.openide.actions.CutAction"),
64.47 + position = 300
64.48 + ),
64.49 + @ActionReference(
64.50 + path = "Loaders/text/x-python/Actions",
64.51 + id = @ActionID(category = "Edit", id = "org.openide.actions.CopyAction"),
64.52 + position = 400,
64.53 + separatorAfter = 500
64.54 + ),
64.55 + @ActionReference(
64.56 + path = "Loaders/text/x-python/Actions",
64.57 + id = @ActionID(category = "Project", id = "org.netbeans.modules.project.ui.RunSingle"),
64.58 + position = 550
64.59 + ),
64.60 + @ActionReference(
64.61 + path = "Loaders/text/x.python/Actions",
64.62 + id = @ActionID(category = "Project", id = "org.netbeans.modules.project.ui.TestSingle"),
64.63 + position = 570
64.64 + ),
64.65 + @ActionReference(
64.66 + path = "Loaders/text/x-python/Actions",
64.67 + id = @ActionID(category = "Edit", id = "org.openide.actions.DeleteAction"),
64.68 + position = 600
64.69 + ),
64.70 + @ActionReference(
64.71 + path = "Loaders/text/x-python/Actions",
64.72 + id = @ActionID(category = "System", id = "org.openide.actions.RenameAction"),
64.73 + position = 700,
64.74 + separatorAfter = 800
64.75 + ),
64.76 + @ActionReference(
64.77 + path = "Loaders/text/x-python/Actions",
64.78 + id = @ActionID(category = "System", id = "org.openide.actions.SaveAsTemplateAction"),
64.79 + position = 900,
64.80 + separatorAfter = 1000
64.81 + ),
64.82 + @ActionReference(
64.83 + path = "Loaders/text/x-python/Actions",
64.84 + id = @ActionID(category = "Refactoring", id = "org.netbeans.modules.refactoring.api.ui.WhereUsedAction"),
64.85 + position = 1050
64.86 + ),
64.87 + @ActionReference(
64.88 + path = "Loaders/text/x-python/Actions",
64.89 + id = @ActionID(category = "Refactoring", id = "RefactoringAll"),
64.90 + position = 1090,
64.91 + separatorAfter = 1095
64.92 + ),
64.93 + @ActionReference(
64.94 + path = "Loaders/text/x-python/Actions",
64.95 + id = @ActionID(category = "System", id = "org.openide.actions.FileSystemAction"),
64.96 + position = 1100,
64.97 + separatorAfter = 1200
64.98 + ),
64.99 + @ActionReference(
64.100 + path = "Loaders/text/x-python/Actions",
64.101 + id = @ActionID(category = "System", id = "org.openide.actions.ToolsAction"),
64.102 + position = 1300
64.103 + ),
64.104 + @ActionReference(
64.105 + path = "Loaders/text/x-python/Actions",
64.106 + id = @ActionID(category = "System", id = "org.openide.actions.PropertiesAction"),
64.107 + position = 1400
64.108 + )
64.109 +})
64.110 +public class PyDataObject extends MultiDataObject {
64.111 +
64.112 + public PyDataObject(FileObject pf, MultiFileLoader loader) throws DataObjectExistsException, IOException {
64.113 + super(pf, loader);
64.114 + registerEditor(PythonMIMEResolver.PYTHON_MIME_TYPE, true);
64.115 + }
64.116 +
64.117 + @Override
64.118 + protected int associateLookup() {
64.119 + return 1;
64.120 + }
64.121 +
64.122 + @MultiViewElement.Registration(
64.123 + displayName = "#LBL_Py_EDITOR",
64.124 + iconBase = "org/netbeans/modules/python/editor/resources/pyNode25.png",
64.125 + mimeType = PythonMIMEResolver.PYTHON_MIME_TYPE,
64.126 + persistenceType = TopComponent.PERSISTENCE_ONLY_OPENED,
64.127 + preferredID = "Py",
64.128 + position = 1000
64.129 + )
64.130 + @Messages("LBL_Py_EDITOR=Source")
64.131 + public static MultiViewEditorElement createEditor(Lookup lkp) {
64.132 + return new MultiViewEditorElement(lkp);
64.133 + }
64.134 +
64.135 +}
65.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
65.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/file/PythonShebangSourceLevelQuery.java Sat Feb 28 17:25:32 2015 -0800
65.3 @@ -0,0 +1,125 @@
65.4 +/*
65.5 + * To change this license header, choose License Headers in Project Properties.
65.6 + * To change this template file, choose Tools | Templates
65.7 + * and open the template in the editor.
65.8 + */
65.9 +package org.netbeans.modules.python.editor.file;
65.10 +
65.11 +import org.netbeans.modules.python.source.queries.SourceLevelQueryImplementation;
65.12 +import java.io.FileNotFoundException;
65.13 +import java.io.IOException;
65.14 +import java.util.Scanner;
65.15 +import javax.swing.event.ChangeListener;
65.16 +import org.openide.filesystems.FileAttributeEvent;
65.17 +import org.openide.filesystems.FileChangeListener;
65.18 +import org.openide.filesystems.FileEvent;
65.19 +import org.openide.filesystems.FileObject;
65.20 +import org.openide.filesystems.FileRenameEvent;
65.21 +import org.openide.util.ChangeSupport;
65.22 +import org.openide.util.Exceptions;
65.23 +import org.openide.util.lookup.ServiceProvider;
65.24 +
65.25 +/**
65.26 + *
65.27 + * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
65.28 + */
65.29 +@ServiceProvider(service = SourceLevelQueryImplementation.class)
65.30 +public class PythonShebangSourceLevelQuery implements SourceLevelQueryImplementation {
65.31 +
65.32 + @Override
65.33 + public Result getSourceLevel(FileObject pythonFile) {
65.34 + if(!pythonFile.isFolder()) {
65.35 + return new ResultImpl(pythonFile);
65.36 + }
65.37 + return null;
65.38 + }
65.39 +
65.40 + private final static class ResultImpl implements Result, FileChangeListener {
65.41 + private final ChangeSupport cs = new ChangeSupport(this);
65.42 +
65.43 + private final FileObject pythonFile;
65.44 + private String sourceLevel = "";
65.45 +
65.46 + @SuppressWarnings("LeakingThisInConstructor")
65.47 + private ResultImpl(FileObject pythonFile) {
65.48 + this.pythonFile = pythonFile;
65.49 + this.pythonFile.addFileChangeListener(this);
65.50 + this.fileChanged(null);
65.51 + }
65.52 +
65.53 + @Override
65.54 + public void addChangeListener(ChangeListener listener) {
65.55 + this.cs.addChangeListener(listener);
65.56 + }
65.57 +
65.58 + @Override
65.59 + public void fileAttributeChanged(FileAttributeEvent fe) {
65.60 + }
65.61 +
65.62 + @Override
65.63 + public void fileChanged(FileEvent fe) {
65.64 + if (pythonFile.isValid()) {
65.65 + String shebang = null;
65.66 + try (Scanner sc = new Scanner(pythonFile.getInputStream())) {
65.67 + if (sc.hasNextLine()) {
65.68 + shebang = sc.nextLine();
65.69 + }
65.70 + } catch (FileNotFoundException ex) {
65.71 + Exceptions.printStackTrace(ex);
65.72 + }
65.73 + processShebang(shebang);
65.74 + }
65.75 + }
65.76 +
65.77 + @Override
65.78 + public void fileDataCreated(FileEvent fe) {
65.79 + }
65.80 +
65.81 + @Override
65.82 + public void fileDeleted(FileEvent fe) {
65.83 + }
65.84 +
65.85 + @Override
65.86 + public void fileFolderCreated(FileEvent fe) {
65.87 + }
65.88 +
65.89 + @Override
65.90 + public void fileRenamed(FileRenameEvent fe) {
65.91 + }
65.92 +
65.93 + @Override
65.94 + public String getSourceLevel() {
65.95 + return this.sourceLevel;
65.96 + }
65.97 +
65.98 + @Override
65.99 + public void removeChangeListener(ChangeListener listener) {
65.100 + this.cs.removeChangeListener(listener);
65.101 + }
65.102 +
65.103 + private void setSourceLevel(String sourceLevel) {
65.104 + this.sourceLevel = sourceLevel;
65.105 + cs.fireChange();
65.106 + }
65.107 +
65.108 + private void processShebang(String shebang) {
65.109 + if (shebang != null && shebang.startsWith("#!")) {
65.110 + try {
65.111 + Process proc = Runtime.getRuntime().exec(shebang.substring(2) + " --version");
65.112 + String version = null;
65.113 + try(Scanner sc = new Scanner(proc.getInputStream())) {
65.114 + if(sc.hasNextLine()) {
65.115 + version = sc.nextLine();
65.116 + }
65.117 + }
65.118 + proc.destroy();
65.119 + if(version != null && !version.isEmpty() && !version.equals(this.sourceLevel)) {
65.120 + setSourceLevel(version);
65.121 + }
65.122 + } catch(IOException ex) {
65.123 + Exceptions.printStackTrace(ex);
65.124 + }
65.125 + }
65.126 + }
65.127 + }
65.128 +}
66.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
66.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/file/PythonTemplateAttributesProvider.java Sat Feb 28 17:25:32 2015 -0800
66.3 @@ -0,0 +1,64 @@
66.4 +/*
66.5 + * To change this license header, choose License Headers in Project Properties.
66.6 + * To change this template file, choose Tools | Templates
66.7 + * and open the template in the editor.
66.8 + */
66.9 +package org.netbeans.modules.python.editor.file;
66.10 +
66.11 +import java.util.HashMap;
66.12 +import java.util.Map;
66.13 +import java.util.logging.Level;
66.14 +import java.util.logging.Logger;
66.15 +import org.netbeans.api.java.classpath.ClassPath;
66.16 +import org.netbeans.modules.python.api.PythonMIMEResolver;
66.17 +import org.netbeans.modules.python.source.queries.SourceLevelQuery;
66.18 +import org.openide.filesystems.FileObject;
66.19 +import org.openide.loaders.CreateFromTemplateAttributesProvider;
66.20 +import org.openide.loaders.DataFolder;
66.21 +import org.openide.loaders.DataObject;
66.22 +import org.openide.modules.SpecificationVersion;
66.23 +import org.openide.util.lookup.ServiceProvider;
66.24 +
66.25 +/**
66.26 + *
66.27 + * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
66.28 + */
66.29 +@ServiceProvider(service = CreateFromTemplateAttributesProvider.class)
66.30 +public class PythonTemplateAttributesProvider implements CreateFromTemplateAttributesProvider {
66.31 +
66.32 + private static final Logger LOG = Logger.getLogger(PythonTemplateAttributesProvider.class.getName());
66.33 + private static final SpecificationVersion VER30 = new SpecificationVersion("3.0");
66.34 +
66.35 + @Override
66.36 + public Map<String, ?> attributesFor(DataObject template, DataFolder target, String name) {
66.37 + FileObject templateFO = template.getPrimaryFile();
66.38 + if (!PythonMIMEResolver.PYTHON_EXTENSION.equals(templateFO.getExt()) || templateFO.isFolder()) {
66.39 + return null;
66.40 + }
66.41 +
66.42 + FileObject targetFO = target.getPrimaryFile();
66.43 + Map<String,Object> result = new HashMap<String,Object>();
66.44 +
66.45 + ClassPath cp = ClassPath.getClassPath(targetFO, ClassPath.SOURCE);
66.46 + if (cp == null) {
66.47 + LOG.log(Level.WARNING, "No classpath was found for folder: {0}", target.getPrimaryFile()); // NOI18N
66.48 + }
66.49 + else {
66.50 + result.put("package", cp.getResourceName(targetFO, '.', false)); // NOI18N
66.51 + }
66.52 +
66.53 + String sourceLevel = SourceLevelQuery.getSourceLevel(targetFO);
66.54 + if (sourceLevel != null) {
66.55 + result.put("pythonSourceLevel", sourceLevel); // NOI18N
66.56 + if (isPython3orLater(sourceLevel))
66.57 + result.put("python3style", Boolean.TRUE); // NOI18N
66.58 + }
66.59 +
66.60 + return result;
66.61 + }
66.62 +
66.63 + private boolean isPython3orLater(String sourceLevel) {
66.64 + SpecificationVersion ver = new SpecificationVersion(sourceLevel);
66.65 + return (ver.compareTo(VER30) >= 0);
66.66 + }
66.67 +}
67.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
67.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/file/RunSingleCommand.java Sat Feb 28 17:25:32 2015 -0800
67.3 @@ -0,0 +1,117 @@
67.4 +package org.netbeans.modules.python.editor.file;
67.5 +
67.6 +import java.io.FileNotFoundException;
67.7 +import java.util.Scanner;
67.8 +import java.util.logging.Level;
67.9 +import java.util.logging.Logger;
67.10 +import javax.swing.JOptionPane;
67.11 +import org.netbeans.modules.python.api.PythonException;
67.12 +import org.netbeans.modules.python.api.PythonExecution;
67.13 +import org.netbeans.modules.python.api.PythonMIMEResolver;
67.14 +import org.netbeans.modules.python.api.PythonOptions;
67.15 +import org.netbeans.modules.python.api.PythonPlatform;
67.16 +import org.netbeans.modules.python.api.PythonPlatformManager;
67.17 +import org.netbeans.spi.project.ActionProvider;
67.18 +import org.openide.filesystems.FileObject;
67.19 +import org.openide.filesystems.FileUtil;
67.20 +import org.openide.loaders.DataObject;
67.21 +import org.openide.nodes.Node;
67.22 +import org.openide.util.Exceptions;
67.23 +import org.openide.util.Lookup;
67.24 +import org.openide.util.lookup.ServiceProvider;
67.25 +import org.openide.windows.TopComponent;
67.26 +
67.27 +/**
67.28 + *
67.29 + * @author Ralph Benjamin Ruijs
67.30 + */
67.31 +@ServiceProvider(service = ActionProvider.class)
67.32 +public class RunSingleCommand implements ActionProvider {
67.33 + private static final Logger LOG = Logger.getLogger(RunSingleCommand.class.getName());
67.34 +
67.35 + PythonPlatformManager manager = PythonPlatformManager.getInstance();
67.36 +
67.37 + public RunSingleCommand() {
67.38 + }
67.39 +
67.40 + private Node[] getSelectedNodes() {
67.41 + return TopComponent.getRegistry().getCurrentNodes();
67.42 + }
67.43 +
67.44 + @Override
67.45 + public void invokeAction(String command, Lookup context) throws IllegalArgumentException {
67.46 + Node[] activatedNodes = getSelectedNodes();
67.47 + DataObject gdo = activatedNodes[0].getLookup().lookup(DataObject.class);
67.48 + FileObject file = gdo.getPrimaryFile();
67.49 + if (file.getMIMEType().equals(PythonMIMEResolver.PYTHON_MIME_TYPE)) {
67.50 + String path = FileUtil.toFile(file.getParent()).getAbsolutePath();
67.51 + String script = FileUtil.toFile(file).getAbsolutePath();
67.52 + String shebang = null;
67.53 + try(Scanner sc = new Scanner(file.getInputStream())) {
67.54 + if(sc.hasNextLine()) {
67.55 + shebang = sc.nextLine();
67.56 + }
67.57 + } catch (FileNotFoundException ex) {
67.58 + Exceptions.printStackTrace(ex);
67.59 + }
67.60 +
67.61 + PythonExecution pyexec = new PythonExecution();
67.62 + pyexec.setDisplayName(gdo.getName());
67.63 + pyexec.setWorkingDirectory(path);
67.64 + if (PythonOptions.getInstance().getPromptForArgs()) {
67.65 + String args = JOptionPane.showInputDialog("Enter the args for this script.", "");
67.66 + pyexec.setScriptArgs(args);
67.67 +
67.68 + }
67.69 + PythonPlatform platform = null;
67.70 + if (shebang != null && shebang.startsWith("#!")) {
67.71 + try {
67.72 + platform = manager.findPlatformProperties(shebang.substring(2), null);
67.73 + } catch (PythonException ex) {
67.74 + LOG.log(Level.WARNING, "Unable to get platform from shebang: " + shebang, ex);
67.75 + }
67.76 + }
67.77 + if(platform == null) {
67.78 + platform = manager.getPlatform(manager.getDefaultPlatform());
67.79 + if (platform == null) {
67.80 + return; // invalid platform user has been warn in check so safe to return
67.81 + }
67.82 + }
67.83 + pyexec.setCommand(platform.getInterpreterCommand());
67.84 + pyexec.setScript(script);
67.85 + pyexec.setCommandArgs(platform.getInterpreterArgs());
67.86 + pyexec.setPath(PythonPlatform.buildPath(platform.getPythonPath()));
67.87 +// pyexec.setJavaPath(PythonPlatform.buildPath(super.buildJavaPath(platform, pyProject)));
67.88 + pyexec.setShowControls(true);
67.89 + pyexec.setShowInput(true);
67.90 + pyexec.setShowWindow(true);
67.91 + pyexec.addStandardRecognizers();
67.92 +
67.93 +// PythonCoverageProvider coverageProvider = PythonCoverageProvider.get(pyProject);
67.94 +// if (coverageProvider != null && coverageProvider.isEnabled()) {
67.95 +// pyexec = coverageProvider.wrapWithCoverage(pyexec);
67.96 +// }
67.97 +
67.98 + pyexec.run();
67.99 + }
67.100 + }
67.101 +
67.102 + @Override
67.103 + public boolean isActionEnabled(String command, Lookup context) throws IllegalArgumentException {
67.104 + boolean results = false; //super.enable(activatedNodes);
67.105 + Node[] activatedNodes = getSelectedNodes();
67.106 + if (activatedNodes != null && activatedNodes.length > 0) {
67.107 + DataObject gdo = activatedNodes[0].getLookup().lookup(DataObject.class);
67.108 + if (gdo != null && gdo.getPrimaryFile() != null) {
67.109 + results = gdo.getPrimaryFile().getMIMEType().equals(
67.110 + PythonMIMEResolver.PYTHON_MIME_TYPE);
67.111 + }
67.112 + }
67.113 + return results;
67.114 + }
67.115 +
67.116 + @Override
67.117 + public String[] getSupportedActions() {
67.118 + return new String[] {ActionProvider.COMMAND_RUN_SINGLE};
67.119 + }
67.120 +}
68.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
68.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/file/package-info.java Sat Feb 28 17:25:32 2015 -0800
68.3 @@ -0,0 +1,6 @@
68.4 +/*
68.5 + * To change this license header, choose License Headers in Project Properties.
68.6 + * To change this template file, choose Tools | Templates
68.7 + * and open the template in the editor.
68.8 + */
68.9 +package org.netbeans.modules.python.editor.file;
69.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/AccessToProtected.java Sun Jan 04 13:11:53 2015 -0600
69.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/AccessToProtected.java Sat Feb 28 17:25:32 2015 -0800
69.3 @@ -46,13 +46,13 @@
69.4 import java.util.Set;
69.5 import java.util.prefs.Preferences;
69.6 import javax.swing.JComponent;
69.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
69.8 -import org.netbeans.modules.gsf.api.Hint;
69.9 -import org.netbeans.modules.gsf.api.HintFix;
69.10 -import org.netbeans.modules.gsf.api.HintSeverity;
69.11 -import org.netbeans.modules.gsf.api.OffsetRange;
69.12 -import org.netbeans.modules.gsf.api.RuleContext;
69.13 +import org.netbeans.modules.csl.api.Hint;
69.14 +import org.netbeans.modules.csl.api.HintFix;
69.15 +import org.netbeans.modules.csl.api.HintSeverity;
69.16 +import org.netbeans.modules.csl.api.OffsetRange;
69.17 +import org.netbeans.modules.csl.api.RuleContext;
69.18 import org.netbeans.modules.python.editor.PythonAstUtils;
69.19 +import org.netbeans.modules.python.editor.PythonParserResult;
69.20 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
69.21 import org.netbeans.modules.python.editor.scopes.SymInfo;
69.22 import org.openide.util.NbBundle;
69.23 @@ -76,7 +76,7 @@
69.24
69.25 @Override
69.26 public void run(PythonRuleContext context, List<Hint> result) {
69.27 - CompilationInfo info = context.compilationInfo;
69.28 + PythonParserResult info = (PythonParserResult) context.parserResult;
69.29 Attribute cur = (Attribute)context.node;
69.30 String curAttr = cur.getInternalAttr();
69.31 if (curAttr == null) {
69.32 @@ -101,7 +101,7 @@
69.33 if (range != OffsetRange.NONE) {
69.34 List<HintFix> fixList = Collections.emptyList();
69.35 String message = NbBundle.getMessage(NameRule.class, ACCESS_PROTECTED_VARIABLE, curAttr);
69.36 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 2305);
69.37 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2305);
69.38 result.add(desc);
69.39 }
69.40 }
70.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/AllAssignExists.java Sun Jan 04 13:11:53 2015 -0600
70.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/AllAssignExists.java Sat Feb 28 17:25:32 2015 -0800
70.3 @@ -46,12 +46,11 @@
70.4 import java.util.Set;
70.5 import java.util.prefs.Preferences;
70.6 import javax.swing.JComponent;
70.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
70.8 -import org.netbeans.modules.gsf.api.Hint;
70.9 -import org.netbeans.modules.gsf.api.HintFix;
70.10 -import org.netbeans.modules.gsf.api.HintSeverity;
70.11 -import org.netbeans.modules.gsf.api.OffsetRange;
70.12 -import org.netbeans.modules.gsf.api.RuleContext;
70.13 +import org.netbeans.modules.csl.api.Hint;
70.14 +import org.netbeans.modules.csl.api.HintFix;
70.15 +import org.netbeans.modules.csl.api.HintSeverity;
70.16 +import org.netbeans.modules.csl.api.OffsetRange;
70.17 +import org.netbeans.modules.csl.api.RuleContext;
70.18 import org.netbeans.modules.python.editor.PythonAstUtils;
70.19 import org.netbeans.modules.python.editor.PythonParserResult;
70.20 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
70.21 @@ -92,13 +91,13 @@
70.22 SymInfo sym = topScope.tbl.get(name);
70.23 if (sym == null) {
70.24 // Uh oh -- missing!
70.25 - CompilationInfo info = context.compilationInfo;
70.26 + PythonParserResult info = (PythonParserResult) context.parserResult;
70.27 OffsetRange range = PythonAstUtils.getNameRange(info, str);
70.28 range = PythonLexerUtils.getLexerOffsets(info, range);
70.29 if (range != OffsetRange.NONE) {
70.30 List<HintFix> fixList = Collections.emptyList();
70.31 String message = NbBundle.getMessage(AllAssignExists.class, "AllAssignExistsMsg", name);
70.32 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 205);
70.33 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 205);
70.34 result.add(desc);
70.35 }
70.36 }
71.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/AssignToVariable.java Sun Jan 04 13:11:53 2015 -0600
71.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/AssignToVariable.java Sat Feb 28 17:25:32 2015 -0800
71.3 @@ -54,15 +54,15 @@
71.4 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
71.5 import org.netbeans.editor.BaseDocument;
71.6 import org.netbeans.editor.Utilities;
71.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
71.8 -import org.netbeans.modules.gsf.api.EditList;
71.9 -import org.netbeans.modules.gsf.api.Hint;
71.10 -import org.netbeans.modules.gsf.api.HintFix;
71.11 -import org.netbeans.modules.gsf.api.HintSeverity;
71.12 -import org.netbeans.modules.gsf.api.OffsetRange;
71.13 -import org.netbeans.modules.gsf.api.PreviewableFix;
71.14 -import org.netbeans.modules.gsf.api.RuleContext;
71.15 -import org.netbeans.modules.gsf.spi.GsfUtilities;
71.16 +import org.netbeans.modules.csl.api.EditList;
71.17 +import org.netbeans.modules.csl.api.Hint;
71.18 +import org.netbeans.modules.csl.api.HintFix;
71.19 +import org.netbeans.modules.csl.api.HintSeverity;
71.20 +import org.netbeans.modules.csl.api.OffsetRange;
71.21 +import org.netbeans.modules.csl.api.PreviewableFix;
71.22 +import org.netbeans.modules.csl.api.RuleContext;
71.23 +import org.netbeans.modules.csl.spi.GsfUtilities;
71.24 +import org.netbeans.modules.python.editor.PythonParserResult;
71.25 import org.openide.util.Exceptions;
71.26 import org.openide.util.NbBundle;
71.27 import org.python.antlr.PythonTree;
71.28 @@ -114,7 +114,7 @@
71.29 return;
71.30 }
71.31 }
71.32 - CompilationInfo info = context.compilationInfo;
71.33 + PythonParserResult info = (PythonParserResult) context.parserResult;
71.34 OffsetRange astOffsets = PythonAstUtils.getNameRange(info, node);
71.35 OffsetRange lexOffsets = PythonLexerUtils.getLexerOffsets(info, astOffsets);
71.36 BaseDocument doc = context.doc;
71.37 @@ -125,7 +125,7 @@
71.38 List<HintFix> fixList = new ArrayList<HintFix>();
71.39 fixList.add(new AssignToVariableFix(context, node));
71.40 String displayName = getDisplayName();
71.41 - Hint desc = new Hint(this, displayName, info.getFileObject(), lexOffsets, fixList, 1500);
71.42 + Hint desc = new Hint(this, displayName, info.getSnapshot().getSource().getFileObject(), lexOffsets, fixList, 1500);
71.43 result.add(desc);
71.44 }
71.45 } catch (BadLocationException ex) {
71.46 @@ -190,7 +190,7 @@
71.47
71.48 OffsetRange astRange = PythonAstUtils.getRange(node);
71.49 if (astRange != OffsetRange.NONE) {
71.50 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(context.compilationInfo, astRange);
71.51 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets((PythonParserResult) context.parserResult, astRange);
71.52 if (lexRange != OffsetRange.NONE) {
71.53 int offset = lexRange.getStart();
71.54 StringBuilder sb = new StringBuilder();
71.55 @@ -211,7 +211,7 @@
71.56 Position pos = edits.createPosition(varOffset);
71.57 edits.apply();
71.58 if (pos != null && pos.getOffset() != -1) {
71.59 - JTextComponent target = GsfUtilities.getPaneFor(context.compilationInfo.getFileObject());
71.60 + JTextComponent target = GsfUtilities.getPaneFor(context.parserResult.getSnapshot().getSource().getFileObject());
71.61 if (target != null) {
71.62 int start = pos.getOffset();
71.63 int end = start + varName.length();
72.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/AttributeDefinedOutsideInit.java Sun Jan 04 13:11:53 2015 -0600
72.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/AttributeDefinedOutsideInit.java Sat Feb 28 17:25:32 2015 -0800
72.3 @@ -46,12 +46,11 @@
72.4 import java.util.Set;
72.5 import java.util.prefs.Preferences;
72.6 import javax.swing.JComponent;
72.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
72.8 -import org.netbeans.modules.gsf.api.Hint;
72.9 -import org.netbeans.modules.gsf.api.HintFix;
72.10 -import org.netbeans.modules.gsf.api.HintSeverity;
72.11 -import org.netbeans.modules.gsf.api.OffsetRange;
72.12 -import org.netbeans.modules.gsf.api.RuleContext;
72.13 +import org.netbeans.modules.csl.api.Hint;
72.14 +import org.netbeans.modules.csl.api.HintFix;
72.15 +import org.netbeans.modules.csl.api.HintSeverity;
72.16 +import org.netbeans.modules.csl.api.OffsetRange;
72.17 +import org.netbeans.modules.csl.api.RuleContext;
72.18 import org.netbeans.modules.python.editor.PythonAstUtils;
72.19 import org.netbeans.modules.python.editor.PythonParserResult;
72.20 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
72.21 @@ -76,7 +75,7 @@
72.22
72.23 @Override
72.24 public void run(PythonRuleContext context, List<Hint> result) {
72.25 - CompilationInfo info = context.compilationInfo;
72.26 + PythonParserResult info = (PythonParserResult) context.parserResult;
72.27 PythonParserResult pr = PythonAstUtils.getParseResult(info);
72.28 SymbolTable symbolTable = pr.getSymbolTable();
72.29
72.30 @@ -91,7 +90,7 @@
72.31 String message = NbBundle.getMessage(NameRule.class,
72.32 ATTRIBUTE_DEFINED_OUTSITE_INIT_VAR,
72.33 cur.getInternalAttr());
72.34 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 2305);
72.35 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2305);
72.36 result.add(desc);
72.37 }
72.38 }
73.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/ClassCircularRedundancy.java Sun Jan 04 13:11:53 2015 -0600
73.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/ClassCircularRedundancy.java Sat Feb 28 17:25:32 2015 -0800
73.3 @@ -48,12 +48,11 @@
73.4 import java.util.Set;
73.5 import java.util.prefs.Preferences;
73.6 import javax.swing.JComponent;
73.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
73.8 -import org.netbeans.modules.gsf.api.Hint;
73.9 -import org.netbeans.modules.gsf.api.HintFix;
73.10 -import org.netbeans.modules.gsf.api.HintSeverity;
73.11 -import org.netbeans.modules.gsf.api.OffsetRange;
73.12 -import org.netbeans.modules.gsf.api.RuleContext;
73.13 +import org.netbeans.modules.csl.api.Hint;
73.14 +import org.netbeans.modules.csl.api.HintFix;
73.15 +import org.netbeans.modules.csl.api.HintSeverity;
73.16 +import org.netbeans.modules.csl.api.OffsetRange;
73.17 +import org.netbeans.modules.csl.api.RuleContext;
73.18 import org.netbeans.modules.python.editor.PythonAstUtils;
73.19 import org.netbeans.modules.python.editor.PythonParserResult;
73.20 import org.netbeans.modules.python.editor.scopes.SymbolTable;
73.21 @@ -77,9 +76,8 @@
73.22
73.23 @Override
73.24 public void run(PythonRuleContext context, List<Hint> result) {
73.25 - CompilationInfo info = context.compilationInfo;
73.26 - PythonParserResult pr = PythonAstUtils.getParseResult(info);
73.27 - SymbolTable symbolTable = pr.getSymbolTable();
73.28 + PythonParserResult info = (PythonParserResult) context.parserResult;
73.29 + SymbolTable symbolTable = info.getSymbolTable();
73.30
73.31
73.32 HashMap<ClassDef, String> cyclingRedundancies = symbolTable.getClassesCyclingRedundancies(info);
73.33 @@ -93,7 +91,7 @@
73.34 if (range != OffsetRange.NONE) {
73.35 List<HintFix> fixList = Collections.emptyList();
73.36 String message = NbBundle.getMessage(NameRule.class, CLASS_CIRCULAR_REDUNDANCY_VAR, curCyclingMsg);
73.37 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 2305);
73.38 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2305);
73.39 result.add(desc);
73.40 }
73.41 }
74.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/CreateDocString.java Sun Jan 04 13:11:53 2015 -0600
74.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/CreateDocString.java Sat Feb 28 17:25:32 2015 -0800
74.3 @@ -47,16 +47,16 @@
74.4 import org.netbeans.api.lexer.TokenSequence;
74.5 import org.netbeans.editor.BaseDocument;
74.6 import org.netbeans.editor.Utilities;
74.7 +import org.netbeans.modules.csl.api.EditList;
74.8 +import org.netbeans.modules.csl.api.Hint;
74.9 +import org.netbeans.modules.csl.api.HintFix;
74.10 +import org.netbeans.modules.csl.api.HintSeverity;
74.11 +import org.netbeans.modules.csl.api.OffsetRange;
74.12 +import org.netbeans.modules.csl.api.PreviewableFix;
74.13 +import org.netbeans.modules.csl.api.RuleContext;
74.14 +import org.netbeans.modules.csl.spi.GsfUtilities;
74.15 import org.netbeans.modules.editor.indent.api.IndentUtils;
74.16 -import org.netbeans.modules.gsf.api.CompilationInfo;
74.17 -import org.netbeans.modules.gsf.api.EditList;
74.18 -import org.netbeans.modules.gsf.api.Hint;
74.19 -import org.netbeans.modules.gsf.api.HintFix;
74.20 -import org.netbeans.modules.gsf.api.HintSeverity;
74.21 -import org.netbeans.modules.gsf.api.OffsetRange;
74.22 -import org.netbeans.modules.gsf.api.PreviewableFix;
74.23 -import org.netbeans.modules.gsf.api.RuleContext;
74.24 -import org.netbeans.modules.gsf.spi.GsfUtilities;
74.25 +import org.netbeans.modules.python.editor.PythonParserResult;
74.26 import org.openide.util.Exceptions;
74.27 import org.openide.util.NbBundle;
74.28 import org.python.antlr.PythonTree;
74.29 @@ -89,7 +89,7 @@
74.30 }
74.31
74.32 // Create new fix
74.33 - CompilationInfo info = context.compilationInfo;
74.34 + PythonParserResult info = (PythonParserResult) context.parserResult;
74.35 OffsetRange astOffsets = PythonAstUtils.getNameRange(info, node);
74.36 OffsetRange lexOffsets = PythonLexerUtils.getLexerOffsets(info, astOffsets);
74.37 BaseDocument doc = context.doc;
74.38 @@ -102,7 +102,7 @@
74.39 fixList.add(new CreateDocStringFix(context, node, !singleIsDefault));
74.40 fixList.add(new CreateDocStringFix(context, node, singleIsDefault));
74.41 String displayName = getDisplayName();
74.42 - Hint desc = new Hint(this, displayName, info.getFileObject(), lexOffsets, fixList, 1500);
74.43 + Hint desc = new Hint(this, displayName, info.getSnapshot().getSource().getFileObject(), lexOffsets, fixList, 1500);
74.44 result.add(desc);
74.45 }
74.46 } catch (BadLocationException ex) {
74.47 @@ -168,7 +168,7 @@
74.48
74.49 OffsetRange astRange = PythonAstUtils.getRange(node);
74.50 if (astRange != OffsetRange.NONE) {
74.51 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(context.compilationInfo, astRange);
74.52 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets((PythonParserResult) context.parserResult, astRange);
74.53 if (lexRange != OffsetRange.NONE) {
74.54 // Find the colon
74.55 TokenSequence<? extends PythonTokenId> ts = PythonLexerUtils.getPositionedSequence(doc, lexRange.getStart());
74.56 @@ -209,7 +209,7 @@
74.57 Position pos = edits.createPosition(editListPosition);
74.58 edits.apply();
74.59 if (pos != null && pos.getOffset() != -1) {
74.60 - JTextComponent target = GsfUtilities.getPaneFor(context.compilationInfo.getFileObject());
74.61 + JTextComponent target = GsfUtilities.getPaneFor(context.parserResult.getSnapshot().getSource().getFileObject());
74.62 if (target != null) {
74.63 target.setCaretPosition(pos.getOffset());
74.64 }
75.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/Deprecations.java Sun Jan 04 13:11:53 2015 -0600
75.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/Deprecations.java Sat Feb 28 17:25:32 2015 -0800
75.3 @@ -54,12 +54,12 @@
75.4 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
75.5 import org.netbeans.editor.BaseDocument;
75.6 import org.netbeans.editor.Utilities;
75.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
75.8 -import org.netbeans.modules.gsf.api.Hint;
75.9 -import org.netbeans.modules.gsf.api.HintFix;
75.10 -import org.netbeans.modules.gsf.api.HintSeverity;
75.11 -import org.netbeans.modules.gsf.api.OffsetRange;
75.12 -import org.netbeans.modules.gsf.api.RuleContext;
75.13 +import org.netbeans.modules.csl.api.Hint;
75.14 +import org.netbeans.modules.csl.api.HintFix;
75.15 +import org.netbeans.modules.csl.api.HintSeverity;
75.16 +import org.netbeans.modules.csl.api.OffsetRange;
75.17 +import org.netbeans.modules.csl.api.RuleContext;
75.18 +import org.netbeans.modules.python.editor.PythonParserResult;
75.19 import org.openide.util.Exceptions;
75.20 import org.openide.util.NbBundle;
75.21 import org.python.antlr.PythonTree;
75.22 @@ -228,7 +228,7 @@
75.23 }
75.24
75.25 private void addDeprecation(String module, String rationale, PythonRuleContext context, List<Hint> result) {
75.26 - CompilationInfo info = context.compilationInfo;
75.27 + PythonParserResult info = (PythonParserResult) context.parserResult;
75.28 OffsetRange astOffsets = PythonAstUtils.getNameRange(info, context.node);
75.29 OffsetRange lexOffsets = PythonLexerUtils.getLexerOffsets(info, astOffsets);
75.30 BaseDocument doc = context.doc;
75.31 @@ -243,7 +243,7 @@
75.32 } else {
75.33 displayName = NbBundle.getMessage(Deprecations.class, "DeprecationsMsg", module);
75.34 }
75.35 - Hint desc = new Hint(this, displayName, info.getFileObject(), lexOffsets, fixList, 1500);
75.36 + Hint desc = new Hint(this, displayName, info.getSnapshot().getSource().getFileObject(), lexOffsets, fixList, 1500);
75.37 result.add(desc);
75.38 }
75.39 } catch (BadLocationException ex) {
76.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/ExtractCode.java Sun Jan 04 13:11:53 2015 -0600
76.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/ExtractCode.java Sat Feb 28 17:25:32 2015 -0800
76.3 @@ -40,19 +40,19 @@
76.4 import javax.swing.text.JTextComponent;
76.5 import org.netbeans.editor.BaseDocument;
76.6 import org.netbeans.editor.Utilities;
76.7 +import org.netbeans.modules.csl.api.EditList;
76.8 +import org.netbeans.modules.csl.api.EditRegions;
76.9 +import org.netbeans.modules.csl.api.Hint;
76.10 +import org.netbeans.modules.csl.api.HintFix;
76.11 +import org.netbeans.modules.csl.api.HintSeverity;
76.12 +import org.netbeans.modules.csl.api.OffsetRange;
76.13 +import org.netbeans.modules.csl.api.PreviewableFix;
76.14 +import org.netbeans.modules.csl.api.RuleContext;
76.15 +import org.netbeans.modules.csl.spi.GsfUtilities;
76.16 import org.netbeans.modules.editor.indent.api.IndentUtils;
76.17 -import org.netbeans.modules.gsf.api.CompilationInfo;
76.18 -import org.netbeans.modules.gsf.api.EditList;
76.19 -import org.netbeans.modules.gsf.api.EditRegions;
76.20 -import org.netbeans.modules.gsf.api.Hint;
76.21 -import org.netbeans.modules.gsf.api.HintFix;
76.22 -import org.netbeans.modules.gsf.api.HintSeverity;
76.23 -import org.netbeans.modules.gsf.api.OffsetRange;
76.24 -import org.netbeans.modules.gsf.api.PreviewableFix;
76.25 -import org.netbeans.modules.gsf.api.RuleContext;
76.26 -import org.netbeans.modules.gsf.spi.GsfUtilities;
76.27 import org.netbeans.modules.python.editor.AstPath;
76.28 import org.netbeans.modules.python.editor.PythonAstUtils;
76.29 +import org.netbeans.modules.python.editor.PythonParserResult;
76.30 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
76.31 import org.openide.util.Exceptions;
76.32 import org.openide.util.NbBundle;
76.33 @@ -124,7 +124,7 @@
76.34
76.35 // Adjust the fix range to be right around the dot so that the light bulb ends up
76.36 // on the same line as the caret and alt-enter works
76.37 - JTextComponent target = GsfUtilities.getPaneFor(context.compilationInfo.getFileObject());
76.38 + JTextComponent target = GsfUtilities.getPaneFor(context.parserResult.getSnapshot().getSource().getFileObject());
76.39 if (target != null) {
76.40 int dot = target.getCaret().getDot();
76.41 range = new OffsetRange(dot, dot);
76.42 @@ -145,7 +145,7 @@
76.43 }
76.44 if (fixList.size() > 0) {
76.45 String displayName = getDisplayName();
76.46 - Hint desc = new Hint(this, displayName, context.compilationInfo.getFileObject(),
76.47 + Hint desc = new Hint(this, displayName, context.parserResult.getSnapshot().getSource().getFileObject(),
76.48 range, fixList, 490);
76.49 result.add(desc);
76.50 }
76.51 @@ -227,7 +227,7 @@
76.52
76.53 public EditList getEditList() throws Exception {
76.54 BaseDocument doc = context.doc;
76.55 - CompilationInfo info = context.compilationInfo;
76.56 + PythonParserResult info = (PythonParserResult) context.parserResult;
76.57 EditList edits = new EditList(doc);
76.58
76.59 int extractedOffset = doc.getLength();
76.60 @@ -473,7 +473,7 @@
76.61 ranges.add(new OffsetRange(finalExtractedSiteOffset, finalExtractedSiteOffset + length));
76.62
76.63 // Initiate synchronous editing:
76.64 - EditRegions.getInstance().edit(context.compilationInfo.getFileObject(), ranges, finalExtractedSiteOffset);
76.65 + EditRegions.getInstance().edit(context.parserResult.getSnapshot().getSource().getFileObject(), ranges, finalExtractedSiteOffset);
76.66 }
76.67
76.68 public boolean isSafe() {
77.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/NameRule.java Sun Jan 04 13:11:53 2015 -0600
77.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/NameRule.java Sat Feb 28 17:25:32 2015 -0800
77.3 @@ -39,17 +39,17 @@
77.4 import javax.swing.JComponent;
77.5 import org.netbeans.editor.BaseDocument;
77.6 import org.netbeans.editor.Utilities;
77.7 +import org.netbeans.modules.csl.api.EditList;
77.8 +import org.netbeans.modules.csl.api.Hint;
77.9 +import org.netbeans.modules.csl.api.HintFix;
77.10 +import org.netbeans.modules.csl.api.HintSeverity;
77.11 +import org.netbeans.modules.csl.api.OffsetRange;
77.12 +import org.netbeans.modules.csl.api.PreviewableFix;
77.13 +import org.netbeans.modules.csl.api.RuleContext;
77.14 import org.netbeans.modules.python.editor.PythonAstUtils;
77.15 +import org.netbeans.modules.python.editor.PythonParserResult;
77.16 import org.netbeans.modules.python.editor.PythonUtils;
77.17 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
77.18 -import org.netbeans.modules.gsf.api.CompilationInfo;
77.19 -import org.netbeans.modules.gsf.api.EditList;
77.20 -import org.netbeans.modules.gsf.api.OffsetRange;
77.21 -import org.netbeans.modules.gsf.api.Hint;
77.22 -import org.netbeans.modules.gsf.api.HintFix;
77.23 -import org.netbeans.modules.gsf.api.HintSeverity;
77.24 -import org.netbeans.modules.gsf.api.PreviewableFix;
77.25 -import org.netbeans.modules.gsf.api.RuleContext;
77.26 import org.openide.util.NbBundle;
77.27 import org.python.antlr.PythonTree;
77.28 import org.python.antlr.ast.ClassDef;
77.29 @@ -122,7 +122,7 @@
77.30 PythonTree node = context.node;
77.31 if (node instanceof Module) {
77.32 if (moduleStyle != NO_PREFERENCE) {
77.33 - String moduleName = PythonUtils.getModuleName(context.compilationInfo.getFileObject(), null);
77.34 + String moduleName = PythonUtils.getModuleName(context.parserResult.getSnapshot().getSource().getFileObject());
77.35 if (!moduleStyle.complies(moduleName) && !moduleStyle.complies(moduleName.substring(moduleName.lastIndexOf('.') + 1))) {
77.36 String typeKey = "Module"; // NOI18N
77.37 String message = NbBundle.getMessage(NameRule.class, "WrongStyle", moduleName,
77.38 @@ -220,12 +220,13 @@
77.39 }
77.40 }
77.41 }
77.42 -
77.43 - CompilationInfo info = context.compilationInfo;
77.44 +
77.45 + PythonParserResult info = (PythonParserResult)context.parserResult;
77.46 OffsetRange range;
77.47 if (node instanceof Module) {
77.48 range = new OffsetRange(0, 0);
77.49 } else {
77.50 +
77.51 range = PythonAstUtils.getNameRange(info, node);
77.52 }
77.53 range = PythonLexerUtils.getLexerOffsets(info, range);
77.54 @@ -233,7 +234,7 @@
77.55 if (fixList == null) {
77.56 fixList = Collections.emptyList();
77.57 }
77.58 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 1500);
77.59 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 1500);
77.60 result.add(desc);
77.61 }
77.62 }
77.63 @@ -435,8 +436,8 @@
77.64 BaseDocument doc = context.doc;
77.65 EditList edits = new EditList(doc);
77.66
77.67 - OffsetRange astRange = PythonAstUtils.getNameRange(context.compilationInfo, func);
77.68 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(context.compilationInfo, astRange);
77.69 + OffsetRange astRange = PythonAstUtils.getNameRange((PythonParserResult) context.parserResult, func);
77.70 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets((PythonParserResult) context.parserResult, astRange);
77.71 if (lexRange == OffsetRange.NONE) {
77.72 return edits;
77.73 }
78.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/PythonAstRule.java Sun Jan 04 13:11:53 2015 -0600
78.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/PythonAstRule.java Sat Feb 28 17:25:32 2015 -0800
78.3 @@ -32,8 +32,8 @@
78.4
78.5 import java.util.List;
78.6 import java.util.Set;
78.7 -import org.netbeans.modules.gsf.api.Hint;
78.8 -import org.netbeans.modules.gsf.api.Rule.AstRule;
78.9 +import org.netbeans.modules.csl.api.Hint;
78.10 +import org.netbeans.modules.csl.api.Rule.AstRule;
78.11
78.12 public abstract class PythonAstRule implements AstRule {
78.13 /**
79.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/PythonHintsProvider.java Sun Jan 04 13:11:53 2015 -0600
79.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/PythonHintsProvider.java Sat Feb 28 17:25:32 2015 -0800
79.3 @@ -38,19 +38,19 @@
79.4 import java.util.Map;
79.5 import java.util.Map.Entry;
79.6 import java.util.Set;
79.7 -import org.netbeans.modules.gsf.api.HintSeverity;
79.8 +import org.netbeans.modules.csl.api.Error;
79.9 +import org.netbeans.modules.csl.api.Hint;
79.10 +import org.netbeans.modules.csl.api.HintFix;
79.11 +import org.netbeans.modules.csl.api.HintSeverity;
79.12 +import org.netbeans.modules.csl.api.HintsProvider;
79.13 +import org.netbeans.modules.csl.api.HintsProvider.HintsManager;
79.14 +import org.netbeans.modules.csl.api.OffsetRange;
79.15 +import org.netbeans.modules.csl.api.Rule;
79.16 +import org.netbeans.modules.csl.api.RuleContext;
79.17 +import org.netbeans.modules.csl.spi.GsfUtilities;
79.18 +import org.netbeans.modules.csl.spi.ParserResult;
79.19 import org.netbeans.modules.python.editor.AstPath;
79.20 import org.netbeans.modules.python.editor.PythonAstUtils;
79.21 -import org.netbeans.modules.gsf.api.CompilationInfo;
79.22 -import org.netbeans.modules.gsf.api.Error;
79.23 -import org.netbeans.modules.gsf.api.Hint;
79.24 -import org.netbeans.modules.gsf.api.HintFix;
79.25 -import org.netbeans.modules.gsf.api.HintsProvider;
79.26 -import org.netbeans.modules.gsf.api.OffsetRange;
79.27 -import org.netbeans.modules.gsf.api.ParserResult;
79.28 -import org.netbeans.modules.gsf.api.Rule;
79.29 -import org.netbeans.modules.gsf.api.RuleContext;
79.30 -import org.netbeans.modules.gsf.spi.GsfUtilities;
79.31 import org.netbeans.modules.python.editor.PythonParserResult;
79.32 import org.openide.util.Exceptions;
79.33 import org.python.antlr.PythonTree;
79.34 @@ -89,7 +89,7 @@
79.35 return HintSeverity.ERROR;
79.36 }
79.37 }
79.38 -
79.39 +
79.40 public void computeErrors(HintsManager manager, RuleContext context, List<Hint> result, List<Error> unhandled) {
79.41 ParserResult parserResult = context.parserResult;
79.42 if (parserResult == null) {
79.43 @@ -108,7 +108,7 @@
79.44 }
79.45 }
79.46
79.47 - List<Error> errors = parserResult.getDiagnostics();
79.48 + List<? extends Error> errors = parserResult.getDiagnostics();
79.49 if (errors == null || errors.size() == 0) {
79.50 return;
79.51 }
79.52 @@ -147,7 +147,7 @@
79.53 return;
79.54 }
79.55 @SuppressWarnings("unchecked")
79.56 - List<PythonSelectionRule> hints = (List<PythonSelectionRule>)manager.getSelectionHints();
79.57 + List<? extends Rule.SelectionRule> hints = manager.getSelectionHints();
79.58
79.59 if (hints.isEmpty()) {
79.60 return;
79.61 @@ -165,22 +165,26 @@
79.62 }
79.63 }
79.64
79.65 - private void applySelectionRules(HintsManager manager, RuleContext context, List<PythonSelectionRule> rules, List<Hint> result) {
79.66 + private void applySelectionRules(HintsManager manager, RuleContext context, List<? extends Rule.SelectionRule> rules, List<Hint> result) {
79.67
79.68 PythonRuleContext pythonContext = (PythonRuleContext)context;
79.69
79.70 - for (PythonSelectionRule rule : rules) {
79.71 + for (Rule.SelectionRule rule : rules) {
79.72 if (!rule.appliesTo(context)) {
79.73 continue;
79.74 }
79.75 +
79.76 + if(!(rule instanceof PythonSelectionRule)) {
79.77 + continue;
79.78 + }
79.79
79.80 - if (!manager.isEnabled(rule)) {
79.81 + if (!manager.isEnabled((PythonSelectionRule)rule)) {
79.82 continue;
79.83 }
79.84
79.85 try {
79.86 context.doc.readLock();
79.87 - rule.run(pythonContext, result);
79.88 + ((PythonSelectionRule)rule).run(pythonContext, result);
79.89 } finally {
79.90 context.doc.readUnlock();
79.91 }
79.92 @@ -274,7 +278,7 @@
79.93 try {
79.94 context.doc.readLock();
79.95
79.96 - CompilationInfo info = context.compilationInfo;
79.97 + PythonParserResult info = (PythonParserResult)context.parserResult;
79.98 int astOffset = PythonAstUtils.getAstOffset(info, caretOffset);
79.99 AstPath path = AstPath.get(root, astOffset);
79.100 Iterator<PythonTree> it = path.leafToRoot();
80.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/PythonRuleContext.java Sun Jan 04 13:11:53 2015 -0600
80.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/PythonRuleContext.java Sat Feb 28 17:25:32 2015 -0800
80.3 @@ -38,7 +38,7 @@
80.4 *
80.5 * @author Tor Norbye
80.6 */
80.7 -public class PythonRuleContext extends org.netbeans.modules.gsf.api.RuleContext {
80.8 +public class PythonRuleContext extends org.netbeans.modules.csl.api.RuleContext {
80.9 public AstPath path;
80.10 public PythonTree node;
80.11 public boolean remove;
81.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/PythonSelectionRule.java Sun Jan 04 13:11:53 2015 -0600
81.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/PythonSelectionRule.java Sat Feb 28 17:25:32 2015 -0800
81.3 @@ -31,7 +31,6 @@
81.4 package org.netbeans.modules.python.editor.hints;
81.5
81.6 import javax.swing.text.BadLocationException;
81.7 -import org.netbeans.modules.gsf.api.Rule.SelectionRule;
81.8 import java.util.List;
81.9 import org.netbeans.modules.python.editor.PythonAstUtils;
81.10 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
81.11 @@ -40,9 +39,10 @@
81.12 import org.netbeans.api.lexer.TokenId;
81.13 import org.netbeans.editor.BaseDocument;
81.14 import org.netbeans.editor.Utilities;
81.15 -import org.netbeans.modules.gsf.api.Hint;
81.16 -import org.netbeans.modules.gsf.api.OffsetRange;
81.17 -import org.netbeans.modules.gsf.api.Rule.UserConfigurableRule;
81.18 +import org.netbeans.modules.csl.api.Hint;
81.19 +import org.netbeans.modules.csl.api.OffsetRange;
81.20 +import org.netbeans.modules.csl.api.Rule.SelectionRule;
81.21 +import org.netbeans.modules.csl.api.Rule.UserConfigurableRule;
81.22 import org.openide.util.Exceptions;
81.23 import org.python.antlr.PythonTree;
81.24
81.25 @@ -90,7 +90,7 @@
81.26 return;
81.27 }
81.28
81.29 - OffsetRange astRange = PythonAstUtils.getAstOffsets(context.compilationInfo, new OffsetRange(start, end));
81.30 + OffsetRange astRange = PythonAstUtils.getAstOffsets(context.parserResult, new OffsetRange(start, end));
81.31 if (astRange == OffsetRange.NONE) {
81.32 return;
81.33 }
82.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/RelativeImports.java Sun Jan 04 13:11:53 2015 -0600
82.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/RelativeImports.java Sat Feb 28 17:25:32 2015 -0800
82.3 @@ -52,14 +52,15 @@
82.4 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
82.5 import org.netbeans.editor.BaseDocument;
82.6 import org.netbeans.editor.Utilities;
82.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
82.8 -import org.netbeans.modules.gsf.api.EditList;
82.9 -import org.netbeans.modules.gsf.api.Hint;
82.10 -import org.netbeans.modules.gsf.api.HintFix;
82.11 -import org.netbeans.modules.gsf.api.HintSeverity;
82.12 -import org.netbeans.modules.gsf.api.OffsetRange;
82.13 -import org.netbeans.modules.gsf.api.PreviewableFix;
82.14 -import org.netbeans.modules.gsf.api.RuleContext;
82.15 +import org.netbeans.modules.csl.api.EditList;
82.16 +import org.netbeans.modules.csl.api.Hint;
82.17 +import org.netbeans.modules.csl.api.HintFix;
82.18 +import org.netbeans.modules.csl.api.HintSeverity;
82.19 +import org.netbeans.modules.csl.api.OffsetRange;
82.20 +import org.netbeans.modules.csl.api.PreviewableFix;
82.21 +import org.netbeans.modules.csl.api.RuleContext;
82.22 +import org.netbeans.modules.csl.spi.ParserResult;
82.23 +import org.netbeans.modules.python.editor.PythonParserResult;
82.24 import org.openide.filesystems.FileObject;
82.25 import org.openide.util.Exceptions;
82.26 import org.openide.util.NbBundle;
82.27 @@ -87,7 +88,7 @@
82.28 ImportFrom imp = (ImportFrom)context.node;
82.29 if (imp.getInternalModule() != null && imp.getInternalModule().startsWith(".")) {
82.30 PythonTree node = context.node;
82.31 - CompilationInfo info = context.compilationInfo;
82.32 + PythonParserResult info = (PythonParserResult) context.parserResult;
82.33 OffsetRange astOffsets = PythonAstUtils.getNameRange(info, node);
82.34 OffsetRange lexOffsets = PythonLexerUtils.getLexerOffsets(info, astOffsets);
82.35 BaseDocument doc = context.doc;
82.36 @@ -98,7 +99,7 @@
82.37 List<HintFix> fixList = new ArrayList<HintFix>();
82.38 fixList.add(new RelativeImportsFix(context, imp));
82.39 String displayName = getDisplayName();
82.40 - Hint desc = new Hint(this, displayName, info.getFileObject(), lexOffsets, fixList, 1500);
82.41 + Hint desc = new Hint(this, displayName, info.getSnapshot().getSource().getFileObject(), lexOffsets, fixList, 1500);
82.42 result.add(desc);
82.43 }
82.44 } catch (BadLocationException ex) {
82.45 @@ -167,9 +168,10 @@
82.46
82.47 OffsetRange astRange = PythonAstUtils.getRange(imp);
82.48 if (astRange != OffsetRange.NONE) {
82.49 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(context.compilationInfo, astRange);
82.50 + PythonParserResult info = (PythonParserResult)context.parserResult;
82.51 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(info, astRange);
82.52 if (lexRange != OffsetRange.NONE) {
82.53 - FileObject fo = context.compilationInfo.getFileObject();
82.54 + FileObject fo = info.getSnapshot().getSource().getFileObject();
82.55 if (fo != null) {
82.56 String path = imp.getInternalModule();
82.57 int i = 0;
83.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/SplitImports.java Sun Jan 04 13:11:53 2015 -0600
83.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/SplitImports.java Sat Feb 28 17:25:32 2015 -0800
83.3 @@ -52,16 +52,16 @@
83.4 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
83.5 import org.netbeans.editor.BaseDocument;
83.6 import org.netbeans.editor.Utilities;
83.7 +import org.netbeans.modules.csl.api.EditList;
83.8 +import org.netbeans.modules.csl.api.Hint;
83.9 +import org.netbeans.modules.csl.api.HintFix;
83.10 +import org.netbeans.modules.csl.api.HintSeverity;
83.11 +import org.netbeans.modules.csl.api.OffsetRange;
83.12 +import org.netbeans.modules.csl.api.PreviewableFix;
83.13 +import org.netbeans.modules.csl.api.RuleContext;
83.14 +import org.netbeans.modules.csl.spi.GsfUtilities;
83.15 import org.netbeans.modules.editor.indent.api.IndentUtils;
83.16 -import org.netbeans.modules.gsf.api.CompilationInfo;
83.17 -import org.netbeans.modules.gsf.api.EditList;
83.18 -import org.netbeans.modules.gsf.api.Hint;
83.19 -import org.netbeans.modules.gsf.api.HintFix;
83.20 -import org.netbeans.modules.gsf.api.HintSeverity;
83.21 -import org.netbeans.modules.gsf.api.OffsetRange;
83.22 -import org.netbeans.modules.gsf.api.PreviewableFix;
83.23 -import org.netbeans.modules.gsf.api.RuleContext;
83.24 -import org.netbeans.modules.gsf.spi.GsfUtilities;
83.25 +import org.netbeans.modules.python.editor.PythonParserResult;
83.26 import org.netbeans.modules.python.editor.options.CodeStyle;
83.27 import org.openide.util.Exceptions;
83.28 import org.openide.util.NbBundle;
83.29 @@ -87,7 +87,7 @@
83.30 List<alias> names = imp.getInternalNames();
83.31 if (names != null && names.size() > 1) {
83.32 PythonTree node = context.node;
83.33 - CompilationInfo info = context.compilationInfo;
83.34 + PythonParserResult info = (PythonParserResult)context.parserResult;
83.35 OffsetRange astOffsets = PythonAstUtils.getNameRange(info, node);
83.36 OffsetRange lexOffsets = PythonLexerUtils.getLexerOffsets(info, astOffsets);
83.37 BaseDocument doc = context.doc;
83.38 @@ -98,7 +98,7 @@
83.39 List<HintFix> fixList = new ArrayList<HintFix>();
83.40 fixList.add(new SplitImportsFix(context, imp));
83.41 String displayName = getDisplayName();
83.42 - Hint desc = new Hint(this, displayName, info.getFileObject(), lexOffsets, fixList, 1500);
83.43 + Hint desc = new Hint(this, displayName, info.getSnapshot().getSource().getFileObject(), lexOffsets, fixList, 1500);
83.44 result.add(desc);
83.45 }
83.46 } catch (BadLocationException ex) {
83.47 @@ -163,7 +163,7 @@
83.48
83.49 OffsetRange astRange = PythonAstUtils.getRange(imp);
83.50 if (astRange != OffsetRange.NONE) {
83.51 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(context.compilationInfo, astRange);
83.52 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets((PythonParserResult) context.parserResult, astRange);
83.53 if (lexRange != OffsetRange.NONE) {
83.54 int indent = GsfUtilities.getLineIndent(doc, lexRange.getStart());
83.55 StringBuilder sb = new StringBuilder();
84.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/SurroundWith.java Sun Jan 04 13:11:53 2015 -0600
84.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/SurroundWith.java Sat Feb 28 17:25:32 2015 -0800
84.3 @@ -39,15 +39,15 @@
84.4 import org.netbeans.editor.BaseDocument;
84.5 import org.netbeans.editor.Utilities;
84.6 import org.netbeans.lib.editor.codetemplates.api.CodeTemplateManager;
84.7 +import org.netbeans.modules.csl.api.EditList;
84.8 +import org.netbeans.modules.csl.api.Hint;
84.9 +import org.netbeans.modules.csl.api.HintFix;
84.10 +import org.netbeans.modules.csl.api.HintSeverity;
84.11 +import org.netbeans.modules.csl.api.OffsetRange;
84.12 +import org.netbeans.modules.csl.api.PreviewableFix;
84.13 +import org.netbeans.modules.csl.api.RuleContext;
84.14 +import org.netbeans.modules.csl.spi.GsfUtilities;
84.15 import org.netbeans.modules.editor.indent.api.IndentUtils;
84.16 -import org.netbeans.modules.gsf.api.EditList;
84.17 -import org.netbeans.modules.gsf.api.Hint;
84.18 -import org.netbeans.modules.gsf.api.HintFix;
84.19 -import org.netbeans.modules.gsf.api.HintSeverity;
84.20 -import org.netbeans.modules.gsf.api.OffsetRange;
84.21 -import org.netbeans.modules.gsf.api.PreviewableFix;
84.22 -import org.netbeans.modules.gsf.api.RuleContext;
84.23 -import org.netbeans.modules.gsf.spi.GsfUtilities;
84.24 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
84.25 import org.openide.util.Exceptions;
84.26 import org.openide.util.NbBundle;
84.27 @@ -80,7 +80,7 @@
84.28
84.29 // Adjust the fix range to be right around the dot so that the light bulb ends up
84.30 // on the same line as the caret and alt-enter works
84.31 - JTextComponent target = GsfUtilities.getPaneFor(context.compilationInfo.getFileObject());
84.32 + JTextComponent target = GsfUtilities.getPaneFor(context.parserResult.getSnapshot().getSource().getFileObject());
84.33 if (target != null) {
84.34 int dot = target.getCaret().getDot();
84.35 range = new OffsetRange(dot, dot);
84.36 @@ -91,7 +91,7 @@
84.37 fixList.add(new SurroundWithFix(context, start, end, true, true));
84.38 fixList.add(new SurroundWithFix(context, start, end, true, false));
84.39 String displayName = getDisplayName();
84.40 - Hint desc = new Hint(this, displayName, context.compilationInfo.getFileObject(),
84.41 + Hint desc = new Hint(this, displayName, context.parserResult.getSnapshot().getSource().getFileObject(),
84.42 range, fixList, 1500);
84.43 result.add(desc);
84.44 }
84.45 @@ -250,7 +250,7 @@
84.46 public void implement() throws Exception {
84.47 EditList edits = getEditList(true);
84.48
84.49 - JTextComponent target = GsfUtilities.getPaneFor(context.compilationInfo.getFileObject());
84.50 + JTextComponent target = GsfUtilities.getPaneFor(context.parserResult.getSnapshot().getSource().getFileObject());
84.51 edits.apply();
84.52 if (target != null) {
84.53 if (codeTemplateText != null && codeTemplatePos != null) {
85.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/UnresolvedClassComponents.java Sun Jan 04 13:11:53 2015 -0600
85.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/UnresolvedClassComponents.java Sat Feb 28 17:25:32 2015 -0800
85.3 @@ -46,12 +46,11 @@
85.4 import java.util.Set;
85.5 import java.util.prefs.Preferences;
85.6 import javax.swing.JComponent;
85.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
85.8 -import org.netbeans.modules.gsf.api.Hint;
85.9 -import org.netbeans.modules.gsf.api.HintFix;
85.10 -import org.netbeans.modules.gsf.api.HintSeverity;
85.11 -import org.netbeans.modules.gsf.api.OffsetRange;
85.12 -import org.netbeans.modules.gsf.api.RuleContext;
85.13 +import org.netbeans.modules.csl.api.Hint;
85.14 +import org.netbeans.modules.csl.api.HintFix;
85.15 +import org.netbeans.modules.csl.api.HintSeverity;
85.16 +import org.netbeans.modules.csl.api.OffsetRange;
85.17 +import org.netbeans.modules.csl.api.RuleContext;
85.18 import org.netbeans.modules.python.editor.PythonAstUtils;
85.19 import org.netbeans.modules.python.editor.PythonParserResult;
85.20 import org.netbeans.modules.python.editor.imports.ImportManager;
85.21 @@ -86,7 +85,7 @@
85.22 return Collections.<Class>singleton(Module.class);
85.23 }
85.24
85.25 - private void populateMessages( CompilationInfo info, List<PythonTree> unresolved , List<Hint> result ,boolean isClass ) {
85.26 + private void populateMessages( PythonParserResult info, List<PythonTree> unresolved , List<Hint> result ,boolean isClass ) {
85.27 if (unresolved.size() > 0) {
85.28
85.29 for (PythonTree node : unresolved) {
85.30 @@ -104,7 +103,7 @@
85.31 OffsetRange range = PythonAstUtils.getRange( node);
85.32 range = PythonLexerUtils.getLexerOffsets(info, range);
85.33 if (range != OffsetRange.NONE) {
85.34 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 2305);
85.35 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2305);
85.36 result.add(desc);
85.37 }
85.38 }
85.39 @@ -113,9 +112,8 @@
85.40
85.41
85.42 public void run(PythonRuleContext context, List<Hint> result) {
85.43 - CompilationInfo info = context.compilationInfo;
85.44 - PythonParserResult pr = PythonAstUtils.getParseResult(info);
85.45 - SymbolTable symbolTable = pr.getSymbolTable();
85.46 + PythonParserResult info = (PythonParserResult) context.parserResult;
85.47 + SymbolTable symbolTable = info.getSymbolTable();
85.48
85.49 List<PythonTree> unresolvedAttributes = symbolTable.getUnresolvedAttributes(info);
85.50 populateMessages(info,unresolvedAttributes,result,false) ;
85.51 @@ -181,7 +179,7 @@
85.52 symbol = mod.substring(colon + 1, end).trim();
85.53 mod = mod.substring(0, colon).trim();
85.54 }
85.55 - new ImportManager(context.compilationInfo).ensureImported(mod, symbol, false, false, true);
85.56 + new ImportManager((PythonParserResult) context.parserResult).ensureImported(mod, symbol, false, false, true);
85.57 }
85.58
85.59 public boolean isSafe() {
86.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/UnresolvedDetector.java Sun Jan 04 13:11:53 2015 -0600
86.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/UnresolvedDetector.java Sat Feb 28 17:25:32 2015 -0800
86.3 @@ -47,13 +47,12 @@
86.4 import java.util.Set;
86.5 import java.util.prefs.Preferences;
86.6 import javax.swing.JComponent;
86.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
86.8 -import org.netbeans.modules.gsf.api.Hint;
86.9 -import org.netbeans.modules.gsf.api.HintFix;
86.10 -import org.netbeans.modules.gsf.api.HintSeverity;
86.11 -import org.netbeans.modules.gsf.api.NameKind;
86.12 -import org.netbeans.modules.gsf.api.OffsetRange;
86.13 -import org.netbeans.modules.gsf.api.RuleContext;
86.14 +import org.netbeans.modules.csl.api.Hint;
86.15 +import org.netbeans.modules.csl.api.HintFix;
86.16 +import org.netbeans.modules.csl.api.HintSeverity;
86.17 +import org.netbeans.modules.csl.api.OffsetRange;
86.18 +import org.netbeans.modules.csl.api.RuleContext;
86.19 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
86.20 import org.netbeans.modules.python.editor.PythonAstUtils;
86.21 import org.netbeans.modules.python.editor.PythonIndex;
86.22 import org.netbeans.modules.python.editor.PythonParserResult;
86.23 @@ -86,13 +85,12 @@
86.24 }
86.25
86.26 public void run(PythonRuleContext context, List<Hint> result) {
86.27 - CompilationInfo info = context.compilationInfo;
86.28 - PythonParserResult pr = PythonAstUtils.getParseResult(info);
86.29 - SymbolTable symbolTable = pr.getSymbolTable();
86.30 + PythonParserResult info = (PythonParserResult) context.parserResult;
86.31 + SymbolTable symbolTable = info.getSymbolTable();
86.32
86.33 List<PythonTree> unresolvedNames = symbolTable.getUnresolved(info);
86.34 if (unresolvedNames.size() > 0) {
86.35 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE), info.getFileObject());
86.36 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
86.37
86.38 for (PythonTree node : unresolvedNames) {
86.39 // Compute suggestions
86.40 @@ -121,7 +119,7 @@
86.41 } else if (name.equals("this")) {
86.42 message = NbBundle.getMessage(NameRule.class, "UnresolvedVariableMaybe", name, "self"); // NOI18N
86.43 } else if (tryModule) {
86.44 - Set<IndexedElement> moduleElements = index.getModules(name, NameKind.EXACT_NAME);
86.45 + Set<IndexedElement> moduleElements = index.getModules(name, QuerySupport.Kind.EXACT);
86.46 if (moduleElements.size() > 0) {
86.47 fixList.add(new ImportFix(context, node, name));
86.48 }
86.49 @@ -137,7 +135,7 @@
86.50 OffsetRange range = PythonAstUtils.getNameRange(info, node);
86.51 range = PythonLexerUtils.getLexerOffsets(info, range);
86.52 if (range != OffsetRange.NONE) {
86.53 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 2305);
86.54 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2305);
86.55 result.add(desc);
86.56 }
86.57 }
86.58 @@ -202,7 +200,7 @@
86.59 symbol = mod.substring(colon + 1, end).trim();
86.60 mod = mod.substring(0, colon).trim();
86.61 }
86.62 - new ImportManager(context.compilationInfo).ensureImported(mod, symbol, false, false, true);
86.63 + new ImportManager((PythonParserResult) context.parserResult).ensureImported(mod, symbol, false, false, true);
86.64 }
86.65
86.66 public boolean isSafe() {
87.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/UnusedDetector.java Sun Jan 04 13:11:53 2015 -0600
87.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/UnusedDetector.java Sat Feb 28 17:25:32 2015 -0800
87.3 @@ -48,12 +48,11 @@
87.4 import java.util.Set;
87.5 import java.util.prefs.Preferences;
87.6 import javax.swing.JComponent;
87.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
87.8 -import org.netbeans.modules.gsf.api.Hint;
87.9 -import org.netbeans.modules.gsf.api.HintFix;
87.10 -import org.netbeans.modules.gsf.api.HintSeverity;
87.11 -import org.netbeans.modules.gsf.api.OffsetRange;
87.12 -import org.netbeans.modules.gsf.api.RuleContext;
87.13 +import org.netbeans.modules.csl.api.Hint;
87.14 +import org.netbeans.modules.csl.api.HintFix;
87.15 +import org.netbeans.modules.csl.api.HintSeverity;
87.16 +import org.netbeans.modules.csl.api.OffsetRange;
87.17 +import org.netbeans.modules.csl.api.RuleContext;
87.18 import org.netbeans.modules.python.editor.PythonAstUtils;
87.19 import org.netbeans.modules.python.editor.PythonParserResult;
87.20 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
87.21 @@ -93,9 +92,8 @@
87.22 }
87.23
87.24 public void run(PythonRuleContext context, List<Hint> result) {
87.25 - CompilationInfo info = context.compilationInfo;
87.26 - PythonParserResult pr = PythonAstUtils.getParseResult(info);
87.27 - SymbolTable symbolTable = pr.getSymbolTable();
87.28 + PythonParserResult info = (PythonParserResult) context.parserResult;
87.29 + SymbolTable symbolTable = info.getSymbolTable();
87.30
87.31 boolean skipParams = true;
87.32 Preferences pref = context.manager.getPreferences(this);
87.33 @@ -138,7 +136,7 @@
87.34 if (range != OffsetRange.NONE) {
87.35 List<HintFix> fixList = new ArrayList<HintFix>(3);
87.36 String message = NbBundle.getMessage(NameRule.class, "UnusedVariable", name);
87.37 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 2305);
87.38 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2305);
87.39 result.add(desc);
87.40 }
87.41 }
88.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/UnusedImports.java Sun Jan 04 13:11:53 2015 -0600
88.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/UnusedImports.java Sat Feb 28 17:25:32 2015 -0800
88.3 @@ -50,13 +50,12 @@
88.4 import java.util.prefs.Preferences;
88.5 import javax.swing.JComponent;
88.6 import org.netbeans.editor.BaseDocument;
88.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
88.8 -import org.netbeans.modules.gsf.api.EditList;
88.9 -import org.netbeans.modules.gsf.api.Hint;
88.10 -import org.netbeans.modules.gsf.api.HintFix;
88.11 -import org.netbeans.modules.gsf.api.HintSeverity;
88.12 -import org.netbeans.modules.gsf.api.OffsetRange;
88.13 -import org.netbeans.modules.gsf.api.RuleContext;
88.14 +import org.netbeans.modules.csl.api.EditList;
88.15 +import org.netbeans.modules.csl.api.Hint;
88.16 +import org.netbeans.modules.csl.api.HintFix;
88.17 +import org.netbeans.modules.csl.api.HintSeverity;
88.18 +import org.netbeans.modules.csl.api.OffsetRange;
88.19 +import org.netbeans.modules.csl.api.RuleContext;
88.20 import org.netbeans.modules.python.editor.PythonAstUtils;
88.21 import org.netbeans.modules.python.editor.PythonParserResult;
88.22 import org.netbeans.modules.python.editor.imports.ImportEntry;
88.23 @@ -81,7 +80,7 @@
88.24 }
88.25
88.26 public boolean appliesTo(RuleContext context) {
88.27 - FileObject fo = context.compilationInfo.getFileObject();
88.28 + FileObject fo = context.parserResult.getSnapshot().getSource().getFileObject();
88.29 return fo == null || !fo.getName().equals("__init__"); // NOI18N
88.30 }
88.31
88.32 @@ -96,11 +95,10 @@
88.33 private static void computeUnusedImports(UnusedImports detector, PythonRuleContext context, List<Hint> result, Map<PythonTree, List<String>> unused) {
88.34 assert result == null || unused == null; // compute either results or set of unused
88.35
88.36 - CompilationInfo info = context.compilationInfo;
88.37 - PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
88.38 - SymbolTable symbolTable = parseResult.getSymbolTable();
88.39 + PythonParserResult info = (PythonParserResult) context.parserResult;
88.40 + SymbolTable symbolTable = info.getSymbolTable();
88.41 List<ImportEntry> unusedImports = symbolTable.getUnusedImports();
88.42 - if (unusedImports.size() == 0) {
88.43 + if (unusedImports.isEmpty()) {
88.44 return;
88.45 }
88.46 Map<PythonTree, List<String>> maps = new HashMap<PythonTree, List<String>>();
88.47 @@ -150,7 +148,7 @@
88.48 }
88.49
88.50 private static void addError(UnusedImports detector, PythonRuleContext context, PythonTree node, List<String> symbols, List<Hint> result) {
88.51 - CompilationInfo info = context.compilationInfo;
88.52 + PythonParserResult info = (PythonParserResult) context.parserResult;
88.53 OffsetRange range = PythonAstUtils.getNameRange(info, node);
88.54 range = PythonLexerUtils.getLexerOffsets(info, range);
88.55 if (range != OffsetRange.NONE) {
88.56 @@ -164,7 +162,7 @@
88.57 } else {
88.58 message = NbBundle.getMessage(NameRule.class, "UnusedImport");
88.59 }
88.60 - Hint desc = new Hint(detector, message, info.getFileObject(), range, fixList, 2500);
88.61 + Hint desc = new Hint(detector, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2500);
88.62 result.add(desc);
88.63 }
88.64 }
88.65 @@ -237,7 +235,7 @@
88.66 BaseDocument doc = context.doc;
88.67 EditList edits = new EditList(doc);
88.68
88.69 - ImportManager importManager = new ImportManager(context.compilationInfo);
88.70 + ImportManager importManager = new ImportManager((PythonParserResult) context.parserResult);
88.71
88.72 if (node == null) {
88.73 if (organizeOnly) {
89.1 --- a/python.editor/src/org/netbeans/modules/python/editor/imports/FastImportAction.java Sun Jan 04 13:11:53 2015 -0600
89.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/imports/FastImportAction.java Sat Feb 28 17:25:32 2015 -0800
89.3 @@ -58,13 +58,10 @@
89.4 import javax.swing.text.JTextComponent;
89.5 import org.netbeans.editor.BaseAction;
89.6 import org.netbeans.editor.Utilities;
89.7 -import org.netbeans.modules.gsf.api.CancellableTask;
89.8 -import org.netbeans.modules.gsf.api.CompilationInfo;
89.9 -import org.netbeans.modules.gsf.api.SourceModel;
89.10 -import org.netbeans.modules.gsf.api.SourceModelFactory;
89.11 -import org.netbeans.modules.gsf.spi.GsfUtilities;
89.12 +import org.netbeans.modules.csl.spi.GsfUtilities;
89.13 import org.netbeans.modules.python.editor.PythonAstUtils;
89.14 import org.netbeans.modules.python.editor.PythonIndex;
89.15 +import org.netbeans.modules.python.editor.PythonParserResult;
89.16 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
89.17 import org.openide.ErrorManager;
89.18 import org.openide.filesystems.FileObject;
89.19 @@ -103,29 +100,29 @@
89.20 return;
89.21 }
89.22
89.23 - SourceModel model = SourceModelFactory.getInstance().getModel(file);
89.24 - if (model != null) {
89.25 - final CompilationInfo[] infoHolder = new CompilationInfo[1];
89.26 - try {
89.27 - model.runUserActionTask(new CancellableTask<CompilationInfo>() {
89.28 - public void cancel() {
89.29 - }
89.30 -
89.31 - public void run(CompilationInfo info) throws Exception {
89.32 - importItem(info, where, caretRectangle, font, position, ident);
89.33 - }
89.34 - }, false);
89.35 - } catch (IOException ex) {
89.36 - Exceptions.printStackTrace(ex);
89.37 - }
89.38 - }
89.39 +// SourceModel model = SourceModelFactory.getInstance().getModel(file);
89.40 +// if (model != null) {
89.41 +// final CompilationInfo[] infoHolder = new CompilationInfo[1];
89.42 +// try {
89.43 +// model.runUserActionTask(new CancellableTask<CompilationInfo>() {
89.44 +// public void cancel() {
89.45 +// }
89.46 +//
89.47 +// public void run(CompilationInfo info) throws Exception {
89.48 +// importItem(info, where, caretRectangle, font, position, ident);
89.49 +// }
89.50 +// }, false);
89.51 +// } catch (IOException ex) {
89.52 +// Exceptions.printStackTrace(ex);
89.53 +// }
89.54 +// }
89.55
89.56 } catch (BadLocationException ex) {
89.57 ErrorManager.getDefault().notify(ex);
89.58 }
89.59 }
89.60
89.61 - private void importItem(final CompilationInfo info, final Point where, final Rectangle caretRectangle, final Font font, final int position, final String ident) {
89.62 + private void importItem(final PythonParserResult info, final Point where, final Rectangle caretRectangle, final Font font, final int position, final String ident) {
89.63 PythonTree root = PythonAstUtils.getRoot(info);
89.64 if (root == null) {
89.65 Toolkit.getDefaultToolkit().beep();
89.66 @@ -133,7 +130,7 @@
89.67 }
89.68
89.69 // Compute suggestions
89.70 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE), info.getFileObject());
89.71 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
89.72 Set<String> modules = index.getImportsFor(ident, true);
89.73
89.74 // TODO - check the file to pick a better default (based on existing imports, usages of the symbol
90.1 --- a/python.editor/src/org/netbeans/modules/python/editor/imports/FixImportsAction.java Sun Jan 04 13:11:53 2015 -0600
90.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/imports/FixImportsAction.java Sat Feb 28 17:25:32 2015 -0800
90.3 @@ -44,7 +44,6 @@
90.4 import java.awt.Dialog;
90.5 import java.awt.Toolkit;
90.6 import java.awt.event.ActionEvent;
90.7 -import java.io.IOException;
90.8 import java.util.ArrayList;
90.9 import java.util.Collections;
90.10 import java.util.HashMap;
90.11 @@ -54,16 +53,17 @@
90.12 import java.util.Set;
90.13 import java.util.prefs.Preferences;
90.14 import javax.swing.Icon;
90.15 -import javax.swing.ImageIcon;
90.16 import javax.swing.text.JTextComponent;
90.17 import org.netbeans.editor.BaseAction;
90.18 import org.netbeans.editor.BaseDocument;
90.19 -import org.netbeans.modules.gsf.api.CancellableTask;
90.20 -import org.netbeans.modules.gsf.api.CompilationInfo;
90.21 -import org.netbeans.modules.gsf.api.SourceModel;
90.22 -import org.netbeans.modules.gsf.api.SourceModelFactory;
90.23 -import org.netbeans.modules.gsf.spi.GsfUtilities;
90.24 +import org.netbeans.modules.csl.spi.GsfUtilities;
90.25 +import org.netbeans.modules.parsing.api.ParserManager;
90.26 +import org.netbeans.modules.parsing.api.ResultIterator;
90.27 +import org.netbeans.modules.parsing.api.Source;
90.28 +import org.netbeans.modules.parsing.api.UserTask;
90.29 +import org.netbeans.modules.parsing.spi.ParseException;
90.30 import org.netbeans.modules.python.editor.PythonAstUtils;
90.31 +import org.netbeans.modules.python.editor.PythonParserResult;
90.32 import org.netbeans.modules.python.editor.options.CodeStyle.ImportCleanupStyle;
90.33 import org.openide.DialogDescriptor;
90.34 import org.openide.DialogDisplayer;
90.35 @@ -129,21 +129,20 @@
90.36 // Move imports that I think may be unused to the end - or just comment them out?
90.37
90.38 // For imports: Gather imports from everywhere... move others into the same section
90.39 - CompilationInfo info = null;
90.40 + PythonParserResult info = null;
90.41
90.42 - SourceModel model = SourceModelFactory.getInstance().getModel(fo);
90.43 + Source model = Source.create(fo);
90.44 if (model != null) {
90.45 - final CompilationInfo[] infoHolder = new CompilationInfo[1];
90.46 + final PythonParserResult[] infoHolder = new PythonParserResult[1];
90.47 try {
90.48 - model.runUserActionTask(new CancellableTask<CompilationInfo>() {
90.49 - public void cancel() {
90.50 + ParserManager.parse(Collections.singleton(model), new UserTask() {
90.51 +
90.52 + @Override
90.53 + public void run(ResultIterator resultIterator) throws Exception {
90.54 + infoHolder[0] = (PythonParserResult) resultIterator.getParserResult();
90.55 }
90.56 -
90.57 - public void run(CompilationInfo info) throws Exception {
90.58 - infoHolder[0] = info;
90.59 - }
90.60 - }, false);
90.61 - } catch (IOException ex) {
90.62 + });
90.63 + } catch (ParseException ex) {
90.64 Exceptions.printStackTrace(ex);
90.65 }
90.66 info = infoHolder[0];
91.1 --- a/python.editor/src/org/netbeans/modules/python/editor/imports/ImportManager.java Sun Jan 04 13:11:53 2015 -0600
91.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/imports/ImportManager.java Sat Feb 28 17:25:32 2015 -0800
91.3 @@ -43,7 +43,6 @@
91.4
91.5 import java.awt.Toolkit;
91.6 import java.util.ArrayList;
91.7 -import java.util.Arrays;
91.8 import java.util.Collection;
91.9 import java.util.Collections;
91.10 import java.util.HashMap;
91.11 @@ -55,14 +54,14 @@
91.12 import org.netbeans.api.editor.EditorRegistry;
91.13 import org.netbeans.editor.BaseDocument;
91.14 import org.netbeans.editor.Utilities;
91.15 +import org.netbeans.modules.csl.api.EditList;
91.16 +import org.netbeans.modules.csl.api.OffsetRange;
91.17 +import org.netbeans.modules.csl.spi.GsfUtilities;
91.18 import org.netbeans.modules.editor.indent.api.IndentUtils;
91.19 -import org.netbeans.modules.gsf.api.CompilationInfo;
91.20 -import org.netbeans.modules.gsf.api.EditList;
91.21 -import org.netbeans.modules.gsf.api.Index;
91.22 -import org.netbeans.modules.gsf.api.NameKind;
91.23 -import org.netbeans.modules.gsf.api.OffsetRange;
91.24 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
91.25 import org.netbeans.modules.python.editor.PythonAstUtils;
91.26 import org.netbeans.modules.python.editor.PythonIndex;
91.27 +import org.netbeans.modules.python.editor.PythonParserResult;
91.28 import org.netbeans.modules.python.editor.elements.IndexedElement;
91.29 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
91.30 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
91.31 @@ -96,7 +95,7 @@
91.32 static final String PREFS_KEY = FixImportsAction.class.getName();
91.33 // TODO - use document style instead!
91.34 static final String KEY_REMOVE_UNUSED_IMPORTS = "removeUnusedImports"; // NOI18N
91.35 - private CompilationInfo info;
91.36 + private PythonParserResult info;
91.37 private List<Import> imports;
91.38 private List<ImportFrom> importsFrom;
91.39 private PythonTree root;
91.40 @@ -113,15 +112,15 @@
91.41 private boolean removeDuplicates;
91.42 private int rightMargin;
91.43
91.44 - public ImportManager(CompilationInfo info) {
91.45 - this(info, (BaseDocument)info.getDocument(), null);
91.46 + public ImportManager(PythonParserResult info) {
91.47 + this(info, GsfUtilities.getDocument(info.getSnapshot().getSource().getFileObject(), false), null);
91.48 }
91.49
91.50 - public ImportManager(CompilationInfo info, BaseDocument doc) {
91.51 + public ImportManager(PythonParserResult info, BaseDocument doc) {
91.52 this(info, doc, null);
91.53 }
91.54
91.55 - public ImportManager(CompilationInfo info, BaseDocument doc, CodeStyle codeStyle) {
91.56 + public ImportManager(PythonParserResult info, BaseDocument doc, CodeStyle codeStyle) {
91.57 this.info = info;
91.58
91.59 root = PythonAstUtils.getRoot(info);
91.60 @@ -209,7 +208,7 @@
91.61
91.62 boolean ambiguous = false;
91.63
91.64 - SymbolTable symbolTable = new SymbolTable(PythonAstUtils.getRoot(info), info.getFileObject());
91.65 + SymbolTable symbolTable = new SymbolTable(PythonAstUtils.getRoot(info), info.getSnapshot().getSource().getFileObject());
91.66 Map<String, SymInfo> unresolved = symbolTable.getUnresolvedNames(info);
91.67
91.68 if (unresolved.size() > 0) {
91.69 @@ -217,9 +216,8 @@
91.70 Collections.sort(ambiguousSymbols);
91.71
91.72 // Try to compute suggestions.
91.73 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
91.74 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
91.75 - Set<IndexedElement> modules = index.getModules("", NameKind.PREFIX);
91.76 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
91.77 + Set<IndexedElement> modules = index.getModules("", QuerySupport.Kind.PREFIX);
91.78 for (IndexedElement module : modules) {
91.79 String name = module.getName();
91.80 if (unresolved.containsKey(name)) {
91.81 @@ -536,8 +534,7 @@
91.82 removeImports(edits, filtered, cleanup == ImportCleanupStyle.COMMENT_OUT, null);
91.83 }
91.84
91.85 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
91.86 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
91.87 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
91.88
91.89 Collection<ImportEntry> newEntries = new ArrayList<ImportEntry>();
91.90 if (selections != null) {
91.91 @@ -752,8 +749,7 @@
91.92 public void rewriteMainImports(EditList edits, Collection<ImportEntry> newEntries, Set<ImportEntry> remove) {
91.93 // Items to be deleted should be deleted after this
91.94
91.95 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
91.96 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
91.97 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
91.98
91.99 // TODO:
91.100 // Look for comments to preserve
92.1 --- a/python.editor/src/org/netbeans/modules/python/editor/imports/ImportModulePanel.java Sun Jan 04 13:11:53 2015 -0600
92.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/imports/ImportModulePanel.java Sat Feb 28 17:25:32 2015 -0800
92.3 @@ -53,7 +53,6 @@
92.4 import java.util.List;
92.5 import javax.swing.DefaultListCellRenderer;
92.6 import javax.swing.DefaultListModel;
92.7 -import javax.swing.ImageIcon;
92.8 import javax.swing.JLabel;
92.9 import javax.swing.JList;
92.10 import javax.swing.KeyStroke;
92.11 @@ -63,9 +62,10 @@
92.12 import org.netbeans.api.lexer.TokenHierarchy;
92.13 import org.netbeans.editor.BaseDocument;
92.14 import org.netbeans.editor.Utilities;
92.15 -import org.netbeans.modules.gsf.api.CompilationInfo;
92.16 -import org.netbeans.modules.gsf.api.ElementKind;
92.17 +import org.netbeans.modules.csl.api.ElementKind;
92.18 +import org.netbeans.modules.csl.spi.GsfUtilities;
92.19 import org.netbeans.modules.python.editor.PythonIndex;
92.20 +import org.netbeans.modules.python.editor.PythonParserResult;
92.21 import org.netbeans.modules.python.editor.lexer.Call;
92.22 import org.openide.util.Exceptions;
92.23 import org.openide.util.ImageUtilities;
92.24 @@ -84,13 +84,13 @@
92.25 public class ImportModulePanel extends javax.swing.JPanel {
92.26
92.27 private final String ident;
92.28 - private CompilationInfo info;
92.29 + private PythonParserResult info;
92.30 private DefaultListModel model;
92.31 private final int position;
92.32
92.33 /** Creates new form ImportClassPanel */
92.34 @SuppressWarnings("deprecation")
92.35 - public ImportModulePanel(String ident, List</*TypeElement*/String> priviledged, List</*TypeElement*/String> denied, Font font, CompilationInfo info, int position) {
92.36 + public ImportModulePanel(String ident, List</*TypeElement*/String> priviledged, List</*TypeElement*/String> denied, Font font, PythonParserResult info, int position) {
92.37 this.ident = ident;
92.38 // System.err.println("priviledged=" + priviledged);
92.39 // System.err.println("denied=" + denied);
92.40 @@ -304,7 +304,7 @@
92.41 }
92.42 PopupUtil.hidePopup();
92.43
92.44 - Document document = info.getDocument();
92.45 + Document document = info.getSnapshot().getSource().getDocument(false);
92.46 try {
92.47 Position pos = document.createPosition(position);
92.48
93.1 --- a/python.editor/src/org/netbeans/modules/python/editor/layer.xml Sun Jan 04 13:11:53 2015 -0600
93.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/layer.xml Sat Feb 28 17:25:32 2015 -0800
93.3 @@ -1,5 +1,5 @@
93.4 <?xml version="1.0" encoding="UTF-8"?>
93.5 -<!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 1.1//EN" "http://www.netbeans.org/dtds/filesystem-1_1.dtd">
93.6 +<!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 1.2//EN" "http://www.netbeans.org/dtds/filesystem-1_2.dtd">
93.7 <filesystem>
93.8
93.9 <folder name="Editors">
93.10 @@ -104,8 +104,8 @@
93.11
93.12
93.13 </folder>
93.14 -
93.15 - <!-- Embedded double-quoted strings -->
93.16 +<!--
93.17 + Embedded double-quoted strings
93.18 <folder name="x-python-string">
93.19 <attr name="SystemFileSystem.localizingBundle" stringvalue="org.netbeans.modules.python.editor.Bundle"/>
93.20 <file name="language.instance">
93.21 @@ -129,20 +129,20 @@
93.22 </folder>
93.23 <folder name="CityLights">
93.24 <folder name="Defaults">
93.25 - <!-- This is just the bluetheme again - not right, but it's better
93.26 - to use a dark theme than the light theme a a backup. -->
93.27 + This is just the bluetheme again - not right, but it's better
93.28 + to use a dark theme than the light theme a a backup.
93.29 <file name="python-colorings.xml" url="resources/BlueTheme-Python-Strings.xml">
93.30 <attr name="SystemFileSystem.localizingBundle" stringvalue="org.netbeans.modules.python.editor.resources.Bundle"/>
93.31 </file>
93.32 </folder>
93.33 </folder>
93.34 </folder>
93.35 - </folder>
93.36 + </folder>-->
93.37
93.38 </folder>
93.39 </folder>
93.40
93.41 - <folder name="gsf-hints">
93.42 + <folder name="csl-hints">
93.43 <folder name="text">
93.44 <folder name="x-python">
93.45 <folder name="hints">
93.46 @@ -173,11 +173,11 @@
93.47 </folder>
93.48 </folder>
93.49
93.50 - <folder name="GsfPlugins">
93.51 + <folder name="CslPlugins">
93.52 <folder name="text">
93.53 <folder name="x-python">
93.54 <file name="language.instance">
93.55 - <attr name="instanceOf" stringvalue="org.netbeans.modules.gsf.api.GsfLanguage"/>
93.56 +<!-- <attr name="instanceOf" stringvalue="org.netbeans.modules.gsf.api.GsfLanguage"/>-->
93.57 <attr name="instanceClass" stringvalue="org.netbeans.modules.python.editor.PythonLanguage"/>
93.58 </file>
93.59 <file name="structure.instance">
93.60 @@ -195,74 +195,6 @@
93.61 <folder name="x-python">
93.62 <attr name="SystemFileSystem.icon" urlvalue="nbresloc:/org/netbeans/modules/python/editor/resources/pyNode25.png"/>
93.63 <attr name="iconBase" stringvalue="org/netbeans/modules/python/editor/resources/pyNode25.png"/>
93.64 - <folder name="Actions">
93.65 -
93.66 - <file name="RefactoringAll.shadow">
93.67 - <attr name="originalFile" stringvalue="Actions/Refactoring/RefactoringAll.instance"/>
93.68 - <attr name="position" intvalue="1800"/>
93.69 - </file>
93.70 - <file name="RefactoringWhereUsed.shadow">
93.71 - <attr name="originalFile" stringvalue="Actions/Refactoring/org-netbeans-modules-refactoring-api-ui-WhereUsedAction.instance"/>
93.72 - <attr name="position" intvalue="1700"/>
93.73 - </file>
93.74 - <file name="org-openide-actions-CopyAction.shadow">
93.75 - <attr name="originalFile" stringvalue="Actions/Edit/org-openide-actions-CopyAction.instance"/>
93.76 - <attr name="position" intvalue="500"/>
93.77 - </file>
93.78 - <file name="org-openide-actions-CutAction.shadow">
93.79 - <attr name="originalFile" stringvalue="Actions/Edit/org-openide-actions-CutAction.instance"/>
93.80 - <attr name="position" intvalue="400"/>
93.81 - </file>
93.82 - <file name="org-openide-actions-DeleteAction.shadow">
93.83 - <attr name="originalFile" stringvalue="Actions/Edit/org-openide-actions-DeleteAction.instance"/>
93.84 - <attr name="position" intvalue="700"/>
93.85 - </file>
93.86 - <file name="org-openide-actions-FileSystemAction.shadow">
93.87 - <attr name="originalFile" stringvalue="Actions/System/org-openide-actions-FileSystemAction.instance"/>
93.88 - <attr name="position" intvalue="200"/>
93.89 - </file>
93.90 - <file name="org-openide-actions-OpenAction.shadow">
93.91 - <attr name="originalFile" stringvalue="Actions/System/org-openide-actions-OpenAction.instance"/>
93.92 - <attr name="position" intvalue="100"/>
93.93 - </file>
93.94 - <file name="org-openide-actions-PropertiesAction.shadow">
93.95 - <attr name="originalFile" stringvalue="Actions/System/org-openide-actions-PropertiesAction.instance"/>
93.96 - <attr name="position" intvalue="1300"/>
93.97 - </file>
93.98 - <file name="org-openide-actions-RenameAction.shadow">
93.99 - <attr name="originalFile" stringvalue="Actions/System/org-openide-actions-RenameAction.instance"/>
93.100 - <attr name="position" intvalue="800"/>
93.101 - </file>
93.102 - <file name="org-openide-actions-SaveAsTemplateAction.shadow">
93.103 - <attr name="originalFile" stringvalue="Actions/System/org-openide-actions-SaveAsTemplateAction.instance"/>
93.104 - <attr name="position" intvalue="1000"/>
93.105 - </file>
93.106 - <file name="org-openide-actions-ToolsAction.shadow">
93.107 - <attr name="originalFile" stringvalue="Actions/System/org-openide-actions-ToolsAction.instance"/>
93.108 - <attr name="position" intvalue="1200"/>
93.109 - </file>
93.110 - <file name="sep-1.instance">
93.111 - <attr name="instanceClass" stringvalue="javax.swing.JSeparator"/>
93.112 - <attr name="position" intvalue="300"/>
93.113 - </file>
93.114 - <file name="sep-2.instance">
93.115 - <attr name="instanceClass" stringvalue="javax.swing.JSeparator"/>
93.116 - <attr name="position" intvalue="600"/>
93.117 - </file>
93.118 - <file name="sep-3.instance">
93.119 - <attr name="instanceClass" stringvalue="javax.swing.JSeparator"/>
93.120 - <attr name="position" intvalue="900"/>
93.121 - </file>
93.122 - <file name="sep-4.instance">
93.123 - <attr name="instanceClass" stringvalue="javax.swing.JSeparator"/>
93.124 - <attr name="position" intvalue="1100"/>
93.125 - </file>
93.126 -
93.127 - <file name="RefactoringSeparator-1.instance">
93.128 - <attr name="instanceClass" stringvalue="javax.swing.JSeparator"/>
93.129 - <attr name="position" intvalue="1900"/>
93.130 - </file>
93.131 - </folder>
93.132 </folder>
93.133 <folder name="x-python-compiled">
93.134 <attr name="SystemFileSystem.icon" urlvalue="nbresloc:/org/netbeans/modules/python/editor/resources/pyc_16.png"/>
93.135 @@ -334,7 +266,7 @@
93.136 <folder name="Services">
93.137 <folder name="MIMEResolver">
93.138 <file name="PythonResolver.xml" url="PythonResolver.xml">
93.139 - <attr name="SystemFileSystem.localizingBundle" stringvalue="org.netbeans.modules.python.editor.Bundle"/>
93.140 + <attr name="displayName" bundlevalue="org.netbeans.modules.python.editor.Bundle#Services/MIMEResolver/PythonResolver.xml"/>
93.141 <attr name="position" intvalue="184"/>
93.142 </file>
93.143 </folder>
94.1 --- a/python.editor/src/org/netbeans/modules/python/editor/lexer/Call.java Sun Jan 04 13:11:53 2015 -0600
94.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/lexer/Call.java Sat Feb 28 17:25:32 2015 -0800
94.3 @@ -45,8 +45,8 @@
94.4
94.5 import javax.swing.text.BadLocationException;
94.6 import javax.swing.text.Document;
94.7 +import org.netbeans.api.annotations.common.NonNull;
94.8
94.9 -import org.netbeans.modules.gsf.api.annotations.NonNull;
94.10 import org.netbeans.api.lexer.Token;
94.11 import org.netbeans.api.lexer.TokenHierarchy;
94.12 import org.netbeans.api.lexer.TokenId;
95.1 --- a/python.editor/src/org/netbeans/modules/python/editor/lexer/PythonLexerUtils.java Sun Jan 04 13:11:53 2015 -0600
95.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/lexer/PythonLexerUtils.java Sat Feb 28 17:25:32 2015 -0800
95.3 @@ -10,16 +10,14 @@
95.4 import java.util.regex.Pattern;
95.5 import javax.swing.text.BadLocationException;
95.6 import javax.swing.text.Document;
95.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
95.8 -import org.netbeans.modules.gsf.api.OffsetRange;
95.9 -import org.netbeans.modules.gsf.api.ParserResult;
95.10 -import org.netbeans.modules.gsf.api.TranslatedSource;
95.11 import org.netbeans.api.lexer.Token;
95.12 import org.netbeans.api.lexer.TokenHierarchy;
95.13 import org.netbeans.api.lexer.TokenId;
95.14 import org.netbeans.api.lexer.TokenSequence;
95.15 import org.netbeans.editor.BaseDocument;
95.16 import org.netbeans.editor.Utilities;
95.17 +import org.netbeans.modules.csl.api.OffsetRange;
95.18 +import org.netbeans.modules.python.editor.PythonParserResult;
95.19 import org.openide.filesystems.FileUtil;
95.20 import org.openide.loaders.DataObject;
95.21 import org.openide.util.Exceptions;
95.22 @@ -71,33 +69,21 @@
95.23 }
95.24
95.25 /** For a possibly generated offset in an AST, return the corresponding lexing/true document offset */
95.26 - public static int getLexerOffset(CompilationInfo info, int astOffset) {
95.27 - ParserResult result = info.getEmbeddedResult(PythonTokenId.PYTHON_MIME_TYPE, 0);
95.28 - if (result != null) {
95.29 - TranslatedSource ts = result.getTranslatedSource();
95.30 - if (ts != null) {
95.31 - return ts.getLexicalOffset(astOffset);
95.32 - }
95.33 - }
95.34 -
95.35 - return astOffset;
95.36 + public static int getLexerOffset(PythonParserResult result, int astOffset) {
95.37 + return result.getSnapshot().getOriginalOffset(astOffset);
95.38 }
95.39
95.40 - public static OffsetRange getLexerOffsets(CompilationInfo info, OffsetRange astRange) {
95.41 - ParserResult result = info.getEmbeddedResult(PythonTokenId.PYTHON_MIME_TYPE, 0);
95.42 + public static OffsetRange getLexerOffsets(PythonParserResult result, OffsetRange astRange) {
95.43 if (result != null) {
95.44 - TranslatedSource ts = result.getTranslatedSource();
95.45 - if (ts != null) {
95.46 - int rangeStart = astRange.getStart();
95.47 - int start = ts.getLexicalOffset(rangeStart);
95.48 - if (start == rangeStart) {
95.49 - return astRange;
95.50 - } else if (start == -1) {
95.51 - return OffsetRange.NONE;
95.52 - } else {
95.53 - // Assumes the translated range maintains size
95.54 - return new OffsetRange(start, start + astRange.getLength());
95.55 - }
95.56 + int rangeStart = astRange.getStart();
95.57 + int start = result.getSnapshot().getOriginalOffset(rangeStart);
95.58 + if (start == rangeStart) {
95.59 + return astRange;
95.60 + } else if (start == -1) {
95.61 + return OffsetRange.NONE;
95.62 + } else {
95.63 + // Assumes the translated range maintains size
95.64 + return new OffsetRange(start, start + astRange.getLength());
95.65 }
95.66 }
95.67
96.1 --- a/python.editor/src/org/netbeans/modules/python/editor/lexer/PythonTokenId.java Sun Jan 04 13:11:53 2015 -0600
96.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/lexer/PythonTokenId.java Sat Feb 28 17:25:32 2015 -0800
96.3 @@ -52,6 +52,7 @@
96.4 import org.netbeans.api.lexer.LanguagePath;
96.5 import org.netbeans.api.lexer.Token;
96.6 import org.netbeans.api.lexer.TokenId;
96.7 +import org.netbeans.modules.python.api.PythonMIMEResolver;
96.8 import org.netbeans.modules.python.editor.PythonUtils;
96.9 import org.netbeans.spi.lexer.LanguageEmbedding;
96.10 import org.netbeans.spi.lexer.LanguageHierarchy;
96.11 @@ -116,7 +117,6 @@
96.12 NONUNARY_OP(null, OPERATOR_CAT);
96.13 private final String fixedText;
96.14 private final String primaryCategory;
96.15 - public static final String PYTHON_MIME_TYPE = "text/x-python"; // NOI18N
96.16
96.17 PythonTokenId(String fixedText, String primaryCategory) {
96.18 this.fixedText = fixedText;
96.19 @@ -133,7 +133,7 @@
96.20 private static final Language<PythonTokenId> language =
96.21 new LanguageHierarchy<PythonTokenId>() {
96.22 protected String mimeType() {
96.23 - return PythonTokenId.PYTHON_MIME_TYPE;
96.24 + return PythonMIMEResolver.PYTHON_MIME_TYPE;
96.25 }
96.26
96.27 protected Collection<PythonTokenId> createTokenIds() {
97.1 --- a/python.editor/src/org/netbeans/modules/python/editor/options/FmtOptions.java Sun Jan 04 13:11:53 2015 -0600
97.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/options/FmtOptions.java Sat Feb 28 17:25:32 2015 -0800
97.3 @@ -52,7 +52,6 @@
97.4 import java.io.File;
97.5 import java.io.FileWriter;
97.6 import java.io.IOException;
97.7 -import java.util.ArrayList;
97.8 import java.util.Arrays;
97.9 import java.util.HashMap;
97.10 import java.util.HashSet;
97.11 @@ -76,27 +75,12 @@
97.12 import javax.swing.text.BadLocationException;
97.13 import javax.swing.text.Document;
97.14 import org.netbeans.api.editor.settings.SimpleValueNames;
97.15 -import org.netbeans.modules.gsf.api.CancellableTask;
97.16 -import org.netbeans.modules.gsf.api.CompilationInfo;
97.17 -import org.netbeans.modules.gsf.api.SourceModel;
97.18 -import org.netbeans.modules.gsf.api.SourceModelFactory;
97.19 -import org.netbeans.modules.gsf.spi.GsfUtilities;
97.20 -import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
97.21 -import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
97.22 -import org.netbeans.modules.python.editor.PythonLanguage;
97.23 import static org.netbeans.modules.python.editor.options.CodeStyle.*;
97.24 import org.netbeans.modules.options.editor.spi.PreferencesCustomizer;
97.25 import org.netbeans.modules.options.editor.spi.PreviewProvider;
97.26 -
97.27 -import org.netbeans.modules.python.api.PythonPlatform;
97.28 -import org.netbeans.modules.python.api.PythonPlatformManager;
97.29 +import org.netbeans.modules.python.api.PythonMIMEResolver;
97.30 import org.netbeans.modules.python.editor.PythonFormatter;
97.31 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
97.32 -import org.netbeans.napi.gsfret.source.ClasspathInfo;
97.33 -import org.netbeans.napi.gsfret.source.CompilationController;
97.34 -import org.netbeans.napi.gsfret.source.Phase;
97.35 -import org.netbeans.napi.gsfret.source.Source;
97.36 -import org.netbeans.napi.gsfret.source.SourceUtils;
97.37 +import org.netbeans.modules.python.editor.PythonParserResult;
97.38 import org.openide.cookies.SaveCookie;
97.39 import org.openide.filesystems.FileObject;
97.40 import org.openide.filesystems.FileUtil;
97.41 @@ -563,7 +547,7 @@
97.42 previewPane.getAccessibleContext().setAccessibleName(NbBundle.getMessage(FmtOptions.class, "AN_Preview")); //NOI18N
97.43 previewPane.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(FmtOptions.class, "AD_Preview")); //NOI18N
97.44 previewPane.putClientProperty("HighlightsLayerIncludes", "^org\\.netbeans\\.modules\\.editor\\.lib2\\.highlighting\\.SyntaxHighlighting$"); //NOI18N
97.45 - previewPane.setEditorKit(CloneableEditorSupport.getEditorKit(PythonTokenId.PYTHON_MIME_TYPE));
97.46 + previewPane.setEditorKit(CloneableEditorSupport.getEditorKit(PythonMIMEResolver.PYTHON_MIME_TYPE));
97.47 previewPane.setEditable(false);
97.48 }
97.49 return previewPane;
97.50 @@ -606,7 +590,7 @@
97.51 // to create a temp file, format it, then save it and delete it
97.52 // (to avoid save confirmation dialogs on the modified file etc)
97.53 PythonFormatter formatter = new PythonFormatter(codeStyle);
97.54 - CompilationInfo info = null;
97.55 + PythonParserResult info = null;
97.56 File tmp = null;
97.57 FileObject tmpFo = null;
97.58 if (formatter.needsParserResult()) {
97.59 @@ -619,55 +603,55 @@
97.60 tmpFo = fo;
97.61 // TODO - I need to get the classpath involved here such that it can
97.62 // find used/unused libraries
97.63 - if (!SourceUtils.isScanInProgress()) {
97.64 - // I'm using custom GSF code here because I want to set up an explicit
97.65 - // source path for the fake file object which includes the Python
97.66 - // libraries (since we need them for the isSystemModule lookup
97.67 - //SourceModel model = SourceModelFactory.getInstance().getModel(fo);
97.68 - //if (model != null && !model.isScanInProgress()) {
97.69 - List<FileObject> roots = new ArrayList<FileObject>(new PythonLanguage().getCoreLibraries());
97.70 -
97.71 - final PythonPlatformManager manager = PythonPlatformManager.getInstance();
97.72 - final String platformName = manager.getDefaultPlatform();
97.73 - PythonPlatform activePlatform = manager.getPlatform(platformName);
97.74 - if (activePlatform != null) {
97.75 - roots.addAll(activePlatform.getUniqueLibraryRoots());
97.76 - ClassPath boot = ClassPathSupport.createClassPath(roots.toArray(new FileObject[roots.size()]));
97.77 - ClassPath source = ClassPathSupport.createClassPath(new FileObject[]{fo.getParent()});
97.78 - ClassPath compile = source;
97.79 -
97.80 - ClasspathInfo cpInfo = ClasspathInfo.create(boot, compile, source);
97.81 - Source model = Source.create(cpInfo, fo);
97.82 - if (model != null) {
97.83 - final CompilationInfo[] infoHolder = new CompilationInfo[1];
97.84 - //model.runUserActionTask(new CancellableTask<CompilationInfo>() {
97.85 - model.runUserActionTask(new CancellableTask<CompilationController>() {
97.86 - public void cancel() {
97.87 - }
97.88 -
97.89 - //public void run(CompilationInfo info) throws Exception {
97.90 - public void run(CompilationController info) throws Exception {
97.91 - info.toPhase(Phase.RESOLVED);
97.92 - infoHolder[0] = info;
97.93 - // Force open so info.getFileObject will succeed
97.94 - GsfUtilities.getDocument(fo, true);
97.95 - }
97.96 - }, false);
97.97 - info = infoHolder[0];
97.98 - }
97.99 - }
97.100 - }
97.101 +// if (!SourceUtils.isScanInProgress()) {
97.102 +// // I'm using custom GSF code here because I want to set up an explicit
97.103 +// // source path for the fake file object which includes the Python
97.104 +// // libraries (since we need them for the isSystemModule lookup
97.105 +// //SourceModel model = SourceModelFactory.getInstance().getModel(fo);
97.106 +// //if (model != null && !model.isScanInProgress()) {
97.107 +// List<FileObject> roots = new ArrayList<FileObject>(new PythonLanguage().getCoreLibraries());
97.108 +//
97.109 +// final PythonPlatformManager manager = PythonPlatformManager.getInstance();
97.110 +// final String platformName = manager.getDefaultPlatform();
97.111 +// PythonPlatform activePlatform = manager.getPlatform(platformName);
97.112 +// if (activePlatform != null) {
97.113 +// roots.addAll(activePlatform.getUniqueLibraryRoots());
97.114 +// ClassPath boot = ClassPathSupport.createClassPath(roots.toArray(new FileObject[roots.size()]));
97.115 +// ClassPath source = ClassPathSupport.createClassPath(new FileObject[]{fo.getParent()});
97.116 +// ClassPath compile = source;
97.117 +//
97.118 +// ClasspathInfo cpInfo = ClasspathInfo.create(boot, compile, source);
97.119 +// Source model = Source.create(cpInfo, fo);
97.120 +// if (model != null) {
97.121 +// final CompilationInfo[] infoHolder = new CompilationInfo[1];
97.122 +// //model.runUserActionTask(new CancellableTask<CompilationInfo>() {
97.123 +// model.runUserActionTask(new CancellableTask<CompilationController>() {
97.124 +// public void cancel() {
97.125 +// }
97.126 +//
97.127 +// //public void run(CompilationInfo info) throws Exception {
97.128 +// public void run(CompilationController info) throws Exception {
97.129 +// info.toPhase(Phase.RESOLVED);
97.130 +// infoHolder[0] = info;
97.131 +// // Force open so info.getFileObject will succeed
97.132 +// GsfUtilities.getDocument(fo, true);
97.133 +// }
97.134 +// }, false);
97.135 +// info = infoHolder[0];
97.136 +// }
97.137 +// }
97.138 +// }
97.139 } catch (IOException ex) {
97.140 Exceptions.printStackTrace(ex);
97.141 }
97.142 }
97.143 try {
97.144 - if (info != null && info.getDocument() != null) {
97.145 - Document doc = info.getDocument();
97.146 + if (info != null && info.getSnapshot().getSource().getDocument(false) != null) {
97.147 + Document doc = info.getSnapshot().getSource().getDocument(false);
97.148 formatter.reformat(null, doc, 0, doc.getLength(), info);
97.149 jep.setText(doc.getText(0, doc.getLength()));
97.150 // Save file to avoid warning on exit
97.151 - DataObject dobj = DataObject.find(info.getFileObject());
97.152 + DataObject dobj = DataObject.find(info.getSnapshot().getSource().getFileObject());
97.153 SaveCookie cookie = dobj.getCookie(SaveCookie.class);
97.154 if (cookie != null) {
97.155 cookie.save();
98.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/DiffElement.java Sun Jan 04 13:11:53 2015 -0600
98.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/DiffElement.java Sat Feb 28 17:25:32 2015 -0800
98.3 @@ -45,8 +45,8 @@
98.4
98.5 import java.io.IOException;
98.6 import java.lang.ref.WeakReference;
98.7 -import org.netbeans.napi.gsfret.source.ModificationResult;
98.8 -import org.netbeans.napi.gsfret.source.ModificationResult.Difference;
98.9 +import org.netbeans.modules.csl.spi.support.ModificationResult;
98.10 +import org.netbeans.modules.csl.spi.support.ModificationResult.Difference;
98.11 import org.netbeans.modules.refactoring.spi.SimpleRefactoringElementImplementation;
98.12 import org.netbeans.modules.python.editor.refactoring.ui.ElementGripFactory;
98.13 import org.openide.filesystems.FileObject;
99.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonElementCtx.java Sun Jan 04 13:11:53 2015 -0600
99.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonElementCtx.java Sat Feb 28 17:25:32 2015 -0800
99.3 @@ -32,13 +32,14 @@
99.4
99.5 import java.util.Iterator;
99.6
99.7 -import org.netbeans.modules.gsf.api.ElementKind;
99.8 import org.netbeans.modules.python.editor.elements.AstElement;
99.9 import org.netbeans.modules.python.editor.elements.Element;
99.10 -import org.netbeans.napi.gsfret.source.CompilationInfo;
99.11 import org.netbeans.editor.BaseDocument;
99.12 +import org.netbeans.modules.csl.api.ElementKind;
99.13 +import org.netbeans.modules.csl.spi.GsfUtilities;
99.14 import org.netbeans.modules.python.editor.AstPath;
99.15 import org.netbeans.modules.python.editor.PythonAstUtils;
99.16 +import org.netbeans.modules.python.editor.PythonParserResult;
99.17 import org.netbeans.modules.python.editor.elements.IndexedElement;
99.18 import org.openide.filesystems.FileObject;
99.19 import org.python.antlr.PythonTree;
99.20 @@ -62,7 +63,7 @@
99.21 public class PythonElementCtx {
99.22 private PythonTree node;
99.23 private PythonTree root;
99.24 - private CompilationInfo info;
99.25 + private PythonParserResult info;
99.26 private FileObject fileObject;
99.27 private AstPath path;
99.28 private int caret;
99.29 @@ -79,12 +80,12 @@
99.30 private String defClass;
99.31
99.32 public PythonElementCtx(PythonTree root, PythonTree node, Element element, FileObject fileObject,
99.33 - CompilationInfo info) {
99.34 + PythonParserResult info) {
99.35 initialize(root, node, element, fileObject, info);
99.36 }
99.37
99.38 /** Create a new element holder representing the node closest to the given caret offset in the given compilation job */
99.39 - public PythonElementCtx(CompilationInfo info, int caret) {
99.40 + public PythonElementCtx(PythonParserResult info, int caret) {
99.41 PythonTree root = PythonAstUtils.getRoot(info);
99.42
99.43 int astOffset = PythonAstUtils.getAstOffset(info, caret);
99.44 @@ -117,7 +118,7 @@
99.45 }
99.46 Element element = AstElement.create(info, leaf);
99.47
99.48 - initialize(root, leaf, element, info.getFileObject(), info);
99.49 + initialize(root, leaf, element, info.getSnapshot().getSource().getFileObject(), info);
99.50
99.51 // name = element.getFqn();
99.52 name = element.getName();
99.53 @@ -132,20 +133,20 @@
99.54 }
99.55
99.56 public PythonElementCtx(IndexedElement element) {
99.57 - CompilationInfo[] infoHolder = new CompilationInfo[1];
99.58 + PythonParserResult[] infoHolder = new PythonParserResult[1];
99.59 PythonTree node = PythonAstUtils.getForeignNode(element, infoHolder);
99.60 - CompilationInfo info = infoHolder[0];
99.61 + PythonParserResult info = infoHolder[0];
99.62
99.63 Element e = AstElement.create(info, node);
99.64
99.65 FileObject fo = element.getFileObject();
99.66 - document = PythonRefUtils.getDocument(null, fo);
99.67 + document = GsfUtilities.getDocument(fileObject, false);
99.68
99.69 initialize(root, node, e, fo, info);
99.70 }
99.71
99.72 private void initialize(PythonTree root, PythonTree node, Element element, FileObject fileObject,
99.73 - CompilationInfo info) {
99.74 + PythonParserResult info) {
99.75 this.root = root;
99.76 this.node = node;
99.77 this.element = element;
99.78 @@ -209,7 +210,7 @@
99.79 this.node = node;
99.80 }
99.81
99.82 - public CompilationInfo getInfo() {
99.83 + public PythonParserResult getInfo() {
99.84 return info;
99.85 }
99.86
99.87 @@ -267,7 +268,7 @@
99.88 // }
99.89 public BaseDocument getDocument() {
99.90 if (document == null) {
99.91 - document = PythonRefUtils.getDocument(info, info.getFileObject());
99.92 + document = GsfUtilities.getDocument(info.getSnapshot().getSource().getFileObject(), false);
99.93 }
99.94
99.95 return document;
100.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRefUtils.java Sun Jan 04 13:11:53 2015 -0600
100.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRefUtils.java Sat Feb 28 17:25:32 2015 -0800
100.3 @@ -58,9 +58,7 @@
100.4 import org.netbeans.api.editor.mimelookup.MimeLookup;
100.5 import org.netbeans.api.editor.mimelookup.MimePath;
100.6 import org.netbeans.api.editor.settings.FontColorSettings;
100.7 -import org.netbeans.modules.gsf.api.ElementKind;
100.8 -import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
100.9 -import org.netbeans.modules.gsfpath.api.classpath.GlobalPathRegistry;
100.10 +import org.netbeans.api.java.classpath.ClassPath;
100.11 import org.netbeans.api.lexer.Token;
100.12 import org.netbeans.api.lexer.TokenHierarchy;
100.13 import org.netbeans.api.lexer.TokenId;
100.14 @@ -70,13 +68,12 @@
100.15 import org.netbeans.api.project.ProjectUtils;
100.16 import org.netbeans.api.project.SourceGroup;
100.17 import org.netbeans.api.project.ui.OpenProjects;
100.18 -import org.netbeans.napi.gsfret.source.ClasspathInfo;
100.19 -import org.netbeans.napi.gsfret.source.CompilationInfo;
100.20 -import org.netbeans.napi.gsfret.source.Source;
100.21 -import org.netbeans.napi.gsfret.source.SourceUtils;
100.22 import org.netbeans.editor.BaseDocument;
100.23 -import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
100.24 +import org.netbeans.modules.csl.api.ElementKind;
100.25 +import org.netbeans.modules.parsing.api.Source;
100.26 +import org.netbeans.modules.python.api.PythonMIMEResolver;
100.27 import org.netbeans.modules.python.editor.PythonAstUtils;
100.28 +import org.netbeans.modules.python.editor.PythonParserResult;
100.29 import org.netbeans.modules.python.editor.PythonUtils;
100.30 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
100.31 import org.openide.cookies.EditorCookie;
100.32 @@ -103,51 +100,6 @@
100.33 private PythonRefUtils() {
100.34 }
100.35
100.36 - // XXX Should this be unused now?
100.37 - public static Source createSource(ClasspathInfo cpInfo, FileObject fo) {
100.38 - if (PythonUtils.canContainPython(fo)) {
100.39 - return Source.create(cpInfo, fo);
100.40 - }
100.41 -
100.42 - return null;
100.43 - }
100.44 -
100.45 - public static Source getSource(FileObject fo) {
100.46 - Source source = Source.forFileObject(fo);
100.47 -
100.48 - return source;
100.49 - }
100.50 -
100.51 - public static Source getSource(Document doc) {
100.52 - Source source = Source.forDocument(doc);
100.53 -
100.54 - return source;
100.55 - }
100.56 -
100.57 - public static BaseDocument getDocument(CompilationInfo info, FileObject fo) {
100.58 - BaseDocument doc = null;
100.59 -
100.60 - if (info != null) {
100.61 - doc = (BaseDocument)info.getDocument();
100.62 - }
100.63 -
100.64 - if (doc == null) {
100.65 - try {
100.66 - // Gotta open it first
100.67 - DataObject od = DataObject.find(fo);
100.68 - EditorCookie ec = od.getCookie(EditorCookie.class);
100.69 -
100.70 - if (ec != null) {
100.71 - doc = (BaseDocument)ec.openDocument();
100.72 - }
100.73 - } catch (IOException ex) {
100.74 - Exceptions.printStackTrace(ex);
100.75 - }
100.76 - }
100.77 -
100.78 - return doc;
100.79 - }
100.80 -
100.81 /** Compute the names (full and simple, e.g. Foo::Bar and Bar) for the given node, if any, and return as
100.82 * a String[2] = {name,simpleName} */
100.83 public static String[] getNodeNames(PythonTree node) {
100.84 @@ -169,10 +121,10 @@
100.85 return new String[]{name, simpleName};
100.86 }
100.87
100.88 - public static CloneableEditorSupport findCloneableEditorSupport(CompilationInfo info) {
100.89 + public static CloneableEditorSupport findCloneableEditorSupport(PythonParserResult info) {
100.90 DataObject dob = null;
100.91 try {
100.92 - dob = DataObject.find(info.getFileObject());
100.93 + dob = DataObject.find(info.getSnapshot().getSource().getFileObject());
100.94 } catch (DataObjectNotFoundException ex) {
100.95 Exceptions.printStackTrace(ex);
100.96 }
100.97 @@ -211,7 +163,7 @@
100.98 StringBuffer buf = new StringBuffer();
100.99 // TODO - check whether we need python highlighting or rhtml highlighting
100.100 TokenHierarchy tokenH = TokenHierarchy.create(text, PythonTokenId.language());
100.101 - Lookup lookup = MimeLookup.getLookup(MimePath.get(PythonTokenId.PYTHON_MIME_TYPE));
100.102 + Lookup lookup = MimeLookup.getLookup(MimePath.get(PythonMIMEResolver.PYTHON_MIME_TYPE));
100.103 FontColorSettings settings = lookup.lookup(FontColorSettings.class);
100.104 @SuppressWarnings("unchecked")
100.105 TokenSequence<? extends TokenId> tok = tokenH.tokenSequence();
100.106 @@ -341,82 +293,82 @@
100.107 return tph.getKind();
100.108 }
100.109
100.110 - public static ClasspathInfo getClasspathInfoFor(FileObject... files) {
100.111 - assert files.length > 0;
100.112 - Set<URL> dependentRoots = new HashSet<URL>();
100.113 - for (FileObject fo : files) {
100.114 - Project p = null;
100.115 - if (fo != null) {
100.116 - p = FileOwnerQuery.getOwner(fo);
100.117 - }
100.118 - if (p != null) {
100.119 - ClassPath classPath = ClassPath.getClassPath(fo, ClassPath.SOURCE);
100.120 - if (classPath == null) {
100.121 - return null;
100.122 - }
100.123 - FileObject ownerRoot = classPath.findOwnerRoot(fo);
100.124 - if (ownerRoot != null) {
100.125 - URL sourceRoot = URLMapper.findURL(ownerRoot, URLMapper.INTERNAL);
100.126 - dependentRoots.addAll(SourceUtils.getDependentRoots(sourceRoot));
100.127 - for (SourceGroup root : ProjectUtils.getSources(p).getSourceGroups(SOURCES_TYPE_PYTHON)) {
100.128 - dependentRoots.add(URLMapper.findURL(root.getRootFolder(), URLMapper.INTERNAL));
100.129 - }
100.130 - } else {
100.131 - dependentRoots.add(URLMapper.findURL(fo.getParent(), URLMapper.INTERNAL));
100.132 - }
100.133 - } else {
100.134 - for (ClassPath cp : GlobalPathRegistry.getDefault().getPaths(ClassPath.SOURCE)) {
100.135 - for (FileObject root : cp.getRoots()) {
100.136 - dependentRoots.add(URLMapper.findURL(root, URLMapper.INTERNAL));
100.137 - }
100.138 - }
100.139 - }
100.140 - }
100.141 -
100.142 - ClassPath rcp = ClassPathSupport.createClassPath(dependentRoots.toArray(new URL[dependentRoots.size()]));
100.143 - ClassPath nullPath = ClassPathSupport.createClassPath(new FileObject[0]);
100.144 - ClassPath boot = files[0] != null ? ClassPath.getClassPath(files[0], ClassPath.BOOT) : nullPath;
100.145 - ClassPath compile = files[0] != null ? ClassPath.getClassPath(files[0], ClassPath.COMPILE) : nullPath;
100.146 -
100.147 - if (boot == null || compile == null) { // 146499
100.148 - return null;
100.149 - }
100.150 -
100.151 - ClasspathInfo cpInfo = ClasspathInfo.create(boot, compile, rcp);
100.152 - return cpInfo;
100.153 - }
100.154 -
100.155 - public static ClasspathInfo getClasspathInfoFor(PythonElementCtx ctx) {
100.156 - return getClasspathInfoFor(ctx.getFileObject());
100.157 - }
100.158 -
100.159 - public static List<FileObject> getPythonFilesInProject(FileObject fileInProject) {
100.160 - List<FileObject> list = new ArrayList<FileObject>(100);
100.161 - ClasspathInfo cpInfo = PythonRefUtils.getClasspathInfoFor(fileInProject);
100.162 - if (cpInfo == null) {
100.163 - return list;
100.164 - }
100.165 - ClassPath cp = cpInfo.getClassPath(ClasspathInfo.PathKind.SOURCE);
100.166 - for (ClassPath.Entry entry : cp.entries()) {
100.167 - FileObject root = entry.getRoot();
100.168 - String name = root.getName();
100.169 - // Skip non-refactorable parts in renaming
100.170 - if (name.equals("vendor") || name.equals("script")) { // NOI18N
100.171 - continue;
100.172 - }
100.173 - addPythonFiles(list, root);
100.174 - }
100.175 -
100.176 - return list;
100.177 - }
100.178 -
100.179 - private static void addPythonFiles(List<FileObject> list, FileObject f) {
100.180 - if (f.isFolder()) {
100.181 - for (FileObject child : f.getChildren()) {
100.182 - addPythonFiles(list, child);
100.183 - }
100.184 - } else if (PythonUtils.canContainPython(f)) {
100.185 - list.add(f);
100.186 - }
100.187 - }
100.188 +// public static ClasspathInfo getClasspathInfoFor(FileObject... files) {
100.189 +// assert files.length > 0;
100.190 +// Set<URL> dependentRoots = new HashSet<URL>();
100.191 +// for (FileObject fo : files) {
100.192 +// Project p = null;
100.193 +// if (fo != null) {
100.194 +// p = FileOwnerQuery.getOwner(fo);
100.195 +// }
100.196 +// if (p != null) {
100.197 +// ClassPath classPath = ClassPath.getClassPath(fo, ClassPath.SOURCE);
100.198 +// if (classPath == null) {
100.199 +// return null;
100.200 +// }
100.201 +// FileObject ownerRoot = classPath.findOwnerRoot(fo);
100.202 +// if (ownerRoot != null) {
100.203 +// URL sourceRoot = URLMapper.findURL(ownerRoot, URLMapper.INTERNAL);
100.204 +// dependentRoots.addAll(SourceUtils.getDependentRoots(sourceRoot));
100.205 +// for (SourceGroup root : ProjectUtils.getSources(p).getSourceGroups(SOURCES_TYPE_PYTHON)) {
100.206 +// dependentRoots.add(URLMapper.findURL(root.getRootFolder(), URLMapper.INTERNAL));
100.207 +// }
100.208 +// } else {
100.209 +// dependentRoots.add(URLMapper.findURL(fo.getParent(), URLMapper.INTERNAL));
100.210 +// }
100.211 +// } else {
100.212 +// for (ClassPath cp : GlobalPathRegistry.getDefault().getPaths(ClassPath.SOURCE)) {
100.213 +// for (FileObject root : cp.getRoots()) {
100.214 +// dependentRoots.add(URLMapper.findURL(root, URLMapper.INTERNAL));
100.215 +// }
100.216 +// }
100.217 +// }
100.218 +// }
100.219 +//
100.220 +// ClassPath rcp = ClassPathSupport.createClassPath(dependentRoots.toArray(new URL[dependentRoots.size()]));
100.221 +// ClassPath nullPath = ClassPathSupport.createClassPath(new FileObject[0]);
100.222 +// ClassPath boot = files[0] != null ? ClassPath.getClassPath(files[0], ClassPath.BOOT) : nullPath;
100.223 +// ClassPath compile = files[0] != null ? ClassPath.getClassPath(files[0], ClassPath.COMPILE) : nullPath;
100.224 +//
100.225 +// if (boot == null || compile == null) { // 146499
100.226 +// return null;
100.227 +// }
100.228 +//
100.229 +// ClasspathInfo cpInfo = ClasspathInfo.create(boot, compile, rcp);
100.230 +// return cpInfo;
100.231 +// }
100.232 +//
100.233 +// public static ClasspathInfo getClasspathInfoFor(PythonElementCtx ctx) {
100.234 +// return getClasspathInfoFor(ctx.getFileObject());
100.235 +// }
100.236 +//
100.237 +// public static List<FileObject> getPythonFilesInProject(FileObject fileInProject) {
100.238 +// List<FileObject> list = new ArrayList<FileObject>(100);
100.239 +// ClasspathInfo cpInfo = PythonRefUtils.getClasspathInfoFor(fileInProject);
100.240 +// if (cpInfo == null) {
100.241 +// return list;
100.242 +// }
100.243 +// ClassPath cp = cpInfo.getClassPath(ClasspathInfo.PathKind.SOURCE);
100.244 +// for (ClassPath.Entry entry : cp.entries()) {
100.245 +// FileObject root = entry.getRoot();
100.246 +// String name = root.getName();
100.247 +// // Skip non-refactorable parts in renaming
100.248 +// if (name.equals("vendor") || name.equals("script")) { // NOI18N
100.249 +// continue;
100.250 +// }
100.251 +// addPythonFiles(list, root);
100.252 +// }
100.253 +//
100.254 +// return list;
100.255 +// }
100.256 +//
100.257 +// private static void addPythonFiles(List<FileObject> list, FileObject f) {
100.258 +// if (f.isFolder()) {
100.259 +// for (FileObject child : f.getChildren()) {
100.260 +// addPythonFiles(list, child);
100.261 +// }
100.262 +// } else if (PythonUtils.canContainPython(f)) {
100.263 +// list.add(f);
100.264 +// }
100.265 +// }
100.266 }
101.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRefactoringPlugin.java Sun Jan 04 13:11:53 2015 -0600
101.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRefactoringPlugin.java Sat Feb 28 17:25:32 2015 -0800
101.3 @@ -43,6 +43,7 @@
101.4 */
101.5 package org.netbeans.modules.python.editor.refactoring;
101.6
101.7 +/*
101.8 import java.io.IOException;
101.9 import java.util.Collection;
101.10 import java.util.HashMap;
101.11 @@ -64,13 +65,14 @@
101.12 import org.netbeans.modules.refactoring.spi.*;
101.13 import org.netbeans.modules.refactoring.api.*;
101.14 import org.openide.filesystems.FileObject;
101.15 -
101.16 +*/
101.17 /**
101.18 * Plugin implementation based on the one for Java refactoring.
101.19 *
101.20 * @author Jan Becicka
101.21 * @author Tor Norbye
101.22 */
101.23 +/* Uncomment when it works ;-)
101.24 public abstract class PythonRefactoringPlugin extends ProgressProviderAdapter implements RefactoringPlugin, CancellableTask<CompilationController> {
101.25 protected enum Phase {
101.26 PRECHECK, FASTCHECKPARAMETERS, CHECKPARAMETERS, PREPARE, DEFAULT
101.27 @@ -262,3 +264,4 @@
101.28 }
101.29 }
101.30 }
101.31 +*/
101.32 \ No newline at end of file
102.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRefactoringsFactory.java Sun Jan 04 13:11:53 2015 -0600
102.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRefactoringsFactory.java Sat Feb 28 17:25:32 2015 -0800
102.3 @@ -63,12 +63,12 @@
102.4 PythonElementCtx handle = look.lookup(PythonElementCtx.class);
102.5 if (refactoring instanceof WhereUsedQuery) {
102.6 if (handle != null) {
102.7 - return new PythonWhereUsedQueryPlugin((WhereUsedQuery)refactoring);
102.8 +// return new PythonWhereUsedQueryPlugin((WhereUsedQuery)refactoring);
102.9 }
102.10 } else if (refactoring instanceof RenameRefactoring) {
102.11 if (handle != null || ((file != null) && PythonUtils.canContainPython(file))) {
102.12 //rename java file, class, method etc..
102.13 - return new PythonRenameRefactoringPlugin((RenameRefactoring)refactoring);
102.14 +// return new PythonRenameRefactoringPlugin((RenameRefactoring)refactoring);
102.15 }
102.16 }
102.17 return null;
103.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRenameRefactoringPlugin.java Sun Jan 04 13:11:53 2015 -0600
103.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRenameRefactoringPlugin.java Sat Feb 28 17:25:32 2015 -0800
103.3 @@ -42,7 +42,7 @@
103.4 * made subject to such option by the copyright holder.
103.5 */
103.6 package org.netbeans.modules.python.editor.refactoring;
103.7 -
103.8 +/*
103.9 import org.netbeans.modules.gsf.api.Error;
103.10 import org.netbeans.modules.gsf.api.Severity;
103.11 import org.netbeans.modules.python.editor.elements.Element;
103.12 @@ -99,7 +99,7 @@
103.13 import org.python.antlr.ast.FunctionDef;
103.14 import org.python.antlr.ast.Name;
103.15 import org.python.antlr.base.expr;
103.16 -
103.17 +*/
103.18 /**
103.19 * The actual Renaming refactoring work for Python.
103.20 *
103.21 @@ -116,6 +116,7 @@
103.22 *
103.23 * @todo Complete this. Most of the prechecks are not implemented - and the refactorings themselves need a lot of work.
103.24 */
103.25 +/* Uncomment when it works ;-)
103.26 public class PythonRenameRefactoringPlugin extends PythonRefactoringPlugin {
103.27 private PythonElementCtx treePathHandle = null;
103.28 private Collection overriddenByMethods = null; // methods that override the method to be renamed
103.29 @@ -123,7 +124,6 @@
103.30 private boolean doCheckName = true;
103.31 private RenameRefactoring refactoring;
103.32
103.33 - /** Creates a new instance of RenameRefactoring */
103.34 public PythonRenameRefactoringPlugin(RenameRefactoring rename) {
103.35 this.refactoring = rename;
103.36 PythonElementCtx tph = rename.getRefactoringSource().lookup(PythonElementCtx.class);
103.37 @@ -352,10 +352,6 @@
103.38 return NbBundle.getMessage(PythonRenameRefactoringPlugin.class, key);
103.39 }
103.40
103.41 - /**
103.42 - *
103.43 - * @author Jan Becicka
103.44 - */
103.45 public class RenameTransformer extends SearchVisitor {
103.46 private Set<PythonElementCtx> allMethods;
103.47 private String newName;
103.48 @@ -645,14 +641,14 @@
103.49 Difference diff = new Difference(Difference.Kind.CHANGE, startPos, endPos, oldCode, newCode, desc);
103.50 diffs.add(diff);
103.51 }
103.52 -
103.53 +*/
103.54 /**
103.55 * @todo P1: This is matching method names on classes that have nothing to do with the class we're searching for
103.56 * - I've gotta filter fields, methods etc. that are not in the current class
103.57 * (but I also have to search for methods that are OVERRIDING the class... so I've gotta work a little harder!)
103.58 * @todo Arity matching on the methods to preclude methods that aren't overriding or aliasing!
103.59 */
103.60 - private class RenameMethodVisitor extends Visitor {
103.61 +/* private class RenameMethodVisitor extends Visitor {
103.62 private String name;
103.63 private PythonElementCtx searchCtx;
103.64 private PythonElementCtx fileCtx;
103.65 @@ -683,7 +679,7 @@
103.66 }
103.67 }
103.68
103.69 - /** @todo Rename!*/
103.70 + ** @todo Rename!*
103.71 private class RenameClassVisitor extends Visitor {
103.72 private String name;
103.73 private PythonElementCtx searchCtx;
103.74 @@ -724,3 +720,4 @@
103.75 }
103.76 }
103.77 }
103.78 +*/
103.79 \ No newline at end of file
104.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonTransaction.java Sun Jan 04 13:11:53 2015 -0600
104.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonTransaction.java Sat Feb 28 17:25:32 2015 -0800
104.3 @@ -42,18 +42,18 @@
104.4 * made subject to such option by the copyright holder.
104.5 */
104.6 package org.netbeans.modules.python.editor.refactoring;
104.7 -
104.8 +/*
104.9 import java.io.IOException;
104.10 import java.util.ArrayList;
104.11 import java.util.Collection;
104.12 -import org.netbeans.napi.gsfret.source.ModificationResult;
104.13 import org.netbeans.modules.refactoring.spi.BackupFacility;
104.14 import org.netbeans.modules.refactoring.spi.Transaction;
104.15 -
104.16 +*/
104.17 /**
104.18 *
104.19 * @author Jan Becicka
104.20 */
104.21 +/* Probably remove completely ;-)
104.22 public class PythonTransaction implements Transaction {
104.23 ArrayList<BackupFacility.Handle> ids = new ArrayList<BackupFacility.Handle>();
104.24 private boolean commited = false;
104.25 @@ -96,4 +96,4 @@
104.26 }
104.27 }
104.28 }
104.29 -
104.30 +*/
104.31 \ No newline at end of file
105.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonWhereUsedQueryPlugin.java Sun Jan 04 13:11:53 2015 -0600
105.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonWhereUsedQueryPlugin.java Sat Feb 28 17:25:32 2015 -0800
105.3 @@ -42,7 +42,7 @@
105.4 * made subject to such option by the copyright holder.
105.5 */
105.6 package org.netbeans.modules.python.editor.refactoring;
105.7 -
105.8 +/*
105.9 import java.io.IOException;
105.10 import java.util.Collections;
105.11 import java.util.HashSet;
105.12 @@ -90,7 +90,7 @@
105.13 import org.python.antlr.ast.FunctionDef;
105.14 import org.python.antlr.ast.Name;
105.15 import org.python.antlr.base.expr;
105.16 -
105.17 +*/
105.18 /**
105.19 * Actual implementation of Find Usages query search for Python
105.20 *
105.21 @@ -99,13 +99,13 @@
105.22 *
105.23 * @author Tor Norbye
105.24 */
105.25 +/* Uncomment when it works ;-)
105.26 public class PythonWhereUsedQueryPlugin extends PythonRefactoringPlugin {
105.27 private WhereUsedQuery refactoring;
105.28 private PythonElementCtx searchHandle;
105.29 private Set<IndexedElement> subclasses;
105.30 private String targetName;
105.31
105.32 - /** Creates a new instance of WhereUsedQuery */
105.33 public PythonWhereUsedQueryPlugin(WhereUsedQuery refactoring) {
105.34 this.refactoring = refactoring;
105.35 this.searchHandle = refactoring.getRefactoringSource().lookup(PythonElementCtx.class);
105.36 @@ -461,7 +461,7 @@
105.37 * - I've gotta filter fields, methods etc. that are not in the current class
105.38 * (but I also have to search for methods that are OVERRIDING the class... so I've gotta work a little harder!)
105.39 * @todo Arity matching on the methods to preclude methods that aren't overriding or aliasing!
105.40 - */
105.41 + *
105.42 private class FindUsagesMethodVisitor extends Visitor {
105.43 private String name;
105.44 private PythonElementCtx searchCtx;
105.45 @@ -541,3 +541,4 @@
105.46 }
105.47 }
105.48 }
105.49 +*/
105.50 \ No newline at end of file
106.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/SearchVisitor.java Sun Jan 04 13:11:53 2015 -0600
106.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/SearchVisitor.java Sat Feb 28 17:25:32 2015 -0800
106.3 @@ -42,16 +42,15 @@
106.4 * made subject to such option by the copyright holder.
106.5 */
106.6 package org.netbeans.modules.python.editor.refactoring;
106.7 -
106.8 +/*
106.9 import java.io.IOException;
106.10 -import org.netbeans.napi.gsfret.source.Phase;
106.11 -import org.netbeans.napi.gsfret.source.WorkingCopy;
106.12 import org.openide.ErrorManager;
106.13 -
106.14 +*
106.15 /**
106.16 *
106.17 * @author Jan Becicka
106.18 */
106.19 +/* Could use a JavaSource like source rewriter
106.20 public abstract class SearchVisitor {
106.21 protected WorkingCopy workingCopy;
106.22
106.23 @@ -66,3 +65,4 @@
106.24
106.25 public abstract void scan();
106.26 }
106.27 +*/
106.28 \ No newline at end of file
107.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/WhereUsedElement.java Sun Jan 04 13:11:53 2015 -0600
107.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/WhereUsedElement.java Sat Feb 28 17:25:32 2015 -0800
107.3 @@ -47,14 +47,14 @@
107.4 import java.util.Set;
107.5 import javax.swing.Icon;
107.6 import javax.swing.text.Position.Bias;
107.7 -import org.netbeans.modules.gsf.api.Modifier;
107.8 -
107.9 -import org.netbeans.modules.gsf.api.OffsetRange;
107.10 -import org.netbeans.napi.gsfret.source.CompilationInfo;
107.11 -import org.netbeans.napi.gsfret.source.UiUtils;
107.12 import org.netbeans.editor.BaseDocument;
107.13 import org.netbeans.editor.Utilities;
107.14 +import org.netbeans.modules.csl.api.Modifier;
107.15 +import org.netbeans.modules.csl.api.OffsetRange;
107.16 +import org.netbeans.modules.csl.api.UiUtils;
107.17 +import org.netbeans.modules.csl.spi.GsfUtilities;
107.18 import org.netbeans.modules.python.editor.PythonAstUtils;
107.19 +import org.netbeans.modules.python.editor.PythonParserResult;
107.20 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
107.21 import org.netbeans.modules.python.editor.refactoring.ui.ElementGripFactory;
107.22 import org.netbeans.modules.refactoring.spi.SimpleRefactoringElementImplementation;
107.23 @@ -115,7 +115,7 @@
107.24 }
107.25
107.26 public static WhereUsedElement create(PythonElementCtx tree) {
107.27 - CompilationInfo info = tree.getInfo();
107.28 + PythonParserResult info = tree.getInfo();
107.29 OffsetRange range = PythonAstUtils.getNameRange(info, tree.getNode());
107.30 assert range != OffsetRange.NONE;
107.31
107.32 @@ -130,8 +130,8 @@
107.33 return create(info, tree.getName(), range, icon);
107.34 }
107.35
107.36 - public static WhereUsedElement create(CompilationInfo info, String name, OffsetRange range, Icon icon) {
107.37 - FileObject fo = info.getFileObject();
107.38 + public static WhereUsedElement create(PythonParserResult info, String name, OffsetRange range, Icon icon) {
107.39 + FileObject fo = info.getSnapshot().getSource().getFileObject();
107.40 int start = range.getStart();
107.41 int end = range.getEnd();
107.42
107.43 @@ -139,7 +139,7 @@
107.44 int en = start; // ! Same line as start
107.45 String content = null;
107.46
107.47 - BaseDocument bdoc = PythonRefUtils.getDocument(info, info.getFileObject());
107.48 + BaseDocument bdoc = GsfUtilities.getDocument(info.getSnapshot().getSource().getFileObject(), false);
107.49 try {
107.50 bdoc.readLock();
107.51
107.52 @@ -204,8 +204,8 @@
107.53 new OffsetRange(start, end), icon);
107.54 }
107.55
107.56 - public static WhereUsedElement create(CompilationInfo info, String name, String html, OffsetRange range, Icon icon) {
107.57 - FileObject fo = info.getFileObject();
107.58 + public static WhereUsedElement create(PythonParserResult info, String name, String html, OffsetRange range, Icon icon) {
107.59 + FileObject fo = info.getSnapshot().getSource().getFileObject();
107.60 int start = range.getStart();
107.61 int end = range.getEnd();
107.62
108.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/ElementGripFactory.java Sun Jan 04 13:11:53 2015 -0600
108.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/ElementGripFactory.java Sat Feb 28 17:25:32 2015 -0800
108.3 @@ -47,7 +47,7 @@
108.4 import java.util.Set;
108.5 import java.util.WeakHashMap;
108.6 import javax.swing.Icon;
108.7 -import org.netbeans.modules.gsf.api.OffsetRange;
108.8 +import org.netbeans.modules.csl.api.OffsetRange;
108.9 import org.openide.filesystems.FileObject;
108.10
108.11 /**
109.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/FolderTreeElement.java Sun Jan 04 13:11:53 2015 -0600
109.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/FolderTreeElement.java Sat Feb 28 17:25:32 2015 -0800
109.3 @@ -44,15 +44,15 @@
109.4 package org.netbeans.modules.python.editor.refactoring.ui;
109.5
109.6 import javax.swing.Icon;
109.7 -import org.netbeans.modules.gsf.api.ElementKind;
109.8 -import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
109.9 +import org.netbeans.api.java.classpath.ClassPath;
109.10 import org.netbeans.api.project.FileOwnerQuery;
109.11 import org.netbeans.api.project.Project;
109.12 import org.netbeans.api.project.ProjectUtils;
109.13 import org.netbeans.api.project.SourceGroup;
109.14 import org.netbeans.api.project.Sources;
109.15 +import org.netbeans.modules.csl.api.ElementKind;
109.16 +import org.netbeans.modules.csl.api.UiUtils;
109.17 import org.netbeans.modules.python.editor.refactoring.PythonRefUtils;
109.18 -import org.netbeans.napi.gsfret.source.UiUtils;
109.19 import org.netbeans.modules.refactoring.spi.ui.*;
109.20 import org.openide.filesystems.FileObject;
109.21 import org.openide.filesystems.FileUtil;
110.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/RefactoringActionsProvider.java Sun Jan 04 13:11:53 2015 -0600
110.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/RefactoringActionsProvider.java Sat Feb 28 17:25:32 2015 -0800
110.3 @@ -47,28 +47,31 @@
110.4 import java.lang.ref.WeakReference;
110.5 import java.util.ArrayList;
110.6 import java.util.Collection;
110.7 +import java.util.Collections;
110.8 import java.util.Dictionary;
110.9 import java.util.List;
110.10 import javax.swing.JOptionPane;
110.11 import javax.swing.text.JTextComponent;
110.12 import org.netbeans.api.fileinfo.NonRecursiveFolder;
110.13 -import org.netbeans.modules.gsf.api.CancellableTask;
110.14 -import org.netbeans.napi.gsfret.source.CompilationController;
110.15 -import org.netbeans.napi.gsfret.source.CompilationInfo;
110.16 -import org.netbeans.napi.gsfret.source.Phase;
110.17 -import org.netbeans.napi.gsfret.source.Source;
110.18 +import org.netbeans.modules.csl.spi.ParserResult;
110.19 +import org.netbeans.modules.parsing.api.ParserManager;
110.20 +import org.netbeans.modules.parsing.api.ResultIterator;
110.21 +import org.netbeans.modules.parsing.api.Source;
110.22 +import org.netbeans.modules.parsing.api.UserTask;
110.23 +import org.netbeans.modules.parsing.spi.ParseException;
110.24 import org.netbeans.modules.python.editor.refactoring.PythonRefUtils;
110.25 import org.netbeans.modules.python.editor.refactoring.PythonElementCtx;
110.26 import org.netbeans.modules.refactoring.spi.ui.UI;
110.27 import org.netbeans.modules.refactoring.spi.ui.ActionsImplementationProvider;
110.28 import org.netbeans.modules.refactoring.spi.ui.RefactoringUI;
110.29 import org.netbeans.modules.python.editor.PythonAstUtils;
110.30 +import org.netbeans.modules.python.editor.PythonIndex;
110.31 import org.netbeans.modules.python.editor.PythonParserResult;
110.32 +import org.netbeans.modules.python.editor.PythonStructureScanner;
110.33 import org.netbeans.modules.python.editor.PythonStructureScanner.AnalysisResult;
110.34 import org.netbeans.modules.python.editor.PythonUtils;
110.35 import org.netbeans.modules.python.editor.elements.AstElement;
110.36 import org.netbeans.modules.python.editor.elements.Element;
110.37 -import org.netbeans.napi.gsfret.source.ClasspathInfo;
110.38 import org.openide.ErrorManager;
110.39 import org.openide.cookies.EditorCookie;
110.40 import org.openide.filesystems.FileObject;
110.41 @@ -98,9 +101,9 @@
110.42 if (isFromEditor(ec)) {
110.43 task = new TextComponentTask(ec) {
110.44 @Override
110.45 - protected RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, int startOffset, int endOffset, final CompilationInfo info) {
110.46 + protected RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, int startOffset, int endOffset, final PythonParserResult info) {
110.47 // If you're trying to rename a constructor, rename the enclosing class instead
110.48 - return new RenameRefactoringUI(selectedElement, info);
110.49 + return new RenameRefactoringUI(selectedElement);
110.50 }
110.51 };
110.52 } else {
110.53 @@ -112,12 +115,12 @@
110.54 if (pkg[0] != null) {
110.55 return new RenameRefactoringUI(pkg[0], newName);
110.56 } else {
110.57 - return new RenameRefactoringUI(selectedElements[0], newName, handles == null || handles.isEmpty() ? null : handles.iterator().next(), cinfo == null ? null : cinfo.get());
110.58 + return new RenameRefactoringUI(selectedElements[0], newName, handles == null || handles.isEmpty() ? null : handles.iterator().next());
110.59 }
110.60 } else if (pkg[0] != null) {
110.61 return new RenameRefactoringUI(pkg[0]);
110.62 } else {
110.63 - return new RenameRefactoringUI(selectedElements[0], handles == null || handles.isEmpty() ? null : handles.iterator().next(), cinfo == null ? null : cinfo.get());
110.64 + return new RenameRefactoringUI(selectedElements[0], handles == null || handles.isEmpty() ? null : handles.iterator().next());
110.65 }
110.66 }
110.67 };
110.68 @@ -218,14 +221,14 @@
110.69 if (isFromEditor(ec)) {
110.70 task = new TextComponentTask(ec) {
110.71 @Override
110.72 - protected RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, int startOffset, int endOffset, CompilationInfo info) {
110.73 - return new WhereUsedQueryUI(selectedElement, info);
110.74 + protected RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, int startOffset, int endOffset, PythonParserResult info) {
110.75 + return new WhereUsedQueryUI(selectedElement);
110.76 }
110.77 };
110.78 } else {
110.79 task = new NodeToElementTask(lookup.lookupAll(Node.class)) {
110.80 - protected RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, CompilationInfo info) {
110.81 - return new WhereUsedQueryUI(selectedElement, info);
110.82 + protected RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, PythonParserResult info) {
110.83 + return new WhereUsedQueryUI(selectedElement);
110.84 }
110.85 };
110.86 }
110.87 @@ -258,7 +261,7 @@
110.88 public void doMove(final Lookup lookup) {
110.89 }
110.90
110.91 - public static abstract class TextComponentTask implements Runnable, CancellableTask<CompilationController> {
110.92 + public static abstract class TextComponentTask extends UserTask implements Runnable {
110.93 private JTextComponent textC;
110.94 private int caret;
110.95 private int start;
110.96 @@ -278,45 +281,41 @@
110.97 public void cancel() {
110.98 }
110.99
110.100 - public void run(CompilationController cc) throws Exception {
110.101 - cc.toPhase(Phase.RESOLVED);
110.102 - PythonTree root = PythonAstUtils.getRoot(cc);
110.103 + public void run(ResultIterator cc) throws Exception {
110.104 + PythonTree root = PythonAstUtils.getRoot((ParserResult) cc.getParserResult());
110.105 if (root == null) {
110.106 // TODO How do I add some kind of error message?
110.107 System.out.println("FAILURE - can't refactor uncompileable sources");
110.108 return;
110.109 }
110.110
110.111 - PythonElementCtx ctx = new PythonElementCtx(cc, caret);
110.112 + PythonElementCtx ctx = new PythonElementCtx((PythonParserResult)cc.getParserResult(), caret);
110.113 if (ctx.getSimpleName() == null) {
110.114 return;
110.115 }
110.116 - ui = createRefactoringUI(ctx, start, end, cc);
110.117 + ui = createRefactoringUI(ctx, start, end, (PythonParserResult)cc.getParserResult());
110.118 }
110.119
110.120 public final void run() {
110.121 FileObject fo = null;
110.122 try {
110.123 - Source source = PythonRefUtils.getSource(textC.getDocument());
110.124 - source.runUserActionTask(this, false);
110.125 - Collection<FileObject> fileObjects = source.getFileObjects();
110.126 - if (fileObjects.size() > 0) {
110.127 - fo = fileObjects.iterator().next();
110.128 - }
110.129 - } catch (IOException ioe) {
110.130 - ErrorManager.getDefault().notify(ioe);
110.131 + Source source = Source.create(textC.getDocument());
110.132 + ParserManager.parse(Collections.singleton(source), this);
110.133 + fo = source.getFileObject();
110.134 + } catch (ParseException ex) {
110.135 + ErrorManager.getDefault().notify(ex);
110.136 return;
110.137 }
110.138 TopComponent activetc = TopComponent.getRegistry().getActivated();
110.139
110.140 if (ui != null) {
110.141 - if (fo != null) {
110.142 - ClasspathInfo classpathInfoFor = PythonRefUtils.getClasspathInfoFor(fo);
110.143 - if (classpathInfoFor == null) {
110.144 - JOptionPane.showMessageDialog(null, NbBundle.getMessage(RefactoringActionsProvider.class, "ERR_CannotFindClasspath"));
110.145 - return;
110.146 - }
110.147 - }
110.148 +// if (fo != null) {
110.149 +// ClasspathInfo classpathInfoFor = PythonRefUtils.getClasspathInfoFor(fo);
110.150 +// if (classpathInfoFor == null) {
110.151 +// JOptionPane.showMessageDialog(null, NbBundle.getMessage(RefactoringActionsProvider.class, "ERR_CannotFindClasspath"));
110.152 +// return;
110.153 +// }
110.154 +// }
110.155
110.156 UI.openRefactoringUI(ui, activetc);
110.157 } else {
110.158 @@ -328,10 +327,10 @@
110.159 }
110.160 }
110.161
110.162 - protected abstract RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, int startOffset, int endOffset, CompilationInfo info);
110.163 + protected abstract RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, int startOffset, int endOffset, PythonParserResult info);
110.164 }
110.165
110.166 - public static abstract class NodeToElementTask implements Runnable, CancellableTask<CompilationController> {
110.167 + public static abstract class NodeToElementTask extends UserTask implements Runnable {
110.168 private Node node;
110.169 private RefactoringUI ui;
110.170
110.171 @@ -343,38 +342,35 @@
110.172 public void cancel() {
110.173 }
110.174
110.175 - public void run(CompilationController info) throws Exception {
110.176 - info.toPhase(Phase.ELEMENTS_RESOLVED);
110.177 - PythonTree root = PythonAstUtils.getRoot(info);
110.178 + public void run(ResultIterator info) throws Exception {
110.179 + PythonTree root = PythonAstUtils.getRoot((ParserResult) info.getParserResult());
110.180 if (root != null) {
110.181 - Element element = AstElement.create(info, root);
110.182 - PythonElementCtx fileCtx = new PythonElementCtx(root, root, element, info.getFileObject(), info);
110.183 - ui = createRefactoringUI(fileCtx, info);
110.184 + Element element = AstElement.create((PythonParserResult) info.getParserResult(), root);
110.185 + PythonElementCtx fileCtx = new PythonElementCtx(root, root, element, info.getSnapshot().getSource().getFileObject(), (PythonParserResult) info.getParserResult());
110.186 + ui = createRefactoringUI(fileCtx, (PythonParserResult) info.getParserResult());
110.187 }
110.188 }
110.189
110.190 public final void run() {
110.191 DataObject o = node.getCookie(DataObject.class);
110.192 - Source source = PythonRefUtils.getSource(o.getPrimaryFile());
110.193 + Source source = Source.create(o.getPrimaryFile());
110.194 assert source != null;
110.195 try {
110.196 - source.runUserActionTask(this, false);
110.197 - } catch (IllegalArgumentException ex) {
110.198 - ex.printStackTrace();
110.199 - } catch (IOException ex) {
110.200 + ParserManager.parse(Collections.singleton(source), this);
110.201 + } catch (ParseException ex) {
110.202 ex.printStackTrace();
110.203 }
110.204 UI.openRefactoringUI(ui);
110.205 }
110.206
110.207 - protected abstract RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, CompilationInfo info);
110.208 + protected abstract RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, PythonParserResult info);
110.209 }
110.210
110.211 - public static abstract class NodeToFileObjectTask implements Runnable, CancellableTask<CompilationController> {
110.212 + public static abstract class NodeToFileObjectTask extends UserTask implements Runnable {
110.213 private Collection<? extends Node> nodes;
110.214 private RefactoringUI ui;
110.215 public NonRecursiveFolder pkg[];
110.216 - public WeakReference<CompilationInfo> cinfo;
110.217 + public WeakReference<ResultIterator> cinfo;
110.218 Collection<PythonElementCtx> handles = new ArrayList<PythonElementCtx>();
110.219
110.220 public NodeToFileObjectTask(Collection<? extends Node> nodes) {
110.221 @@ -384,13 +380,12 @@
110.222 public void cancel() {
110.223 }
110.224
110.225 - public void run(CompilationController info) throws Exception {
110.226 - info.toPhase(Phase.ELEMENTS_RESOLVED);
110.227 - PythonTree root = PythonAstUtils.getRoot(info);
110.228 + public void run(ResultIterator info) throws Exception {
110.229 + PythonTree root = PythonAstUtils.getRoot((ParserResult) info.getParserResult());
110.230 if (root != null) {
110.231 - PythonParserResult rpr = PythonAstUtils.getParseResult(info);
110.232 + PythonParserResult rpr = PythonAstUtils.getParseResult((ParserResult) info.getParserResult());
110.233 if (rpr != null) {
110.234 - AnalysisResult ar = rpr.getStructure();
110.235 + AnalysisResult ar = PythonStructureScanner.analyze(rpr);
110.236 List<? extends AstElement> els = ar.getElements();
110.237 if (els.size() > 0) {
110.238 // TODO - try to find the outermost or most "relevant" module/class in the file?
110.239 @@ -398,14 +393,14 @@
110.240 // It's not as simple in Python.
110.241 AstElement element = els.get(0);
110.242 PythonTree node = element.getNode();
110.243 - PythonElementCtx representedObject = new PythonElementCtx(root, node, element, info.getFileObject(), info);
110.244 + PythonElementCtx representedObject = new PythonElementCtx(root, node, element, info.getParserResult().getSnapshot().getSource().getFileObject(), (PythonParserResult) info.getParserResult());
110.245 //representedObject.setNames(element.getFqn(), element.getName());
110.246 representedObject.setNames(element.getIn() + "." + element.getName(), element.getName());
110.247 handles.add(representedObject);
110.248 }
110.249 }
110.250 }
110.251 - cinfo = new WeakReference<CompilationInfo>(info);
110.252 + cinfo = new WeakReference<ResultIterator>(info);
110.253 }
110.254
110.255 public void run() {
110.256 @@ -416,16 +411,14 @@
110.257 DataObject dob = node.getCookie(DataObject.class);
110.258 if (dob != null) {
110.259 fobs[i] = dob.getPrimaryFile();
110.260 - Source source = PythonRefUtils.getSource(fobs[i]);
110.261 + Source source = Source.create(fobs[i]);
110.262 if (source == null) {
110.263 continue;
110.264 }
110.265 assert source != null;
110.266 try {
110.267 - source.runUserActionTask(this, false);
110.268 - } catch (IllegalArgumentException ex) {
110.269 - ex.printStackTrace();
110.270 - } catch (IOException ex) {
110.271 + ParserManager.parse(Collections.singleton(source), this);
110.272 + } catch (ParseException ex) {
110.273 ex.printStackTrace();
110.274 }
110.275
111.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/RenameRefactoringUI.java Sun Jan 04 13:11:53 2015 -0600
111.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/RenameRefactoringUI.java Sat Feb 28 17:25:32 2015 -0800
111.3 @@ -47,9 +47,7 @@
111.4 import java.text.MessageFormat;
111.5 import javax.swing.event.ChangeListener;
111.6 import org.netbeans.api.fileinfo.NonRecursiveFolder;
111.7 -import org.netbeans.modules.gsf.api.ElementKind;
111.8 -import org.netbeans.napi.gsfret.source.ClasspathInfo;
111.9 -import org.netbeans.napi.gsfret.source.CompilationInfo;
111.10 +import org.netbeans.modules.csl.api.ElementKind;
111.11 import org.netbeans.modules.refactoring.api.AbstractRefactoring;
111.12 import org.netbeans.modules.refactoring.api.RenameRefactoring;
111.13 import org.netbeans.modules.python.editor.refactoring.PythonRefUtils;
111.14 @@ -85,17 +83,17 @@
111.15 private boolean pkgRename = true;
111.16 private String stripPrefix;
111.17
111.18 - public RenameRefactoringUI(PythonElementCtx handle, CompilationInfo info) {
111.19 + public RenameRefactoringUI(PythonElementCtx handle) {
111.20 this.jmiObject = handle;
111.21 stripPrefix = handle.getStripPrefix();
111.22 this.refactoring = new RenameRefactoring(Lookups.singleton(handle));
111.23 //oldName = handle.resolveElement(info).getSimpleName().toString();
111.24 oldName = handle.getSimpleName();
111.25
111.26 - ClasspathInfo classpath = PythonRefUtils.getClasspathInfoFor(handle);
111.27 - if (classpath != null) {
111.28 - refactoring.getContext().add(classpath);
111.29 - }
111.30 +// ClasspathInfo classpath = PythonRefUtils.getClasspathInfoFor(handle);
111.31 +// if (classpath != null) {
111.32 +// refactoring.getContext().add(classpath);
111.33 +// }
111.34
111.35 dispOldName = oldName;
111.36
111.37 @@ -105,7 +103,7 @@
111.38 this.refactoring.getContext().add(UI.Constants.REQUEST_PREVIEW);
111.39 }
111.40
111.41 - public RenameRefactoringUI(FileObject file, PythonElementCtx handle, CompilationInfo info) {
111.42 + public RenameRefactoringUI(FileObject file, PythonElementCtx handle) {
111.43 if (handle != null) {
111.44 jmiObject = handle;
111.45 this.refactoring = new RenameRefactoring(Lookups.fixed(file, handle));
111.46 @@ -116,10 +114,10 @@
111.47 oldName = file.getName();
111.48 }
111.49 dispOldName = oldName;
111.50 - ClasspathInfo cpInfo = handle == null ? PythonRefUtils.getClasspathInfoFor(file) : PythonRefUtils.getClasspathInfoFor(handle);
111.51 - if (cpInfo != null) {
111.52 - refactoring.getContext().add(cpInfo);
111.53 - }
111.54 +// ClasspathInfo cpInfo = handle == null ? PythonRefUtils.getClasspathInfoFor(file) : PythonRefUtils.getClasspathInfoFor(handle);
111.55 +// if (cpInfo != null) {
111.56 +// refactoring.getContext().add(cpInfo);
111.57 +// }
111.58 //this(jmiObject, (FileObject) null, true);
111.59
111.60 // Force refresh!
111.61 @@ -129,10 +127,10 @@
111.62 public RenameRefactoringUI(NonRecursiveFolder file) {
111.63 this.refactoring = new RenameRefactoring(Lookups.singleton(file));
111.64 oldName = PythonRefUtils.getPackageName(file.getFolder());
111.65 - ClasspathInfo classpath = PythonRefUtils.getClasspathInfoFor(file.getFolder());
111.66 - if (classpath != null) {
111.67 - refactoring.getContext().add(classpath);
111.68 - }
111.69 +// ClasspathInfo classpath = PythonRefUtils.getClasspathInfoFor(file.getFolder());
111.70 +// if (classpath != null) {
111.71 +// refactoring.getContext().add(classpath);
111.72 +// }
111.73 dispOldName = oldName;
111.74 pkgRename = true;
111.75 //this(jmiObject, (FileObject) null, true);
111.76 @@ -141,7 +139,7 @@
111.77 this.refactoring.getContext().add(UI.Constants.REQUEST_PREVIEW);
111.78 }
111.79
111.80 - RenameRefactoringUI(FileObject jmiObject, String newName, PythonElementCtx handle, CompilationInfo info) {
111.81 + RenameRefactoringUI(FileObject jmiObject, String newName, PythonElementCtx handle) {
111.82 if (handle != null) {
111.83 this.refactoring = new RenameRefactoring(Lookups.fixed(jmiObject, handle));
111.84 } else {
111.85 @@ -151,10 +149,10 @@
111.86 oldName = newName;
111.87 //[FIXME] this should be oldName of refactored object
111.88 this.dispOldName = newName;
111.89 - ClasspathInfo cpInfo = handle == null ? PythonRefUtils.getClasspathInfoFor(jmiObject) : PythonRefUtils.getClasspathInfoFor(handle);
111.90 - if (cpInfo != null) {
111.91 - refactoring.getContext().add(cpInfo);
111.92 - }
111.93 +// ClasspathInfo cpInfo = handle == null ? PythonRefUtils.getClasspathInfoFor(jmiObject) : PythonRefUtils.getClasspathInfoFor(handle);
111.94 +// if (cpInfo != null) {
111.95 +// refactoring.getContext().add(cpInfo);
111.96 +// }
111.97 fromListener = true;
111.98
111.99 // Force refresh!
111.100 @@ -163,10 +161,10 @@
111.101
111.102 RenameRefactoringUI(NonRecursiveFolder jmiObject, String newName) {
111.103 this.refactoring = new RenameRefactoring(Lookups.singleton(jmiObject));
111.104 - ClasspathInfo classpath = PythonRefUtils.getClasspathInfoFor(jmiObject.getFolder());
111.105 - if (classpath != null) {
111.106 - refactoring.getContext().add(classpath);
111.107 - }
111.108 +// ClasspathInfo classpath = PythonRefUtils.getClasspathInfoFor(jmiObject.getFolder());
111.109 +// if (classpath != null) {
111.110 +// refactoring.getContext().add(classpath);
111.111 +// }
111.112 //this.jmiObject = jmiObject;
111.113 oldName = newName;
111.114 //[FIXME] this should be oldName of refactored object
112.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/WhereUsedPanel.form Sun Jan 04 13:11:53 2015 -0600
112.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/WhereUsedPanel.form Sat Feb 28 17:25:32 2015 -0800
112.3 @@ -1,12 +1,14 @@
112.4 <?xml version="1.0" encoding="UTF-8" ?>
112.5
112.6 -<Form version="1.2" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
112.7 +<Form version="1.2" maxVersion="1.2" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
112.8 <NonVisualComponents>
112.9 <Component class="javax.swing.ButtonGroup" name="buttonGroup">
112.10 </Component>
112.11 </NonVisualComponents>
112.12 <AuxValues>
112.13 <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
112.14 + <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
112.15 + <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
112.16 <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
112.17 <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
112.18 <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
113.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/WhereUsedPanel.java Sun Jan 04 13:11:53 2015 -0600
113.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/WhereUsedPanel.java Sat Feb 28 17:25:32 2015 -0800
113.3 @@ -48,6 +48,7 @@
113.4 import java.awt.Dimension;
113.5 import java.awt.event.ItemEvent;
113.6 import java.io.IOException;
113.7 +import java.util.Collections;
113.8 import java.util.HashSet;
113.9 import java.util.Set;
113.10 import javax.swing.SwingUtilities;
113.11 @@ -58,13 +59,15 @@
113.12 import org.openide.util.NbBundle;
113.13 import org.netbeans.modules.python.editor.refactoring.RefactoringModule;
113.14 import javax.swing.JPanel;
113.15 -import org.netbeans.modules.gsf.api.CancellableTask;
113.16 -import org.netbeans.modules.gsf.api.ElementKind;
113.17 -import org.netbeans.modules.gsf.api.Modifier;
113.18 -import org.netbeans.napi.gsfret.source.CompilationController;
113.19 -import org.netbeans.napi.gsfret.source.Phase;
113.20 -import org.netbeans.napi.gsfret.source.Source;
113.21 +import org.netbeans.modules.csl.api.ElementKind;
113.22 +import org.netbeans.modules.csl.api.Modifier;
113.23 +import org.netbeans.modules.parsing.api.ParserManager;
113.24 +import org.netbeans.modules.parsing.api.ResultIterator;
113.25 +import org.netbeans.modules.parsing.api.Source;
113.26 +import org.netbeans.modules.parsing.api.UserTask;
113.27 +import org.netbeans.modules.parsing.spi.ParseException;
113.28 import org.netbeans.modules.python.editor.refactoring.PythonElementCtx;
113.29 +import org.openide.util.Exceptions;
113.30
113.31 /**
113.32 * Based on the WhereUsedPanel in Java refactoring by Jan Becicka.
113.33 @@ -95,11 +98,8 @@
113.34 if (initialized) {
113.35 return;
113.36 }
113.37 - Source source = PythonRefUtils.getSource(element.getFileObject());
113.38 - CancellableTask<CompilationController> task = new CancellableTask<CompilationController>() {
113.39 - public void cancel() {
113.40 - throw new UnsupportedOperationException("Not supported yet.");
113.41 - }
113.42 + Source source = Source.create(element.getFileObject());
113.43 + UserTask task = new UserTask() {
113.44
113.45 // TODO - handle methods in modules!!!!
113.46 private String getClassName(PythonElementCtx element) {
113.47 @@ -109,8 +109,7 @@
113.48 /**
113.49 * @todo For method calls, try to figure out the call type with the type analyzer
113.50 */
113.51 - public void run(CompilationController info) throws Exception {
113.52 - info.toPhase(Phase.RESOLVED);
113.53 + public void run(ResultIterator iter) throws Exception {
113.54 String m_isBaseClassText = null;
113.55 final String labelText;
113.56 Set<Modifier> modif = new HashSet<Modifier>();
113.57 @@ -192,9 +191,9 @@
113.58 }
113.59 };
113.60 try {
113.61 - source.runUserActionTask(task, true);
113.62 - } catch (IOException ioe) {
113.63 - throw (RuntimeException)new RuntimeException().initCause(ioe);
113.64 + ParserManager.parse(Collections.singleton(source), task);
113.65 + } catch (ParseException ex) {
113.66 + Exceptions.printStackTrace(ex);
113.67 }
113.68 initialized = true;
113.69 }
114.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/WhereUsedQueryUI.java Sun Jan 04 13:11:53 2015 -0600
114.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/WhereUsedQueryUI.java Sat Feb 28 17:25:32 2015 -0800
114.3 @@ -46,8 +46,7 @@
114.4 import java.text.MessageFormat;
114.5 import java.util.ResourceBundle;
114.6 import javax.swing.event.ChangeListener;
114.7 -import org.netbeans.modules.gsf.api.ElementKind;
114.8 -import org.netbeans.napi.gsfret.source.CompilationInfo;
114.9 +import org.netbeans.modules.csl.api.ElementKind;
114.10 import org.netbeans.modules.refactoring.api.AbstractRefactoring;
114.11 import org.netbeans.modules.refactoring.api.WhereUsedQuery;
114.12 import org.netbeans.modules.python.editor.refactoring.PythonRefUtils;
114.13 @@ -55,7 +54,6 @@
114.14 import org.netbeans.modules.python.editor.refactoring.WhereUsedQueryConstants;
114.15 import org.netbeans.modules.refactoring.spi.ui.CustomRefactoringPanel;
114.16 import org.netbeans.modules.refactoring.spi.ui.RefactoringUI;
114.17 -import org.netbeans.napi.gsfret.source.ClasspathInfo;
114.18 import org.openide.util.HelpCtx;
114.19 import org.openide.util.NbBundle;
114.20 import org.openide.util.lookup.Lookups;
114.21 @@ -73,12 +71,12 @@
114.22 private ElementKind kind;
114.23 private AbstractRefactoring delegate;
114.24
114.25 - public WhereUsedQueryUI(PythonElementCtx jmiObject, CompilationInfo info) {
114.26 + public WhereUsedQueryUI(PythonElementCtx jmiObject) {
114.27 this.query = new WhereUsedQuery(Lookups.singleton(jmiObject));
114.28 - ClasspathInfo classpathInfoFor = PythonRefUtils.getClasspathInfoFor(jmiObject);
114.29 - if (classpathInfoFor != null) {
114.30 - this.query.getContext().add(classpathInfoFor);
114.31 - }
114.32 +// ClasspathInfo classpathInfoFor = PythonRefUtils.getClasspathInfoFor(jmiObject);
114.33 +// if (classpathInfoFor != null) {
114.34 +// this.query.getContext().add(classpathInfoFor);
114.35 +// }
114.36 this.element = jmiObject;
114.37 name = jmiObject.getName();
114.38 kind = jmiObject.getKind();
115.1 --- a/python.editor/src/org/netbeans/modules/python/editor/scopes/SymbolTable.java Sun Jan 04 13:11:53 2015 -0600
115.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/scopes/SymbolTable.java Sat Feb 28 17:25:32 2015 -0800
115.3 @@ -48,17 +48,16 @@
115.4 import java.util.List;
115.5 import java.util.Map;
115.6 import java.util.Set;
115.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
115.8 -import org.netbeans.modules.gsf.api.ElementKind;
115.9 -import org.netbeans.modules.gsf.api.Error;
115.10 -import org.netbeans.modules.gsf.api.Index;
115.11 -import org.netbeans.modules.gsf.api.NameKind;
115.12 -import org.netbeans.modules.gsf.api.OffsetRange;
115.13 -import org.netbeans.modules.gsf.api.Severity;
115.14 -import org.netbeans.modules.gsf.spi.DefaultError;
115.15 +import org.netbeans.modules.csl.api.ElementKind;
115.16 +import org.netbeans.modules.csl.api.OffsetRange;
115.17 +import org.netbeans.modules.csl.api.Severity;
115.18 +import org.netbeans.modules.csl.api.Error;
115.19 +import org.netbeans.modules.csl.spi.DefaultError;
115.20 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
115.21 import org.netbeans.modules.python.editor.PythonAstUtils;
115.22 import org.netbeans.modules.python.editor.PythonIndex;
115.23 import org.netbeans.modules.python.editor.PythonIndexer;
115.24 +import org.netbeans.modules.python.editor.PythonParserResult;
115.25 import org.netbeans.modules.python.editor.PythonUtils;
115.26 import org.netbeans.modules.python.editor.elements.AstElement;
115.27 import org.netbeans.modules.python.editor.elements.Element;
115.28 @@ -325,41 +324,39 @@
115.29 return modules;
115.30 }
115.31
115.32 - private void addSymbolsFromModule(CompilationInfo info, String module, String prefix, NameKind kind, Set<? super IndexedElement> result) {
115.33 + private void addSymbolsFromModule(PythonParserResult info, String module, String prefix, QuerySupport.Kind kind, Set<? super IndexedElement> result) {
115.34 if (PythonIndex.isBuiltinModule(module)) {
115.35 Set<IndexedElement> all = getAllSymbolsFromModule(info, module);
115.36 for (IndexedElement e : all) {
115.37 - if (kind == NameKind.PREFIX) {
115.38 + if (kind == QuerySupport.Kind.PREFIX) {
115.39 if (e.getName().startsWith(prefix)) {
115.40 result.add(e);
115.41 }
115.42 - } else if (kind == NameKind.EXACT_NAME) {
115.43 + } else if (kind == QuerySupport.Kind.EXACT) {
115.44 if (prefix.equals(e.getName())) {
115.45 result.add(e);
115.46 }
115.47 - } else if (kind == NameKind.CASE_INSENSITIVE_PREFIX) {
115.48 + } else if (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX) {
115.49 if (e.getName().regionMatches(true, 0, prefix, 0, prefix.length())) {
115.50 result.add(e);
115.51 }
115.52 }
115.53 }
115.54 } else {
115.55 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
115.56 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
115.57 - Set<IndexedElement> elements = index.getImportedElements(prefix, kind, PythonIndex.ALL_SCOPE, Collections.singleton(module), null);
115.58 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
115.59 + Set<IndexedElement> elements = index.getImportedElements(prefix, kind, Collections.singleton(module), null);
115.60 for (IndexedElement e : elements) {
115.61 result.add(e);
115.62 }
115.63 }
115.64 }
115.65
115.66 - private Set<IndexedElement> getAllSymbolsFromModule(CompilationInfo info, String module) {
115.67 + private Set<IndexedElement> getAllSymbolsFromModule(PythonParserResult info, String module) {
115.68 Set<IndexedElement> elements = importedElements.get(module);
115.69 if (elements == null) {
115.70 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
115.71 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
115.72 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
115.73 Set<String> systemHolder = new HashSet<String>(3);
115.74 - elements = index.getImportedElements("", NameKind.PREFIX, PythonIndex.ALL_SCOPE, Collections.singleton(module), systemHolder);
115.75 + elements = index.getImportedElements("", QuerySupport.Kind.PREFIX, Collections.singleton(module), systemHolder);
115.76 // Cache system modules - don't cache local modules
115.77 if (!systemHolder.isEmpty()) {
115.78 importedElements.put(module, elements);
115.79 @@ -369,16 +366,11 @@
115.80 return elements;
115.81 }
115.82
115.83 - public Set<Element> getDefinedElements(CompilationInfo info, PythonTree scope, String prefix, NameKind kind) {
115.84 + public Set<Element> getDefinedElements(PythonParserResult info, PythonTree scope, String prefix, QuerySupport.Kind kind) {
115.85 Set<Element> elements = new HashSet<Element>(300);
115.86 ScopeInfo scopeInfo = scopes.get(scope);
115.87 - String module = PythonUtils.getModuleName(fileObject, null);
115.88 - String url = null;
115.89 - try {
115.90 - url = fileObject.getURL().toExternalForm();
115.91 - } catch (FileStateInvalidException ex) {
115.92 - Exceptions.printStackTrace(ex);
115.93 - }
115.94 + String module = PythonUtils.getModuleName(fileObject);
115.95 + String url = fileObject.toURL().toExternalForm();
115.96
115.97 // Get builtin symbols
115.98 for (String mod : getModulesToStarImport()) {
115.99 @@ -401,15 +393,15 @@
115.100 // Something in narrower scope already processed this one
115.101 continue;
115.102 }
115.103 - if (kind == NameKind.EXACT_NAME) {
115.104 + if (kind == QuerySupport.Kind.EXACT) {
115.105 if (!(name.equals(prefix))) {
115.106 continue;
115.107 }
115.108 - } else if (kind == NameKind.PREFIX) {
115.109 + } else if (kind == QuerySupport.Kind.PREFIX) {
115.110 if (!name.startsWith(prefix)) {
115.111 continue;
115.112 }
115.113 - } else if (kind == NameKind.CASE_INSENSITIVE_PREFIX) {
115.114 + } else if (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX) {
115.115 if (!name.regionMatches(true, 0, prefix, 0, prefix.length())) {
115.116 continue;
115.117 }
115.118 @@ -782,7 +774,7 @@
115.119 }
115.120 }
115.121
115.122 - public Map<String, SymInfo> getUnresolvedNames(CompilationInfo info) {
115.123 + public Map<String, SymInfo> getUnresolvedNames(PythonParserResult info) {
115.124 Map<String, SymInfo> unresolved = new HashMap<String, SymInfo>();
115.125 Set<String> builtin = getBuiltin(info);
115.126
115.127 @@ -821,7 +813,7 @@
115.128 return unresolved;
115.129 }
115.130
115.131 - public List<Attribute> getNotInInitAttributes(CompilationInfo info) {
115.132 + public List<Attribute> getNotInInitAttributes(PythonParserResult info) {
115.133 List<Attribute> notInInitAttribs = new ArrayList<Attribute>();
115.134 for (ScopeInfo scopeInfo : scopes.values()) {
115.135 if (scopeInfo.scope_node instanceof ClassDef) {
115.136 @@ -932,11 +924,10 @@
115.137 return false;
115.138 }
115.139
115.140 - public List<PythonTree> getUnresolvedParents(CompilationInfo info) {
115.141 + public List<PythonTree> getUnresolvedParents(PythonParserResult info) {
115.142 // deal with unresolved parents in inherit trees
115.143 List<PythonTree> unresolvedParents = new ArrayList<PythonTree>();
115.144 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
115.145 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
115.146 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
115.147
115.148 for (String cur : classes.keySet()) {
115.149 ClassDef cls = classes.get(cur);
115.150 @@ -965,7 +956,7 @@
115.151 if (!isImported(moduleName)) {
115.152 unresolvedParents.add(base);
115.153 } else {
115.154 - Set<IndexedElement> found = index.getImportedElements(clsName, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, Collections.<String>singleton(moduleName), null);
115.155 + Set<IndexedElement> found = index.getImportedElements(clsName, QuerySupport.Kind.EXACT, Collections.<String>singleton(moduleName), null);
115.156 if (found.size() == 0) {
115.157 unresolvedParents.add(base);
115.158 }
115.159 @@ -980,7 +971,7 @@
115.160 return unresolvedParents;
115.161 }
115.162
115.163 - public HashMap<ClassDef, String> getClassesCyclingRedundancies(CompilationInfo info) {
115.164 + public HashMap<ClassDef, String> getClassesCyclingRedundancies(PythonParserResult info) {
115.165 HashMap<ClassDef, String> cyclingRedundancies = new HashMap<ClassDef, String>();
115.166 for (String cur : classes.keySet()) {
115.167 HashMap<String, String> returned = new HashMap<String, String>();
115.168 @@ -996,8 +987,7 @@
115.169 return cyclingRedundancies;
115.170 }
115.171
115.172 - @SuppressWarnings("unchecked")
115.173 - public List<PythonTree> getUnresolvedAttributes(CompilationInfo info) {
115.174 + public List<PythonTree> getUnresolvedAttributes(PythonParserResult info) {
115.175 List<PythonTree> unresolvedNodes = new ArrayList<PythonTree>();
115.176 for (ScopeInfo scopeInfo : scopes.values()) {
115.177 Set<String> unresolved = new HashSet<String>();
115.178 @@ -1054,8 +1044,7 @@
115.179 return unresolvedNodes;
115.180 }
115.181
115.182 - @SuppressWarnings("unchecked")
115.183 - public List<PythonTree> getUnresolved(CompilationInfo info) {
115.184 + public List<PythonTree> getUnresolved(PythonParserResult info) {
115.185 List<PythonTree> unresolvedNodes = new ArrayList<PythonTree>();
115.186 Set<String> builtin = getBuiltin(info);
115.187
115.188 @@ -1094,8 +1083,7 @@
115.189
115.190 if (unresolved.size() > 0) {
115.191 // Check imports and see if it's resolved by existing imports
115.192 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
115.193 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
115.194 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
115.195 // TODO - cache system libraries!
115.196 // TODO - make method which doesn't create elements for these guys!
115.197 // Set<IndexedElement> elements = index.getImportedElements("", NameKind.PREFIX, PythonIndex.ALL_SCOPE, imports, importsFrom);
115.198 @@ -1121,7 +1109,6 @@
115.199 return unresolvedNodes;
115.200 }
115.201
115.202 - @SuppressWarnings("unchecked")
115.203 public List<PythonTree> getUnused(boolean skipSelf, boolean skipParams) { // not used for unused imports, see separate method
115.204 List<PythonTree> unusedNodes = new ArrayList<PythonTree>();
115.205
115.206 @@ -1207,10 +1194,9 @@
115.207 }
115.208 private static Set<String> builtinSymbols;
115.209
115.210 - private Set<String> getBuiltin(CompilationInfo info) {
115.211 + private Set<String> getBuiltin(PythonParserResult info) {
115.212 if (builtinSymbols == null) {
115.213 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
115.214 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
115.215 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
115.216 builtinSymbols = index.getBuiltinSymbols();
115.217 }
115.218
116.1 --- a/python.editor/src/org/netbeans/modules/python/editor/templates/executable_module.py.ftl Sun Jan 04 13:11:53 2015 -0600
116.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/templates/executable_module.py.ftl Sat Feb 28 17:25:32 2015 -0800
116.3 @@ -1,4 +1,8 @@
116.4 -#! /usr/bin/python
116.5 +<#if python3style?? && python3style>
116.6 +#!/usr/bin/env python3
116.7 +<#else>
116.8 +#!/usr/bin/env python2
116.9 +</#if>
116.10
116.11 <#-- This is a FreeMarker template -->
116.12 <#-- You can change the contents of the license inserted into
116.13 @@ -7,8 +11,9 @@
116.14 <#assign licensePrefix = "# ">
116.15 <#include "../Licenses/license-${project.license}.txt">
116.16
116.17 -__author__="${user}"
116.18 -__date__ ="$${date} ${time}$"
116.19 -
116.20 if __name__ == "__main__":
116.21 - print "Hello World";
116.22 +<#if python3style?? && python3style>
116.23 + print("Hello World")
116.24 +<#else>
116.25 + print "Hello World"
116.26 +</#if>
116.27 \ No newline at end of file
117.1 --- a/python.editor/src/org/netbeans/modules/python/editor/templates/init.py.ftl Sun Jan 04 13:11:53 2015 -0600
117.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/templates/init.py.ftl Sat Feb 28 17:25:32 2015 -0800
117.3 @@ -1,2 +0,0 @@
117.4 -__author__="${user}"
117.5 -__date__ ="$${date} ${time}$"
117.6 \ No newline at end of file
118.1 --- a/python.editor/src/org/netbeans/modules/python/editor/templates/module.py.ftl Sun Jan 04 13:11:53 2015 -0600
118.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/templates/module.py.ftl Sat Feb 28 17:25:32 2015 -0800
118.3 @@ -5,8 +5,9 @@
118.4 <#assign licensePrefix = "# ">
118.5 <#include "../Licenses/license-${project.license}.txt">
118.6
118.7 -__author__="${user}"
118.8 -__date__ ="$${date} ${time}$"
118.9 -
118.10 if __name__ == "__main__":
118.11 +<#if python3style?? && python3style>
118.12 + print("Hello World")
118.13 +<#else>
118.14 print "Hello World"
118.15 +</#if>
119.1 --- a/python.editor/src/org/netbeans/modules/python/editor/templates/setup.py.ftl Sun Jan 04 13:11:53 2015 -0600
119.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/templates/setup.py.ftl Sat Feb 28 17:25:32 2015 -0800
119.3 @@ -1,6 +1,3 @@
119.4 -__author__="${user}"
119.5 -__date__ ="$${date} ${time}$"
119.6 -
119.7 from setuptools import setup,find_packages
119.8
119.9 setup (
119.10 @@ -16,7 +13,7 @@
119.11 author = '${user}',
119.12 author_email = '',
119.13
119.14 - summary = 'Just another Python package for the cheese shop',
119.15 + #summary = 'Just another Python package for the cheese shop',
119.16 url = '',
119.17 license = '',
119.18 long_description= 'Long description of the package',
120.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py Sun Jan 04 13:11:53 2015 -0600
120.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
120.3 @@ -1,615 +0,0 @@
120.4 -"""Configuration file parser.
120.5 -
120.6 -A setup file consists of sections, lead by a "[section]" header,
120.7 -and followed by "name: value" entries, with continuations and such in
120.8 -the style of RFC 822.
120.9 -
120.10 - the same section, or values in a special [DEFAULT] section.
120.11 -
120.12 -For example:
120.13 -
120.14 - something: %(dir)s/whatever
120.15 -
120.16 -would resolve the "%(dir)s" to the value of dir. All reference
120.17 -expansions are done late, on demand.
120.18 -
120.19 -Intrinsic defaults can be specified by passing them into the
120.20 -ConfigParser constructor as a dictionary.
120.21 -
120.22 -class:
120.23 -
120.24 -ConfigParser -- responsible for parsing a list of
120.25 - configuration files, and managing the parsed database.
120.26 -
120.27 - methods:
120.28 -
120.29 - __init__(defaults=None)
120.30 - create the parser and specify a dictionary of intrinsic defaults. The
120.31 - keys must be strings, the values must be appropriate for %()s string
120.32 - interpolation. Note that `__name__' is always an intrinsic default;
120.33 - it's value is the section's name.
120.34 -
120.35 - sections()
120.36 - return all the configuration section names, sans DEFAULT
120.37 -
120.38 - has_section(section)
120.39 - return whether the given section exists
120.40 -
120.41 - has_option(section, option)
120.42 - return whether the given option exists in the given section
120.43 -
120.44 - options(section)
120.45 - return list of configuration options for the named section
120.46 -
120.47 - read(filenames)
120.48 - read and parse the list of named configuration files, given by
120.49 - name. A single filename is also allowed. Non-existing files
120.50 - are ignored.
120.51 -
120.52 - readfp(fp, filename=None)
120.53 - read and parse one configuration file, given as a file object.
120.54 - The filename defaults to fp.name; it is only used in error
120.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
120.56 -
120.57 - get(section, option, raw=False, vars=None)
120.58 - return a string value for the named option. All % interpolations are
120.59 - expanded in the return values, based on the defaults passed into the
120.60 - constructor and the DEFAULT section. Additional substitutions may be
120.61 - provided using the `vars' argument, which must be a dictionary whose
120.62 - contents override any pre-existing defaults.
120.63 -
120.64 - getint(section, options)
120.65 - like get(), but convert value to an integer
120.66 -
120.67 - getfloat(section, options)
120.68 - like get(), but convert value to a float
120.69 -
120.70 - getboolean(section, options)
120.71 - like get(), but convert value to a boolean (currently case
120.72 - insensitively defined as 0, false, no, off for False, and 1, true,
120.73 - yes, on for True). Returns False or True.
120.74 -
120.75 - items(section, raw=False, vars=None)
120.76 - return a list of tuples with (name, value) for each option
120.77 - in the section.
120.78 -
120.79 - remove_section(section)
120.80 - remove the given file section and all its options
120.81 -
120.82 - remove_option(section, option)
120.83 - remove the given option from the given section
120.84 -
120.85 - set(section, option, value)
120.86 - set the given option
120.87 -
120.88 - write(fp)
120.89 - write the configuration state in .ini format
120.90 -"""
120.91 -
120.92 -import re
120.93 -
120.94 -__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
120.95 - "InterpolationError", "InterpolationDepthError",
120.96 - "InterpolationSyntaxError", "ParsingError",
120.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
120.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
120.99 -
120.100 -DEFAULTSECT = "DEFAULT"
120.101 -
120.102 -MAX_INTERPOLATION_DEPTH = 10
120.103 -
120.104 -
120.105 -
120.106 -# exception classes
120.107 -class Error(Exception):
120.108 - """Base class for ConfigParser exceptions."""
120.109 -
120.110 - def __init__(self, msg=''):
120.111 - self.message = msg
120.112 - Exception.__init__(self, msg)
120.113 -
120.114 - def __repr__(self):
120.115 - return self.message
120.116 -
120.117 - __str__ = __repr__
120.118 -
120.119 -class NoSectionError(Error):
120.120 - """Rasssised when no section matches a requested option."""
120.121 -
120.122 - def __init__(self, section):
120.123 - Error.__init__(self, 'No section: ' + `section`)
120.124 - self.section = section
120.125 -
120.126 -class DuplicateSectionError(Error):
120.127 - """Raised when a section is multiply-created."""
120.128 -
120.129 - def __init__(self, section):
120.130 - Error.__init__(self, "Section %r already exists" % section)
120.131 - self.section = section
120.132 -
120.133 -class NoOptionError(Error):
120.134 - """A requested option was not found."""
120.135 -
120.136 - def __init__(self, option, section):
120.137 - Error.__init__(self, "No option %r in section: %r" %
120.138 - (option, section))
120.139 - self.option = option
120.140 - self.section = section
120.141 -
120.142 -class InterpolationError(Error):
120.143 - """Base class for interpolation-related exceptions."""
120.144 -
120.145 - def __init__(self, option, section, msg):
120.146 - Error.__init__(self, msg)
120.147 - self.option = option
120.148 - self.section = section
120.149 -
120.150 -class InterpolationMissingOptionError(InterpolationError):
120.151 - """A string substitution required a setting which was not available."""
120.152 -
120.153 - def __init__(self, option, section, rawval, reference):
120.154 - msg = ("Bad value substitution:\n"
120.155 - "\tsection: [%s]\n"
120.156 - "\toption : %s\n"
120.157 - "\tkey : %s\n"
120.158 - "\trawval : %s\n"
120.159 - % (section, option, reference, rawval))
120.160 - InterpolationError.__init__(self, option, section, msg)
120.161 - self.reference = reference
120.162 -
120.163 -class InterpolationSyntaxError(InterpolationError):
120.164 - """Raised when the source text into which substitutions are made
120.165 - does not conform to the required syntax."""
120.166 -
120.167 -class InterpolationDepthError(InterpolationError):
120.168 - """Raised when substitutions are nested too deeply."""
120.169 -
120.170 - def __init__(self, option, section, rawval):
120.171 - msg = ("Value interpolation too deeply recursive:\n"
120.172 - "\tsection: [%s]\n"
120.173 - "\toption : %s\n"
120.174 - "\trawval : %s\n"
120.175 - % (section, option, rawval))
120.176 - InterpolationError.__init__(self, option, section, msg)
120.177 -
120.178 -class ParsingError(Error):
120.179 - """Raised when a configuration file does not follow legal syntax."""
120.180 -
120.181 - def __init__(self, filename):
120.182 - Error.__init__(self, 'File contains parsing errors: %s' % filename)
120.183 - self.filename = filename
120.184 - self.errors = []
120.185 -
120.186 - def append(self, lineno, line):
120.187 - self.errors.append((lineno, line))
120.188 - self.message += '\n\t[line %2d]: %s' % (lineno, line)
120.189 -
120.190 -class MissingSectionHeaderError(ParsingError):
120.191 - """Raised when a key-value pair is found before any section header."""
120.192 -
120.193 - def __init__(self, filename, lineno, line):
120.194 - Error.__init__(
120.195 - self,
120.196 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
120.197 - (filename, lineno, line))
120.198 - self.filename = filename
120.199 - self.lineno = lineno
120.200 - self.line = line
120.201 -
120.202 -
120.203 -
120.204 -class RawConfigParser:
120.205 - def __init__(self, defaults=None):
120.206 - self._sections = {}
120.207 - if defaults is None:
120.208 - self._defaults = {}
120.209 - else:
120.210 - self._defaults = defaults
120.211 -
120.212 - def defaults(self):
120.213 - return self._defaults
120.214 -
120.215 - def sections(self):
120.216 - """Return a list of section names, excluding [DEFAULT]"""
120.217 - # self._sections will never have [DEFAULT] in it
120.218 - return self._sections.keys()
120.219 -
120.220 - def add_section(self, section):
120.221 - """Create a new section in the configuration.
120.222 -
120.223 - Raise DuplicateSectionError if a section by the specified name
120.224 - already exists.
120.225 - """
120.226 - if section in self._sections:
120.227 - raise DuplicateSectionError(section)
120.228 - self._sections[section] = {}
120.229 -
120.230 - def has_section(self, section):
120.231 - """Indicate whether the named section is present in the configuration.
120.232 -
120.233 - The DEFAULT section is not acknowledged.
120.234 - """
120.235 - return section in self._sections
120.236 -
120.237 - def options(self, section):
120.238 - """Return a list of option names for the given section name."""
120.239 - try:
120.240 - opts = self._sections[section].copy()
120.241 - except KeyError:
120.242 - raise NoSectionError(section)
120.243 - opts.update(self._defaults)
120.244 - if '__name__' in opts:
120.245 - del opts['__name__']
120.246 - return opts.keys()
120.247 -
120.248 - def read(self, filenames):
120.249 - """Read and parse a filename or a list of filenames.
120.250 -
120.251 - Files that cannot be opened are silently ignored; this is
120.252 - designed so that you can specify a list of potential
120.253 - configuration file locations (e.g. current directory, user's
120.254 - home directory, systemwide directory), and all existing
120.255 - configuration files in the list will be read. A single
120.256 - filename may also be given.
120.257 - """
120.258 - if isinstance(filenames, basestring):
120.259 - filenames = [filenames]
120.260 - for filename in filenames:
120.261 - try:
120.262 - fp = open(filename)
120.263 - except IOError:
120.264 - continue
120.265 - self._read(fp, filename)
120.266 - fp.close()
120.267 -
120.268 - def readfp(self, fp, filename=None):
120.269 - """Like read() but the argument must be a file-like object.
120.270 -
120.271 - The `fp' argument must have a `readline' method. Optional
120.272 - second argument is the `filename', which if not given, is
120.273 - taken from fp.name. If fp has no `name' attribute, `<???>' is
120.274 - used.
120.275 -
120.276 - """
120.277 - if filename is None:
120.278 - try:
120.279 - filename = fp.name
120.280 - except AttributeError:
120.281 - filename = '<???>'
120.282 - self._read(fp, filename)
120.283 -
120.284 - def get(self, section, option):
120.285 - opt = self.optionxform(option)
120.286 - if section not in self._sections:
120.287 - if section != DEFAULTSECT:
120.288 - raise NoSectionError(section)
120.289 - if opt in self._defaults:
120.290 - return self._defaults[opt]
120.291 - else:
120.292 - raise NoOptionError(option, section)
120.293 - elif opt in self._sections[section]:
120.294 - return self._sections[section][opt]
120.295 - elif opt in self._defaults:
120.296 - return self._defaults[opt]
120.297 - else:
120.298 - raise NoOptionError(option, section)
120.299 -
120.300 - def items(self, section):
120.301 - try:
120.302 - d2 = self._sections[section]
120.303 - except KeyError:
120.304 - if section != DEFAULTSECT:
120.305 - raise NoSectionError(section)
120.306 - d2 = {}
120.307 - d = self._defaults.copy()
120.308 - d.update(d2)
120.309 - if "__name__" in d:
120.310 - del d["__name__"]
120.311 - return d.items()
120.312 -
120.313 - def _get(self, section, conv, option):
120.314 - return conv(self.get(section, option))
120.315 -
120.316 - def getint(self, section, option):
120.317 - return self._get(section, int, option)
120.318 -
120.319 - def getfloat(self, section, option):
120.320 - return self._get(section, float, option)
120.321 -
120.322 - _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
120.323 - '0': False, 'no': False, 'false': False, 'off': False}
120.324 -
120.325 - def getboolean(self, section, option):
120.326 - v = self.get(section, option)
120.327 - if v.lower() not in self._boolean_states:
120.328 - raise ValueError, 'Not a boolean: %s' % v
120.329 - return self._boolean_states[v.lower()]
120.330 -
120.331 - def optionxform(self, optionstr):
120.332 - return optionstr.lower()
120.333 -
120.334 - def has_option(self, section, option):
120.335 - """Check for the existence of a given option in a given section."""
120.336 - if not section or section == DEFAULTSECT:
120.337 - option = self.optionxform(option)
120.338 - return option in self._defaults
120.339 - elif section not in self._sections:
120.340 - return False
120.341 - else:
120.342 - option = self.optionxform(option)
120.343 - return (option in self._sections[section]
120.344 - or option in self._defaults)
120.345 -
120.346 - def set(self, section, option, value):
120.347 - """Set an option."""
120.348 - if not section or section == DEFAULTSECT:
120.349 - sectdict = self._defaults
120.350 - else:
120.351 - try:
120.352 - sectdict = self._sections[section]
120.353 - except KeyError:
120.354 - raise NoSectionError(section)
120.355 - sectdict[self.optionxform(option)] = value
120.356 -
120.357 - def write(self, fp):
120.358 - """Write an .ini-format representation of the configuration state."""
120.359 - if self._defaults:
120.360 - fp.write("[%s]\n" % DEFAULTSECT)
120.361 - for (key, value) in self._defaults.items():
120.362 - fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
120.363 - fp.write("\n")
120.364 - for section in self._sections:
120.365 - fp.write("[%s]\n" % section)
120.366 - for (key, value) in self._sections[section].items():
120.367 - if key != "__name__":
120.368 - fp.write("%s = %s\n" %
120.369 - (key, str(value).replace('\n', '\n\t')))
120.370 - fp.write("\n")
120.371 -
120.372 - def remove_option(self, section, option):
120.373 - """Remove an option."""
120.374 - if not section or section == DEFAULTSECT:
120.375 - sectdict = self._defaults
120.376 - else:
120.377 - try:
120.378 - sectdict = self._sections[section]
120.379 - except KeyError:
120.380 - raise NoSectionError(section)
120.381 - option = self.optionxform(option)
120.382 - existed = option in sectdict
120.383 - if existed:
120.384 - del sectdict[option]
120.385 - return existed
120.386 -
120.387 - def remove_section(self, section):
120.388 - """Remove a file section."""
120.389 - existed = section in self._sections
120.390 - if existed:
120.391 - del self._sections[section]
120.392 - return existed
120.393 -
120.394 - #
120.395 - # Regular expressions for parsing section headers and options.
120.396 - #
120.397 - SECTCRE = re.compile(
120.398 - r'\[' # [
120.399 - r'(?P<header>[^]]+)' # very permissive!
120.400 - r'\]' # ]
120.401 - )
120.402 - OPTCRE = re.compile(
120.403 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
120.404 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
120.405 - # followed by separator
120.406 - # (either : or =), followed
120.407 - # by any # space/tab
120.408 - r'(?P<value>.*)$' # everything up to eol
120.409 - )
120.410 -
120.411 - def _read(self, fp, fpname):
120.412 - """Parse a sectioned setup file.
120.413 -
120.414 - The sections in setup file contains a title line at the top,
120.415 - indicated by a name in square brackets (`[]'), plus key/value
120.416 - options lines, indicated by `name: value' format lines.
120.417 - Continuations are represented by an embedded newline then
120.418 - leading whitespace. Blank lines, lines beginning with a '#',
120.419 - and just about everything else are ignored.
120.420 - """
120.421 - cursect = None # None, or a dictionary
120.422 - optname = None
120.423 - lineno = 0
120.424 - e = None # None, or an exception
120.425 - while True:
120.426 - line = fp.readline()
120.427 - if not line:
120.428 - break
120.429 - lineno = lineno + 1
120.430 - # comment or blank line?
120.431 - if line.strip() == '' or line[0] in '#;':
120.432 - continue
120.433 - if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
120.434 - # no leading whitespace
120.435 - continue
120.436 - # continuation line?
120.437 - if line[0].isspace() and cursect is not None and optname:
120.438 - value = line.strip()
120.439 - if value:
120.440 - cursect[optname] = "%s\n%s" % (cursect[optname], value)
120.441 - # a section header or option header?
120.442 - else:
120.443 - # is it a section header?
120.444 - mo = self.SECTCRE.match(line)
120.445 - if mo:
120.446 - sectname = mo.group('header')
120.447 - if sectname in self._sections:
120.448 - cursect = self._sections[sectname]
120.449 - elif sectname == DEFAULTSECT:
120.450 - cursect = self._defaults
120.451 - else:
120.452 - cursect = {'__name__': sectname}
120.453 - self._sections[sectname] = cursect
120.454 - # So sections can't start with a continuation line
120.455 - optname = None
120.456 - # no section header in the file?
120.457 - elif cursect is None:
120.458 - raise MissingSectionHeaderError(fpname, lineno, `line`)
120.459 - # an option line?
120.460 - else:
120.461 - mo = self.OPTCRE.match(line)
120.462 - if mo:
120.463 - optname, vi, optval = mo.group('option', 'vi', 'value')
120.464 - if vi in ('=', ':') and ';' in optval:
120.465 - # ';' is a comment delimiter only if it follows
120.466 - # a spacing character
120.467 - pos = optval.find(';')
120.468 - if pos != -1 and optval[pos-1].isspace():
120.469 - optval = optval[:pos]
120.470 - optval = optval.strip()
120.471 - # allow empty values
120.472 - if optval == '""':
120.473 - optval = ''
120.474 - optname = self.optionxform(optname.rstrip())
120.475 - cursect[optname] = optval
120.476 - else:
120.477 - # a non-fatal parsing error occurred. set up the
120.478 - # exception but keep going. the exception will be
120.479 - # raised at the end of the file and will contain a
120.480 - # list of all bogus lines
120.481 - if not e:
120.482 - e = ParsingError(fpname)
120.483 - e.append(lineno, `line`)
120.484 - # if any parsing errors occurred, raise an exception
120.485 - if e:
120.486 - raise e
120.487 -
120.488 -
120.489 -class ConfigParser(RawConfigParser):
120.490 -
120.491 - def get(self, section, option, raw=False, vars=None):
120.492 - """Get an option value for a given section.
120.493 -
120.494 - All % interpolations are expanded in the return values, based on the
120.495 - defaults passed into the constructor, unless the optional argument
120.496 - `raw' is true. Additional substitutions may be provided using the
120.497 - `vars' argument, which must be a dictionary whose contents overrides
120.498 - any pre-existing defaults.
120.499 -
120.500 - The section DEFAULT is special.
120.501 - """
120.502 - d = self._defaults.copy()
120.503 - try:
120.504 - d.update(self._sections[section])
120.505 - except KeyError:
120.506 - if section != DEFAULTSECT:
120.507 - raise NoSectionError(section)
120.508 - # Update with the entry specific variables
120.509 - if vars is not None:
120.510 - d.update(vars)
120.511 - option = self.optionxform(option)
120.512 - try:
120.513 - value = d[option]
120.514 - except KeyError:
120.515 - raise NoOptionError(option, section)
120.516 -
120.517 - if raw:
120.518 - return value
120.519 - else:
120.520 - return self._interpolate(section, option, value, d)
120.521 -
120.522 - def items(self, section, raw=False, vars=None):
120.523 - """Return a list of tuples with (name, value) for each option
120.524 - in the section.
120.525 -
120.526 - All % interpolations are expanded in the return values, based on the
120.527 - defaults passed into the constructor, unless the optional argument
120.528 - `raw' is true. Additional substitutions may be provided using the
120.529 - `vars' argument, which must be a dictionary whose contents overrides
120.530 - any pre-existing defaults.
120.531 -
120.532 - The section DEFAULT is special.
120.533 - """
120.534 - d = self._defaults.copy()
120.535 - try:
120.536 - d.update(self._sections[section])
120.537 - except KeyError:
120.538 - if section != DEFAULTSECT:
120.539 - raise NoSectionError(section)
120.540 - # Update with the entry specific variables
120.541 - if vars:
120.542 - d.update(vars)
120.543 - options = d.keys()
120.544 - if "__name__" in options:
120.545 - options.remove("__name__")
120.546 - if raw:
120.547 - return [(option, d[option])
120.548 - for option in options]
120.549 - else:
120.550 - return [(option, self._interpolate(section, option, d[option], d))
120.551 - for option in options]
120.552 -
120.553 - def _interpolate(self, section, option, rawval, vars):
120.554 - # do the string interpolation
120.555 - value = rawval
120.556 - depth = MAX_INTERPOLATION_DEPTH
120.557 - while depth: # Loop through this until it's done
120.558 - depth -= 1
120.559 - if value.find("%(") != -1:
120.560 - try:
120.561 - value = value % vars
120.562 - except KeyError, e:
120.563 - raise InterpolationMissingOptionError(
120.564 - option, section, rawval, e[0])
120.565 - else:
120.566 - break
120.567 - if value.find("%(") != -1:
120.568 - raise InterpolationDepthError(option, section, rawval)
120.569 - return value
120.570 -
120.571 -
120.572 -class SafeConfigParser(ConfigParser):
120.573 -
120.574 - def _interpolate(self, section, option, rawval, vars):
120.575 - # do the string interpolation
120.576 - L = []
120.577 - self._interpolate_some(option, L, rawval, section, vars, 1)
120.578 - return ''.join(L)
120.579 -
120.580 - _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
120.581 -
120.582 - def _interpolate_some(self, option, accum, rest, section, map, depth):
120.583 - if depth > MAX_INTERPOLATION_DEPTH:
120.584 - raise InterpolationDepthError(option, section, rest)
120.585 - while rest:
120.586 - p = rest.find("%")
120.587 - if p < 0:
120.588 - accum.append(rest)
120.589 - return
120.590 - if p > 0:
120.591 - accum.append(rest[:p])
120.592 - rest = rest[p:]
120.593 - # p is no longer used
120.594 - c = rest[1:2]
120.595 - if c == "%":
120.596 - accum.append("%")
120.597 - rest = rest[2:]
120.598 - elif c == "(":
120.599 - m = self._interpvar_match(rest)
120.600 - if m is None:
120.601 - raise InterpolationSyntaxError(option, section,
120.602 - "bad interpolation variable reference %r" % rest)
120.603 - var = m.group(1)
120.604 - rest = rest[m.end():]
120.605 - try:
120.606 - v = map[var]
120.607 - except KeyError:
120.608 - raise InterpolationMissingOptionError(
120.609 - option, section, rest, var)
120.610 - if "%" in v:
120.611 - self._interpolate_some(option, accum, v,
120.612 - section, map, depth + 1)
120.613 - else:
120.614 - accum.append(v)
120.615 - else:
120.616 - raise InterpolationSyntaxError(
120.617 - option, section,
120.618 - "'%' must be followed by '%' or '(', found: " + `ret`)
121.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.folds Sun Jan 04 13:11:53 2015 -0600
121.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
121.3 @@ -1,616 +0,0 @@
121.4 -+ """Configuration file parser.
121.5 -|
121.6 -| A setup file consists of sections, lead by a "[section]" header,
121.7 -| and followed by "name: value" entries, with continuations and such in
121.8 -| the style of RFC 822.
121.9 -|
121.10 -| the same section, or values in a special [DEFAULT] section.
121.11 -|
121.12 -| For example:
121.13 -|
121.14 -| something: %(dir)s/whatever
121.15 -|
121.16 -| would resolve the "%(dir)s" to the value of dir. All reference
121.17 -| expansions are done late, on demand.
121.18 -|
121.19 -| Intrinsic defaults can be specified by passing them into the
121.20 -| ConfigParser constructor as a dictionary.
121.21 -|
121.22 -| class:
121.23 -|
121.24 -| ConfigParser -- responsible for parsing a list of
121.25 -| configuration files, and managing the parsed database.
121.26 -|
121.27 -| methods:
121.28 -|
121.29 -| __init__(defaults=None)
121.30 -| create the parser and specify a dictionary of intrinsic defaults. The
121.31 -| keys must be strings, the values must be appropriate for %()s string
121.32 -| interpolation. Note that `__name__' is always an intrinsic default;
121.33 -| it's value is the section's name.
121.34 -|
121.35 -| sections()
121.36 -| return all the configuration section names, sans DEFAULT
121.37 -|
121.38 -| has_section(section)
121.39 -| return whether the given section exists
121.40 -|
121.41 -| has_option(section, option)
121.42 -| return whether the given option exists in the given section
121.43 -|
121.44 -| options(section)
121.45 -| return list of configuration options for the named section
121.46 -|
121.47 -| read(filenames)
121.48 -| read and parse the list of named configuration files, given by
121.49 -| name. A single filename is also allowed. Non-existing files
121.50 -| are ignored.
121.51 -|
121.52 -| readfp(fp, filename=None)
121.53 -| read and parse one configuration file, given as a file object.
121.54 -| The filename defaults to fp.name; it is only used in error
121.55 -| messages (if fp has no `name' attribute, the string `<???>' is used).
121.56 -|
121.57 -| get(section, option, raw=False, vars=None)
121.58 -| return a string value for the named option. All % interpolations are
121.59 -| expanded in the return values, based on the defaults passed into the
121.60 -| constructor and the DEFAULT section. Additional substitutions may be
121.61 -| provided using the `vars' argument, which must be a dictionary whose
121.62 -| contents override any pre-existing defaults.
121.63 -|
121.64 -| getint(section, options)
121.65 -| like get(), but convert value to an integer
121.66 -|
121.67 -| getfloat(section, options)
121.68 -| like get(), but convert value to a float
121.69 -|
121.70 -| getboolean(section, options)
121.71 -| like get(), but convert value to a boolean (currently case
121.72 -| insensitively defined as 0, false, no, off for False, and 1, true,
121.73 -| yes, on for True). Returns False or True.
121.74 -|
121.75 -| items(section, raw=False, vars=None)
121.76 -| return a list of tuples with (name, value) for each option
121.77 -| in the section.
121.78 -|
121.79 -| remove_section(section)
121.80 -| remove the given file section and all its options
121.81 -|
121.82 -| remove_option(section, option)
121.83 -| remove the given option from the given section
121.84 -|
121.85 -| set(section, option, value)
121.86 -| set the given option
121.87 -|
121.88 -| write(fp)
121.89 -| write the configuration state in .ini format
121.90 -- """
121.91 -
121.92 - import re
121.93 -
121.94 - __all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
121.95 - "InterpolationError", "InterpolationDepthError",
121.96 - "InterpolationSyntaxError", "ParsingError",
121.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
121.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
121.99 -
121.100 - DEFAULTSECT = "DEFAULT"
121.101 -
121.102 - MAX_INTERPOLATION_DEPTH = 10
121.103 -
121.104 -
121.105 -
121.106 - # exception classes
121.107 -+ class Error(Exception):
121.108 -| """Base class for ConfigParser exceptions."""
121.109 -|
121.110 -+ def __init__(self, msg=''):
121.111 -| self.message = msg
121.112 -| Exception.__init__(self, msg)
121.113 --
121.114 -+ def __repr__(self):
121.115 -| return self.message
121.116 --
121.117 -| __str__ = __repr__
121.118 --
121.119 -+ class NoSectionError(Error):
121.120 -| """Rasssised when no section matches a requested option."""
121.121 -|
121.122 -+ def __init__(self, section):
121.123 -| Error.__init__(self, 'No section: ' + `section`)
121.124 -| self.section = section
121.125 --
121.126 -+ class DuplicateSectionError(Error):
121.127 -| """Raised when a section is multiply-created."""
121.128 -|
121.129 -+ def __init__(self, section):
121.130 -| Error.__init__(self, "Section %r already exists" % section)
121.131 -| self.section = section
121.132 --
121.133 -+ class NoOptionError(Error):
121.134 -| """A requested option was not found."""
121.135 -|
121.136 -+ def __init__(self, option, section):
121.137 -| Error.__init__(self, "No option %r in section: %r" %
121.138 -| (option, section))
121.139 -| self.option = option
121.140 -| self.section = section
121.141 --
121.142 -+ class InterpolationError(Error):
121.143 -| """Base class for interpolation-related exceptions."""
121.144 -|
121.145 -+ def __init__(self, option, section, msg):
121.146 -| Error.__init__(self, msg)
121.147 -| self.option = option
121.148 -| self.section = section
121.149 --
121.150 -+ class InterpolationMissingOptionError(InterpolationError):
121.151 -| """A string substitution required a setting which was not available."""
121.152 -|
121.153 -+ def __init__(self, option, section, rawval, reference):
121.154 -+ msg = ("Bad value substitution:\n"
121.155 -| "\tsection: [%s]\n"
121.156 -| "\toption : %s\n"
121.157 -| "\tkey : %s\n"
121.158 -- "\trawval : %s\n"
121.159 -| % (section, option, reference, rawval))
121.160 -| InterpolationError.__init__(self, option, section, msg)
121.161 -| self.reference = reference
121.162 --
121.163 -+ class InterpolationSyntaxError(InterpolationError):
121.164 -+ """Raised when the source text into which substitutions are made
121.165 -- does not conform to the required syntax."""
121.166 --
121.167 -+ class InterpolationDepthError(InterpolationError):
121.168 -| """Raised when substitutions are nested too deeply."""
121.169 -|
121.170 -+ def __init__(self, option, section, rawval):
121.171 -+ msg = ("Value interpolation too deeply recursive:\n"
121.172 -| "\tsection: [%s]\n"
121.173 -| "\toption : %s\n"
121.174 -- "\trawval : %s\n"
121.175 -| % (section, option, rawval))
121.176 -| InterpolationError.__init__(self, option, section, msg)
121.177 --
121.178 -+ class ParsingError(Error):
121.179 -| """Raised when a configuration file does not follow legal syntax."""
121.180 -|
121.181 -+ def __init__(self, filename):
121.182 -| Error.__init__(self, 'File contains parsing errors: %s' % filename)
121.183 -| self.filename = filename
121.184 -| self.errors = []
121.185 --
121.186 -+ def append(self, lineno, line):
121.187 -| self.errors.append((lineno, line))
121.188 -| self.message += '\n\t[line %2d]: %s' % (lineno, line)
121.189 --
121.190 -+ class MissingSectionHeaderError(ParsingError):
121.191 -| """Raised when a key-value pair is found before any section header."""
121.192 -|
121.193 -+ def __init__(self, filename, lineno, line):
121.194 -| Error.__init__(
121.195 -| self,
121.196 -| 'File contains no section headers.\nfile: %s, line: %d\n%s' %
121.197 -| (filename, lineno, line))
121.198 -| self.filename = filename
121.199 -| self.lineno = lineno
121.200 -| self.line = line
121.201 -|
121.202 -|
121.203 --
121.204 -+ class RawConfigParser:
121.205 -+ def __init__(self, defaults=None):
121.206 -| self._sections = {}
121.207 -| if defaults is None:
121.208 -| self._defaults = {}
121.209 -| else:
121.210 -| self._defaults = defaults
121.211 --
121.212 -+ def defaults(self):
121.213 -| return self._defaults
121.214 --
121.215 -+ def sections(self):
121.216 -| """Return a list of section names, excluding [DEFAULT]"""
121.217 -| # self._sections will never have [DEFAULT] in it
121.218 -| return self._sections.keys()
121.219 --
121.220 -+ def add_section(self, section):
121.221 -+ """Create a new section in the configuration.
121.222 -|
121.223 -| Raise DuplicateSectionError if a section by the specified name
121.224 -| already exists.
121.225 -- """
121.226 -| if section in self._sections:
121.227 -| raise DuplicateSectionError(section)
121.228 -| self._sections[section] = {}
121.229 --
121.230 -+ def has_section(self, section):
121.231 -+ """Indicate whether the named section is present in the configuration.
121.232 -|
121.233 -| The DEFAULT section is not acknowledged.
121.234 -- """
121.235 -| return section in self._sections
121.236 --
121.237 -+ def options(self, section):
121.238 -| """Return a list of option names for the given section name."""
121.239 -| try:
121.240 -| opts = self._sections[section].copy()
121.241 -| except KeyError:
121.242 -| raise NoSectionError(section)
121.243 -| opts.update(self._defaults)
121.244 -| if '__name__' in opts:
121.245 -| del opts['__name__']
121.246 -| return opts.keys()
121.247 --
121.248 -+ def read(self, filenames):
121.249 -+ """Read and parse a filename or a list of filenames.
121.250 -|
121.251 -| Files that cannot be opened are silently ignored; this is
121.252 -| designed so that you can specify a list of potential
121.253 -| configuration file locations (e.g. current directory, user's
121.254 -| home directory, systemwide directory), and all existing
121.255 -| configuration files in the list will be read. A single
121.256 -| filename may also be given.
121.257 -- """
121.258 -| if isinstance(filenames, basestring):
121.259 -| filenames = [filenames]
121.260 -| for filename in filenames:
121.261 -| try:
121.262 -| fp = open(filename)
121.263 -| except IOError:
121.264 -| continue
121.265 -| self._read(fp, filename)
121.266 -| fp.close()
121.267 --
121.268 -+ def readfp(self, fp, filename=None):
121.269 -+ """Like read() but the argument must be a file-like object.
121.270 -|
121.271 -| The `fp' argument must have a `readline' method. Optional
121.272 -| second argument is the `filename', which if not given, is
121.273 -| taken from fp.name. If fp has no `name' attribute, `<???>' is
121.274 -| used.
121.275 -|
121.276 -- """
121.277 -| if filename is None:
121.278 -| try:
121.279 -| filename = fp.name
121.280 -| except AttributeError:
121.281 -| filename = '<???>'
121.282 -| self._read(fp, filename)
121.283 --
121.284 -+ def get(self, section, option):
121.285 -| opt = self.optionxform(option)
121.286 -| if section not in self._sections:
121.287 -| if section != DEFAULTSECT:
121.288 -| raise NoSectionError(section)
121.289 -| if opt in self._defaults:
121.290 -| return self._defaults[opt]
121.291 -| else:
121.292 -| raise NoOptionError(option, section)
121.293 -| elif opt in self._sections[section]:
121.294 -| return self._sections[section][opt]
121.295 -| elif opt in self._defaults:
121.296 -| return self._defaults[opt]
121.297 -| else:
121.298 -| raise NoOptionError(option, section)
121.299 --
121.300 -+ def items(self, section):
121.301 -| try:
121.302 -| d2 = self._sections[section]
121.303 -| except KeyError:
121.304 -| if section != DEFAULTSECT:
121.305 -| raise NoSectionError(section)
121.306 -| d2 = {}
121.307 -| d = self._defaults.copy()
121.308 -| d.update(d2)
121.309 -| if "__name__" in d:
121.310 -| del d["__name__"]
121.311 -| return d.items()
121.312 --
121.313 -+ def _get(self, section, conv, option):
121.314 -| return conv(self.get(section, option))
121.315 --
121.316 -+ def getint(self, section, option):
121.317 -| return self._get(section, int, option)
121.318 --
121.319 -+ def getfloat(self, section, option):
121.320 -| return self._get(section, float, option)
121.321 --
121.322 -| _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
121.323 -| '0': False, 'no': False, 'false': False, 'off': False}
121.324 -|
121.325 -+ def getboolean(self, section, option):
121.326 -| v = self.get(section, option)
121.327 -| if v.lower() not in self._boolean_states:
121.328 -| raise ValueError, 'Not a boolean: %s' % v
121.329 -| return self._boolean_states[v.lower()]
121.330 --
121.331 -+ def optionxform(self, optionstr):
121.332 -| return optionstr.lower()
121.333 --
121.334 -+ def has_option(self, section, option):
121.335 -| """Check for the existence of a given option in a given section."""
121.336 -| if not section or section == DEFAULTSECT:
121.337 -| option = self.optionxform(option)
121.338 -| return option in self._defaults
121.339 -| elif section not in self._sections:
121.340 -| return False
121.341 -| else:
121.342 -| option = self.optionxform(option)
121.343 -| return (option in self._sections[section]
121.344 -| or option in self._defaults)
121.345 --
121.346 -+ def set(self, section, option, value):
121.347 -| """Set an option."""
121.348 -| if not section or section == DEFAULTSECT:
121.349 -| sectdict = self._defaults
121.350 -| else:
121.351 -| try:
121.352 -| sectdict = self._sections[section]
121.353 -| except KeyError:
121.354 -| raise NoSectionError(section)
121.355 -| sectdict[self.optionxform(option)] = value
121.356 --
121.357 -+ def write(self, fp):
121.358 -| """Write an .ini-format representation of the configuration state."""
121.359 -| if self._defaults:
121.360 -| fp.write("[%s]\n" % DEFAULTSECT)
121.361 -| for (key, value) in self._defaults.items():
121.362 -| fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
121.363 -| fp.write("\n")
121.364 -| for section in self._sections:
121.365 -| fp.write("[%s]\n" % section)
121.366 -| for (key, value) in self._sections[section].items():
121.367 -| if key != "__name__":
121.368 -| fp.write("%s = %s\n" %
121.369 -| (key, str(value).replace('\n', '\n\t')))
121.370 -| fp.write("\n")
121.371 --
121.372 -+ def remove_option(self, section, option):
121.373 -| """Remove an option."""
121.374 -| if not section or section == DEFAULTSECT:
121.375 -| sectdict = self._defaults
121.376 -| else:
121.377 -| try:
121.378 -| sectdict = self._sections[section]
121.379 -| except KeyError:
121.380 -| raise NoSectionError(section)
121.381 -| option = self.optionxform(option)
121.382 -| existed = option in sectdict
121.383 -| if existed:
121.384 -| del sectdict[option]
121.385 -| return existed
121.386 --
121.387 -+ def remove_section(self, section):
121.388 -| """Remove a file section."""
121.389 -| existed = section in self._sections
121.390 -| if existed:
121.391 -| del self._sections[section]
121.392 -| return existed
121.393 -|
121.394 -| #
121.395 -| # Regular expressions for parsing section headers and options.
121.396 -- #
121.397 -| SECTCRE = re.compile(
121.398 -+ r'\[' # [
121.399 -- r'(?P<header>[^]]+)' # very permissive!
121.400 -| r'\]' # ]
121.401 -| )
121.402 -| OPTCRE = re.compile(
121.403 -+ r'(?P<option>[^:=\s][^:=]*)' # very permissive!
121.404 -| r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
121.405 -| # followed by separator
121.406 -| # (either : or =), followed
121.407 -- # by any # space/tab
121.408 -| r'(?P<value>.*)$' # everything up to eol
121.409 -| )
121.410 -|
121.411 -+ def _read(self, fp, fpname):
121.412 -+ """Parse a sectioned setup file.
121.413 -|
121.414 -| The sections in setup file contains a title line at the top,
121.415 -| indicated by a name in square brackets (`[]'), plus key/value
121.416 -| options lines, indicated by `name: value' format lines.
121.417 -| Continuations are represented by an embedded newline then
121.418 -| leading whitespace. Blank lines, lines beginning with a '#',
121.419 -| and just about everything else are ignored.
121.420 -- """
121.421 -| cursect = None # None, or a dictionary
121.422 -| optname = None
121.423 -| lineno = 0
121.424 -| e = None # None, or an exception
121.425 -| while True:
121.426 -| line = fp.readline()
121.427 -| if not line:
121.428 -| break
121.429 -| lineno = lineno + 1
121.430 -| # comment or blank line?
121.431 -| if line.strip() == '' or line[0] in '#;':
121.432 -| continue
121.433 -| if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
121.434 -| # no leading whitespace
121.435 -| continue
121.436 -| # continuation line?
121.437 -| if line[0].isspace() and cursect is not None and optname:
121.438 -| value = line.strip()
121.439 -| if value:
121.440 -| cursect[optname] = "%s\n%s" % (cursect[optname], value)
121.441 -| # a section header or option header?
121.442 -| else:
121.443 -| # is it a section header?
121.444 -| mo = self.SECTCRE.match(line)
121.445 -| if mo:
121.446 -| sectname = mo.group('header')
121.447 -| if sectname in self._sections:
121.448 -| cursect = self._sections[sectname]
121.449 -| elif sectname == DEFAULTSECT:
121.450 -| cursect = self._defaults
121.451 -| else:
121.452 -| cursect = {'__name__': sectname}
121.453 -| self._sections[sectname] = cursect
121.454 -| # So sections can't start with a continuation line
121.455 -| optname = None
121.456 -| # no section header in the file?
121.457 -| elif cursect is None:
121.458 -| raise MissingSectionHeaderError(fpname, lineno, `line`)
121.459 -| # an option line?
121.460 -| else:
121.461 -| mo = self.OPTCRE.match(line)
121.462 -| if mo:
121.463 -| optname, vi, optval = mo.group('option', 'vi', 'value')
121.464 -| if vi in ('=', ':') and ';' in optval:
121.465 -| # ';' is a comment delimiter only if it follows
121.466 -| # a spacing character
121.467 -| pos = optval.find(';')
121.468 -| if pos != -1 and optval[pos-1].isspace():
121.469 -| optval = optval[:pos]
121.470 -| optval = optval.strip()
121.471 -| # allow empty values
121.472 -| if optval == '""':
121.473 -| optval = ''
121.474 -| optname = self.optionxform(optname.rstrip())
121.475 -| cursect[optname] = optval
121.476 -| else:
121.477 -| # a non-fatal parsing error occurred. set up the
121.478 -| # exception but keep going. the exception will be
121.479 -| # raised at the end of the file and will contain a
121.480 -| # list of all bogus lines
121.481 -| if not e:
121.482 -| e = ParsingError(fpname)
121.483 -| e.append(lineno, `line`)
121.484 -| # if any parsing errors occurred, raise an exception
121.485 -| if e:
121.486 -| raise e
121.487 -|
121.488 --
121.489 -+ class ConfigParser(RawConfigParser):
121.490 -|
121.491 -+ def get(self, section, option, raw=False, vars=None):
121.492 -+ """Get an option value for a given section.
121.493 -|
121.494 -| All % interpolations are expanded in the return values, based on the
121.495 -| defaults passed into the constructor, unless the optional argument
121.496 -| `raw' is true. Additional substitutions may be provided using the
121.497 -| `vars' argument, which must be a dictionary whose contents overrides
121.498 -| any pre-existing defaults.
121.499 -|
121.500 -| The section DEFAULT is special.
121.501 -- """
121.502 -| d = self._defaults.copy()
121.503 -| try:
121.504 -| d.update(self._sections[section])
121.505 -| except KeyError:
121.506 -| if section != DEFAULTSECT:
121.507 -| raise NoSectionError(section)
121.508 -| # Update with the entry specific variables
121.509 -| if vars is not None:
121.510 -| d.update(vars)
121.511 -| option = self.optionxform(option)
121.512 -| try:
121.513 -| value = d[option]
121.514 -| except KeyError:
121.515 -| raise NoOptionError(option, section)
121.516 -|
121.517 -| if raw:
121.518 -| return value
121.519 -| else:
121.520 -| return self._interpolate(section, option, value, d)
121.521 --
121.522 -+ def items(self, section, raw=False, vars=None):
121.523 -+ """Return a list of tuples with (name, value) for each option
121.524 -| in the section.
121.525 -|
121.526 -| All % interpolations are expanded in the return values, based on the
121.527 -| defaults passed into the constructor, unless the optional argument
121.528 -| `raw' is true. Additional substitutions may be provided using the
121.529 -| `vars' argument, which must be a dictionary whose contents overrides
121.530 -| any pre-existing defaults.
121.531 -|
121.532 -| The section DEFAULT is special.
121.533 -- """
121.534 -| d = self._defaults.copy()
121.535 -| try:
121.536 -| d.update(self._sections[section])
121.537 -| except KeyError:
121.538 -| if section != DEFAULTSECT:
121.539 -| raise NoSectionError(section)
121.540 -| # Update with the entry specific variables
121.541 -| if vars:
121.542 -| d.update(vars)
121.543 -| options = d.keys()
121.544 -| if "__name__" in options:
121.545 -| options.remove("__name__")
121.546 -| if raw:
121.547 -| return [(option, d[option])
121.548 -| for option in options]
121.549 -| else:
121.550 -| return [(option, self._interpolate(section, option, d[option], d))
121.551 -| for option in options]
121.552 --
121.553 -+ def _interpolate(self, section, option, rawval, vars):
121.554 -| # do the string interpolation
121.555 -| value = rawval
121.556 -| depth = MAX_INTERPOLATION_DEPTH
121.557 -| while depth: # Loop through this until it's done
121.558 -| depth -= 1
121.559 -| if value.find("%(") != -1:
121.560 -| try:
121.561 -| value = value % vars
121.562 -| except KeyError, e:
121.563 -| raise InterpolationMissingOptionError(
121.564 -| option, section, rawval, e[0])
121.565 -| else:
121.566 -| break
121.567 -| if value.find("%(") != -1:
121.568 -| raise InterpolationDepthError(option, section, rawval)
121.569 -| return value
121.570 -|
121.571 --
121.572 -+ class SafeConfigParser(ConfigParser):
121.573 -|
121.574 -+ def _interpolate(self, section, option, rawval, vars):
121.575 -| # do the string interpolation
121.576 -| L = []
121.577 -| self._interpolate_some(option, L, rawval, section, vars, 1)
121.578 -| return ''.join(L)
121.579 --
121.580 -| _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
121.581 -|
121.582 -+ def _interpolate_some(self, option, accum, rest, section, map, depth):
121.583 -| if depth > MAX_INTERPOLATION_DEPTH:
121.584 -| raise InterpolationDepthError(option, section, rest)
121.585 -| while rest:
121.586 -| p = rest.find("%")
121.587 -| if p < 0:
121.588 -| accum.append(rest)
121.589 -| return
121.590 -| if p > 0:
121.591 -| accum.append(rest[:p])
121.592 -| rest = rest[p:]
121.593 -| # p is no longer used
121.594 -| c = rest[1:2]
121.595 -| if c == "%":
121.596 -| accum.append("%")
121.597 -| rest = rest[2:]
121.598 -| elif c == "(":
121.599 -| m = self._interpvar_match(rest)
121.600 -| if m is None:
121.601 -| raise InterpolationSyntaxError(option, section,
121.602 -| "bad interpolation variable reference %r" % rest)
121.603 -| var = m.group(1)
121.604 -| rest = rest[m.end():]
121.605 -| try:
121.606 -| v = map[var]
121.607 -| except KeyError:
121.608 -| raise InterpolationMissingOptionError(
121.609 -| option, section, rest, var)
121.610 -| if "%" in v:
121.611 -| self._interpolate_some(option, accum, v,
121.612 -| section, map, depth + 1)
121.613 -| else:
121.614 -| accum.append(v)
121.615 -| else:
121.616 -| raise InterpolationSyntaxError(
121.617 -| option, section,
121.618 -- "'%' must be followed by '%' or '(', found: " + `ret`)
121.619 -
122.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.formatted Sun Jan 04 13:11:53 2015 -0600
122.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
122.3 @@ -1,615 +0,0 @@
122.4 -"""Configuration file parser.
122.5 -
122.6 -A setup file consists of sections, lead by a "[section]" header,
122.7 -and followed by "name: value" entries, with continuations and such in
122.8 -the style of RFC 822.
122.9 -
122.10 - the same section, or values in a special [DEFAULT] section.
122.11 -
122.12 -For example:
122.13 -
122.14 - something: %(dir)s/whatever
122.15 -
122.16 -would resolve the "%(dir)s" to the value of dir. All reference
122.17 -expansions are done late, on demand.
122.18 -
122.19 -Intrinsic defaults can be specified by passing them into the
122.20 -ConfigParser constructor as a dictionary.
122.21 -
122.22 -class:
122.23 -
122.24 -ConfigParser -- responsible for parsing a list of
122.25 - configuration files, and managing the parsed database.
122.26 -
122.27 - methods:
122.28 -
122.29 - __init__(defaults=None)
122.30 - create the parser and specify a dictionary of intrinsic defaults. The
122.31 - keys must be strings, the values must be appropriate for %()s string
122.32 - interpolation. Note that `__name__' is always an intrinsic default;
122.33 - it's value is the section's name.
122.34 -
122.35 - sections()
122.36 - return all the configuration section names, sans DEFAULT
122.37 -
122.38 - has_section(section)
122.39 - return whether the given section exists
122.40 -
122.41 - has_option(section, option)
122.42 - return whether the given option exists in the given section
122.43 -
122.44 - options(section)
122.45 - return list of configuration options for the named section
122.46 -
122.47 - read(filenames)
122.48 - read and parse the list of named configuration files, given by
122.49 - name. A single filename is also allowed. Non-existing files
122.50 - are ignored.
122.51 -
122.52 - readfp(fp, filename=None)
122.53 - read and parse one configuration file, given as a file object.
122.54 - The filename defaults to fp.name; it is only used in error
122.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
122.56 -
122.57 - get(section, option, raw=False, vars=None)
122.58 - return a string value for the named option. All % interpolations are
122.59 - expanded in the return values, based on the defaults passed into the
122.60 - constructor and the DEFAULT section. Additional substitutions may be
122.61 - provided using the `vars' argument, which must be a dictionary whose
122.62 - contents override any pre-existing defaults.
122.63 -
122.64 - getint(section, options)
122.65 - like get(), but convert value to an integer
122.66 -
122.67 - getfloat(section, options)
122.68 - like get(), but convert value to a float
122.69 -
122.70 - getboolean(section, options)
122.71 - like get(), but convert value to a boolean (currently case
122.72 - insensitively defined as 0, false, no, off for False, and 1, true,
122.73 - yes, on for True). Returns False or True.
122.74 -
122.75 - items(section, raw=False, vars=None)
122.76 - return a list of tuples with (name, value) for each option
122.77 - in the section.
122.78 -
122.79 - remove_section(section)
122.80 - remove the given file section and all its options
122.81 -
122.82 - remove_option(section, option)
122.83 - remove the given option from the given section
122.84 -
122.85 - set(section, option, value)
122.86 - set the given option
122.87 -
122.88 - write(fp)
122.89 - write the configuration state in .ini format
122.90 -"""
122.91 -
122.92 -import re
122.93 -
122.94 -__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
122.95 - "InterpolationError", "InterpolationDepthError",
122.96 - "InterpolationSyntaxError", "ParsingError",
122.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
122.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
122.99 -
122.100 -DEFAULTSECT = "DEFAULT"
122.101 -
122.102 -MAX_INTERPOLATION_DEPTH = 10
122.103 -
122.104 -
122.105 -
122.106 -# exception classes
122.107 -class Error(Exception):
122.108 - """Base class for ConfigParser exceptions."""
122.109 -
122.110 - def __init__(self, msg=''):
122.111 - self.message = msg
122.112 - Exception.__init__(self, msg)
122.113 -
122.114 - def __repr__(self):
122.115 - return self.message
122.116 -
122.117 - __str__ = __repr__
122.118 -
122.119 -class NoSectionError(Error):
122.120 - """Rasssised when no section matches a requested option."""
122.121 -
122.122 - def __init__(self, section):
122.123 - Error.__init__(self, 'No section: ' + `section`)
122.124 - self.section = section
122.125 -
122.126 -class DuplicateSectionError(Error):
122.127 - """Raised when a section is multiply-created."""
122.128 -
122.129 - def __init__(self, section):
122.130 - Error.__init__(self, "Section %r already exists" % section)
122.131 - self.section = section
122.132 -
122.133 -class NoOptionError(Error):
122.134 - """A requested option was not found."""
122.135 -
122.136 - def __init__(self, option, section):
122.137 - Error.__init__(self, "No option %r in section: %r" %
122.138 - (option, section))
122.139 - self.option = option
122.140 - self.section = section
122.141 -
122.142 -class InterpolationError(Error):
122.143 - """Base class for interpolation-related exceptions."""
122.144 -
122.145 - def __init__(self, option, section, msg):
122.146 - Error.__init__(self, msg)
122.147 - self.option = option
122.148 - self.section = section
122.149 -
122.150 -class InterpolationMissingOptionError(InterpolationError):
122.151 - """A string substitution required a setting which was not available."""
122.152 -
122.153 - def __init__(self, option, section, rawval, reference):
122.154 - msg = ("Bad value substitution:\n"
122.155 - "\tsection: [%s]\n"
122.156 - "\toption : %s\n"
122.157 - "\tkey : %s\n"
122.158 - "\trawval : %s\n"
122.159 - % (section, option, reference, rawval))
122.160 - InterpolationError.__init__(self, option, section, msg)
122.161 - self.reference = reference
122.162 -
122.163 -class InterpolationSyntaxError(InterpolationError):
122.164 - """Raised when the source text into which substitutions are made
122.165 - does not conform to the required syntax."""
122.166 -
122.167 -class InterpolationDepthError(InterpolationError):
122.168 - """Raised when substitutions are nested too deeply."""
122.169 -
122.170 - def __init__(self, option, section, rawval):
122.171 - msg = ("Value interpolation too deeply recursive:\n"
122.172 - "\tsection: [%s]\n"
122.173 - "\toption : %s\n"
122.174 - "\trawval : %s\n"
122.175 - % (section, option, rawval))
122.176 - InterpolationError.__init__(self, option, section, msg)
122.177 -
122.178 -class ParsingError(Error):
122.179 - """Raised when a configuration file does not follow legal syntax."""
122.180 -
122.181 - def __init__(self, filename):
122.182 - Error.__init__(self, 'File contains parsing errors: %s' % filename)
122.183 - self.filename = filename
122.184 - self.errors = []
122.185 -
122.186 - def append(self, lineno, line):
122.187 - self.errors.append((lineno, line))
122.188 - self.message += '\n\t[line %2d]: %s' % (lineno, line)
122.189 -
122.190 -class MissingSectionHeaderError(ParsingError):
122.191 - """Raised when a key-value pair is found before any section header."""
122.192 -
122.193 - def __init__(self, filename, lineno, line):
122.194 - Error.__init__(
122.195 - self,
122.196 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
122.197 - (filename, lineno, line))
122.198 - self.filename = filename
122.199 - self.lineno = lineno
122.200 - self.line = line
122.201 -
122.202 -
122.203 -
122.204 -class RawConfigParser:
122.205 - def __init__(self, defaults=None):
122.206 - self._sections = {}
122.207 - if defaults is None:
122.208 - self._defaults = {}
122.209 - else:
122.210 - self._defaults = defaults
122.211 -
122.212 - def defaults(self):
122.213 - return self._defaults
122.214 -
122.215 - def sections(self):
122.216 - """Return a list of section names, excluding [DEFAULT]"""
122.217 - # self._sections will never have [DEFAULT] in it
122.218 - return self._sections.keys()
122.219 -
122.220 - def add_section(self, section):
122.221 - """Create a new section in the configuration.
122.222 -
122.223 - Raise DuplicateSectionError if a section by the specified name
122.224 - already exists.
122.225 - """
122.226 - if section in self._sections:
122.227 - raise DuplicateSectionError(section)
122.228 - self._sections[section] = {}
122.229 -
122.230 - def has_section(self, section):
122.231 - """Indicate whether the named section is present in the configuration.
122.232 -
122.233 - The DEFAULT section is not acknowledged.
122.234 - """
122.235 - return section in self._sections
122.236 -
122.237 - def options(self, section):
122.238 - """Return a list of option names for the given section name."""
122.239 - try:
122.240 - opts = self._sections[section].copy()
122.241 - except KeyError:
122.242 - raise NoSectionError(section)
122.243 - opts.update(self._defaults)
122.244 - if '__name__' in opts:
122.245 - del opts['__name__']
122.246 - return opts.keys()
122.247 -
122.248 - def read(self, filenames):
122.249 - """Read and parse a filename or a list of filenames.
122.250 -
122.251 - Files that cannot be opened are silently ignored; this is
122.252 - designed so that you can specify a list of potential
122.253 - configuration file locations (e.g. current directory, user's
122.254 - home directory, systemwide directory), and all existing
122.255 - configuration files in the list will be read. A single
122.256 - filename may also be given.
122.257 - """
122.258 - if isinstance(filenames, basestring):
122.259 - filenames = [filenames]
122.260 - for filename in filenames:
122.261 - try:
122.262 - fp = open(filename)
122.263 - except IOError:
122.264 - continue
122.265 - self._read(fp, filename)
122.266 - fp.close()
122.267 -
122.268 - def readfp(self, fp, filename=None):
122.269 - """Like read() but the argument must be a file-like object.
122.270 -
122.271 - The `fp' argument must have a `readline' method. Optional
122.272 - second argument is the `filename', which if not given, is
122.273 - taken from fp.name. If fp has no `name' attribute, `<???>' is
122.274 - used.
122.275 -
122.276 - """
122.277 - if filename is None:
122.278 - try:
122.279 - filename = fp.name
122.280 - except AttributeError:
122.281 - filename = '<???>'
122.282 - self._read(fp, filename)
122.283 -
122.284 - def get(self, section, option):
122.285 - opt = self.optionxform(option)
122.286 - if section not in self._sections:
122.287 - if section != DEFAULTSECT:
122.288 - raise NoSectionError(section)
122.289 - if opt in self._defaults:
122.290 - return self._defaults[opt]
122.291 - else:
122.292 - raise NoOptionError(option, section)
122.293 - elif opt in self._sections[section]:
122.294 - return self._sections[section][opt]
122.295 - elif opt in self._defaults:
122.296 - return self._defaults[opt]
122.297 - else:
122.298 - raise NoOptionError(option, section)
122.299 -
122.300 - def items(self, section):
122.301 - try:
122.302 - d2 = self._sections[section]
122.303 - except KeyError:
122.304 - if section != DEFAULTSECT:
122.305 - raise NoSectionError(section)
122.306 - d2 = {}
122.307 - d = self._defaults.copy()
122.308 - d.update(d2)
122.309 - if "__name__" in d:
122.310 - del d["__name__"]
122.311 - return d.items()
122.312 -
122.313 - def _get(self, section, conv, option):
122.314 - return conv(self.get(section, option))
122.315 -
122.316 - def getint(self, section, option):
122.317 - return self._get(section, int, option)
122.318 -
122.319 - def getfloat(self, section, option):
122.320 - return self._get(section, float, option)
122.321 -
122.322 - _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
122.323 - '0': False, 'no': False, 'false': False, 'off': False}
122.324 -
122.325 - def getboolean(self, section, option):
122.326 - v = self.get(section, option)
122.327 - if v.lower() not in self._boolean_states:
122.328 - raise ValueError, 'Not a boolean: %s' % v
122.329 - return self._boolean_states[v.lower()]
122.330 -
122.331 - def optionxform(self, optionstr):
122.332 - return optionstr.lower()
122.333 -
122.334 - def has_option(self, section, option):
122.335 - """Check for the existence of a given option in a given section."""
122.336 - if not section or section == DEFAULTSECT:
122.337 - option = self.optionxform(option)
122.338 - return option in self._defaults
122.339 - elif section not in self._sections:
122.340 - return False
122.341 - else:
122.342 - option = self.optionxform(option)
122.343 - return (option in self._sections[section]
122.344 - or option in self._defaults)
122.345 -
122.346 - def set(self, section, option, value):
122.347 - """Set an option."""
122.348 - if not section or section == DEFAULTSECT:
122.349 - sectdict = self._defaults
122.350 - else:
122.351 - try:
122.352 - sectdict = self._sections[section]
122.353 - except KeyError:
122.354 - raise NoSectionError(section)
122.355 - sectdict[self.optionxform(option)] = value
122.356 -
122.357 - def write(self, fp):
122.358 - """Write an .ini-format representation of the configuration state."""
122.359 - if self._defaults:
122.360 - fp.write("[%s]\n" % DEFAULTSECT)
122.361 - for (key, value) in self._defaults.items():
122.362 - fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
122.363 - fp.write("\n")
122.364 - for section in self._sections:
122.365 - fp.write("[%s]\n" % section)
122.366 - for (key, value) in self._sections[section].items():
122.367 - if key != "__name__":
122.368 - fp.write("%s = %s\n" %
122.369 - (key, str(value).replace('\n', '\n\t')))
122.370 - fp.write("\n")
122.371 -
122.372 - def remove_option(self, section, option):
122.373 - """Remove an option."""
122.374 - if not section or section == DEFAULTSECT:
122.375 - sectdict = self._defaults
122.376 - else:
122.377 - try:
122.378 - sectdict = self._sections[section]
122.379 - except KeyError:
122.380 - raise NoSectionError(section)
122.381 - option = self.optionxform(option)
122.382 - existed = option in sectdict
122.383 - if existed:
122.384 - del sectdict[option]
122.385 - return existed
122.386 -
122.387 - def remove_section(self, section):
122.388 - """Remove a file section."""
122.389 - existed = section in self._sections
122.390 - if existed:
122.391 - del self._sections[section]
122.392 - return existed
122.393 -
122.394 - #
122.395 - # Regular expressions for parsing section headers and options.
122.396 - #
122.397 - SECTCRE = re.compile(
122.398 - r'\[' # [
122.399 - r'(?P<header>[^]]+)' # very permissive!
122.400 - r'\]' # ]
122.401 - )
122.402 - OPTCRE = re.compile(
122.403 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
122.404 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
122.405 - # followed by separator
122.406 - # (either : or =), followed
122.407 - # by any # space/tab
122.408 - r'(?P<value>.*)$' # everything up to eol
122.409 - )
122.410 -
122.411 - def _read(self, fp, fpname):
122.412 - """Parse a sectioned setup file.
122.413 -
122.414 - The sections in setup file contains a title line at the top,
122.415 - indicated by a name in square brackets (`[]'), plus key/value
122.416 - options lines, indicated by `name: value' format lines.
122.417 - Continuations are represented by an embedded newline then
122.418 - leading whitespace. Blank lines, lines beginning with a '#',
122.419 - and just about everything else are ignored.
122.420 - """
122.421 - cursect = None # None, or a dictionary
122.422 - optname = None
122.423 - lineno = 0
122.424 - e = None # None, or an exception
122.425 - while True:
122.426 - line = fp.readline()
122.427 - if not line:
122.428 - break
122.429 - lineno = lineno + 1
122.430 - # comment or blank line?
122.431 - if line.strip() == '' or line[0] in '#;':
122.432 - continue
122.433 - if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
122.434 - # no leading whitespace
122.435 - continue
122.436 - # continuation line?
122.437 - if line[0].isspace() and cursect is not None and optname:
122.438 - value = line.strip()
122.439 - if value:
122.440 - cursect[optname] = "%s\n%s" % (cursect[optname], value)
122.441 - # a section header or option header?
122.442 - else:
122.443 - # is it a section header?
122.444 - mo = self.SECTCRE.match(line)
122.445 - if mo:
122.446 - sectname = mo.group('header')
122.447 - if sectname in self._sections:
122.448 - cursect = self._sections[sectname]
122.449 - elif sectname == DEFAULTSECT:
122.450 - cursect = self._defaults
122.451 - else:
122.452 - cursect = {'__name__': sectname}
122.453 - self._sections[sectname] = cursect
122.454 - # So sections can't start with a continuation line
122.455 - optname = None
122.456 - # no section header in the file?
122.457 - elif cursect is None:
122.458 - raise MissingSectionHeaderError(fpname, lineno, `line`)
122.459 - # an option line?
122.460 - else:
122.461 - mo = self.OPTCRE.match(line)
122.462 - if mo:
122.463 - optname, vi, optval = mo.group('option', 'vi', 'value')
122.464 - if vi in ('=', ':') and ';' in optval:
122.465 - # ';' is a comment delimiter only if it follows
122.466 - # a spacing character
122.467 - pos = optval.find(';')
122.468 - if pos != -1 and optval[pos-1].isspace():
122.469 - optval = optval[:pos]
122.470 - optval = optval.strip()
122.471 - # allow empty values
122.472 - if optval == '""':
122.473 - optval = ''
122.474 - optname = self.optionxform(optname.rstrip())
122.475 - cursect[optname] = optval
122.476 - else:
122.477 - # a non-fatal parsing error occurred. set up the
122.478 - # exception but keep going. the exception will be
122.479 - # raised at the end of the file and will contain a
122.480 - # list of all bogus lines
122.481 - if not e:
122.482 - e = ParsingError(fpname)
122.483 - e.append(lineno, `line`)
122.484 - # if any parsing errors occurred, raise an exception
122.485 - if e:
122.486 - raise e
122.487 -
122.488 -
122.489 -class ConfigParser(RawConfigParser):
122.490 -
122.491 - def get(self, section, option, raw=False, vars=None):
122.492 - """Get an option value for a given section.
122.493 -
122.494 - All % interpolations are expanded in the return values, based on the
122.495 - defaults passed into the constructor, unless the optional argument
122.496 - `raw' is true. Additional substitutions may be provided using the
122.497 - `vars' argument, which must be a dictionary whose contents overrides
122.498 - any pre-existing defaults.
122.499 -
122.500 - The section DEFAULT is special.
122.501 - """
122.502 - d = self._defaults.copy()
122.503 - try:
122.504 - d.update(self._sections[section])
122.505 - except KeyError:
122.506 - if section != DEFAULTSECT:
122.507 - raise NoSectionError(section)
122.508 - # Update with the entry specific variables
122.509 - if vars is not None:
122.510 - d.update(vars)
122.511 - option = self.optionxform(option)
122.512 - try:
122.513 - value = d[option]
122.514 - except KeyError:
122.515 - raise NoOptionError(option, section)
122.516 -
122.517 - if raw:
122.518 - return value
122.519 - else:
122.520 - return self._interpolate(section, option, value, d)
122.521 -
122.522 - def items(self, section, raw=False, vars=None):
122.523 - """Return a list of tuples with (name, value) for each option
122.524 - in the section.
122.525 -
122.526 - All % interpolations are expanded in the return values, based on the
122.527 - defaults passed into the constructor, unless the optional argument
122.528 - `raw' is true. Additional substitutions may be provided using the
122.529 - `vars' argument, which must be a dictionary whose contents overrides
122.530 - any pre-existing defaults.
122.531 -
122.532 - The section DEFAULT is special.
122.533 - """
122.534 - d = self._defaults.copy()
122.535 - try:
122.536 - d.update(self._sections[section])
122.537 - except KeyError:
122.538 - if section != DEFAULTSECT:
122.539 - raise NoSectionError(section)
122.540 - # Update with the entry specific variables
122.541 - if vars:
122.542 - d.update(vars)
122.543 - options = d.keys()
122.544 - if "__name__" in options:
122.545 - options.remove("__name__")
122.546 - if raw:
122.547 - return [(option, d[option])
122.548 - for option in options]
122.549 - else:
122.550 - return [(option, self._interpolate(section, option, d[option], d))
122.551 - for option in options]
122.552 -
122.553 - def _interpolate(self, section, option, rawval, vars):
122.554 - # do the string interpolation
122.555 - value = rawval
122.556 - depth = MAX_INTERPOLATION_DEPTH
122.557 - while depth: # Loop through this until it's done
122.558 - depth -= 1
122.559 - if value.find("%(") != -1:
122.560 - try:
122.561 - value = value % vars
122.562 - except KeyError, e:
122.563 - raise InterpolationMissingOptionError(
122.564 - option, section, rawval, e[0])
122.565 - else:
122.566 - break
122.567 - if value.find("%(") != -1:
122.568 - raise InterpolationDepthError(option, section, rawval)
122.569 - return value
122.570 -
122.571 -
122.572 -class SafeConfigParser(ConfigParser):
122.573 -
122.574 - def _interpolate(self, section, option, rawval, vars):
122.575 - # do the string interpolation
122.576 - L = []
122.577 - self._interpolate_some(option, L, rawval, section, vars, 1)
122.578 - return ''.join(L)
122.579 -
122.580 - _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
122.581 -
122.582 - def _interpolate_some(self, option, accum, rest, section, map, depth):
122.583 - if depth > MAX_INTERPOLATION_DEPTH:
122.584 - raise InterpolationDepthError(option, section, rest)
122.585 - while rest:
122.586 - p = rest.find("%")
122.587 - if p < 0:
122.588 - accum.append(rest)
122.589 - return
122.590 - if p > 0:
122.591 - accum.append(rest[:p])
122.592 - rest = rest[p:]
122.593 - # p is no longer used
122.594 - c = rest[1:2]
122.595 - if c == "%":
122.596 - accum.append("%")
122.597 - rest = rest[2:]
122.598 - elif c == "(":
122.599 - m = self._interpvar_match(rest)
122.600 - if m is None:
122.601 - raise InterpolationSyntaxError(option, section,
122.602 - "bad interpolation variable reference %r" % rest)
122.603 - var = m.group(1)
122.604 - rest = rest[m.end():]
122.605 - try:
122.606 - v = map[var]
122.607 - except KeyError:
122.608 - raise InterpolationMissingOptionError(
122.609 - option, section, rest, var)
122.610 - if "%" in v:
122.611 - self._interpolate_some(option, accum, v,
122.612 - section, map, depth + 1)
122.613 - else:
122.614 - accum.append(v)
122.615 - else:
122.616 - raise InterpolationSyntaxError(
122.617 - option, section,
122.618 - "'%' must be followed by '%' or '(', found: " + `ret`)
123.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.html Sun Jan 04 13:11:53 2015 -0600
123.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
123.3 @@ -1,302 +0,0 @@
123.4 -<html><body>
123.5 -<h2 style="color: green">Next Comment</h2>
123.6 -<pre><b>ConfigParser.py</b></pre>
123.7 -
123.8 -<hr>
123.9 -Configuration file parser.
123.10 -
123.11 -<br><br>
123.12 -A setup file consists of sections, lead by a "[section]" header,
123.13 -and followed by "name: value" entries, with continuations and such in
123.14 -the style of RFC 822.
123.15 -
123.16 -<br><br>
123.17 - the same section, or values in a special [DEFAULT] section.
123.18 -
123.19 -<br><br>
123.20 -For example:
123.21 -
123.22 -<br><br>
123.23 - something: %(dir)s/whatever
123.24 -
123.25 -<br><br>
123.26 -would resolve the "%(dir)s" to the value of dir. All reference
123.27 -expansions are done late, on demand.
123.28 -
123.29 -<br><br>
123.30 -Intrinsic defaults can be specified by passing them into the
123.31 -ConfigParser constructor as a dictionary.
123.32 -
123.33 -<br><br>
123.34 -class:
123.35 -
123.36 -<br><br>
123.37 -ConfigParser -- responsible for parsing a list of
123.38 - configuration files, and managing the parsed database.
123.39 -
123.40 -<br><br>
123.41 - methods:
123.42 -
123.43 -<br><br>
123.44 - __init__(defaults=None)
123.45 - create the parser and specify a dictionary of intrinsic defaults. The
123.46 - keys must be strings, the values must be appropriate for %()s string
123.47 - interpolation. Note that `__name__' is always an intrinsic default;
123.48 - it's value is the section's name.
123.49 -
123.50 -<br><br>
123.51 - sections()
123.52 - return all the configuration section names, sans DEFAULT
123.53 -
123.54 -<br><br>
123.55 - has_section(section)
123.56 - return whether the given section exists
123.57 -
123.58 -<br><br>
123.59 - has_option(section, option)
123.60 - return whether the given option exists in the given section
123.61 -
123.62 -<br><br>
123.63 - options(section)
123.64 - return list of configuration options for the named section
123.65 -
123.66 -<br><br>
123.67 - read(filenames)
123.68 - read and parse the list of named configuration files, given by
123.69 - name. A single filename is also allowed. Non-existing files
123.70 - are ignored.
123.71 -
123.72 -<br><br>
123.73 - readfp(fp, filename=None)
123.74 - read and parse one configuration file, given as a file object.
123.75 - The filename defaults to fp.name; it is only used in error
123.76 - messages (if fp has no `name' attribute, the string `<???>' is used).
123.77 -
123.78 -<br><br>
123.79 - get(section, option, raw=False, vars=None)
123.80 - return a string value for the named option. All % interpolations are
123.81 - expanded in the return values, based on the defaults passed into the
123.82 - constructor and the DEFAULT section. Additional substitutions may be
123.83 - provided using the `vars' argument, which must be a dictionary whose
123.84 - contents override any pre-existing defaults.
123.85 -
123.86 -<br><br>
123.87 - getint(section, options)
123.88 - like get(), but convert value to an integer
123.89 -
123.90 -<br><br>
123.91 - getfloat(section, options)
123.92 - like get(), but convert value to a float
123.93 -
123.94 -<br><br>
123.95 - getboolean(section, options)
123.96 - like get(), but convert value to a boolean (currently case
123.97 - insensitively defined as 0, false, no, off for False, and 1, true,
123.98 - yes, on for True). Returns False or True.
123.99 -
123.100 -<br><br>
123.101 - items(section, raw=False, vars=None)
123.102 - return a list of tuples with (name, value) for each option
123.103 - in the section.
123.104 -
123.105 -<br><br>
123.106 - remove_section(section)
123.107 - remove the given file section and all its options
123.108 -
123.109 -<br><br>
123.110 - remove_option(section, option)
123.111 - remove the given option from the given section
123.112 -
123.113 -<br><br>
123.114 - set(section, option, value)
123.115 - set the given option
123.116 -
123.117 -<br><br>
123.118 - write(fp)
123.119 - write the configuration state in .ini format
123.120 -<h2 style="color: green">Next Comment</h2>
123.121 -<pre><b>Error</b></pre>
123.122 -
123.123 -<hr>
123.124 -Base class for ConfigParser exceptions.
123.125 -<h2 style="color: green">Next Comment</h2>
123.126 -<pre><b>NoSectionError</b></pre>
123.127 -
123.128 -<hr>
123.129 -Rasssised when no section matches a requested option.
123.130 -<h2 style="color: green">Next Comment</h2>
123.131 -<pre><b>DuplicateSectionError</b></pre>
123.132 -
123.133 -<hr>
123.134 -Raised when a section is multiply-created.
123.135 -<h2 style="color: green">Next Comment</h2>
123.136 -<pre><b>NoOptionError</b></pre>
123.137 -
123.138 -<hr>
123.139 -A requested option was not found.
123.140 -<h2 style="color: green">Next Comment</h2>
123.141 -<pre><b>InterpolationError</b></pre>
123.142 -
123.143 -<hr>
123.144 -Base class for interpolation-related exceptions.
123.145 -<h2 style="color: green">Next Comment</h2>
123.146 -<pre><b>InterpolationMissingOptionError</b></pre>
123.147 -
123.148 -<hr>
123.149 -A string substitution required a setting which was not available.
123.150 -<h2 style="color: green">Next Comment</h2>
123.151 -<pre><b>InterpolationSyntaxError</b></pre>
123.152 -
123.153 -<hr>
123.154 -Raised when the source text into which substitutions are made
123.155 - does not conform to the required syntax.
123.156 -<h2 style="color: green">Next Comment</h2>
123.157 -<pre><b>InterpolationDepthError</b></pre>
123.158 -
123.159 -<hr>
123.160 -Raised when substitutions are nested too deeply.
123.161 -<h2 style="color: green">Next Comment</h2>
123.162 -<pre><b>ParsingError</b></pre>
123.163 -
123.164 -<hr>
123.165 -Raised when a configuration file does not follow legal syntax.
123.166 -<h2 style="color: green">Next Comment</h2>
123.167 -<pre><b>MissingSectionHeaderError</b></pre>
123.168 -
123.169 -<hr>
123.170 -Raised when a key-value pair is found before any section header.
123.171 -<h2 style="color: green">Next Comment</h2>
123.172 -<pre><b>sections</b>(<font color="#808080">self</font>)</pre>
123.173 -
123.174 -<hr>
123.175 -Return a list of section names, excluding [DEFAULT]
123.176 -<h2 style="color: green">Next Comment</h2>
123.177 -<pre><b>add_section</b>(<font color="#808080">self, section</font>)</pre>
123.178 -
123.179 -<hr>
123.180 -Create a new section in the configuration.
123.181 -
123.182 -<br><br>
123.183 - Raise DuplicateSectionError if a section by the specified name
123.184 - already exists.
123.185 -
123.186 -<br><br>
123.187 -<h2 style="color: green">Next Comment</h2>
123.188 -<pre><b>has_section</b>(<font color="#808080">self, section</font>)</pre>
123.189 -
123.190 -<hr>
123.191 -Indicate whether the named section is present in the configuration.
123.192 -
123.193 -<br><br>
123.194 - The DEFAULT section is not acknowledged.
123.195 -
123.196 -<br><br>
123.197 -<h2 style="color: green">Next Comment</h2>
123.198 -<pre><b>options</b>(<font color="#808080">self, section</font>)</pre>
123.199 -
123.200 -<hr>
123.201 -Return a list of option names for the given section name.
123.202 -<h2 style="color: green">Next Comment</h2>
123.203 -<pre><b>read</b>(<font color="#808080">self, filenames</font>)</pre>
123.204 -
123.205 -<hr>
123.206 -Read and parse a filename or a list of filenames.
123.207 -
123.208 -<br><br>
123.209 - Files that cannot be opened are silently ignored; this is
123.210 - designed so that you can specify a list of potential
123.211 - configuration file locations (e.g. current directory, user's
123.212 - home directory, systemwide directory), and all existing
123.213 - configuration files in the list will be read. A single
123.214 - filename may also be given.
123.215 -
123.216 -<br><br>
123.217 -<h2 style="color: green">Next Comment</h2>
123.218 -<pre><b>readfp</b>(<font color="#808080">self, fp, filename</font>)</pre>
123.219 -
123.220 -<hr>
123.221 -Like read() but the argument must be a file-like object.
123.222 -
123.223 -<br><br>
123.224 - The `fp' argument must have a `readline' method. Optional
123.225 - second argument is the `filename', which if not given, is
123.226 - taken from fp.name. If fp has no `name' attribute, `<???>' is
123.227 - used.
123.228 -
123.229 -<br><br>
123.230 -<h2 style="color: green">Next Comment</h2>
123.231 -<pre><b>has_option</b>(<font color="#808080">self, section, option</font>)</pre>
123.232 -
123.233 -<hr>
123.234 -Check for the existence of a given option in a given section.
123.235 -<h2 style="color: green">Next Comment</h2>
123.236 -<pre><b>set</b>(<font color="#808080">self, section, option, value</font>)</pre>
123.237 -
123.238 -<hr>
123.239 -Set an option.
123.240 -<h2 style="color: green">Next Comment</h2>
123.241 -<pre><b>write</b>(<font color="#808080">self, fp</font>)</pre>
123.242 -
123.243 -<hr>
123.244 -Write an .ini-format representation of the configuration state.
123.245 -<h2 style="color: green">Next Comment</h2>
123.246 -<pre><b>remove_option</b>(<font color="#808080">self, section, option</font>)</pre>
123.247 -
123.248 -<hr>
123.249 -Remove an option.
123.250 -<h2 style="color: green">Next Comment</h2>
123.251 -<pre><b>remove_section</b>(<font color="#808080">self, section</font>)</pre>
123.252 -
123.253 -<hr>
123.254 -Remove a file section.
123.255 -<h2 style="color: green">Next Comment</h2>
123.256 -<pre><b>_read</b>(<font color="#808080">self, fp, fpname</font>)</pre>
123.257 -
123.258 -<hr>
123.259 -Parse a sectioned setup file.
123.260 -
123.261 -<br><br>
123.262 - The sections in setup file contains a title line at the top,
123.263 - indicated by a name in square brackets (`[]'), plus key/value
123.264 - options lines, indicated by `name: value' format lines.
123.265 - Continuations are represented by an embedded newline then
123.266 - leading whitespace. Blank lines, lines beginning with a '#',
123.267 - and just about everything else are ignored.
123.268 -
123.269 -<br><br>
123.270 -<h2 style="color: green">Next Comment</h2>
123.271 -<pre><b>get</b>(<font color="#808080">self, section, option, raw, vars</font>)</pre>
123.272 -
123.273 -<hr>
123.274 -Get an option value for a given section.
123.275 -
123.276 -<br><br>
123.277 - All % interpolations are expanded in the return values, based on the
123.278 - defaults passed into the constructor, unless the optional argument
123.279 - `raw' is true. Additional substitutions may be provided using the
123.280 - `vars' argument, which must be a dictionary whose contents overrides
123.281 - any pre-existing defaults.
123.282 -
123.283 -<br><br>
123.284 - The section DEFAULT is special.
123.285 -
123.286 -<br><br>
123.287 -<h2 style="color: green">Next Comment</h2>
123.288 -<pre><b>items</b>(<font color="#808080">self, section, raw, vars</font>)</pre>
123.289 -
123.290 -<hr>
123.291 -Return a list of tuples with (name, value) for each option
123.292 - in the section.
123.293 -
123.294 -<br><br>
123.295 - All % interpolations are expanded in the return values, based on the
123.296 - defaults passed into the constructor, unless the optional argument
123.297 - `raw' is true. Additional substitutions may be provided using the
123.298 - `vars' argument, which must be a dictionary whose contents overrides
123.299 - any pre-existing defaults.
123.300 -
123.301 -<br><br>
123.302 - The section DEFAULT is special.
123.303 -
123.304 -<br><br>
123.305 -</body></html>
124.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.indexed Sun Jan 04 13:11:53 2015 -0600
124.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
124.3 @@ -1,213 +0,0 @@
124.4 -
124.5 -
124.6 -Document 0
124.7 -Searchable Keys:
124.8 - class : ConfigParser
124.9 - class-ig : configparser
124.10 - extends : RawConfigParser
124.11 - in : ConfigParser
124.12 - member : _interpolate;F;|PRIVATE|;self,section,option,rawval,vars;
124.13 - member : get;F;;self,section,option,raw,vars;
124.14 - member : items;F;;self,section,raw,vars;
124.15 -
124.16 -Not Searchable Keys:
124.17 -
124.18 -
124.19 -Document 1
124.20 -Searchable Keys:
124.21 - class : DuplicateSectionError
124.22 - class-ig : duplicatesectionerror
124.23 - extends : Error
124.24 - in : ConfigParser
124.25 - member : __init__;c;|CONSTRUCTOR|;self,section;
124.26 - member : section;D;;
124.27 -
124.28 -Not Searchable Keys:
124.29 -
124.30 -
124.31 -Document 2
124.32 -Searchable Keys:
124.33 - class : Error
124.34 - class-ig : error
124.35 - extends : Exception
124.36 - in : ConfigParser
124.37 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,msg;
124.38 - member : __repr__;F;|PRIVATE|;self;
124.39 - member : __str__;F;|PRIVATE|;self;
124.40 - member : message;D;;
124.41 -
124.42 -Not Searchable Keys:
124.43 - clzattrs : ;|PRIVATE|;
124.44 -
124.45 -
124.46 -Document 3
124.47 -Searchable Keys:
124.48 - class : InterpolationDepthError
124.49 - class-ig : interpolationdeptherror
124.50 - extends : InterpolationError
124.51 - in : ConfigParser
124.52 - member : __init__;c;|CONSTRUCTOR|;self,option,section,rawval;
124.53 -
124.54 -Not Searchable Keys:
124.55 -
124.56 -
124.57 -Document 4
124.58 -Searchable Keys:
124.59 - class : InterpolationError
124.60 - class-ig : interpolationerror
124.61 - extends : Error
124.62 - in : ConfigParser
124.63 - member : __init__;c;|CONSTRUCTOR|;self,option,section,msg;
124.64 - member : option;D;;
124.65 - member : section;D;;
124.66 -
124.67 -Not Searchable Keys:
124.68 -
124.69 -
124.70 -Document 5
124.71 -Searchable Keys:
124.72 - class : InterpolationMissingOptionError
124.73 - class-ig : interpolationmissingoptionerror
124.74 - extends : InterpolationError
124.75 - in : ConfigParser
124.76 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,option,section,rawval,reference;
124.77 - member : reference;D;;
124.78 -
124.79 -Not Searchable Keys:
124.80 - clzattrs : ;|PRIVATE|;
124.81 -
124.82 -
124.83 -Document 6
124.84 -Searchable Keys:
124.85 - class : InterpolationSyntaxError
124.86 - class-ig : interpolationsyntaxerror
124.87 - extends : InterpolationError
124.88 - in : ConfigParser
124.89 -
124.90 -Not Searchable Keys:
124.91 -
124.92 -
124.93 -Document 7
124.94 -Searchable Keys:
124.95 - class : MissingSectionHeaderError
124.96 - class-ig : missingsectionheadererror
124.97 - extends : ParsingError
124.98 - in : ConfigParser
124.99 - member : __init__;c;|CONSTRUCTOR|;self,filename,lineno,line;
124.100 - member : filename;D;;
124.101 - member : line;D;;
124.102 - member : lineno;D;;
124.103 -
124.104 -Not Searchable Keys:
124.105 -
124.106 -
124.107 -Document 8
124.108 -Searchable Keys:
124.109 - class : NoOptionError
124.110 - class-ig : nooptionerror
124.111 - extends : Error
124.112 - in : ConfigParser
124.113 - member : __init__;c;|CONSTRUCTOR|;self,option,section;
124.114 - member : option;D;;
124.115 - member : section;D;;
124.116 -
124.117 -Not Searchable Keys:
124.118 -
124.119 -
124.120 -Document 9
124.121 -Searchable Keys:
124.122 - class : NoSectionError
124.123 - class-ig : nosectionerror
124.124 - extends : Error
124.125 - in : ConfigParser
124.126 - member : __init__;c;|CONSTRUCTOR|;self,section;
124.127 - member : section;D;;
124.128 -
124.129 -Not Searchable Keys:
124.130 -
124.131 -
124.132 -Document 10
124.133 -Searchable Keys:
124.134 - class : ParsingError
124.135 - class-ig : parsingerror
124.136 - extends : Error
124.137 - in : ConfigParser
124.138 - member : __init__;c;|CONSTRUCTOR|;self,filename;
124.139 - member : append;F;;self,lineno,line;
124.140 - member : errors;D;;
124.141 - member : filename;D;;
124.142 -
124.143 -Not Searchable Keys:
124.144 -
124.145 -
124.146 -Document 11
124.147 -Searchable Keys:
124.148 - class : RawConfigParser
124.149 - class-ig : rawconfigparser
124.150 - in : ConfigParser
124.151 - member : OPTCRE;D;|PRIVATE|;
124.152 - member : SECTCRE;D;|PRIVATE|;
124.153 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,defaults;
124.154 - member : _boolean_states;D;|PRIVATE|;
124.155 - member : _defaults;D;|PRIVATE|;
124.156 - member : _get;F;|PRIVATE|;self,section,conv,option;
124.157 - member : _read;F;|PRIVATE|;self,fp,fpname;
124.158 - member : _sections;D;|PRIVATE|;
124.159 - member : add_section;F;|PRIVATE|;self,section;
124.160 - member : defaults;F;|PRIVATE|;self;
124.161 - member : get;F;|PRIVATE|;self,section,option;
124.162 - member : getboolean;F;|PRIVATE|;self,section,option;
124.163 - member : getfloat;F;|PRIVATE|;self,section,option;
124.164 - member : getint;F;|PRIVATE|;self,section,option;
124.165 - member : has_option;F;|PRIVATE|;self,section,option;
124.166 - member : has_section;F;|PRIVATE|;self,section;
124.167 - member : items;F;|PRIVATE|;self,section;
124.168 - member : options;F;|PRIVATE|;self,section;
124.169 - member : optionxform;F;|PRIVATE|;self,optionstr;
124.170 - member : read;F;|PRIVATE|;self,filenames;
124.171 - member : readfp;F;|PRIVATE|;self,fp,filename;
124.172 - member : remove_option;F;|PRIVATE|;self,section,option;
124.173 - member : remove_section;F;|PRIVATE|;self,section;
124.174 - member : sections;F;|PRIVATE|;self;
124.175 - member : set;F;|PRIVATE|;self,section,option,value;
124.176 - member : write;F;|PRIVATE|;self,fp;
124.177 -
124.178 -Not Searchable Keys:
124.179 - clzattrs : ;|PRIVATE|;
124.180 -
124.181 -
124.182 -Document 12
124.183 -Searchable Keys:
124.184 - class : SafeConfigParser
124.185 - class-ig : safeconfigparser
124.186 - extends : ConfigParser
124.187 - in : ConfigParser
124.188 - member : _interpolate;F;|PRIVATE|;self,section,option,rawval,vars;
124.189 - member : _interpolate_some;F;|PRIVATE|;self,option,accum,rest,section,map,depth;
124.190 - member : _interpvar_match;D;|PRIVATE|;
124.191 -
124.192 -Not Searchable Keys:
124.193 -
124.194 -
124.195 -Document 13
124.196 -Searchable Keys:
124.197 - item : ConfigParser;C;;
124.198 - item : DEFAULTSECT;D;;
124.199 - item : DuplicateSectionError;C;;
124.200 - item : Error;C;|PRIVATE|;
124.201 - item : InterpolationDepthError;C;;
124.202 - item : InterpolationError;C;;
124.203 - item : InterpolationMissingOptionError;C;|PRIVATE|;
124.204 - item : InterpolationSyntaxError;C;;
124.205 - item : MAX_INTERPOLATION_DEPTH;D;;
124.206 - item : MissingSectionHeaderError;C;;
124.207 - item : NoOptionError;C;;
124.208 - item : NoSectionError;C;;
124.209 - item : ParsingError;C;;
124.210 - item : RawConfigParser;C;|PRIVATE|;
124.211 - item : SafeConfigParser;C;;
124.212 - item : __all__;D;;
124.213 - item : re;I;|PRIVATE|;
124.214 - module : ConfigParser
124.215 -
124.216 -Not Searchable Keys:
125.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.nameoffsets Sun Jan 04 13:11:53 2015 -0600
125.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
125.3 @@ -1,616 +0,0 @@
125.4 -
125.5 -"""Configuration file parser.
125.6 -
125.7 -A setup file consists of sections, lead by a "[section]" header,
125.8 -and followed by "name: value" entries, with continuations and such in
125.9 -the style of RFC 822.
125.10 -
125.11 - the same section, or values in a special [DEFAULT] section.
125.12 -
125.13 -For example:
125.14 -
125.15 - something: %(dir)s/whatever
125.16 -
125.17 -would resolve the "%(dir)s" to the value of dir. All reference
125.18 -expansions are done late, on demand.
125.19 -
125.20 -Intrinsic defaults can be specified by passing them into the
125.21 -ConfigParser constructor as a dictionary.
125.22 -
125.23 -class:
125.24 -
125.25 -ConfigParser -- responsible for parsing a list of
125.26 - configuration files, and managing the parsed database.
125.27 -
125.28 - methods:
125.29 -
125.30 - __init__(defaults=None)
125.31 - create the parser and specify a dictionary of intrinsic defaults. The
125.32 - keys must be strings, the values must be appropriate for %()s string
125.33 - interpolation. Note that `__name__' is always an intrinsic default;
125.34 - it's value is the section's name.
125.35 -
125.36 - sections()
125.37 - return all the configuration section names, sans DEFAULT
125.38 -
125.39 - has_section(section)
125.40 - return whether the given section exists
125.41 -
125.42 - has_option(section, option)
125.43 - return whether the given option exists in the given section
125.44 -
125.45 - options(section)
125.46 - return list of configuration options for the named section
125.47 -
125.48 - read(filenames)
125.49 - read and parse the list of named configuration files, given by
125.50 - name. A single filename is also allowed. Non-existing files
125.51 - are ignored.
125.52 -
125.53 - readfp(fp, filename=None)
125.54 - read and parse one configuration file, given as a file object.
125.55 - The filename defaults to fp.name; it is only used in error
125.56 - messages (if fp has no `name' attribute, the string `<???>' is used).
125.57 -
125.58 - get(section, option, raw=False, vars=None)
125.59 - return a string value for the named option. All % interpolations are
125.60 - expanded in the return values, based on the defaults passed into the
125.61 - constructor and the DEFAULT section. Additional substitutions may be
125.62 - provided using the `vars' argument, which must be a dictionary whose
125.63 - contents override any pre-existing defaults.
125.64 -
125.65 - getint(section, options)
125.66 - like get(), but convert value to an integer
125.67 -
125.68 - getfloat(section, options)
125.69 - like get(), but convert value to a float
125.70 -
125.71 - getboolean(section, options)
125.72 - like get(), but convert value to a boolean (currently case
125.73 - insensitively defined as 0, false, no, off for False, and 1, true,
125.74 - yes, on for True). Returns False or True.
125.75 -
125.76 - items(section, raw=False, vars=None)
125.77 - return a list of tuples with (name, value) for each option
125.78 - in the section.
125.79 -
125.80 - remove_section(section)
125.81 - remove the given file section and all its options
125.82 -
125.83 - remove_option(section, option)
125.84 - remove the given option from the given section
125.85 -
125.86 - set(section, option, value)
125.87 - set the given option
125.88 -
125.89 - write(fp)
125.90 - write the configuration state in .ini format
125.91 -"""
125.92 -
125.93 -import re
125.94 -
125.95 -<Name>__all__</Name> = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
125.96 - "InterpolationError", "InterpolationDepthError",
125.97 - "InterpolationSyntaxError", "ParsingError",
125.98 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
125.99 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
125.100 -
125.101 -<Name>DEFAULTSECT</Name> = "DEFAULT"
125.102 -
125.103 -<Name>MAX_INTERPOLATION_DEPTH</Name> = 10
125.104 -
125.105 -
125.106 -
125.107 -# exception classes
125.108 -class <ClassDef>Error</ClassDef>(<Name>Exception</Name>):
125.109 - """Base class for ConfigParser exceptions."""
125.110 -
125.111 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>msg</Name>=''):
125.112 - <Attribute><Name>self</Name></Attribute>.message = <Name>msg</Name>
125.113 - <Attribute><Name>Exception</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, <Name>msg</Name>)
125.114 -
125.115 - def <FunctionDef>__repr__</FunctionDef>(<Name>self</Name>):
125.116 - return <Attribute><Name>self</Name></Attribute>.message
125.117 -
125.118 - <Name>__str__</Name> = <Name>__repr__</Name>
125.119 -
125.120 -class <ClassDef>NoSectionError</ClassDef>(<Name>Error</Name>):
125.121 - """Rasssised when no section matches a requested option."""
125.122 -
125.123 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
125.124 - <Attribute><Name>Error</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, 'No section: ' + `<Name>section</Name>`)
125.125 - <Attribute><Name>self</Name></Attribute>.section = <Name>section</Name>
125.126 -
125.127 -class <ClassDef>DuplicateSectionError</ClassDef>(<Name>Error</Name>):
125.128 - """Raised when a section is multiply-created."""
125.129 -
125.130 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
125.131 - <Attribute><Name>Error</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, "Section %r already exists" % <Name>section</Name>)
125.132 - <Attribute><Name>self</Name></Attribute>.section = <Name>section</Name>
125.133 -
125.134 -class <ClassDef>NoOptionError</ClassDef>(<Name>Error</Name>):
125.135 - """A requested option was not found."""
125.136 -
125.137 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>):
125.138 - <Attribute><Name>Error</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, "No option %r in section: %r" %
125.139 - (<Name>option</Name>, <Name>section</Name>))
125.140 - <Attribute><Name>self</Name></Attribute>.option = <Name>option</Name>
125.141 - <Attribute><Name>self</Name></Attribute>.section = <Name>section</Name>
125.142 -
125.143 -class <ClassDef>InterpolationError</ClassDef>(<Name>Error</Name>):
125.144 - """Base class for interpolation-related exceptions."""
125.145 -
125.146 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>msg</Name>):
125.147 - <Attribute><Name>Error</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, <Name>msg</Name>)
125.148 - <Attribute><Name>self</Name></Attribute>.option = <Name>option</Name>
125.149 - <Attribute><Name>self</Name></Attribute>.section = <Name>section</Name>
125.150 -
125.151 -class <ClassDef>InterpolationMissingOptionError</ClassDef>(<Name>InterpolationError</Name>):
125.152 - """A string substitution required a setting which was not available."""
125.153 -
125.154 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>, <Name>reference</Name>):
125.155 - <Name>msg</Name> = ("Bad value substitution:\n"
125.156 - "\tsection: [%s]\n"
125.157 - "\toption : %s\n"
125.158 - "\tkey : %s\n"
125.159 - "\trawval : %s\n"
125.160 - % (<Name>section</Name>, <Name>option</Name>, <Name>reference</Name>, <Name>rawval</Name>))
125.161 - <Attribute><Name>InterpolationError</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>msg</Name>)
125.162 - <Attribute><Name>self</Name></Attribute>.reference = <Name>reference</Name>
125.163 -
125.164 -class <ClassDef>InterpolationSyntaxError</ClassDef>(<Name>InterpolationError</Name>):
125.165 - """Raised when the source text into which substitutions are made
125.166 - does not conform to the required syntax."""
125.167 -
125.168 -class <ClassDef>InterpolationDepthError</ClassDef>(<Name>InterpolationError</Name>):
125.169 - """Raised when substitutions are nested too deeply."""
125.170 -
125.171 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>):
125.172 - <Name>msg</Name> = ("Value interpolation too deeply recursive:\n"
125.173 - "\tsection: [%s]\n"
125.174 - "\toption : %s\n"
125.175 - "\trawval : %s\n"
125.176 - % (<Name>section</Name>, <Name>option</Name>, <Name>rawval</Name>))
125.177 - <Attribute><Name>InterpolationError</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>msg</Name>)
125.178 -
125.179 -class <ClassDef>ParsingError</ClassDef>(<Name>Error</Name>):
125.180 - """Raised when a configuration file does not follow legal syntax."""
125.181 -
125.182 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>filename</Name>):
125.183 - <Attribute><Name>Error</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, 'File contains parsing errors: %s' % <Name>filename</Name>)
125.184 - <Attribute><Name>self</Name></Attribute>.filename = <Name>filename</Name>
125.185 - <Attribute><Name>self</Name></Attribute>.errors = []
125.186 -
125.187 - def <FunctionDef>append</FunctionDef>(<Name>self</Name>, <Name>lineno</Name>, <Name>line</Name>):
125.188 - <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.errors.<Call>append</Call>((<Name>lineno</Name>, <Name>line</Name>))
125.189 - <Attribute><Name>self</Name></Attribute>.message += '\n\t[line %2d]: %s' % (<Name>lineno</Name>, <Name>line</Name>)
125.190 -
125.191 -class <ClassDef>MissingSectionHeaderError</ClassDef>(<Name>ParsingError</Name>):
125.192 - """Raised when a key-value pair is found before any section header."""
125.193 -
125.194 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>filename</Name>, <Name>lineno</Name>, <Name>line</Name>):
125.195 - <Attribute><Name>Error</Name></Attribute>.<Call>__init__</Call>(
125.196 - <Name>self</Name>,
125.197 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
125.198 - (<Name>filename</Name>, <Name>lineno</Name>, <Name>line</Name>))
125.199 - <Attribute><Name>self</Name></Attribute>.filename = <Name>filename</Name>
125.200 - <Attribute><Name>self</Name></Attribute>.lineno = <Name>lineno</Name>
125.201 - <Attribute><Name>self</Name></Attribute>.line = <Name>line</Name>
125.202 -
125.203 -
125.204 -
125.205 -class <ClassDef>RawConfigParser</ClassDef>:
125.206 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>defaults</Name>=<Name>None</Name>):
125.207 - <Attribute><Name>self</Name></Attribute>._sections = {}
125.208 - if <Name>defaults</Name> is <Name>None</Name>:
125.209 - <Attribute><Name>self</Name></Attribute>._defaults = {}
125.210 - else:
125.211 - <Attribute><Name>self</Name></Attribute>._defaults = <Name>defaults</Name>
125.212 -
125.213 - def <FunctionDef>defaults</FunctionDef>(<Name>self</Name>):
125.214 - return <Attribute><Name>self</Name></Attribute>._defaults
125.215 -
125.216 - def <FunctionDef>sections</FunctionDef>(<Name>self</Name>):
125.217 - """Return a list of section names, excluding [DEFAULT]"""
125.218 - # self._sections will never have [DEFAULT] in it
125.219 - return <Attribute><Attribute><Name>self</Name></Attribute></Attribute>._sections.<Call>keys</Call>()
125.220 -
125.221 - def <FunctionDef>add_section</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
125.222 - """Create a new section in the configuration.
125.223 -
125.224 - Raise DuplicateSectionError if a section by the specified name
125.225 - already exists.
125.226 - """
125.227 - if <Name>section</Name> in <Attribute><Name>self</Name></Attribute>._sections:
125.228 - raise <Call><Name>DuplicateSectionError</Name></Call>(<Name>section</Name>)
125.229 - <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>] = {}
125.230 -
125.231 - def <FunctionDef>has_section</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
125.232 - """Indicate whether the named section is present in the configuration.
125.233 -
125.234 - The DEFAULT section is not acknowledged.
125.235 - """
125.236 - return <Name>section</Name> in <Attribute><Name>self</Name></Attribute>._sections
125.237 -
125.238 - def <FunctionDef>options</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
125.239 - """Return a list of option names for the given section name."""
125.240 - try:
125.241 - <Name>opts</Name> = <Attribute><Name>self</Name></Attribute>._sections<Attribute>[<Name>section</Name>]</Attribute>.<Call>copy</Call>()
125.242 - except <Name>KeyError</Name>:
125.243 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
125.244 - <Attribute><Name>opts</Name></Attribute>.<Call>update</Call>(<Attribute><Name>self</Name></Attribute>._defaults)
125.245 - if '__name__' in <Name>opts</Name>:
125.246 - del <Name>opts</Name>['__name__']
125.247 - return <Attribute><Name>opts</Name></Attribute>.<Call>keys</Call>()
125.248 -
125.249 - def <FunctionDef>read</FunctionDef>(<Name>self</Name>, <Name>filenames</Name>):
125.250 - """Read and parse a filename or a list of filenames.
125.251 -
125.252 - Files that cannot be opened are silently ignored; this is
125.253 - designed so that you can specify a list of potential
125.254 - configuration file locations (e.g. current directory, user's
125.255 - home directory, systemwide directory), and all existing
125.256 - configuration files in the list will be read. A single
125.257 - filename may also be given.
125.258 - """
125.259 - if <Call><Name>isinstance</Name></Call>(<Name>filenames</Name>, <Name>basestring</Name>):
125.260 - <Name>filenames</Name> = [<Name>filenames</Name>]
125.261 - for <Name>filename</Name> in <Name>filenames</Name>:
125.262 - try:
125.263 - <Name>fp</Name> = <Call><Name>open</Name></Call>(<Name>filename</Name>)
125.264 - except <Name>IOError</Name>:
125.265 - continue
125.266 - <Attribute><Name>self</Name></Attribute>.<Call>_read</Call>(<Name>fp</Name>, <Name>filename</Name>)
125.267 - <Attribute><Name>fp</Name></Attribute>.<Call>close</Call>()
125.268 -
125.269 - def <FunctionDef>readfp</FunctionDef>(<Name>self</Name>, <Name>fp</Name>, <Name>filename</Name>=<Name>None</Name>):
125.270 - """Like read() but the argument must be a file-like object.
125.271 -
125.272 - The `fp' argument must have a `readline' method. Optional
125.273 - second argument is the `filename', which if not given, is
125.274 - taken from fp.name. If fp has no `name' attribute, `<???>' is
125.275 - used.
125.276 -
125.277 - """
125.278 - if <Name>filename</Name> is <Name>None</Name>:
125.279 - try:
125.280 - <Name>filename</Name> = <Attribute><Name>fp</Name></Attribute>.name
125.281 - except <Name>AttributeError</Name>:
125.282 - <Name>filename</Name> = '<???>'
125.283 - <Attribute><Name>self</Name></Attribute>.<Call>_read</Call>(<Name>fp</Name>, <Name>filename</Name>)
125.284 -
125.285 - def <FunctionDef>get</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
125.286 - <Name>opt</Name> = <Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Name>option</Name>)
125.287 - if <Name>section</Name> not in <Attribute><Name>self</Name></Attribute>._sections:
125.288 - if <Name>section</Name> != <Name>DEFAULTSECT</Name>:
125.289 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
125.290 - if <Name>opt</Name> in <Attribute><Name>self</Name></Attribute>._defaults:
125.291 - return <Attribute><Name>self</Name></Attribute>._defaults[<Name>opt</Name>]
125.292 - else:
125.293 - raise <Call><Name>NoOptionError</Name></Call>(<Name>option</Name>, <Name>section</Name>)
125.294 - elif <Name>opt</Name> in <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>]:
125.295 - return <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>][<Name>opt</Name>]
125.296 - elif <Name>opt</Name> in <Attribute><Name>self</Name></Attribute>._defaults:
125.297 - return <Attribute><Name>self</Name></Attribute>._defaults[<Name>opt</Name>]
125.298 - else:
125.299 - raise <Call><Name>NoOptionError</Name></Call>(<Name>option</Name>, <Name>section</Name>)
125.300 -
125.301 - def <FunctionDef>items</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
125.302 - try:
125.303 - <Name>d2</Name> = <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>]
125.304 - except <Name>KeyError</Name>:
125.305 - if <Name>section</Name> != <Name>DEFAULTSECT</Name>:
125.306 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
125.307 - <Name>d2</Name> = {}
125.308 - <Name>d</Name> = <Attribute><Attribute><Name>self</Name></Attribute></Attribute>._defaults.<Call>copy</Call>()
125.309 - <Attribute><Name>d</Name></Attribute>.<Call>update</Call>(<Name>d2</Name>)
125.310 - if "__name__" in <Name>d</Name>:
125.311 - del <Name>d</Name>["__name__"]
125.312 - return <Attribute><Name>d</Name></Attribute>.<Call>items</Call>()
125.313 -
125.314 - def <FunctionDef>_get</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>conv</Name>, <Name>option</Name>):
125.315 - return <Call><Name>conv</Name></Call>(<Attribute><Name>self</Name></Attribute>.<Call>get</Call>(<Name>section</Name>, <Name>option</Name>))
125.316 -
125.317 - def <FunctionDef>getint</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
125.318 - return <Attribute><Name>self</Name></Attribute>.<Call>_get</Call>(<Name>section</Name>, <Name>int</Name>, <Name>option</Name>)
125.319 -
125.320 - def <FunctionDef>getfloat</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
125.321 - return <Attribute><Name>self</Name></Attribute>.<Call>_get</Call>(<Name>section</Name>, <Name>float</Name>, <Name>option</Name>)
125.322 -
125.323 - <Name>_boolean_states</Name> = {'1': <Name>True</Name>, 'yes': <Name>True</Name>, 'true': <Name>True</Name>, 'on': <Name>True</Name>,
125.324 - '0': <Name>False</Name>, 'no': <Name>False</Name>, 'false': <Name>False</Name>, 'off': <Name>False</Name>}
125.325 -
125.326 - def <FunctionDef>getboolean</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
125.327 - <Name>v</Name> = <Attribute><Name>self</Name></Attribute>.<Call>get</Call>(<Name>section</Name>, <Name>option</Name>)
125.328 - if <Attribute><Name>v</Name></Attribute>.<Call>lower</Call>() not in <Attribute><Name>self</Name></Attribute>._boolean_states:
125.329 - raise <Name>ValueError</Name>, 'Not a boolean: %s' % <Name>v</Name>
125.330 - return <Attribute><Name>self</Name></Attribute>._boolean_states[<Attribute><Name>v</Name></Attribute>.<Call>lower</Call>()]
125.331 -
125.332 - def <FunctionDef>optionxform</FunctionDef>(<Name>self</Name>, <Name>optionstr</Name>):
125.333 - return <Attribute><Name>optionstr</Name></Attribute>.<Call>lower</Call>()
125.334 -
125.335 - def <FunctionDef>has_option</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
125.336 - """Check for the existence of a given option in a given section."""
125.337 - if not <Name>section</Name> or <Name>section</Name> == <Name>DEFAULTSECT</Name>:
125.338 - <Name>option</Name> = <Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Name>option</Name>)
125.339 - return <Name>option</Name> in <Attribute><Name>self</Name></Attribute>._defaults
125.340 - elif <Name>section</Name> not in <Attribute><Name>self</Name></Attribute>._sections:
125.341 - return <Name>False</Name>
125.342 - else:
125.343 - <Name>option</Name> = <Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Name>option</Name>)
125.344 - return (<Name>option</Name> in <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>]
125.345 - or <Name>option</Name> in <Attribute><Name>self</Name></Attribute>._defaults)
125.346 -
125.347 - def <FunctionDef>set</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>value</Name>):
125.348 - """Set an option."""
125.349 - if not <Name>section</Name> or <Name>section</Name> == <Name>DEFAULTSECT</Name>:
125.350 - <Name>sectdict</Name> = <Attribute><Name>self</Name></Attribute>._defaults
125.351 - else:
125.352 - try:
125.353 - <Name>sectdict</Name> = <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>]
125.354 - except <Name>KeyError</Name>:
125.355 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
125.356 - <Name>sectdict</Name>[<Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Name>option</Name>)] = <Name>value</Name>
125.357 -
125.358 - def <FunctionDef>write</FunctionDef>(<Name>self</Name>, <Name>fp</Name>):
125.359 - """Write an .ini-format representation of the configuration state."""
125.360 - if <Attribute><Name>self</Name></Attribute>._defaults:
125.361 - <Attribute><Name>fp</Name></Attribute>.<Call>write</Call>("[%s]\n" % <Name>DEFAULTSECT</Name>)
125.362 - for (<Name>key</Name>, <Name>value</Name>) in <Attribute><Attribute><Name>self</Name></Attribute></Attribute>._defaults.<Call>items</Call>():
125.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')))
125.364 - <Attribute><Name>fp</Name></Attribute>.<Call>write</Call>("\n")
125.365 - for <Name>section</Name> in <Attribute><Name>self</Name></Attribute>._sections:
125.366 - <Attribute><Name>fp</Name></Attribute>.<Call>write</Call>("[%s]\n" % <Name>section</Name>)
125.367 - for (<Name>key</Name>, <Name>value</Name>) in <Attribute><Name>self</Name></Attribute>._sections<Attribute>[<Name>section</Name>]</Attribute>.<Call>items</Call>():
125.368 - if <Name>key</Name> != "__name__":
125.369 - <Attribute><Name>fp</Name></Attribute>.<Call>write</Call>("%s = %s\n" %
125.370 - (<Name>key</Name>, <Attribute><Call><Name>str</Name></Call></Attribute>(<Name>value</Name>).<Call>replace</Call>('\n', '\n\t')))
125.371 - <Attribute><Name>fp</Name></Attribute>.<Call>write</Call>("\n")
125.372 -
125.373 - def <FunctionDef>remove_option</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
125.374 - """Remove an option."""
125.375 - if not <Name>section</Name> or <Name>section</Name> == <Name>DEFAULTSECT</Name>:
125.376 - <Name>sectdict</Name> = <Attribute><Name>self</Name></Attribute>._defaults
125.377 - else:
125.378 - try:
125.379 - <Name>sectdict</Name> = <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>]
125.380 - except <Name>KeyError</Name>:
125.381 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
125.382 - <Name>option</Name> = <Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Name>option</Name>)
125.383 - <Name>existed</Name> = <Name>option</Name> in <Name>sectdict</Name>
125.384 - if <Name>existed</Name>:
125.385 - del <Name>sectdict</Name>[<Name>option</Name>]
125.386 - return <Name>existed</Name>
125.387 -
125.388 - def <FunctionDef>remove_section</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
125.389 - """Remove a file section."""
125.390 - <Name>existed</Name> = <Name>section</Name> in <Attribute><Name>self</Name></Attribute>._sections
125.391 - if <Name>existed</Name>:
125.392 - del <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>]
125.393 - return <Name>existed</Name>
125.394 -
125.395 - #
125.396 - # Regular expressions for parsing section headers and options.
125.397 - #
125.398 - <Name>SECTCRE</Name> = <Attribute><Name>re</Name></Attribute>.<Call>compile</Call>(
125.399 - r'\[' # [
125.400 - r'(?P<header>[^]]+)' # very permissive!
125.401 - r'\]' # ]
125.402 - )
125.403 - <Name>OPTCRE</Name> = <Attribute><Name>re</Name></Attribute>.<Call>compile</Call>(
125.404 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
125.405 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
125.406 - # followed by separator
125.407 - # (either : or =), followed
125.408 - # by any # space/tab
125.409 - r'(?P<value>.*)$' # everything up to eol
125.410 - )
125.411 -
125.412 - def <FunctionDef>_read</FunctionDef>(<Name>self</Name>, <Name>fp</Name>, <Name>fpname</Name>):
125.413 - """Parse a sectioned setup file.
125.414 -
125.415 - The sections in setup file contains a title line at the top,
125.416 - indicated by a name in square brackets (`[]'), plus key/value
125.417 - options lines, indicated by `name: value' format lines.
125.418 - Continuations are represented by an embedded newline then
125.419 - leading whitespace. Blank lines, lines beginning with a '#',
125.420 - and just about everything else are ignored.
125.421 - """
125.422 - <Name>cursect</Name> = <Name>None</Name> # None, or a dictionary
125.423 - <Name>optname</Name> = <Name>None</Name>
125.424 - <Name>lineno</Name> = 0
125.425 - <Name>e</Name> = <Name>None</Name> # None, or an exception
125.426 - while <Name>True</Name>:
125.427 - <Name>line</Name> = <Attribute><Name>fp</Name></Attribute>.<Call>readline</Call>()
125.428 - if not <Name>line</Name>:
125.429 - break
125.430 - <Name>lineno</Name> = <Name>lineno</Name> + 1
125.431 - # comment or blank line?
125.432 - if <Attribute><Name>line</Name></Attribute>.<Call>strip</Call>() == '' or <Name>line</Name>[0] in '#;':
125.433 - continue
125.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":
125.435 - # no leading whitespace
125.436 - continue
125.437 - # continuation line?
125.438 - if <Name>line</Name><Attribute>[0]</Attribute>.<Call>isspace</Call>() and <Name>cursect</Name> is not <Name>None</Name> and <Name>optname</Name>:
125.439 - <Name>value</Name> = <Attribute><Name>line</Name></Attribute>.<Call>strip</Call>()
125.440 - if <Name>value</Name>:
125.441 - <Name>cursect</Name>[<Name>optname</Name>] = "%s\n%s" % (<Name>cursect</Name>[<Name>optname</Name>], <Name>value</Name>)
125.442 - # a section header or option header?
125.443 - else:
125.444 - # is it a section header?
125.445 - <Name>mo</Name> = <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.SECTCRE.<Call>match</Call>(<Name>line</Name>)
125.446 - if <Name>mo</Name>:
125.447 - <Name>sectname</Name> = <Attribute><Name>mo</Name></Attribute>.<Call>group</Call>('header')
125.448 - if <Name>sectname</Name> in <Attribute><Name>self</Name></Attribute>._sections:
125.449 - <Name>cursect</Name> = <Attribute><Name>self</Name></Attribute>._sections[<Name>sectname</Name>]
125.450 - elif <Name>sectname</Name> == <Name>DEFAULTSECT</Name>:
125.451 - <Name>cursect</Name> = <Attribute><Name>self</Name></Attribute>._defaults
125.452 - else:
125.453 - <Name>cursect</Name> = {'__name__': <Name>sectname</Name>}
125.454 - <Attribute><Name>self</Name></Attribute>._sections[<Name>sectname</Name>] = <Name>cursect</Name>
125.455 - # So sections can't start with a continuation line
125.456 - <Name>optname</Name> = <Name>None</Name>
125.457 - # no section header in the file?
125.458 - elif <Name>cursect</Name> is <Name>None</Name>:
125.459 - raise <Call><Name>MissingSectionHeaderError</Name></Call>(<Name>fpname</Name>, <Name>lineno</Name>, `<Name>line</Name>`)
125.460 - # an option line?
125.461 - else:
125.462 - <Name>mo</Name> = <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.OPTCRE.<Call>match</Call>(<Name>line</Name>)
125.463 - if <Name>mo</Name>:
125.464 - <Name>optname</Name>, <Name>vi</Name>, <Name>optval</Name> = <Attribute><Name>mo</Name></Attribute>.<Call>group</Call>('option', 'vi', 'value')
125.465 - if <Name>vi</Name> in ('=', ':') and ';' in <Name>optval</Name>:
125.466 - # ';' is a comment delimiter only if it follows
125.467 - # a spacing character
125.468 - <Name>pos</Name> = <Attribute><Name>optval</Name></Attribute>.<Call>find</Call>(';')
125.469 - if <Name>pos</Name> != -1 and <Name>optval</Name><Attribute>[<Name>pos</Name>-1]</Attribute>.<Call>isspace</Call>():
125.470 - <Name>optval</Name> = <Name>optval</Name>[:<Name>pos</Name>]
125.471 - <Name>optval</Name> = <Attribute><Name>optval</Name></Attribute>.<Call>strip</Call>()
125.472 - # allow empty values
125.473 - if <Name>optval</Name> == '""':
125.474 - <Name>optval</Name> = ''
125.475 - <Name>optname</Name> = <Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Attribute><Name>optname</Name></Attribute>.<Call>rstrip</Call>())
125.476 - <Name>cursect</Name>[<Name>optname</Name>] = <Name>optval</Name>
125.477 - else:
125.478 - # a non-fatal parsing error occurred. set up the
125.479 - # exception but keep going. the exception will be
125.480 - # raised at the end of the file and will contain a
125.481 - # list of all bogus lines
125.482 - if not <Name>e</Name>:
125.483 - <Name>e</Name> = <Call><Name>ParsingError</Name></Call>(<Name>fpname</Name>)
125.484 - <Attribute><Name>e</Name></Attribute>.<Call>append</Call>(<Name>lineno</Name>, `<Name>line</Name>`)
125.485 - # if any parsing errors occurred, raise an exception
125.486 - if <Name>e</Name>:
125.487 - raise <Name>e</Name>
125.488 -
125.489 -
125.490 -class <ClassDef>ConfigParser</ClassDef>(<Name>RawConfigParser</Name>):
125.491 -
125.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>):
125.493 - """Get an option value for a given section.
125.494 -
125.495 - All % interpolations are expanded in the return values, based on the
125.496 - defaults passed into the constructor, unless the optional argument
125.497 - `raw' is true. Additional substitutions may be provided using the
125.498 - `vars' argument, which must be a dictionary whose contents overrides
125.499 - any pre-existing defaults.
125.500 -
125.501 - The section DEFAULT is special.
125.502 - """
125.503 - <Name>d</Name> = <Attribute><Attribute><Name>self</Name></Attribute></Attribute>._defaults.<Call>copy</Call>()
125.504 - try:
125.505 - <Attribute><Name>d</Name></Attribute>.<Call>update</Call>(<Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>])
125.506 - except <Name>KeyError</Name>:
125.507 - if <Name>section</Name> != <Name>DEFAULTSECT</Name>:
125.508 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
125.509 - # Update with the entry specific variables
125.510 - if <Name>vars</Name> is not <Name>None</Name>:
125.511 - <Attribute><Name>d</Name></Attribute>.<Call>update</Call>(<Name>vars</Name>)
125.512 - <Name>option</Name> = <Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Name>option</Name>)
125.513 - try:
125.514 - <Name>value</Name> = <Name>d</Name>[<Name>option</Name>]
125.515 - except <Name>KeyError</Name>:
125.516 - raise <Call><Name>NoOptionError</Name></Call>(<Name>option</Name>, <Name>section</Name>)
125.517 -
125.518 - if <Name>raw</Name>:
125.519 - return <Name>value</Name>
125.520 - else:
125.521 - return <Attribute><Name>self</Name></Attribute>.<Call>_interpolate</Call>(<Name>section</Name>, <Name>option</Name>, <Name>value</Name>, <Name>d</Name>)
125.522 -
125.523 - def <FunctionDef>items</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>raw</Name>=<Name>False</Name>, <Name>vars</Name>=<Name>None</Name>):
125.524 - """Return a list of tuples with (name, value) for each option
125.525 - in the section.
125.526 -
125.527 - All % interpolations are expanded in the return values, based on the
125.528 - defaults passed into the constructor, unless the optional argument
125.529 - `raw' is true. Additional substitutions may be provided using the
125.530 - `vars' argument, which must be a dictionary whose contents overrides
125.531 - any pre-existing defaults.
125.532 -
125.533 - The section DEFAULT is special.
125.534 - """
125.535 - <Name>d</Name> = <Attribute><Attribute><Name>self</Name></Attribute></Attribute>._defaults.<Call>copy</Call>()
125.536 - try:
125.537 - <Attribute><Name>d</Name></Attribute>.<Call>update</Call>(<Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>])
125.538 - except <Name>KeyError</Name>:
125.539 - if <Name>section</Name> != <Name>DEFAULTSECT</Name>:
125.540 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
125.541 - # Update with the entry specific variables
125.542 - if <Name>vars</Name>:
125.543 - <Attribute><Name>d</Name></Attribute>.<Call>update</Call>(<Name>vars</Name>)
125.544 - <Name>options</Name> = <Attribute><Name>d</Name></Attribute>.<Call>keys</Call>()
125.545 - if "__name__" in <Name>options</Name>:
125.546 - <Attribute><Name>options</Name></Attribute>.<Call>remove</Call>("__name__")
125.547 - if <Name>raw</Name>:
125.548 - return [(<Name>option</Name>, <Name>d</Name>[<Name>option</Name>])
125.549 - for <Name>option</Name> in <Name>options</Name>]
125.550 - else:
125.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>))
125.552 - for <Name>option</Name> in <Name>options</Name>]
125.553 -
125.554 - def <FunctionDef>_interpolate</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>rawval</Name>, <Name>vars</Name>):
125.555 - # do the string interpolation
125.556 - <Name>value</Name> = <Name>rawval</Name>
125.557 - <Name>depth</Name> = <Name>MAX_INTERPOLATION_DEPTH</Name>
125.558 - while <Name>depth</Name>: # Loop through this until it's done
125.559 - <Name>depth</Name> -= 1
125.560 - if <Attribute><Name>value</Name></Attribute>.<Call>find</Call>("%(") != -1:
125.561 - try:
125.562 - <Name>value</Name> = <Name>value</Name> % <Name>vars</Name>
125.563 - except <Name>KeyError</Name>, <Name>e</Name>:
125.564 - raise <Call><Name>InterpolationMissingOptionError</Name></Call>(
125.565 - <Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>, <Name>e</Name>[0])
125.566 - else:
125.567 - break
125.568 - if <Attribute><Name>value</Name></Attribute>.<Call>find</Call>("%(") != -1:
125.569 - raise <Call><Name>InterpolationDepthError</Name></Call>(<Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>)
125.570 - return <Name>value</Name>
125.571 -
125.572 -
125.573 -class <ClassDef>SafeConfigParser</ClassDef>(<Name>ConfigParser</Name>):
125.574 -
125.575 - def <FunctionDef>_interpolate</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>rawval</Name>, <Name>vars</Name>):
125.576 - # do the string interpolation
125.577 - <Name>L</Name> = []
125.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)
125.579 - return <Attribute>''</Attribute>.<Call>join</Call>(<Name>L</Name>)
125.580 -
125.581 - <Name>_interpvar_match</Name> = <Attribute><Name>re</Name></Attribute>.<Attribute><Call>compile</Call></Attribute>(r"%\(([^)]+)\)s").match
125.582 -
125.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>):
125.584 - if <Name>depth</Name> > <Name>MAX_INTERPOLATION_DEPTH</Name>:
125.585 - raise <Call><Name>InterpolationDepthError</Name></Call>(<Name>option</Name>, <Name>section</Name>, <Name>rest</Name>)
125.586 - while <Name>rest</Name>:
125.587 - <Name>p</Name> = <Attribute><Name>rest</Name></Attribute>.<Call>find</Call>("%")
125.588 - if <Name>p</Name> < 0:
125.589 - <Attribute><Name>accum</Name></Attribute>.<Call>append</Call>(<Name>rest</Name>)
125.590 - return
125.591 - if <Name>p</Name> > 0:
125.592 - <Attribute><Name>accum</Name></Attribute>.<Call>append</Call>(<Name>rest</Name>[:<Name>p</Name>])
125.593 - <Name>rest</Name> = <Name>rest</Name>[<Name>p</Name>:]
125.594 - # p is no longer used
125.595 - <Name>c</Name> = <Name>rest</Name>[1:2]
125.596 - if <Name>c</Name> == "%":
125.597 - <Attribute><Name>accum</Name></Attribute>.<Call>append</Call>("%")
125.598 - <Name>rest</Name> = <Name>rest</Name>[2:]
125.599 - elif <Name>c</Name> == "(":
125.600 - <Name>m</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_interpvar_match</Call>(<Name>rest</Name>)
125.601 - if <Name>m</Name> is <Name>None</Name>:
125.602 - raise <Call><Name>InterpolationSyntaxError</Name></Call>(<Name>option</Name>, <Name>section</Name>,
125.603 - "bad interpolation variable reference %r" % <Name>rest</Name>)
125.604 - <Name>var</Name> = <Attribute><Name>m</Name></Attribute>.<Call>group</Call>(1)
125.605 - <Name>rest</Name> = <Name>rest</Name>[<Attribute><Name>m</Name></Attribute>.<Call>end</Call>():]
125.606 - try:
125.607 - <Name>v</Name> = <Name>map</Name>[<Name>var</Name>]
125.608 - except <Name>KeyError</Name>:
125.609 - raise <Call><Name>InterpolationMissingOptionError</Name></Call>(
125.610 - <Name>option</Name>, <Name>section</Name>, <Name>rest</Name>, <Name>var</Name>)
125.611 - if "%" in <Name>v</Name>:
125.612 - <Attribute><Name>self</Name></Attribute>.<Call>_interpolate_some</Call>(<Name>option</Name>, <Name>accum</Name>, <Name>v</Name>,
125.613 - <Name>section</Name>, <Name>map</Name>, <Name>depth</Name> + 1)
125.614 - else:
125.615 - <Attribute><Name>accum</Name></Attribute>.<Call>append</Call>(<Name>v</Name>)
125.616 - else:
125.617 - raise <Call><Name>InterpolationSyntaxError</Name></Call>(
125.618 - <Name>option</Name>, <Name>section</Name>,
125.619 - "'%' must be followed by '%' or '(', found: " + `<Name>ret</Name>`)
126.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.offsets Sun Jan 04 13:11:53 2015 -0600
126.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
126.3 @@ -1,616 +0,0 @@
126.4 -
126.5 -<Module><Expr><Str>"""Configuration file parser.
126.6 -
126.7 -A setup file consists of sections, lead by a "[section]" header,
126.8 -and followed by "name: value" entries, with continuations and such in
126.9 -the style of RFC 822.
126.10 -
126.11 - the same section, or values in a special [DEFAULT] section.
126.12 -
126.13 -For example:
126.14 -
126.15 - something: %(dir)s/whatever
126.16 -
126.17 -would resolve the "%(dir)s" to the value of dir. All reference
126.18 -expansions are done late, on demand.
126.19 -
126.20 -Intrinsic defaults can be specified by passing them into the
126.21 -ConfigParser constructor as a dictionary.
126.22 -
126.23 -class:
126.24 -
126.25 -ConfigParser -- responsible for parsing a list of
126.26 - configuration files, and managing the parsed database.
126.27 -
126.28 - methods:
126.29 -
126.30 - __init__(defaults=None)
126.31 - create the parser and specify a dictionary of intrinsic defaults. The
126.32 - keys must be strings, the values must be appropriate for %()s string
126.33 - interpolation. Note that `__name__' is always an intrinsic default;
126.34 - it's value is the section's name.
126.35 -
126.36 - sections()
126.37 - return all the configuration section names, sans DEFAULT
126.38 -
126.39 - has_section(section)
126.40 - return whether the given section exists
126.41 -
126.42 - has_option(section, option)
126.43 - return whether the given option exists in the given section
126.44 -
126.45 - options(section)
126.46 - return list of configuration options for the named section
126.47 -
126.48 - read(filenames)
126.49 - read and parse the list of named configuration files, given by
126.50 - name. A single filename is also allowed. Non-existing files
126.51 - are ignored.
126.52 -
126.53 - readfp(fp, filename=None)
126.54 - read and parse one configuration file, given as a file object.
126.55 - The filename defaults to fp.name; it is only used in error
126.56 - messages (if fp has no `name' attribute, the string `<???>' is used).
126.57 -
126.58 - get(section, option, raw=False, vars=None)
126.59 - return a string value for the named option. All % interpolations are
126.60 - expanded in the return values, based on the defaults passed into the
126.61 - constructor and the DEFAULT section. Additional substitutions may be
126.62 - provided using the `vars' argument, which must be a dictionary whose
126.63 - contents override any pre-existing defaults.
126.64 -
126.65 - getint(section, options)
126.66 - like get(), but convert value to an integer
126.67 -
126.68 - getfloat(section, options)
126.69 - like get(), but convert value to a float
126.70 -
126.71 - getboolean(section, options)
126.72 - like get(), but convert value to a boolean (currently case
126.73 - insensitively defined as 0, false, no, off for False, and 1, true,
126.74 - yes, on for True). Returns False or True.
126.75 -
126.76 - items(section, raw=False, vars=None)
126.77 - return a list of tuples with (name, value) for each option
126.78 - in the section.
126.79 -
126.80 - remove_section(section)
126.81 - remove the given file section and all its options
126.82 -
126.83 - remove_option(section, option)
126.84 - remove the given option from the given section
126.85 -
126.86 - set(section, option, value)
126.87 - set the given option
126.88 -
126.89 - write(fp)
126.90 - write the configuration state in .ini format
126.91 -"""</Str></Expr>
126.92 -
126.93 -<Import>import re</Import>
126.94 -
126.95 -<Assign><Name>__all__</Name> = <List>[<Str>"NoSectionError"</Str>, <Str>"DuplicateSectionError"</Str>, <Str>"NoOptionError"</Str>,
126.96 - <Str>"InterpolationError"</Str>, <Str>"InterpolationDepthError"</Str>,
126.97 - <Str>"InterpolationSyntaxError"</Str>, <Str>"ParsingError"</Str>,
126.98 - <Str>"MissingSectionHeaderError"</Str>, <Str>"ConfigParser"</Str>, <Str>"SafeConfigParser"</Str>,
126.99 - <Str>"DEFAULTSECT"</Str>, <Str>"MAX_INTERPOLATION_DEPTH"</Str>]</List></Assign>
126.100 -
126.101 -<Assign><Name>DEFAULTSECT</Name> = <Str>"DEFAULT"</Str></Assign>
126.102 -
126.103 -<Assign><Name>MAX_INTERPOLATION_DEPTH</Name> = <Num>10</Num></Assign>
126.104 -
126.105 -
126.106 -
126.107 -# exception classes
126.108 -<ClassDef>class Error(<Name>Exception</Name>):
126.109 - <Expr><Str>"""Base class for ConfigParser exceptions."""</Str></Expr>
126.110 -
126.111 - <FunctionDef>def __init__(<Name>self</Name>, <Name>msg</Name>=<Str>''</Str>):
126.112 - <Assign><Attribute><Name>self</Name>.message</Attribute> = <Name>msg</Name></Assign>
126.113 - <Expr><Call><Attribute><Name>Exception</Name>.__init__</Attribute>(<Name>self</Name>, <Name>msg</Name>)</Call></Expr>
126.114 -
126.115 - </FunctionDef> <FunctionDef>def __repr__(<Name>self</Name>):
126.116 - <Return>return <Attribute><Name>self</Name>.message</Attribute></Return>
126.117 -
126.118 - </FunctionDef> <Assign><Name>__str__</Name> = <Name>__repr__</Name></Assign>
126.119 -
126.120 -</ClassDef><ClassDef>class NoSectionError(<Name>Error</Name>):
126.121 - <Expr><Str>"""Rasssised when no section matches a requested option."""</Str></Expr>
126.122 -
126.123 - <FunctionDef>def __init__(<Name>self</Name>, <Name>section</Name>):
126.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>
126.125 - <Assign><Attribute><Name>self</Name>.section</Attribute> = <Name>section</Name></Assign>
126.126 -
126.127 -</FunctionDef></ClassDef><ClassDef>class DuplicateSectionError(<Name>Error</Name>):
126.128 - <Expr><Str>"""Raised when a section is multiply-created."""</Str></Expr>
126.129 -
126.130 - <FunctionDef>def __init__(<Name>self</Name>, <Name>section</Name>):
126.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>
126.132 - <Assign><Attribute><Name>self</Name>.section</Attribute> = <Name>section</Name></Assign>
126.133 -
126.134 -</FunctionDef></ClassDef><ClassDef>class NoOptionError(<Name>Error</Name>):
126.135 - <Expr><Str>"""A requested option was not found."""</Str></Expr>
126.136 -
126.137 - <FunctionDef>def __init__(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>):
126.138 - <Expr><Call><Attribute><Name>Error</Name>.__init__</Attribute>(<Name>self</Name>, <BinOp><Str>"No option %r in section: %r"</Str> %
126.139 - <Tuple>(<Name>option</Name>, <Name>section</Name>)</Tuple></BinOp>)</Call></Expr>
126.140 - <Assign><Attribute><Name>self</Name>.option</Attribute> = <Name>option</Name></Assign>
126.141 - <Assign><Attribute><Name>self</Name>.section</Attribute> = <Name>section</Name></Assign>
126.142 -
126.143 -</FunctionDef></ClassDef><ClassDef>class InterpolationError(<Name>Error</Name>):
126.144 - <Expr><Str>"""Base class for interpolation-related exceptions."""</Str></Expr>
126.145 -
126.146 - <FunctionDef>def __init__(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>msg</Name>):
126.147 - <Expr><Call><Attribute><Name>Error</Name>.__init__</Attribute>(<Name>self</Name>, <Name>msg</Name>)</Call></Expr>
126.148 - <Assign><Attribute><Name>self</Name>.option</Attribute> = <Name>option</Name></Assign>
126.149 - <Assign><Attribute><Name>self</Name>.section</Attribute> = <Name>section</Name></Assign>
126.150 -
126.151 -</FunctionDef></ClassDef><ClassDef>class InterpolationMissingOptionError(<Name>InterpolationError</Name>):
126.152 - <Expr><Str>"""A string substitution required a setting which was not available."""</Str></Expr>
126.153 -
126.154 - <FunctionDef>def __init__(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>, <Name>reference</Name>):
126.155 - <Assign><Name>msg</Name> = <BinOp>(<Str>"Bad value substitution:\n"
126.156 - "\tsection: [%s]\n"
126.157 - "\toption : %s\n"
126.158 - "\tkey : %s\n"
126.159 - "\trawval : %s\n"</Str>
126.160 - % <Tuple>(<Name>section</Name>, <Name>option</Name>, <Name>reference</Name>, <Name>rawval</Name>)</Tuple>)</BinOp></Assign>
126.161 - <Expr><Call><Attribute><Name>InterpolationError</Name>.__init__</Attribute>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>msg</Name>)</Call></Expr>
126.162 - <Assign><Attribute><Name>self</Name>.reference</Attribute> = <Name>reference</Name></Assign>
126.163 -
126.164 -</FunctionDef></ClassDef><ClassDef>class InterpolationSyntaxError(<Name>InterpolationError</Name>):
126.165 - <Expr><Str>"""Raised when the source text into which substitutions are made
126.166 - does not conform to the required syntax."""</Str></Expr>
126.167 -
126.168 -</ClassDef><ClassDef>class InterpolationDepthError(<Name>InterpolationError</Name>):
126.169 - <Expr><Str>"""Raised when substitutions are nested too deeply."""</Str></Expr>
126.170 -
126.171 - <FunctionDef>def __init__(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>):
126.172 - <Assign><Name>msg</Name> = <BinOp>(<Str>"Value interpolation too deeply recursive:\n"
126.173 - "\tsection: [%s]\n"
126.174 - "\toption : %s\n"
126.175 - "\trawval : %s\n"</Str>
126.176 - % <Tuple>(<Name>section</Name>, <Name>option</Name>, <Name>rawval</Name>)</Tuple>)</BinOp></Assign>
126.177 - <Expr><Call><Attribute><Name>InterpolationError</Name>.__init__</Attribute>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>msg</Name>)</Call></Expr>
126.178 -
126.179 -</FunctionDef></ClassDef><ClassDef>class ParsingError(<Name>Error</Name>):
126.180 - <Expr><Str>"""Raised when a configuration file does not follow legal syntax."""</Str></Expr>
126.181 -
126.182 - <FunctionDef>def __init__(<Name>self</Name>, <Name>filename</Name>):
126.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>
126.184 - <Assign><Attribute><Name>self</Name>.filename</Attribute> = <Name>filename</Name></Assign>
126.185 - <Assign><Attribute><Name>self</Name>.errors</Attribute> = <List>[]</List></Assign>
126.186 -
126.187 - </FunctionDef> <FunctionDef>def append(<Name>self</Name>, <Name>lineno</Name>, <Name>line</Name>):
126.188 - <Expr><Call><Attribute><Attribute><Name>self</Name>.errors</Attribute>.append</Attribute>(<Tuple>(<Name>lineno</Name>, <Name>line</Name>)</Tuple>)</Call></Expr>
126.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>
126.190 -
126.191 -</FunctionDef></ClassDef><ClassDef>class MissingSectionHeaderError(<Name>ParsingError</Name>):
126.192 - <Expr><Str>"""Raised when a key-value pair is found before any section header."""</Str></Expr>
126.193 -
126.194 - <FunctionDef>def __init__(<Name>self</Name>, <Name>filename</Name>, <Name>lineno</Name>, <Name>line</Name>):
126.195 - <Expr><Call><Attribute><Name>Error</Name>.__init__</Attribute>(
126.196 - <Name>self</Name>,
126.197 - <BinOp><Str>'File contains no section headers.\nfile: %s, line: %d\n%s'</Str> %
126.198 - <Tuple>(<Name>filename</Name>, <Name>lineno</Name>, <Name>line</Name>)</Tuple></BinOp>)</Call></Expr>
126.199 - <Assign><Attribute><Name>self</Name>.filename</Attribute> = <Name>filename</Name></Assign>
126.200 - <Assign><Attribute><Name>self</Name>.lineno</Attribute> = <Name>lineno</Name></Assign>
126.201 - <Assign><Attribute><Name>self</Name>.line</Attribute> = <Name>line</Name></Assign>
126.202 -
126.203 -
126.204 -
126.205 -</FunctionDef></ClassDef><ClassDef>class RawConfigParser:
126.206 - <FunctionDef>def __init__(<Name>self</Name>, <Name>defaults</Name>=<Name>None</Name>):
126.207 - <Assign><Attribute><Name>self</Name>._sections</Attribute> = <Dict>{}</Dict></Assign>
126.208 - <If>if <Compare><Name>defaults</Name> is <Name>None</Name></Compare>:
126.209 - <Assign><Attribute><Name>self</Name>._defaults</Attribute> = <Dict>{}</Dict></Assign>
126.210 - else:
126.211 - <Assign><Attribute><Name>self</Name>._defaults</Attribute> = <Name>defaults</Name></Assign>
126.212 -
126.213 - </If></FunctionDef> <FunctionDef>def defaults(<Name>self</Name>):
126.214 - <Return>return <Attribute><Name>self</Name>._defaults</Attribute></Return>
126.215 -
126.216 - </FunctionDef> <FunctionDef>def sections(<Name>self</Name>):
126.217 - <Expr><Str>"""Return a list of section names, excluding [DEFAULT]"""</Str></Expr>
126.218 - # self._sections will never have [DEFAULT] in it
126.219 - <Return>return <Call><Attribute><Attribute><Name>self</Name>._sections</Attribute>.keys</Attribute>()</Call></Return>
126.220 -
126.221 - </FunctionDef> <FunctionDef>def add_section(<Name>self</Name>, <Name>section</Name>):
126.222 - <Expr><Str>"""Create a new section in the configuration.
126.223 -
126.224 - Raise DuplicateSectionError if a section by the specified name
126.225 - already exists.
126.226 - """</Str></Expr>
126.227 - <If>if <Compare><Name>section</Name> in <Attribute><Name>self</Name>._sections</Attribute></Compare>:
126.228 - <Raise>raise <Call><Name>DuplicateSectionError</Name>(<Name>section</Name>)</Call></Raise>
126.229 - </If> <Assign><Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript> = <Dict>{}</Dict></Assign>
126.230 -
126.231 - </FunctionDef> <FunctionDef>def has_section(<Name>self</Name>, <Name>section</Name>):
126.232 - <Expr><Str>"""Indicate whether the named section is present in the configuration.
126.233 -
126.234 - The DEFAULT section is not acknowledged.
126.235 - """</Str></Expr>
126.236 - <Return>return <Compare><Name>section</Name> in <Attribute><Name>self</Name>._sections</Attribute></Compare></Return>
126.237 -
126.238 - </FunctionDef> <FunctionDef>def options(<Name>self</Name>, <Name>section</Name>):
126.239 - <Expr><Str>"""Return a list of option names for the given section name."""</Str></Expr>
126.240 - <TryExcept>try:
126.241 - <Assign><Name>opts</Name> = <Call><Attribute><Name>self</Name>._sections</Attribute><Attribute><Subscript>[<Index><Name>section</Name></Index>]</Subscript>.copy</Attribute>()</Call></Assign>
126.242 - <ExceptHandler>except <Name>KeyError</Name>:
126.243 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
126.244 - </ExceptHandler></TryExcept> <Expr><Call><Attribute><Name>opts</Name>.update</Attribute>(<Attribute><Name>self</Name>._defaults</Attribute>)</Call></Expr>
126.245 - <If>if <Compare><Str>'__name__'</Str> in <Name>opts</Name></Compare>:
126.246 - <Delete>del <Subscript><Name>opts</Name>[<Index><Str>'__name__'</Str></Index>]</Subscript></Delete>
126.247 - </If> <Return>return <Call><Attribute><Name>opts</Name>.keys</Attribute>()</Call></Return>
126.248 -
126.249 - </FunctionDef> <FunctionDef>def read(<Name>self</Name>, <Name>filenames</Name>):
126.250 - <Expr><Str>"""Read and parse a filename or a list of filenames.
126.251 -
126.252 - Files that cannot be opened are silently ignored; this is
126.253 - designed so that you can specify a list of potential
126.254 - configuration file locations (e.g. current directory, user's
126.255 - home directory, systemwide directory), and all existing
126.256 - configuration files in the list will be read. A single
126.257 - filename may also be given.
126.258 - """</Str></Expr>
126.259 - <If>if <Call><Name>isinstance</Name>(<Name>filenames</Name>, <Name>basestring</Name>)</Call>:
126.260 - <Assign><Name>filenames</Name> = <List>[<Name>filenames</Name>]</List></Assign>
126.261 - </If> <For>for <Name>filename</Name> in <Name>filenames</Name>:
126.262 - <TryExcept>try:
126.263 - <Assign><Name>fp</Name> = <Call><Name>open</Name>(<Name>filename</Name>)</Call></Assign>
126.264 - <ExceptHandler>except <Name>IOError</Name>:
126.265 - <Continue>continue</Continue>
126.266 - </ExceptHandler></TryExcept> <Expr><Call><Attribute><Name>self</Name>._read</Attribute>(<Name>fp</Name>, <Name>filename</Name>)</Call></Expr>
126.267 - <Expr><Call><Attribute><Name>fp</Name>.close</Attribute>()</Call></Expr>
126.268 -
126.269 - </For></FunctionDef> <FunctionDef>def readfp(<Name>self</Name>, <Name>fp</Name>, <Name>filename</Name>=<Name>None</Name>):
126.270 - <Expr><Str>"""Like read() but the argument must be a file-like object.
126.271 -
126.272 - The `fp' argument must have a `readline' method. Optional
126.273 - second argument is the `filename', which if not given, is
126.274 - taken from fp.name. If fp has no `name' attribute, `<???>' is
126.275 - used.
126.276 -
126.277 - """</Str></Expr>
126.278 - <If>if <Compare><Name>filename</Name> is <Name>None</Name></Compare>:
126.279 - <TryExcept>try:
126.280 - <Assign><Name>filename</Name> = <Attribute><Name>fp</Name>.name</Attribute></Assign>
126.281 - <ExceptHandler>except <Name>AttributeError</Name>:
126.282 - <Assign><Name>filename</Name> = <Str>'<???>'</Str></Assign>
126.283 - </ExceptHandler></TryExcept></If> <Expr><Call><Attribute><Name>self</Name>._read</Attribute>(<Name>fp</Name>, <Name>filename</Name>)</Call></Expr>
126.284 -
126.285 - </FunctionDef> <FunctionDef>def get(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
126.286 - <Assign><Name>opt</Name> = <Call><Attribute><Name>self</Name>.optionxform</Attribute>(<Name>option</Name>)</Call></Assign>
126.287 - <If>if <Compare><Name>section</Name> not in <Attribute><Name>self</Name>._sections</Attribute></Compare>:
126.288 - <If>if <Compare><Name>section</Name> != <Name>DEFAULTSECT</Name></Compare>:
126.289 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
126.290 - </If> <If>if <Compare><Name>opt</Name> in <Attribute><Name>self</Name>._defaults</Attribute></Compare>:
126.291 - <Return>return <Subscript><Attribute><Name>self</Name>._defaults</Attribute>[<Index><Name>opt</Name></Index>]</Subscript></Return>
126.292 - else:
126.293 - <Raise>raise <Call><Name>NoOptionError</Name>(<Name>option</Name>, <Name>section</Name>)</Call></Raise>
126.294 - </If> <If>elif <Compare><Name>opt</Name> in <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript></Compare>:
126.295 - <Return>return <Subscript><Attribute><Name>self</Name>._sections</Attribute><Subscript>[<Index><Name>section</Name></Index>]</Subscript>[<Index><Name>opt</Name></Index>]</Subscript></Return>
126.296 - <If>elif <Compare><Name>opt</Name> in <Attribute><Name>self</Name>._defaults</Attribute></Compare>:
126.297 - <Return>return <Subscript><Attribute><Name>self</Name>._defaults</Attribute>[<Index><Name>opt</Name></Index>]</Subscript></Return>
126.298 - else:
126.299 - <Raise>raise <Call><Name>NoOptionError</Name>(<Name>option</Name>, <Name>section</Name>)</Call></Raise>
126.300 -
126.301 - </If></If></If></FunctionDef> <FunctionDef>def items(<Name>self</Name>, <Name>section</Name>):
126.302 - <TryExcept>try:
126.303 - <Assign><Name>d2</Name> = <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript></Assign>
126.304 - <ExceptHandler>except <Name>KeyError</Name>:
126.305 - <If>if <Compare><Name>section</Name> != <Name>DEFAULTSECT</Name></Compare>:
126.306 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
126.307 - </If> <Assign><Name>d2</Name> = <Dict>{}</Dict></Assign>
126.308 - </ExceptHandler></TryExcept> <Assign><Name>d</Name> = <Call><Attribute><Attribute><Name>self</Name>._defaults</Attribute>.copy</Attribute>()</Call></Assign>
126.309 - <Expr><Call><Attribute><Name>d</Name>.update</Attribute>(<Name>d2</Name>)</Call></Expr>
126.310 - <If>if <Compare><Str>"__name__"</Str> in <Name>d</Name></Compare>:
126.311 - <Delete>del <Subscript><Name>d</Name>[<Index><Str>"__name__"</Str></Index>]</Subscript></Delete>
126.312 - </If> <Return>return <Call><Attribute><Name>d</Name>.items</Attribute>()</Call></Return>
126.313 -
126.314 - </FunctionDef> <FunctionDef>def _get(<Name>self</Name>, <Name>section</Name>, <Name>conv</Name>, <Name>option</Name>):
126.315 - <Return>return <Call><Name>conv</Name>(<Call><Attribute><Name>self</Name>.get</Attribute>(<Name>section</Name>, <Name>option</Name>)</Call>)</Call></Return>
126.316 -
126.317 - </FunctionDef> <FunctionDef>def getint(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
126.318 - <Return>return <Call><Attribute><Name>self</Name>._get</Attribute>(<Name>section</Name>, <Name>int</Name>, <Name>option</Name>)</Call></Return>
126.319 -
126.320 - </FunctionDef> <FunctionDef>def getfloat(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
126.321 - <Return>return <Call><Attribute><Name>self</Name>._get</Attribute>(<Name>section</Name>, <Name>float</Name>, <Name>option</Name>)</Call></Return>
126.322 -
126.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>,
126.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>
126.325 -
126.326 - <FunctionDef>def getboolean(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
126.327 - <Assign><Name>v</Name> = <Call><Attribute><Name>self</Name>.get</Attribute>(<Name>section</Name>, <Name>option</Name>)</Call></Assign>
126.328 - <If>if <Compare><Call><Attribute><Name>v</Name>.lower</Attribute>()</Call> not in <Attribute><Name>self</Name>._boolean_states</Attribute></Compare>:
126.329 - <Raise>raise <Name>ValueError</Name>, <BinOp><Str>'Not a boolean: %s'</Str> % <Name>v</Name></BinOp></Raise>
126.330 - </If> <Return>return <Subscript><Attribute><Name>self</Name>._boolean_states</Attribute>[<Index><Call><Attribute><Name>v</Name>.lower</Attribute>()</Call></Index>]</Subscript></Return>
126.331 -
126.332 - </FunctionDef> <FunctionDef>def optionxform(<Name>self</Name>, <Name>optionstr</Name>):
126.333 - <Return>return <Call><Attribute><Name>optionstr</Name>.lower</Attribute>()</Call></Return>
126.334 -
126.335 - </FunctionDef> <FunctionDef>def has_option(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
126.336 - <Expr><Str>"""Check for the existence of a given option in a given section."""</Str></Expr>
126.337 - <If>if <BoolOp><UnaryOp>not <Name>section</Name></UnaryOp> or <Compare><Name>section</Name> == <Name>DEFAULTSECT</Name></Compare></BoolOp>:
126.338 - <Assign><Name>option</Name> = <Call><Attribute><Name>self</Name>.optionxform</Attribute>(<Name>option</Name>)</Call></Assign>
126.339 - <Return>return <Compare><Name>option</Name> in <Attribute><Name>self</Name>._defaults</Attribute></Compare></Return>
126.340 - <If>elif <Compare><Name>section</Name> not in <Attribute><Name>self</Name>._sections</Attribute></Compare>:
126.341 - <Return>return <Name>False</Name></Return>
126.342 - else:
126.343 - <Assign><Name>option</Name> = <Call><Attribute><Name>self</Name>.optionxform</Attribute>(<Name>option</Name>)</Call></Assign>
126.344 - <Return>return <BoolOp>(<Compare><Name>option</Name> in <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript></Compare>
126.345 - or <Compare><Name>option</Name> in <Attribute><Name>self</Name>._defaults</Attribute></Compare>)</BoolOp></Return>
126.346 -
126.347 - </If></If></FunctionDef> <FunctionDef>def set(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>value</Name>):
126.348 - <Expr><Str>"""Set an option."""</Str></Expr>
126.349 - <If>if <BoolOp><UnaryOp>not <Name>section</Name></UnaryOp> or <Compare><Name>section</Name> == <Name>DEFAULTSECT</Name></Compare></BoolOp>:
126.350 - <Assign><Name>sectdict</Name> = <Attribute><Name>self</Name>._defaults</Attribute></Assign>
126.351 - else:
126.352 - <TryExcept>try:
126.353 - <Assign><Name>sectdict</Name> = <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript></Assign>
126.354 - <ExceptHandler>except <Name>KeyError</Name>:
126.355 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
126.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>
126.357 -
126.358 - </FunctionDef> <FunctionDef>def write(<Name>self</Name>, <Name>fp</Name>):
126.359 - <Expr><Str>"""Write an .ini-format representation of the configuration state."""</Str></Expr>
126.360 - <If>if <Attribute><Name>self</Name>._defaults</Attribute>:
126.361 - <Expr><Call><Attribute><Name>fp</Name>.write</Attribute>(<BinOp><Str>"[%s]\n"</Str> % <Name>DEFAULTSECT</Name></BinOp>)</Call></Expr>
126.362 - <For>for <Tuple>(<Name>key</Name>, <Name>value</Name>)</Tuple> in <Call><Attribute><Attribute><Name>self</Name>._defaults</Attribute>.items</Attribute>()</Call>:
126.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>
126.364 - </For> <Expr><Call><Attribute><Name>fp</Name>.write</Attribute>(<Str>"\n"</Str>)</Call></Expr>
126.365 - </If> <For>for <Name>section</Name> in <Attribute><Name>self</Name>._sections</Attribute>:
126.366 - <Expr><Call><Attribute><Name>fp</Name>.write</Attribute>(<BinOp><Str>"[%s]\n"</Str> % <Name>section</Name></BinOp>)</Call></Expr>
126.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>:
126.368 - <If>if <Compare><Name>key</Name> != <Str>"__name__"</Str></Compare>:
126.369 - <Expr><Call><Attribute><Name>fp</Name>.write</Attribute>(<BinOp><Str>"%s = %s\n"</Str> %
126.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>
126.371 - </If></For> <Expr><Call><Attribute><Name>fp</Name>.write</Attribute>(<Str>"\n"</Str>)</Call></Expr>
126.372 -
126.373 - </For></FunctionDef> <FunctionDef>def remove_option(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
126.374 - <Expr><Str>"""Remove an option."""</Str></Expr>
126.375 - <If>if <BoolOp><UnaryOp>not <Name>section</Name></UnaryOp> or <Compare><Name>section</Name> == <Name>DEFAULTSECT</Name></Compare></BoolOp>:
126.376 - <Assign><Name>sectdict</Name> = <Attribute><Name>self</Name>._defaults</Attribute></Assign>
126.377 - else:
126.378 - <TryExcept>try:
126.379 - <Assign><Name>sectdict</Name> = <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript></Assign>
126.380 - <ExceptHandler>except <Name>KeyError</Name>:
126.381 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
126.382 - </ExceptHandler></TryExcept></If> <Assign><Name>option</Name> = <Call><Attribute><Name>self</Name>.optionxform</Attribute>(<Name>option</Name>)</Call></Assign>
126.383 - <Assign><Name>existed</Name> = <Compare><Name>option</Name> in <Name>sectdict</Name></Compare></Assign>
126.384 - <If>if <Name>existed</Name>:
126.385 - <Delete>del <Subscript><Name>sectdict</Name>[<Index><Name>option</Name></Index>]</Subscript></Delete>
126.386 - </If> <Return>return <Name>existed</Name></Return>
126.387 -
126.388 - </FunctionDef> <FunctionDef>def remove_section(<Name>self</Name>, <Name>section</Name>):
126.389 - <Expr><Str>"""Remove a file section."""</Str></Expr>
126.390 - <Assign><Name>existed</Name> = <Compare><Name>section</Name> in <Attribute><Name>self</Name>._sections</Attribute></Compare></Assign>
126.391 - <If>if <Name>existed</Name>:
126.392 - <Delete>del <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript></Delete>
126.393 - </If> <Return>return <Name>existed</Name></Return>
126.394 -
126.395 - #
126.396 - # Regular expressions for parsing section headers and options.
126.397 - #
126.398 - </FunctionDef> <Assign><Name>SECTCRE</Name> = <Call><Attribute><Name>re</Name>.compile</Attribute>(
126.399 - <Str>r'\[' # [
126.400 - r'(?P<header>[^]]+)' # very permissive!
126.401 - r'\]'</Str> # ]
126.402 - )</Call></Assign>
126.403 - <Assign><Name>OPTCRE</Name> = <Call><Attribute><Name>re</Name>.compile</Attribute>(
126.404 - <Str>r'(?P<option>[^:=\s][^:=]*)' # very permissive!
126.405 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
126.406 - # followed by separator
126.407 - # (either : or =), followed
126.408 - # by any # space/tab
126.409 - r'(?P<value>.*)$'</Str> # everything up to eol
126.410 - )</Call></Assign>
126.411 -
126.412 - <FunctionDef>def _read(<Name>self</Name>, <Name>fp</Name>, <Name>fpname</Name>):
126.413 - <Expr><Str>"""Parse a sectioned setup file.
126.414 -
126.415 - The sections in setup file contains a title line at the top,
126.416 - indicated by a name in square brackets (`[]'), plus key/value
126.417 - options lines, indicated by `name: value' format lines.
126.418 - Continuations are represented by an embedded newline then
126.419 - leading whitespace. Blank lines, lines beginning with a '#',
126.420 - and just about everything else are ignored.
126.421 - """</Str></Expr>
126.422 - <Assign><Name>cursect</Name> = <Name>None</Name></Assign> # None, or a dictionary
126.423 - <Assign><Name>optname</Name> = <Name>None</Name></Assign>
126.424 - <Assign><Name>lineno</Name> = <Num>0</Num></Assign>
126.425 - <Assign><Name>e</Name> = <Name>None</Name></Assign> # None, or an exception
126.426 - <While>while <Name>True</Name>:
126.427 - <Assign><Name>line</Name> = <Call><Attribute><Name>fp</Name>.readline</Attribute>()</Call></Assign>
126.428 - <If>if <UnaryOp>not <Name>line</Name></UnaryOp>:
126.429 - <Break>break</Break>
126.430 - </If> <Assign><Name>lineno</Name> = <BinOp><Name>lineno</Name> + <Num>1</Num></BinOp></Assign>
126.431 - # comment or blank line?
126.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>:
126.433 - <Continue>continue</Continue>
126.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>:
126.435 - # no leading whitespace
126.436 - <Continue>continue</Continue>
126.437 - # continuation line?
126.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>:
126.439 - <Assign><Name>value</Name> = <Call><Attribute><Name>line</Name>.strip</Attribute>()</Call></Assign>
126.440 - <If>if <Name>value</Name>:
126.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>
126.442 - # a section header or option header?
126.443 - </If> else:
126.444 - # is it a section header?
126.445 - <Assign><Name>mo</Name> = <Call><Attribute><Attribute><Name>self</Name>.SECTCRE</Attribute>.match</Attribute>(<Name>line</Name>)</Call></Assign>
126.446 - <If>if <Name>mo</Name>:
126.447 - <Assign><Name>sectname</Name> = <Call><Attribute><Name>mo</Name>.group</Attribute>(<Str>'header'</Str>)</Call></Assign>
126.448 - <If>if <Compare><Name>sectname</Name> in <Attribute><Name>self</Name>._sections</Attribute></Compare>:
126.449 - <Assign><Name>cursect</Name> = <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>sectname</Name></Index>]</Subscript></Assign>
126.450 - <If>elif <Compare><Name>sectname</Name> == <Name>DEFAULTSECT</Name></Compare>:
126.451 - <Assign><Name>cursect</Name> = <Attribute><Name>self</Name>._defaults</Attribute></Assign>
126.452 - else:
126.453 - <Assign><Name>cursect</Name> = <Dict>{<Str>'__name__'</Str>: <Name>sectname</Name>}</Dict></Assign>
126.454 - <Assign><Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>sectname</Name></Index>]</Subscript> = <Name>cursect</Name></Assign>
126.455 - # So sections can't start with a continuation line
126.456 - </If></If> <Assign><Name>optname</Name> = <Name>None</Name></Assign>
126.457 - # no section header in the file?
126.458 - <If>elif <Compare><Name>cursect</Name> is <Name>None</Name></Compare>:
126.459 - <Raise>raise <Call><Name>MissingSectionHeaderError</Name>(<Name>fpname</Name>, <Name>lineno</Name>, <Repr>`<Name>line</Name>`</Repr>)</Call></Raise>
126.460 - # an option line?
126.461 - else:
126.462 - <Assign><Name>mo</Name> = <Call><Attribute><Attribute><Name>self</Name>.OPTCRE</Attribute>.match</Attribute>(<Name>line</Name>)</Call></Assign>
126.463 - <If>if <Name>mo</Name>:
126.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>
126.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>:
126.466 - # ';' is a comment delimiter only if it follows
126.467 - # a spacing character
126.468 - <Assign><Name>pos</Name> = <Call><Attribute><Name>optval</Name>.find</Attribute>(<Str>';'</Str>)</Call></Assign>
126.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>:
126.470 - <Assign><Name>optval</Name> = <Subscript><Name>optval</Name>[<Slice>:<Name>pos</Name></Slice>]</Subscript></Assign>
126.471 - </If></If> <Assign><Name>optval</Name> = <Call><Attribute><Name>optval</Name>.strip</Attribute>()</Call></Assign>
126.472 - # allow empty values
126.473 - <If>if <Compare><Name>optval</Name> == <Str>'""'</Str></Compare>:
126.474 - <Assign><Name>optval</Name> = <Str>''</Str></Assign>
126.475 - </If> <Assign><Name>optname</Name> = <Call><Attribute><Name>self</Name>.optionxform</Attribute>(<Call><Attribute><Name>optname</Name>.rstrip</Attribute>()</Call>)</Call></Assign>
126.476 - <Assign><Subscript><Name>cursect</Name>[<Index><Name>optname</Name></Index>]</Subscript> = <Name>optval</Name></Assign>
126.477 - else:
126.478 - # a non-fatal parsing error occurred. set up the
126.479 - # exception but keep going. the exception will be
126.480 - # raised at the end of the file and will contain a
126.481 - # list of all bogus lines
126.482 - <If>if <UnaryOp>not <Name>e</Name></UnaryOp>:
126.483 - <Assign><Name>e</Name> = <Call><Name>ParsingError</Name>(<Name>fpname</Name>)</Call></Assign>
126.484 - </If> <Expr><Call><Attribute><Name>e</Name>.append</Attribute>(<Name>lineno</Name>, <Repr>`<Name>line</Name>`</Repr>)</Call></Expr>
126.485 - # if any parsing errors occurred, raise an exception
126.486 - </If></If></If></If></While> <If>if <Name>e</Name>:
126.487 - <Raise>raise <Name>e</Name></Raise>
126.488 -
126.489 -
126.490 -</If></FunctionDef></ClassDef><ClassDef>class ConfigParser(<Name>RawConfigParser</Name>):
126.491 -
126.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>):
126.493 - <Expr><Str>"""Get an option value for a given section.
126.494 -
126.495 - All % interpolations are expanded in the return values, based on the
126.496 - defaults passed into the constructor, unless the optional argument
126.497 - `raw' is true. Additional substitutions may be provided using the
126.498 - `vars' argument, which must be a dictionary whose contents overrides
126.499 - any pre-existing defaults.
126.500 -
126.501 - The section DEFAULT is special.
126.502 - """</Str></Expr>
126.503 - <Assign><Name>d</Name> = <Call><Attribute><Attribute><Name>self</Name>._defaults</Attribute>.copy</Attribute>()</Call></Assign>
126.504 - <TryExcept>try:
126.505 - <Expr><Call><Attribute><Name>d</Name>.update</Attribute>(<Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript>)</Call></Expr>
126.506 - <ExceptHandler>except <Name>KeyError</Name>:
126.507 - <If>if <Compare><Name>section</Name> != <Name>DEFAULTSECT</Name></Compare>:
126.508 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
126.509 - # Update with the entry specific variables
126.510 - </If></ExceptHandler></TryExcept> <If>if <Compare><Name>vars</Name> is not <Name>None</Name></Compare>:
126.511 - <Expr><Call><Attribute><Name>d</Name>.update</Attribute>(<Name>vars</Name>)</Call></Expr>
126.512 - </If> <Assign><Name>option</Name> = <Call><Attribute><Name>self</Name>.optionxform</Attribute>(<Name>option</Name>)</Call></Assign>
126.513 - <TryExcept>try:
126.514 - <Assign><Name>value</Name> = <Subscript><Name>d</Name>[<Index><Name>option</Name></Index>]</Subscript></Assign>
126.515 - <ExceptHandler>except <Name>KeyError</Name>:
126.516 - <Raise>raise <Call><Name>NoOptionError</Name>(<Name>option</Name>, <Name>section</Name>)</Call></Raise>
126.517 -
126.518 - </ExceptHandler></TryExcept> <If>if <Name>raw</Name>:
126.519 - <Return>return <Name>value</Name></Return>
126.520 - else:
126.521 - <Return>return <Call><Attribute><Name>self</Name>._interpolate</Attribute>(<Name>section</Name>, <Name>option</Name>, <Name>value</Name>, <Name>d</Name>)</Call></Return>
126.522 -
126.523 - </If></FunctionDef> <FunctionDef>def items(<Name>self</Name>, <Name>section</Name>, <Name>raw</Name>=<Name>False</Name>, <Name>vars</Name>=<Name>None</Name>):
126.524 - <Expr><Str>"""Return a list of tuples with (name, value) for each option
126.525 - in the section.
126.526 -
126.527 - All % interpolations are expanded in the return values, based on the
126.528 - defaults passed into the constructor, unless the optional argument
126.529 - `raw' is true. Additional substitutions may be provided using the
126.530 - `vars' argument, which must be a dictionary whose contents overrides
126.531 - any pre-existing defaults.
126.532 -
126.533 - The section DEFAULT is special.
126.534 - """</Str></Expr>
126.535 - <Assign><Name>d</Name> = <Call><Attribute><Attribute><Name>self</Name>._defaults</Attribute>.copy</Attribute>()</Call></Assign>
126.536 - <TryExcept>try:
126.537 - <Expr><Call><Attribute><Name>d</Name>.update</Attribute>(<Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript>)</Call></Expr>
126.538 - <ExceptHandler>except <Name>KeyError</Name>:
126.539 - <If>if <Compare><Name>section</Name> != <Name>DEFAULTSECT</Name></Compare>:
126.540 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
126.541 - # Update with the entry specific variables
126.542 - </If></ExceptHandler></TryExcept> <If>if <Name>vars</Name>:
126.543 - <Expr><Call><Attribute><Name>d</Name>.update</Attribute>(<Name>vars</Name>)</Call></Expr>
126.544 - </If> <Assign><Name>options</Name> = <Call><Attribute><Name>d</Name>.keys</Attribute>()</Call></Assign>
126.545 - <If>if <Compare><Str>"__name__"</Str> in <Name>options</Name></Compare>:
126.546 - <Expr><Call><Attribute><Name>options</Name>.remove</Attribute>(<Str>"__name__"</Str>)</Call></Expr>
126.547 - </If> <If>if <Name>raw</Name>:
126.548 - <Return>return <ListComp>[<Tuple>(<Name>option</Name>, <Subscript><Name>d</Name>[<Index><Name>option</Name></Index>]</Subscript>)</Tuple>
126.549 - for <Name>option</Name> in <Name>options</Name>]</ListComp></Return>
126.550 - else:
126.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>
126.552 - for <Name>option</Name> in <Name>options</Name>]</ListComp></Return>
126.553 -
126.554 - </If></FunctionDef> <FunctionDef>def _interpolate(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>rawval</Name>, <Name>vars</Name>):
126.555 - # do the string interpolation
126.556 - <Assign><Name>value</Name> = <Name>rawval</Name></Assign>
126.557 - <Assign><Name>depth</Name> = <Name>MAX_INTERPOLATION_DEPTH</Name></Assign>
126.558 - <While>while <Name>depth</Name>: # Loop through this until it's done
126.559 - <AugAssign><Name>depth</Name> -= <Num>1</Num></AugAssign>
126.560 - <If>if <Compare><Call><Attribute><Name>value</Name>.find</Attribute>(<Str>"%("</Str>)</Call> != <Num>-1</Num></Compare>:
126.561 - <TryExcept>try:
126.562 - <Assign><Name>value</Name> = <BinOp><Name>value</Name> % <Name>vars</Name></BinOp></Assign>
126.563 - <ExceptHandler>except <Name>KeyError</Name>, <Name>e</Name>:
126.564 - <Raise>raise <Call><Name>InterpolationMissingOptionError</Name>(
126.565 - <Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>, <Subscript><Name>e</Name>[<Index><Num>0</Num></Index>]</Subscript>)</Call></Raise>
126.566 - </ExceptHandler></TryExcept> else:
126.567 - <Break>break</Break>
126.568 - </If></While> <If>if <Compare><Call><Attribute><Name>value</Name>.find</Attribute>(<Str>"%("</Str>)</Call> != <Num>-1</Num></Compare>:
126.569 - <Raise>raise <Call><Name>InterpolationDepthError</Name>(<Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>)</Call></Raise>
126.570 - </If> <Return>return <Name>value</Name></Return>
126.571 -
126.572 -
126.573 -</FunctionDef></ClassDef><ClassDef>class SafeConfigParser(<Name>ConfigParser</Name>):
126.574 -
126.575 - <FunctionDef>def _interpolate(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>rawval</Name>, <Name>vars</Name>):
126.576 - # do the string interpolation
126.577 - <Assign><Name>L</Name> = <List>[]</List></Assign>
126.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>
126.579 - <Return>return <Call><Attribute><Str>''</Str>.join</Attribute>(<Name>L</Name>)</Call></Return>
126.580 -
126.581 - </FunctionDef> <Assign><Name>_interpvar_match</Name> = <Attribute><Attribute><Name>re</Name>.compile</Attribute><Call>(<Str>r"%\(([^)]+)\)s"</Str>)</Call>.match</Attribute></Assign>
126.582 -
126.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>):
126.584 - <If>if <Compare><Name>depth</Name> > <Name>MAX_INTERPOLATION_DEPTH</Name></Compare>:
126.585 - <Raise>raise <Call><Name>InterpolationDepthError</Name>(<Name>option</Name>, <Name>section</Name>, <Name>rest</Name>)</Call></Raise>
126.586 - </If> <While>while <Name>rest</Name>:
126.587 - <Assign><Name>p</Name> = <Call><Attribute><Name>rest</Name>.find</Attribute>(<Str>"%"</Str>)</Call></Assign>
126.588 - <If>if <Compare><Name>p</Name> < <Num>0</Num></Compare>:
126.589 - <Expr><Call><Attribute><Name>accum</Name>.append</Attribute>(<Name>rest</Name>)</Call></Expr>
126.590 - <Return>return</Return>
126.591 - </If> <If>if <Compare><Name>p</Name> > <Num>0</Num></Compare>:
126.592 - <Expr><Call><Attribute><Name>accum</Name>.append</Attribute>(<Subscript><Name>rest</Name>[<Slice>:<Name>p</Name></Slice>]</Subscript>)</Call></Expr>
126.593 - <Assign><Name>rest</Name> = <Subscript><Name>rest</Name>[<Slice><Name>p</Name>:</Slice>]</Subscript></Assign>
126.594 - # p is no longer used
126.595 - </If> <Assign><Name>c</Name> = <Subscript><Name>rest</Name>[<Slice><Num>1</Num>:<Num>2</Num></Slice>]</Subscript></Assign>
126.596 - <If>if <Compare><Name>c</Name> == <Str>"%"</Str></Compare>:
126.597 - <Expr><Call><Attribute><Name>accum</Name>.append</Attribute>(<Str>"%"</Str>)</Call></Expr>
126.598 - <Assign><Name>rest</Name> = <Subscript><Name>rest</Name>[<Slice><Num>2</Num>:</Slice>]</Subscript></Assign>
126.599 - <If>elif <Compare><Name>c</Name> == <Str>"("</Str></Compare>:
126.600 - <Assign><Name>m</Name> = <Call><Attribute><Name>self</Name>._interpvar_match</Attribute>(<Name>rest</Name>)</Call></Assign>
126.601 - <If>if <Compare><Name>m</Name> is <Name>None</Name></Compare>:
126.602 - <Raise>raise <Call><Name>InterpolationSyntaxError</Name>(<Name>option</Name>, <Name>section</Name>,
126.603 - <BinOp><Str>"bad interpolation variable reference %r"</Str> % <Name>rest</Name></BinOp>)</Call></Raise>
126.604 - </If> <Assign><Name>var</Name> = <Call><Attribute><Name>m</Name>.group</Attribute>(<Num>1</Num>)</Call></Assign>
126.605 - <Assign><Name>rest</Name> = <Subscript><Name>rest</Name>[<Slice><Call><Attribute><Name>m</Name>.end</Attribute>()</Call>:</Slice>]</Subscript></Assign>
126.606 - <TryExcept>try:
126.607 - <Assign><Name>v</Name> = <Subscript><Name>map</Name>[<Index><Name>var</Name></Index>]</Subscript></Assign>
126.608 - <ExceptHandler>except <Name>KeyError</Name>:
126.609 - <Raise>raise <Call><Name>InterpolationMissingOptionError</Name>(
126.610 - <Name>option</Name>, <Name>section</Name>, <Name>rest</Name>, <Name>var</Name>)</Call></Raise>
126.611 - </ExceptHandler></TryExcept> <If>if <Compare><Str>"%"</Str> in <Name>v</Name></Compare>:
126.612 - <Expr><Call><Attribute><Name>self</Name>._interpolate_some</Attribute>(<Name>option</Name>, <Name>accum</Name>, <Name>v</Name>,
126.613 - <Name>section</Name>, <Name>map</Name>, <BinOp><Name>depth</Name> + <Num>1</Num></BinOp>)</Call></Expr>
126.614 - else:
126.615 - <Expr><Call><Attribute><Name>accum</Name>.append</Attribute>(<Name>v</Name>)</Call></Expr>
126.616 - </If> else:
126.617 - <Raise>raise <Call><Name>InterpolationSyntaxError</Name>(
126.618 - <Name>option</Name>, <Name>section</Name>,
126.619 - <BinOp><Str>"'%' must be followed by '%' or '(', found: "</Str> + <Repr>`<Name>ret</Name>`</Repr></BinOp>)</Call></Raise></If></If></While></FunctionDef></ClassDef></Module>
127.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.scopes Sun Jan 04 13:11:53 2015 -0600
127.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
127.3 @@ -1,548 +0,0 @@
127.4 -=============================================
127.5 -<file-top>: Module : OffsetRange[0,22066>
127.6 -ConfigParser [bound][class][def][read][node=ClassDef]
127.7 -DEFAULTSECT [bound][data][read][node=Name]
127.8 -DuplicateSectionError [bound][class][def][read][called][node=ClassDef]
127.9 -Error [bound][private][class][def][read][node=ClassDef]
127.10 -Exception [private][read][UNRESOLVED][node=Name]
127.11 -InterpolationDepthError [bound][class][def][read][called][node=ClassDef]
127.12 -InterpolationError [bound][class][def][read][node=ClassDef]
127.13 -InterpolationMissingOptionError [bound][private][class][def][read][called][node=ClassDef]
127.14 -InterpolationSyntaxError [bound][class][def][read][called][node=ClassDef]
127.15 -MAX_INTERPOLATION_DEPTH [bound][data][read][node=Name]
127.16 -MissingSectionHeaderError [bound][class][def][read][called][node=ClassDef]
127.17 -NoOptionError [bound][class][def][read][called][node=ClassDef]
127.18 -NoSectionError [bound][class][def][read][called][node=ClassDef]
127.19 -ParsingError [bound][class][def][read][called][node=ClassDef]
127.20 -RawConfigParser [bound][private][class][def][read][node=ClassDef]
127.21 -SafeConfigParser [bound][class][def][node=ClassDef]
127.22 -__all__ [bound][data][node=Name]
127.23 -re [bound][imported][private][data][read][node=Import]
127.24 -
127.25 - =============================================
127.26 - class Error: ClassDef : OffsetRange[3377,3627>
127.27 - __init__ [bound][private][function][def][node=FunctionDef]
127.28 - __repr__ [bound][private][function][def][read][node=FunctionDef]
127.29 - __str__ [bound][private][function][alias][node=FunctionDef]
127.30 - ------ Attributes ---------------------------------------
127.31 - message : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.32 -
127.33 - =============================================
127.34 - __init__: FunctionDef : OffsetRange[3456,3553>
127.35 - Exception [free][private][read][node=Name]
127.36 - msg [bound][param][private][data][read][node=Name]
127.37 - self [bound][param][private][data][read][node=Name]
127.38 - ------ Attributes ---------------------------------------
127.39 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.40 -
127.41 - =============================================
127.42 - __repr__: FunctionDef : OffsetRange[3554,3606>
127.43 - self [bound][param][private][data][read][node=Name]
127.44 - ------ Attributes ---------------------------------------
127.45 - message : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
127.46 -
127.47 - =============================================
127.48 - class NoSectionError: ClassDef : OffsetRange[3627,3844>
127.49 - __init__ [bound][function][def][node=FunctionDef]
127.50 - ------ Attributes ---------------------------------------
127.51 - section : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.52 -
127.53 - =============================================
127.54 - __init__: FunctionDef : OffsetRange[3726,3844>
127.55 - Error [free][read][node=Name]
127.56 - section [bound][param][data][read][node=Name]
127.57 - self [bound][param][data][read][node=Name]
127.58 - ------ Attributes ---------------------------------------
127.59 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.60 -
127.61 - =============================================
127.62 - class DuplicateSectionError: ClassDef : OffsetRange[3844,4067>
127.63 - __init__ [bound][function][def][node=FunctionDef]
127.64 - ------ Attributes ---------------------------------------
127.65 - section : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.66 -
127.67 - =============================================
127.68 - __init__: FunctionDef : OffsetRange[3938,4067>
127.69 - Error [free][read][node=Name]
127.70 - section [bound][param][data][read][node=Name]
127.71 - self [bound][param][data][read][node=Name]
127.72 - ------ Attributes ---------------------------------------
127.73 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.74 -
127.75 - =============================================
127.76 - class NoOptionError: ClassDef : OffsetRange[4067,4345>
127.77 - __init__ [bound][function][def][node=FunctionDef]
127.78 - ------ Attributes ---------------------------------------
127.79 - option : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.80 - section : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.81 -
127.82 - =============================================
127.83 - __init__: FunctionDef : OffsetRange[4144,4345>
127.84 - Error [free][read][node=Name]
127.85 - option [bound][param][data][read][node=Name]
127.86 - section [bound][param][data][read][node=Name]
127.87 - self [bound][param][data][read][node=Name]
127.88 - ------ Attributes ---------------------------------------
127.89 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.90 -
127.91 - =============================================
127.92 - class InterpolationError: ClassDef : OffsetRange[4345,4579>
127.93 - __init__ [bound][function][def][node=FunctionDef]
127.94 - ------ Attributes ---------------------------------------
127.95 - option : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.96 - section : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.97 -
127.98 - =============================================
127.99 - __init__: FunctionDef : OffsetRange[4442,4579>
127.100 - Error [free][read][node=Name]
127.101 - msg [bound][param][data][read][node=Name]
127.102 - option [bound][param][data][read][node=Name]
127.103 - section [bound][param][data][read][node=Name]
127.104 - self [bound][param][data][read][node=Name]
127.105 - ------ Attributes ---------------------------------------
127.106 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.107 -
127.108 - =============================================
127.109 - class InterpolationMissingOptionError: ClassDef : OffsetRange[4579,5107>
127.110 - __init__ [bound][private][function][def][node=FunctionDef]
127.111 - ------ Attributes ---------------------------------------
127.112 - reference : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.113 -
127.114 - =============================================
127.115 - __init__: FunctionDef : OffsetRange[4719,5107>
127.116 - InterpolationError [free][private][read][node=Name]
127.117 - msg [bound][private][data][read][node=Name]
127.118 - option [bound][param][private][data][read][node=Name]
127.119 - rawval [bound][param][private][data][read][node=Name]
127.120 - reference [bound][param][private][data][read][node=Name]
127.121 - section [bound][param][private][data][read][node=Name]
127.122 - self [bound][param][private][data][read][node=Name]
127.123 - ------ Attributes ---------------------------------------
127.124 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.125 -
127.126 - =============================================
127.127 - class InterpolationSyntaxError: ClassDef : OffsetRange[5107,5277>
127.128 -
127.129 - =============================================
127.130 - class InterpolationDepthError: ClassDef : OffsetRange[5277,5708>
127.131 - __init__ [bound][function][def][node=FunctionDef]
127.132 -
127.133 - =============================================
127.134 - __init__: FunctionDef : OffsetRange[5392,5708>
127.135 - InterpolationError [free][read][node=Name]
127.136 - msg [bound][data][read][node=Name]
127.137 - option [bound][param][data][read][node=Name]
127.138 - rawval [bound][param][data][read][node=Name]
127.139 - section [bound][param][data][read][node=Name]
127.140 - self [bound][param][data][read][node=Name]
127.141 - ------ Attributes ---------------------------------------
127.142 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.143 -
127.144 - =============================================
127.145 - class ParsingError: ClassDef : OffsetRange[5708,6121>
127.146 - __init__ [bound][function][def][node=FunctionDef]
127.147 - append [bound][function][def][node=FunctionDef]
127.148 - ------ Attributes ---------------------------------------
127.149 - errors : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.150 - filename : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.151 -
127.152 - =============================================
127.153 - __init__: FunctionDef : OffsetRange[5813,5982>
127.154 - Error [free][read][node=Name]
127.155 - filename [bound][param][data][read][node=Name]
127.156 - self [bound][param][data][read][node=Name]
127.157 - ------ Attributes ---------------------------------------
127.158 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.159 -
127.160 - =============================================
127.161 - append: FunctionDef : OffsetRange[5983,6121>
127.162 - line [bound][param][data][read][node=Name]
127.163 - lineno [bound][param][data][read][node=Name]
127.164 - self [bound][param][data][read][node=Name]
127.165 - ------ Attributes ---------------------------------------
127.166 - errors : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
127.167 - message : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
127.168 -
127.169 - =============================================
127.170 - class MissingSectionHeaderError: ClassDef : OffsetRange[6121,6536>
127.171 - __init__ [bound][function][def][node=FunctionDef]
127.172 - ------ Attributes ---------------------------------------
127.173 - filename : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.174 - line : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.175 - lineno : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.176 -
127.177 - =============================================
127.178 - __init__: FunctionDef : OffsetRange[6248,6536>
127.179 - Error [free][read][node=Name]
127.180 - filename [bound][param][data][read][node=Name]
127.181 - line [bound][param][data][read][node=Name]
127.182 - lineno [bound][param][data][read][node=Name]
127.183 - self [bound][param][data][read][node=Name]
127.184 -
127.185 - =============================================
127.186 - class RawConfigParser: ClassDef : OffsetRange[6536,17314>
127.187 - False [free][private][read][node=Name]
127.188 - None [free][private][read][node=Name]
127.189 - OPTCRE [bound][private][data][node=Name]
127.190 - SECTCRE [bound][private][data][node=Name]
127.191 - True [free][private][read][node=Name]
127.192 - __init__ [bound][private][function][def][node=FunctionDef]
127.193 - _boolean_states [bound][private][data][node=Name]
127.194 - _get [bound][private][function][def][node=FunctionDef]
127.195 - _read [bound][private][function][def][node=FunctionDef]
127.196 - add_section [bound][private][function][def][node=FunctionDef]
127.197 - defaults [bound][private][function][def][node=FunctionDef]
127.198 - get [bound][private][function][def][node=FunctionDef]
127.199 - getboolean [bound][private][function][def][node=FunctionDef]
127.200 - getfloat [bound][private][function][def][node=FunctionDef]
127.201 - getint [bound][private][function][def][node=FunctionDef]
127.202 - has_option [bound][private][function][def][node=FunctionDef]
127.203 - has_section [bound][private][function][def][node=FunctionDef]
127.204 - items [bound][private][function][def][node=FunctionDef]
127.205 - options [bound][private][function][def][node=FunctionDef]
127.206 - optionxform [bound][private][function][def][node=FunctionDef]
127.207 - re [free][private][read][node=Name]
127.208 - read [bound][private][function][def][node=FunctionDef]
127.209 - readfp [bound][private][function][def][node=FunctionDef]
127.210 - remove_option [bound][private][function][def][node=FunctionDef]
127.211 - remove_section [bound][private][function][def][node=FunctionDef]
127.212 - sections [bound][private][function][def][node=FunctionDef]
127.213 - set [bound][private][function][def][node=FunctionDef]
127.214 - write [bound][private][function][def][node=FunctionDef]
127.215 - ------ Attributes ---------------------------------------
127.216 - _defaults : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.217 - _sections : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
127.218 -
127.219 - =============================================
127.220 - __init__: FunctionDef : OffsetRange[6563,6743>
127.221 - None [free][private][read][node=Name]
127.222 - defaults [bound][param][private][data][read][node=Name]
127.223 - self [bound][param][private][data][read][node=Name]
127.224 -
127.225 - =============================================
127.226 - defaults: FunctionDef : OffsetRange[6744,6798>
127.227 - self [bound][param][private][data][read][node=Name]
127.228 - ------ Attributes ---------------------------------------
127.229 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.230 -
127.231 - =============================================
127.232 - sections: FunctionDef : OffsetRange[6799,6983>
127.233 - self [bound][param][private][data][read][node=Name]
127.234 - ------ Attributes ---------------------------------------
127.235 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.236 -
127.237 - =============================================
127.238 - add_section: FunctionDef : OffsetRange[6984,7306>
127.239 - DuplicateSectionError [free][private][read][called][node=Name]
127.240 - section [bound][param][private][data][read][node=Name]
127.241 - self [bound][param][private][data][read][node=Name]
127.242 - ------ Attributes ---------------------------------------
127.243 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.244 -
127.245 - =============================================
127.246 - has_section: FunctionDef : OffsetRange[7307,7525>
127.247 - section [bound][param][private][data][read][node=Name]
127.248 - self [bound][param][private][data][read][node=Name]
127.249 - ------ Attributes ---------------------------------------
127.250 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.251 -
127.252 - =============================================
127.253 - options: FunctionDef : OffsetRange[7526,7887>
127.254 - KeyError [free][private][read][node=Name]
127.255 - NoSectionError [free][private][read][called][node=Name]
127.256 - opts [bound][private][data][read][node=Name]
127.257 - section [bound][param][private][data][read][node=Name]
127.258 - self [bound][param][private][data][read][node=Name]
127.259 - ------ Attributes ---------------------------------------
127.260 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.261 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.262 -
127.263 - =============================================
127.264 - read: FunctionDef : OffsetRange[7888,8636>
127.265 - IOError [free][private][read][node=Name]
127.266 - basestring [free][private][read][node=Name]
127.267 - filename [bound][private][data][read][node=Name]
127.268 - filenames [bound][param][private][data][read][node=Name]
127.269 - fp [bound][private][data][read][node=Name]
127.270 - isinstance [free][private][read][called][node=Name]
127.271 - open [free][private][read][called][node=Name]
127.272 - self [bound][param][private][data][read][node=Name]
127.273 - ------ Attributes ---------------------------------------
127.274 - _read : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
127.275 -
127.276 - =============================================
127.277 - readfp: FunctionDef : OffsetRange[8637,9162>
127.278 - AttributeError [free][private][read][node=Name]
127.279 - None [free][private][read][node=Name]
127.280 - filename [bound][param][private][data][read][node=Name]
127.281 - fp [bound][param][private][data][read][node=Name]
127.282 - self [bound][param][private][data][read][node=Name]
127.283 - ------ Attributes ---------------------------------------
127.284 - _read : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
127.285 -
127.286 - =============================================
127.287 - get: FunctionDef : OffsetRange[9163,9748>
127.288 - DEFAULTSECT [free][private][read][node=Name]
127.289 - NoOptionError [free][private][read][called][node=Name]
127.290 - NoSectionError [free][private][read][called][node=Name]
127.291 - opt [bound][private][data][read][node=Name]
127.292 - option [bound][param][private][data][read][node=Name]
127.293 - section [bound][param][private][data][read][node=Name]
127.294 - self [bound][param][private][data][read][node=Name]
127.295 - ------ Attributes ---------------------------------------
127.296 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.297 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.298 - optionxform : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.299 -
127.300 - =============================================
127.301 - items: FunctionDef : OffsetRange[9749,10101>
127.302 - DEFAULTSECT [free][private][read][node=Name]
127.303 - KeyError [free][private][read][node=Name]
127.304 - NoSectionError [free][private][read][called][node=Name]
127.305 - d [bound][private][data][read][node=Name]
127.306 - d2 [bound][private][data][read][node=Name]
127.307 - section [bound][param][private][data][read][node=Name]
127.308 - self [bound][param][private][data][read][node=Name]
127.309 - ------ Attributes ---------------------------------------
127.310 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.311 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.312 -
127.313 - =============================================
127.314 - _get: FunctionDef : OffsetRange[10102,10192>
127.315 - conv [bound][param][private][data][read][called][node=Name]
127.316 - option [bound][param][private][data][read][node=Name]
127.317 - section [bound][param][private][data][read][node=Name]
127.318 - self [bound][param][private][data][read][node=Name]
127.319 - ------ Attributes ---------------------------------------
127.320 - get : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.321 -
127.322 - =============================================
127.323 - getint: FunctionDef : OffsetRange[10193,10279>
127.324 - int [free][private][read][node=Name]
127.325 - option [bound][param][private][data][read][node=Name]
127.326 - section [bound][param][private][data][read][node=Name]
127.327 - self [bound][param][private][data][read][node=Name]
127.328 - ------ Attributes ---------------------------------------
127.329 - _get : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
127.330 -
127.331 - =============================================
127.332 - getfloat: FunctionDef : OffsetRange[10280,10370>
127.333 - float [free][private][read][node=Name]
127.334 - option [bound][param][private][data][read][node=Name]
127.335 - section [bound][param][private][data][read][node=Name]
127.336 - self [bound][param][private][data][read][node=Name]
127.337 - ------ Attributes ---------------------------------------
127.338 - _get : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
127.339 -
127.340 - =============================================
127.341 - getboolean: FunctionDef : OffsetRange[10523,10755>
127.342 - ValueError [free][private][read][node=Name]
127.343 - option [bound][param][private][data][read][node=Name]
127.344 - section [bound][param][private][data][read][node=Name]
127.345 - self [bound][param][private][data][read][node=Name]
127.346 - v [bound][private][data][read][node=Name]
127.347 - ------ Attributes ---------------------------------------
127.348 - _boolean_states : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.349 - get : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.350 -
127.351 - =============================================
127.352 - optionxform: FunctionDef : OffsetRange[10756,10827>
127.353 - optionstr [bound][param][private][data][read][node=Name]
127.354 - self [bound][param][private][data][unused][node=Name]
127.355 -
127.356 - =============================================
127.357 - has_option: FunctionDef : OffsetRange[10828,11319>
127.358 - DEFAULTSECT [free][private][read][node=Name]
127.359 - False [free][private][read][node=Name]
127.360 - option [bound][param][private][data][read][node=Name]
127.361 - section [bound][param][private][data][read][node=Name]
127.362 - self [bound][param][private][data][read][node=Name]
127.363 - ------ Attributes ---------------------------------------
127.364 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.365 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.366 - optionxform : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.367 -
127.368 - =============================================
127.369 - set: FunctionDef : OffsetRange[11320,11688>
127.370 - DEFAULTSECT [free][private][read][node=Name]
127.371 - KeyError [free][private][read][node=Name]
127.372 - NoSectionError [free][private][read][called][node=Name]
127.373 - option [bound][param][private][data][read][node=Name]
127.374 - sectdict [bound][private][data][read][node=Name]
127.375 - section [bound][param][private][data][read][node=Name]
127.376 - self [bound][param][private][data][read][node=Name]
127.377 - value [bound][param][private][data][read][node=Name]
127.378 - ------ Attributes ---------------------------------------
127.379 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.380 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.381 - optionxform : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.382 -
127.383 - =============================================
127.384 - write: FunctionDef : OffsetRange[11689,12350>
127.385 - DEFAULTSECT [free][private][read][node=Name]
127.386 - fp [bound][param][private][data][read][node=Name]
127.387 - key [bound][private][data][read][node=Name]
127.388 - section [bound][private][data][read][node=Name]
127.389 - self [bound][param][private][data][read][node=Name]
127.390 - str [free][private][read][called][node=Name]
127.391 - value [bound][private][data][read][node=Name]
127.392 - ------ Attributes ---------------------------------------
127.393 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.394 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.395 -
127.396 - =============================================
127.397 - remove_option: FunctionDef : OffsetRange[12351,12829>
127.398 - DEFAULTSECT [free][private][read][node=Name]
127.399 - KeyError [free][private][read][node=Name]
127.400 - NoSectionError [free][private][read][called][node=Name]
127.401 - existed [bound][private][data][read][node=Name]
127.402 - option [bound][param][private][data][read][node=Name]
127.403 - sectdict [bound][private][data][read][node=Name]
127.404 - section [bound][param][private][data][read][node=Name]
127.405 - self [bound][param][private][data][read][node=Name]
127.406 - ------ Attributes ---------------------------------------
127.407 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.408 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.409 - optionxform : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.410 -
127.411 - =============================================
127.412 - remove_section: FunctionDef : OffsetRange[12830,13112>
127.413 - existed [bound][private][data][read][node=Name]
127.414 - section [bound][param][private][data][read][node=Name]
127.415 - self [bound][param][private][data][read][node=Name]
127.416 - ------ Attributes ---------------------------------------
127.417 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.418 -
127.419 - =============================================
127.420 - _read: FunctionDef : OffsetRange[13768,17314>
127.421 - DEFAULTSECT [free][private][read][node=Name]
127.422 - MissingSectionHeaderError [free][private][read][called][node=Name]
127.423 - None [free][private][read][node=Name]
127.424 - ParsingError [free][private][read][called][node=Name]
127.425 - True [free][private][read][node=Name]
127.426 - cursect [bound][private][data][read][node=Name]
127.427 - e [bound][private][data][read][node=Name]
127.428 - fp [bound][param][private][data][read][node=Name]
127.429 - fpname [bound][param][private][data][read][node=Name]
127.430 - line [bound][private][data][read][node=Name]
127.431 - lineno [bound][private][data][read][node=Name]
127.432 - mo [bound][private][data][read][node=Name]
127.433 - optname [bound][private][data][read][node=Name]
127.434 - optval [bound][private][data][read][node=Name]
127.435 - pos [bound][private][data][read][node=Name]
127.436 - sectname [bound][private][data][read][node=Name]
127.437 - self [bound][param][private][data][read][node=Name]
127.438 - value [bound][private][data][read][node=Name]
127.439 - vi [bound][private][data][read][node=Name]
127.440 - ------ Attributes ---------------------------------------
127.441 - OPTCRE : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
127.442 - SECTCRE : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
127.443 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.444 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.445 - optionxform : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.446 -
127.447 - =============================================
127.448 - class ConfigParser: ClassDef : OffsetRange[17314,20293>
127.449 - False [free][read][node=Name]
127.450 - None [free][read][node=Name]
127.451 - _interpolate [bound][private][function][def][node=FunctionDef]
127.452 - get [bound][function][def][node=FunctionDef]
127.453 - items [bound][function][def][node=FunctionDef]
127.454 -
127.455 - =============================================
127.456 - get: FunctionDef : OffsetRange[17356,18448>
127.457 - DEFAULTSECT [free][read][node=Name]
127.458 - KeyError [free][read][node=Name]
127.459 - NoOptionError [free][read][called][node=Name]
127.460 - NoSectionError [free][read][called][node=Name]
127.461 - None [free][read][node=Name]
127.462 - d [bound][data][read][node=Name]
127.463 - option [bound][param][data][read][node=Name]
127.464 - raw [bound][param][data][read][node=Name]
127.465 - section [bound][param][data][read][node=Name]
127.466 - self [bound][param][data][read][node=Name]
127.467 - value [bound][data][read][node=Name]
127.468 - vars [bound][param][data][read][node=Name]
127.469 - ------ Attributes ---------------------------------------
127.470 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.471 - _interpolate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
127.472 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.473 - optionxform : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
127.474 -
127.475 - =============================================
127.476 - items: FunctionDef : OffsetRange[18449,19621>
127.477 - DEFAULTSECT [free][read][node=Name]
127.478 - KeyError [free][read][node=Name]
127.479 - NoSectionError [free][read][called][node=Name]
127.480 - _[544_20] [bound][private][data][unused][node=ListComp]
127.481 - _[547_20] [bound][private][data][unused][node=ListComp]
127.482 - d [bound][data][read][node=Name]
127.483 - option [bound][data][read][node=Name]
127.484 - options [bound][data][read][node=Name]
127.485 - raw [bound][param][data][read][node=Name]
127.486 - section [bound][param][data][read][node=Name]
127.487 - self [bound][param][data][read][node=Name]
127.488 - vars [bound][param][data][read][node=Name]
127.489 - ------ Attributes ---------------------------------------
127.490 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.491 - _interpolate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
127.492 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
127.493 -
127.494 - =============================================
127.495 - _interpolate: FunctionDef : OffsetRange[19622,20293>
127.496 - InterpolationDepthError [free][read][called][node=Name]
127.497 - InterpolationMissingOptionError [free][read][called][node=Name]
127.498 - KeyError [free][read][node=Name]
127.499 - MAX_INTERPOLATION_DEPTH [free][read][node=Name]
127.500 - depth [bound][data][read][node=Name]
127.501 - e [bound][data][read][node=Name]
127.502 - option [bound][param][data][read][node=Name]
127.503 - rawval [bound][param][data][read][node=Name]
127.504 - section [bound][param][data][read][node=Name]
127.505 - self [bound][param][data][unused][node=Name]
127.506 - value [bound][data][read][node=Name]
127.507 - vars [bound][param][data][read][node=Name]
127.508 -
127.509 - =============================================
127.510 - class SafeConfigParser: ClassDef : OffsetRange[20293,22066>
127.511 - _interpolate [bound][private][function][def][node=FunctionDef]
127.512 - _interpolate_some [bound][private][function][def][node=FunctionDef]
127.513 - _interpvar_match [bound][private][data][node=Name]
127.514 - re [free][read][node=Name]
127.515 -
127.516 - =============================================
127.517 - _interpolate: FunctionDef : OffsetRange[20336,20542>
127.518 - L [bound][data][read][node=Name]
127.519 - option [bound][param][data][read][node=Name]
127.520 - rawval [bound][param][data][read][node=Name]
127.521 - section [bound][param][data][read][node=Name]
127.522 - self [bound][param][data][read][node=Name]
127.523 - vars [bound][param][data][read][node=Name]
127.524 - ------ Attributes ---------------------------------------
127.525 - _interpolate_some : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
127.526 -
127.527 - =============================================
127.528 - _interpolate_some: FunctionDef : OffsetRange[20602,22066>
127.529 - InterpolationDepthError [free][read][called][node=Name]
127.530 - InterpolationMissingOptionError [free][read][called][node=Name]
127.531 - InterpolationSyntaxError [free][read][called][node=Name]
127.532 - KeyError [free][read][node=Name]
127.533 - MAX_INTERPOLATION_DEPTH [free][read][node=Name]
127.534 - None [free][read][node=Name]
127.535 - accum [bound][param][data][read][node=Name]
127.536 - c [bound][data][read][node=Name]
127.537 - depth [bound][param][data][read][node=Name]
127.538 - m [bound][data][read][node=Name]
127.539 - map [bound][param][data][read][node=Name]
127.540 - option [bound][param][data][read][node=Name]
127.541 - p [bound][data][read][node=Name]
127.542 - rest [bound][param][data][read][node=Name]
127.543 - ret [free][read][node=Name]
127.544 - section [bound][param][data][read][node=Name]
127.545 - self [bound][param][data][read][node=Name]
127.546 - v [bound][data][read][node=Name]
127.547 - var [bound][data][read][node=Name]
127.548 - ------ Attributes ---------------------------------------
127.549 - _interpolate_some : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
127.550 - _interpvar_match : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
127.551 -
128.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.semantic Sun Jan 04 13:11:53 2015 -0600
128.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
128.3 @@ -1,615 +0,0 @@
128.4 -"""Configuration file parser.
128.5 -
128.6 -A setup file consists of sections, lead by a "[section]" header,
128.7 -and followed by "name: value" entries, with continuations and such in
128.8 -the style of RFC 822.
128.9 -
128.10 - the same section, or values in a special [DEFAULT] section.
128.11 -
128.12 -For example:
128.13 -
128.14 - something: %(dir)s/whatever
128.15 -
128.16 -would resolve the "%(dir)s" to the value of dir. All reference
128.17 -expansions are done late, on demand.
128.18 -
128.19 -Intrinsic defaults can be specified by passing them into the
128.20 -ConfigParser constructor as a dictionary.
128.21 -
128.22 -class:
128.23 -
128.24 -ConfigParser -- responsible for parsing a list of
128.25 - configuration files, and managing the parsed database.
128.26 -
128.27 - methods:
128.28 -
128.29 - __init__(defaults=None)
128.30 - create the parser and specify a dictionary of intrinsic defaults. The
128.31 - keys must be strings, the values must be appropriate for %()s string
128.32 - interpolation. Note that `__name__' is always an intrinsic default;
128.33 - it's value is the section's name.
128.34 -
128.35 - sections()
128.36 - return all the configuration section names, sans DEFAULT
128.37 -
128.38 - has_section(section)
128.39 - return whether the given section exists
128.40 -
128.41 - has_option(section, option)
128.42 - return whether the given option exists in the given section
128.43 -
128.44 - options(section)
128.45 - return list of configuration options for the named section
128.46 -
128.47 - read(filenames)
128.48 - read and parse the list of named configuration files, given by
128.49 - name. A single filename is also allowed. Non-existing files
128.50 - are ignored.
128.51 -
128.52 - readfp(fp, filename=None)
128.53 - read and parse one configuration file, given as a file object.
128.54 - The filename defaults to fp.name; it is only used in error
128.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
128.56 -
128.57 - get(section, option, raw=False, vars=None)
128.58 - return a string value for the named option. All % interpolations are
128.59 - expanded in the return values, based on the defaults passed into the
128.60 - constructor and the DEFAULT section. Additional substitutions may be
128.61 - provided using the `vars' argument, which must be a dictionary whose
128.62 - contents override any pre-existing defaults.
128.63 -
128.64 - getint(section, options)
128.65 - like get(), but convert value to an integer
128.66 -
128.67 - getfloat(section, options)
128.68 - like get(), but convert value to a float
128.69 -
128.70 - getboolean(section, options)
128.71 - like get(), but convert value to a boolean (currently case
128.72 - insensitively defined as 0, false, no, off for False, and 1, true,
128.73 - yes, on for True). Returns False or True.
128.74 -
128.75 - items(section, raw=False, vars=None)
128.76 - return a list of tuples with (name, value) for each option
128.77 - in the section.
128.78 -
128.79 - remove_section(section)
128.80 - remove the given file section and all its options
128.81 -
128.82 - remove_option(section, option)
128.83 - remove the given option from the given section
128.84 -
128.85 - set(section, option, value)
128.86 - set the given option
128.87 -
128.88 - write(fp)
128.89 - write the configuration state in .ini format
128.90 -"""
128.91 -
128.92 -import re
128.93 -
128.94 -__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
128.95 - "InterpolationError", "InterpolationDepthError",
128.96 - "InterpolationSyntaxError", "ParsingError",
128.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
128.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
128.99 -
128.100 -DEFAULTSECT = "DEFAULT"
128.101 -
128.102 -MAX_INTERPOLATION_DEPTH = 10
128.103 -
128.104 -
128.105 -
128.106 -# exception classes
128.107 -class Error(Exception):
128.108 - """Base class for ConfigParser exceptions."""
128.109 -
128.110 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:msg<|=''):
128.111 - |>PARAMETER:self<|.message = |>PARAMETER:msg<|
128.112 - Exception.__init__(|>PARAMETER:self<|, |>PARAMETER:msg<|)
128.113 -
128.114 - def |>METHOD:__repr__<|(|>PARAMETER:self<|):
128.115 - return |>PARAMETER:self<|.message
128.116 -
128.117 - __str__ = __repr__
128.118 -
128.119 -class NoSectionError(Error):
128.120 - """Rasssised when no section matches a requested option."""
128.121 -
128.122 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
128.123 - Error.__init__(|>PARAMETER:self<|, 'No section: ' + `|>PARAMETER:section<|`)
128.124 - |>PARAMETER:self<|.section = |>PARAMETER:section<|
128.125 -
128.126 -class DuplicateSectionError(Error):
128.127 - """Raised when a section is multiply-created."""
128.128 -
128.129 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
128.130 - Error.__init__(|>PARAMETER:self<|, "Section %r already exists" % |>PARAMETER:section<|)
128.131 - |>PARAMETER:self<|.section = |>PARAMETER:section<|
128.132 -
128.133 -class NoOptionError(Error):
128.134 - """A requested option was not found."""
128.135 -
128.136 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:section<|):
128.137 - Error.__init__(|>PARAMETER:self<|, "No option %r in section: %r" %
128.138 - (|>PARAMETER:option<|, |>PARAMETER:section<|))
128.139 - |>PARAMETER:self<|.option = |>PARAMETER:option<|
128.140 - |>PARAMETER:self<|.section = |>PARAMETER:section<|
128.141 -
128.142 -class InterpolationError(Error):
128.143 - """Base class for interpolation-related exceptions."""
128.144 -
128.145 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:msg<|):
128.146 - Error.__init__(|>PARAMETER:self<|, |>PARAMETER:msg<|)
128.147 - |>PARAMETER:self<|.option = |>PARAMETER:option<|
128.148 - |>PARAMETER:self<|.section = |>PARAMETER:section<|
128.149 -
128.150 -class InterpolationMissingOptionError(InterpolationError):
128.151 - """A string substitution required a setting which was not available."""
128.152 -
128.153 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:rawval<|, |>PARAMETER:reference<|):
128.154 - msg = ("Bad value substitution:\n"
128.155 - "\tsection: [%s]\n"
128.156 - "\toption : %s\n"
128.157 - "\tkey : %s\n"
128.158 - "\trawval : %s\n"
128.159 - % (|>PARAMETER:section<|, |>PARAMETER:option<|, |>PARAMETER:reference<|, |>PARAMETER:rawval<|))
128.160 - InterpolationError.__init__(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:section<|, msg)
128.161 - |>PARAMETER:self<|.reference = |>PARAMETER:reference<|
128.162 -
128.163 -class InterpolationSyntaxError(InterpolationError):
128.164 - """Raised when the source text into which substitutions are made
128.165 - does not conform to the required syntax."""
128.166 -
128.167 -class InterpolationDepthError(InterpolationError):
128.168 - """Raised when substitutions are nested too deeply."""
128.169 -
128.170 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:rawval<|):
128.171 - msg = ("Value interpolation too deeply recursive:\n"
128.172 - "\tsection: [%s]\n"
128.173 - "\toption : %s\n"
128.174 - "\trawval : %s\n"
128.175 - % (|>PARAMETER:section<|, |>PARAMETER:option<|, |>PARAMETER:rawval<|))
128.176 - InterpolationError.__init__(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:section<|, msg)
128.177 -
128.178 -class ParsingError(Error):
128.179 - """Raised when a configuration file does not follow legal syntax."""
128.180 -
128.181 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:filename<|):
128.182 - Error.__init__(|>PARAMETER:self<|, 'File contains parsing errors: %s' % |>PARAMETER:filename<|)
128.183 - |>PARAMETER:self<|.filename = |>PARAMETER:filename<|
128.184 - |>PARAMETER:self<|.errors = []
128.185 -
128.186 - def |>METHOD:append<|(|>PARAMETER:self<|, |>PARAMETER:lineno<|, |>PARAMETER:line<|):
128.187 - |>PARAMETER:self<|.errors.append((|>PARAMETER:lineno<|, |>PARAMETER:line<|))
128.188 - |>PARAMETER:self<|.message += '\n\t[line %2d]: %s' % (|>PARAMETER:lineno<|, |>PARAMETER:line<|)
128.189 -
128.190 -class MissingSectionHeaderError(ParsingError):
128.191 - """Raised when a key-value pair is found before any section header."""
128.192 -
128.193 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:filename<|, |>PARAMETER:lineno<|, |>PARAMETER:line<|):
128.194 - Error.__init__(
128.195 - |>PARAMETER:self<|,
128.196 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
128.197 - (|>PARAMETER:filename<|, |>PARAMETER:lineno<|, |>PARAMETER:line<|))
128.198 - |>PARAMETER:self<|.filename = |>PARAMETER:filename<|
128.199 - |>PARAMETER:self<|.lineno = |>PARAMETER:lineno<|
128.200 - |>PARAMETER:self<|.line = |>PARAMETER:line<|
128.201 -
128.202 -
128.203 -
128.204 -class RawConfigParser:
128.205 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:defaults<|=None):
128.206 - |>PARAMETER:self<|._sections = {}
128.207 - if |>PARAMETER:defaults<| is None:
128.208 - |>PARAMETER:self<|._defaults = {}
128.209 - else:
128.210 - |>PARAMETER:self<|._defaults = |>PARAMETER:defaults<|
128.211 -
128.212 - def |>METHOD:defaults<|(|>PARAMETER:self<|):
128.213 - return |>PARAMETER:self<|._defaults
128.214 -
128.215 - def |>METHOD:sections<|(|>PARAMETER:self<|):
128.216 - """Return a list of section names, excluding [DEFAULT]"""
128.217 - # self._sections will never have [DEFAULT] in it
128.218 - return |>PARAMETER:self<|._sections.keys()
128.219 -
128.220 - def |>METHOD:add_section<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
128.221 - """Create a new section in the configuration.
128.222 -
128.223 - Raise DuplicateSectionError if a section by the specified name
128.224 - already exists.
128.225 - """
128.226 - if |>PARAMETER:section<| in |>PARAMETER:self<|._sections:
128.227 - raise DuplicateSectionError(|>PARAMETER:section<|)
128.228 - |>PARAMETER:self<|._sections[|>PARAMETER:section<|] = {}
128.229 -
128.230 - def |>METHOD:has_section<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
128.231 - """Indicate whether the named section is present in the configuration.
128.232 -
128.233 - The DEFAULT section is not acknowledged.
128.234 - """
128.235 - return |>PARAMETER:section<| in |>PARAMETER:self<|._sections
128.236 -
128.237 - def |>METHOD:options<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
128.238 - """Return a list of option names for the given section name."""
128.239 - try:
128.240 - opts = |>PARAMETER:self<|._sections[|>PARAMETER:section<|].copy()
128.241 - except KeyError:
128.242 - raise NoSectionError(|>PARAMETER:section<|)
128.243 - opts.update(|>PARAMETER:self<|._defaults)
128.244 - if '__name__' in opts:
128.245 - del opts['__name__']
128.246 - return opts.keys()
128.247 -
128.248 - def |>METHOD:read<|(|>PARAMETER:self<|, |>PARAMETER:filenames<|):
128.249 - """Read and parse a filename or a list of filenames.
128.250 -
128.251 - Files that cannot be opened are silently ignored; this is
128.252 - designed so that you can specify a list of potential
128.253 - configuration file locations (e.g. current directory, user's
128.254 - home directory, systemwide directory), and all existing
128.255 - configuration files in the list will be read. A single
128.256 - filename may also be given.
128.257 - """
128.258 - if isinstance(|>PARAMETER:filenames<|, basestring):
128.259 - |>PARAMETER:filenames<| = [|>PARAMETER:filenames<|]
128.260 - for filename in |>PARAMETER:filenames<|:
128.261 - try:
128.262 - fp = open(filename)
128.263 - except IOError:
128.264 - continue
128.265 - |>PARAMETER:self<|._read(fp, filename)
128.266 - fp.close()
128.267 -
128.268 - def |>METHOD:readfp<|(|>PARAMETER:self<|, |>PARAMETER:fp<|, |>PARAMETER:filename<|=None):
128.269 - """Like read() but the argument must be a file-like object.
128.270 -
128.271 - The `fp' argument must have a `readline' method. Optional
128.272 - second argument is the `filename', which if not given, is
128.273 - taken from fp.name. If fp has no `name' attribute, `<???>' is
128.274 - used.
128.275 -
128.276 - """
128.277 - if |>PARAMETER:filename<| is None:
128.278 - try:
128.279 - |>PARAMETER:filename<| = |>PARAMETER:fp<|.name
128.280 - except AttributeError:
128.281 - |>PARAMETER:filename<| = '<???>'
128.282 - |>PARAMETER:self<|._read(|>PARAMETER:fp<|, |>PARAMETER:filename<|)
128.283 -
128.284 - def |>METHOD:get<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|):
128.285 - opt = |>PARAMETER:self<|.optionxform(|>PARAMETER:option<|)
128.286 - if |>PARAMETER:section<| not in |>PARAMETER:self<|._sections:
128.287 - if |>PARAMETER:section<| != DEFAULTSECT:
128.288 - raise NoSectionError(|>PARAMETER:section<|)
128.289 - if opt in |>PARAMETER:self<|._defaults:
128.290 - return |>PARAMETER:self<|._defaults[opt]
128.291 - else:
128.292 - raise NoOptionError(|>PARAMETER:option<|, |>PARAMETER:section<|)
128.293 - elif opt in |>PARAMETER:self<|._sections[|>PARAMETER:section<|]:
128.294 - return |>PARAMETER:self<|._sections[|>PARAMETER:section<|][opt]
128.295 - elif opt in |>PARAMETER:self<|._defaults:
128.296 - return |>PARAMETER:self<|._defaults[opt]
128.297 - else:
128.298 - raise NoOptionError(|>PARAMETER:option<|, |>PARAMETER:section<|)
128.299 -
128.300 - def |>METHOD:items<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
128.301 - try:
128.302 - d2 = |>PARAMETER:self<|._sections[|>PARAMETER:section<|]
128.303 - except KeyError:
128.304 - if |>PARAMETER:section<| != DEFAULTSECT:
128.305 - raise NoSectionError(|>PARAMETER:section<|)
128.306 - d2 = {}
128.307 - d = |>PARAMETER:self<|._defaults.copy()
128.308 - d.update(d2)
128.309 - if "__name__" in d:
128.310 - del d["__name__"]
128.311 - return d.items()
128.312 -
128.313 - def |>METHOD:_get<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:conv<|, |>PARAMETER:option<|):
128.314 - return |>PARAMETER:conv<|(|>PARAMETER:self<|.get(|>PARAMETER:section<|, |>PARAMETER:option<|))
128.315 -
128.316 - def |>METHOD:getint<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|):
128.317 - return |>PARAMETER:self<|._get(|>PARAMETER:section<|, int, |>PARAMETER:option<|)
128.318 -
128.319 - def |>METHOD:getfloat<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|):
128.320 - return |>PARAMETER:self<|._get(|>PARAMETER:section<|, float, |>PARAMETER:option<|)
128.321 -
128.322 - _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
128.323 - '0': False, 'no': False, 'false': False, 'off': False}
128.324 -
128.325 - def |>METHOD:getboolean<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|):
128.326 - v = |>PARAMETER:self<|.get(|>PARAMETER:section<|, |>PARAMETER:option<|)
128.327 - if v.lower() not in |>PARAMETER:self<|._boolean_states:
128.328 - raise ValueError, 'Not a boolean: %s' % v
128.329 - return |>PARAMETER:self<|._boolean_states[v.lower()]
128.330 -
128.331 - def |>METHOD:optionxform<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER:optionstr<|):
128.332 - return |>PARAMETER:optionstr<|.lower()
128.333 -
128.334 - def |>METHOD:has_option<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|):
128.335 - """Check for the existence of a given option in a given section."""
128.336 - if not |>PARAMETER:section<| or |>PARAMETER:section<| == DEFAULTSECT:
128.337 - |>PARAMETER:option<| = |>PARAMETER:self<|.optionxform(|>PARAMETER:option<|)
128.338 - return |>PARAMETER:option<| in |>PARAMETER:self<|._defaults
128.339 - elif |>PARAMETER:section<| not in |>PARAMETER:self<|._sections:
128.340 - return False
128.341 - else:
128.342 - |>PARAMETER:option<| = |>PARAMETER:self<|.optionxform(|>PARAMETER:option<|)
128.343 - return (|>PARAMETER:option<| in |>PARAMETER:self<|._sections[|>PARAMETER:section<|]
128.344 - or |>PARAMETER:option<| in |>PARAMETER:self<|._defaults)
128.345 -
128.346 - def |>METHOD:set<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|, |>PARAMETER:value<|):
128.347 - """Set an option."""
128.348 - if not |>PARAMETER:section<| or |>PARAMETER:section<| == DEFAULTSECT:
128.349 - sectdict = |>PARAMETER:self<|._defaults
128.350 - else:
128.351 - try:
128.352 - sectdict = |>PARAMETER:self<|._sections[|>PARAMETER:section<|]
128.353 - except KeyError:
128.354 - raise NoSectionError(|>PARAMETER:section<|)
128.355 - sectdict[|>PARAMETER:self<|.optionxform(|>PARAMETER:option<|)] = |>PARAMETER:value<|
128.356 -
128.357 - def |>METHOD:write<|(|>PARAMETER:self<|, |>PARAMETER:fp<|):
128.358 - """Write an .ini-format representation of the configuration state."""
128.359 - if |>PARAMETER:self<|._defaults:
128.360 - |>PARAMETER:fp<|.write("[%s]\n" % DEFAULTSECT)
128.361 - for (key, value) in |>PARAMETER:self<|._defaults.items():
128.362 - |>PARAMETER:fp<|.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
128.363 - |>PARAMETER:fp<|.write("\n")
128.364 - for section in |>PARAMETER:self<|._sections:
128.365 - |>PARAMETER:fp<|.write("[%s]\n" % section)
128.366 - for (key, value) in |>PARAMETER:self<|._sections[section].items():
128.367 - if key != "__name__":
128.368 - |>PARAMETER:fp<|.write("%s = %s\n" %
128.369 - (key, str(value).replace('\n', '\n\t')))
128.370 - |>PARAMETER:fp<|.write("\n")
128.371 -
128.372 - def |>METHOD:remove_option<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|):
128.373 - """Remove an option."""
128.374 - if not |>PARAMETER:section<| or |>PARAMETER:section<| == DEFAULTSECT:
128.375 - sectdict = |>PARAMETER:self<|._defaults
128.376 - else:
128.377 - try:
128.378 - sectdict = |>PARAMETER:self<|._sections[|>PARAMETER:section<|]
128.379 - except KeyError:
128.380 - raise NoSectionError(|>PARAMETER:section<|)
128.381 - |>PARAMETER:option<| = |>PARAMETER:self<|.optionxform(|>PARAMETER:option<|)
128.382 - existed = |>PARAMETER:option<| in sectdict
128.383 - if existed:
128.384 - del sectdict[|>PARAMETER:option<|]
128.385 - return existed
128.386 -
128.387 - def |>METHOD:remove_section<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
128.388 - """Remove a file section."""
128.389 - existed = |>PARAMETER:section<| in |>PARAMETER:self<|._sections
128.390 - if existed:
128.391 - del |>PARAMETER:self<|._sections[|>PARAMETER:section<|]
128.392 - return existed
128.393 -
128.394 - #
128.395 - # Regular expressions for parsing section headers and options.
128.396 - #
128.397 - SECTCRE = re.compile(
128.398 - r'\[' # [
128.399 - r'(?P<header>[^]]+)' # very permissive!
128.400 - r'\]' # ]
128.401 - )
128.402 - OPTCRE = re.compile(
128.403 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
128.404 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
128.405 - # followed by separator
128.406 - # (either : or =), followed
128.407 - # by any # space/tab
128.408 - r'(?P<value>.*)$' # everything up to eol
128.409 - )
128.410 -
128.411 - def |>METHOD:_read<|(|>PARAMETER:self<|, |>PARAMETER:fp<|, |>PARAMETER:fpname<|):
128.412 - """Parse a sectioned setup file.
128.413 -
128.414 - The sections in setup file contains a title line at the top,
128.415 - indicated by a name in square brackets (`[]'), plus key/value
128.416 - options lines, indicated by `name: value' format lines.
128.417 - Continuations are represented by an embedded newline then
128.418 - leading whitespace. Blank lines, lines beginning with a '#',
128.419 - and just about everything else are ignored.
128.420 - """
128.421 - cursect = None # None, or a dictionary
128.422 - optname = None
128.423 - lineno = 0
128.424 - e = None # None, or an exception
128.425 - while True:
128.426 - line = |>PARAMETER:fp<|.readline()
128.427 - if not line:
128.428 - break
128.429 - lineno = lineno + 1
128.430 - # comment or blank line?
128.431 - if line.strip() == '' or line[0] in '#;':
128.432 - continue
128.433 - if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
128.434 - # no leading whitespace
128.435 - continue
128.436 - # continuation line?
128.437 - if line[0].isspace() and cursect is not None and optname:
128.438 - value = line.strip()
128.439 - if value:
128.440 - cursect[optname] = "%s\n%s" % (cursect[optname], value)
128.441 - # a section header or option header?
128.442 - else:
128.443 - # is it a section header?
128.444 - mo = |>PARAMETER:self<|.SECTCRE.match(line)
128.445 - if mo:
128.446 - sectname = mo.group('header')
128.447 - if sectname in |>PARAMETER:self<|._sections:
128.448 - cursect = |>PARAMETER:self<|._sections[sectname]
128.449 - elif sectname == DEFAULTSECT:
128.450 - cursect = |>PARAMETER:self<|._defaults
128.451 - else:
128.452 - cursect = {'__name__': sectname}
128.453 - |>PARAMETER:self<|._sections[sectname] = cursect
128.454 - # So sections can't start with a continuation line
128.455 - optname = None
128.456 - # no section header in the file?
128.457 - elif cursect is None:
128.458 - raise MissingSectionHeaderError(|>PARAMETER:fpname<|, lineno, `line`)
128.459 - # an option line?
128.460 - else:
128.461 - mo = |>PARAMETER:self<|.OPTCRE.match(line)
128.462 - if mo:
128.463 - optname, vi, optval = mo.group('option', 'vi', 'value')
128.464 - if vi in ('=', ':') and ';' in optval:
128.465 - # ';' is a comment delimiter only if it follows
128.466 - # a spacing character
128.467 - pos = optval.find(';')
128.468 - if pos != -1 and optval[pos-1].isspace():
128.469 - optval = optval[:pos]
128.470 - optval = optval.strip()
128.471 - # allow empty values
128.472 - if optval == '""':
128.473 - optval = ''
128.474 - optname = |>PARAMETER:self<|.optionxform(optname.rstrip())
128.475 - cursect[optname] = optval
128.476 - else:
128.477 - # a non-fatal parsing error occurred. set up the
128.478 - # exception but keep going. the exception will be
128.479 - # raised at the end of the file and will contain a
128.480 - # list of all bogus lines
128.481 - if not e:
128.482 - e = ParsingError(|>PARAMETER:fpname<|)
128.483 - e.append(lineno, `line`)
128.484 - # if any parsing errors occurred, raise an exception
128.485 - if e:
128.486 - raise e
128.487 -
128.488 -
128.489 -class ConfigParser(RawConfigParser):
128.490 -
128.491 - def |>METHOD:get<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|, |>PARAMETER:raw<|=False, |>PARAMETER:vars<|=None):
128.492 - """Get an option value for a given section.
128.493 -
128.494 - All % interpolations are expanded in the return values, based on the
128.495 - defaults passed into the constructor, unless the optional argument
128.496 - `raw' is true. Additional substitutions may be provided using the
128.497 - `vars' argument, which must be a dictionary whose contents overrides
128.498 - any pre-existing defaults.
128.499 -
128.500 - The section DEFAULT is special.
128.501 - """
128.502 - d = |>PARAMETER:self<|._defaults.copy()
128.503 - try:
128.504 - d.update(|>PARAMETER:self<|._sections[|>PARAMETER:section<|])
128.505 - except KeyError:
128.506 - if |>PARAMETER:section<| != DEFAULTSECT:
128.507 - raise NoSectionError(|>PARAMETER:section<|)
128.508 - # Update with the entry specific variables
128.509 - if |>PARAMETER:vars<| is not None:
128.510 - d.update(|>PARAMETER:vars<|)
128.511 - |>PARAMETER:option<| = |>PARAMETER:self<|.optionxform(|>PARAMETER:option<|)
128.512 - try:
128.513 - value = d[|>PARAMETER:option<|]
128.514 - except KeyError:
128.515 - raise NoOptionError(|>PARAMETER:option<|, |>PARAMETER:section<|)
128.516 -
128.517 - if |>PARAMETER:raw<|:
128.518 - return value
128.519 - else:
128.520 - return |>PARAMETER:self<|._interpolate(|>PARAMETER:section<|, |>PARAMETER:option<|, value, d)
128.521 -
128.522 - def |>METHOD:items<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:raw<|=False, |>PARAMETER:vars<|=None):
128.523 - """Return a list of tuples with (name, value) for each option
128.524 - in the section.
128.525 -
128.526 - All % interpolations are expanded in the return values, based on the
128.527 - defaults passed into the constructor, unless the optional argument
128.528 - `raw' is true. Additional substitutions may be provided using the
128.529 - `vars' argument, which must be a dictionary whose contents overrides
128.530 - any pre-existing defaults.
128.531 -
128.532 - The section DEFAULT is special.
128.533 - """
128.534 - d = |>PARAMETER:self<|._defaults.copy()
128.535 - try:
128.536 - d.update(|>PARAMETER:self<|._sections[|>PARAMETER:section<|])
128.537 - except KeyError:
128.538 - if |>PARAMETER:section<| != DEFAULTSECT:
128.539 - raise NoSectionError(|>PARAMETER:section<|)
128.540 - # Update with the entry specific variables
128.541 - if |>PARAMETER:vars<|:
128.542 - d.update(|>PARAMETER:vars<|)
128.543 - options = d.keys()
128.544 - if "__name__" in options:
128.545 - options.remove("__name__")
128.546 - if |>PARAMETER:raw<|:
128.547 - return [(option, d[option])
128.548 - for option in options]
128.549 - else:
128.550 - return [(option, |>PARAMETER:self<|._interpolate(|>PARAMETER:section<|, option, d[option], d))
128.551 - for option in options]
128.552 -
128.553 - def |>METHOD:_interpolate<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|, |>PARAMETER:rawval<|, |>PARAMETER:vars<|):
128.554 - # do the string interpolation
128.555 - value = |>PARAMETER:rawval<|
128.556 - depth = MAX_INTERPOLATION_DEPTH
128.557 - while depth: # Loop through this until it's done
128.558 - depth -= 1
128.559 - if value.find("%(") != -1:
128.560 - try:
128.561 - value = value % |>PARAMETER:vars<|
128.562 - except KeyError, e:
128.563 - raise InterpolationMissingOptionError(
128.564 - |>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:rawval<|, e[0])
128.565 - else:
128.566 - break
128.567 - if value.find("%(") != -1:
128.568 - raise InterpolationDepthError(|>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:rawval<|)
128.569 - return value
128.570 -
128.571 -
128.572 -class SafeConfigParser(ConfigParser):
128.573 -
128.574 - def |>METHOD:_interpolate<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|, |>PARAMETER:rawval<|, |>PARAMETER:vars<|):
128.575 - # do the string interpolation
128.576 - L = []
128.577 - |>PARAMETER:self<|._interpolate_some(|>PARAMETER:option<|, L, |>PARAMETER:rawval<|, |>PARAMETER:section<|, |>PARAMETER:vars<|, 1)
128.578 - return ''.join(L)
128.579 -
128.580 - _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
128.581 -
128.582 - def |>METHOD:_interpolate_some<|(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:accum<|, |>PARAMETER:rest<|, |>PARAMETER:section<|, |>PARAMETER:map<|, |>PARAMETER:depth<|):
128.583 - if |>PARAMETER:depth<| > MAX_INTERPOLATION_DEPTH:
128.584 - raise InterpolationDepthError(|>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:rest<|)
128.585 - while |>PARAMETER:rest<|:
128.586 - p = |>PARAMETER:rest<|.find("%")
128.587 - if p < 0:
128.588 - |>PARAMETER:accum<|.append(|>PARAMETER:rest<|)
128.589 - return
128.590 - if p > 0:
128.591 - |>PARAMETER:accum<|.append(|>PARAMETER:rest<|[:p])
128.592 - |>PARAMETER:rest<| = |>PARAMETER:rest<|[p:]
128.593 - # p is no longer used
128.594 - c = |>PARAMETER:rest<|[1:2]
128.595 - if c == "%":
128.596 - |>PARAMETER:accum<|.append("%")
128.597 - |>PARAMETER:rest<| = |>PARAMETER:rest<|[2:]
128.598 - elif c == "(":
128.599 - m = |>PARAMETER:self<|._interpvar_match(|>PARAMETER:rest<|)
128.600 - if m is None:
128.601 - raise InterpolationSyntaxError(|>PARAMETER:option<|, |>PARAMETER:section<|,
128.602 - "bad interpolation variable reference %r" % |>PARAMETER:rest<|)
128.603 - var = m.group(1)
128.604 - |>PARAMETER:rest<| = |>PARAMETER:rest<|[m.end():]
128.605 - try:
128.606 - v = |>PARAMETER:map<|[var]
128.607 - except KeyError:
128.608 - raise InterpolationMissingOptionError(
128.609 - |>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:rest<|, var)
128.610 - if "%" in v:
128.611 - |>PARAMETER:self<|._interpolate_some(|>PARAMETER:option<|, |>PARAMETER:accum<|, v,
128.612 - |>PARAMETER:section<|, |>PARAMETER:map<|, |>PARAMETER:depth<| + 1)
128.613 - else:
128.614 - |>PARAMETER:accum<|.append(v)
128.615 - else:
128.616 - raise InterpolationSyntaxError(
128.617 - |>PARAMETER:option<|, |>PARAMETER:section<|,
128.618 - "'%' must be followed by '%' or '(', found: " + `ret`)
129.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.structure Sun Jan 04 13:11:53 2015 -0600
129.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
129.3 @@ -1,65 +0,0 @@
129.4 -Error:CLASS:[PRIVATE]:ESCAPED{Error}:
129.5 - __init__:CONSTRUCTOR:[PRIVATE]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{msg}}):
129.6 - __repr__:METHOD:[PRIVATE]:ESCAPED{__repr__}(PARAMETERS{ESCAPED{self}}):
129.7 - message:ATTRIBUTE:[]:ESCAPED{message}:
129.8 -NoSectionError:CLASS:[]:ESCAPED{NoSectionError}:
129.9 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
129.10 - section:ATTRIBUTE:[]:ESCAPED{section}:
129.11 -DuplicateSectionError:CLASS:[]:ESCAPED{DuplicateSectionError}:
129.12 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
129.13 - section:ATTRIBUTE:[]:ESCAPED{section}:
129.14 -NoOptionError:CLASS:[]:ESCAPED{NoOptionError}:
129.15 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{section}}):
129.16 - option:ATTRIBUTE:[]:ESCAPED{option}:
129.17 - section:ATTRIBUTE:[]:ESCAPED{section}:
129.18 -InterpolationError:CLASS:[]:ESCAPED{InterpolationError}:
129.19 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{msg}}):
129.20 - option:ATTRIBUTE:[]:ESCAPED{option}:
129.21 - section:ATTRIBUTE:[]:ESCAPED{section}:
129.22 -InterpolationMissingOptionError:CLASS:[PRIVATE]:ESCAPED{InterpolationMissingOptionError}:
129.23 - __init__:CONSTRUCTOR:[PRIVATE]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{rawval}ESCAPED{,}ESCAPED{reference}}):
129.24 - reference:ATTRIBUTE:[]:ESCAPED{reference}:
129.25 -InterpolationSyntaxError:CLASS:[]:ESCAPED{InterpolationSyntaxError}:
129.26 -InterpolationDepthError:CLASS:[]:ESCAPED{InterpolationDepthError}:
129.27 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{rawval}}):
129.28 -ParsingError:CLASS:[]:ESCAPED{ParsingError}:
129.29 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{filename}}):
129.30 - append:METHOD:[]:ESCAPED{append}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{lineno}ESCAPED{,}ESCAPED{line}}):
129.31 - errors:ATTRIBUTE:[]:ESCAPED{errors}:
129.32 - filename:ATTRIBUTE:[]:ESCAPED{filename}:
129.33 -MissingSectionHeaderError:CLASS:[]:ESCAPED{MissingSectionHeaderError}:
129.34 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{filename}ESCAPED{,}ESCAPED{lineno}ESCAPED{,}ESCAPED{line}}):
129.35 - filename:ATTRIBUTE:[]:ESCAPED{filename}:
129.36 - line:ATTRIBUTE:[]:ESCAPED{line}:
129.37 - lineno:ATTRIBUTE:[]:ESCAPED{lineno}:
129.38 -RawConfigParser:CLASS:[PRIVATE]:ESCAPED{RawConfigParser}:
129.39 - __init__:CONSTRUCTOR:[PRIVATE]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{defaults}}):
129.40 - _defaults:ATTRIBUTE:[]:ESCAPED{_defaults}:
129.41 - _get:METHOD:[PRIVATE]:ESCAPED{_get}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{conv}ESCAPED{,}ESCAPED{option}}):
129.42 - _read:METHOD:[PRIVATE]:ESCAPED{_read}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{fp}ESCAPED{,}ESCAPED{fpname}}):
129.43 - _sections:ATTRIBUTE:[]:ESCAPED{_sections}:
129.44 - add_section:METHOD:[PRIVATE]:ESCAPED{add_section}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
129.45 - defaults:METHOD:[PRIVATE]:ESCAPED{defaults}(PARAMETERS{ESCAPED{self}}):
129.46 - get:METHOD:[PRIVATE]:ESCAPED{get}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}}):
129.47 - getboolean:METHOD:[PRIVATE]:ESCAPED{getboolean}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}}):
129.48 - getfloat:METHOD:[PRIVATE]:ESCAPED{getfloat}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}}):
129.49 - getint:METHOD:[PRIVATE]:ESCAPED{getint}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}}):
129.50 - has_option:METHOD:[PRIVATE]:ESCAPED{has_option}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}}):
129.51 - has_section:METHOD:[PRIVATE]:ESCAPED{has_section}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
129.52 - items:METHOD:[PRIVATE]:ESCAPED{items}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
129.53 - options:METHOD:[PRIVATE]:ESCAPED{options}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
129.54 - optionxform:METHOD:[PRIVATE]:ESCAPED{optionxform}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{optionstr}}):
129.55 - read:METHOD:[PRIVATE]:ESCAPED{read}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{filenames}}):
129.56 - readfp:METHOD:[PRIVATE]:ESCAPED{readfp}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{fp}ESCAPED{,}ESCAPED{filename}}):
129.57 - remove_option:METHOD:[PRIVATE]:ESCAPED{remove_option}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}}):
129.58 - remove_section:METHOD:[PRIVATE]:ESCAPED{remove_section}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
129.59 - sections:METHOD:[PRIVATE]:ESCAPED{sections}(PARAMETERS{ESCAPED{self}}):
129.60 - set:METHOD:[PRIVATE]:ESCAPED{set}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{value}}):
129.61 - write:METHOD:[PRIVATE]:ESCAPED{write}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{fp}}):
129.62 -ConfigParser:CLASS:[]:ESCAPED{ConfigParser}:
129.63 - _interpolate:METHOD:[PRIVATE]:ESCAPED{_interpolate}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{rawval}ESCAPED{,}ESCAPED{vars}}):
129.64 - get:METHOD:[]:ESCAPED{get}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{raw}ESCAPED{,}ESCAPED{vars}}):
129.65 - items:METHOD:[]:ESCAPED{items}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{raw}ESCAPED{,}ESCAPED{vars}}):
129.66 -SafeConfigParser:CLASS:[]:ESCAPED{SafeConfigParser}:
129.67 - _interpolate:METHOD:[PRIVATE]:ESCAPED{_interpolate}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{rawval}ESCAPED{,}ESCAPED{vars}}):
129.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}}):
130.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testClasses.completion Sun Jan 04 13:11:53 2015 -0600
130.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
130.3 @@ -1,1241 +0,0 @@
130.4 -Code completion result for source line:
130.5 -|self.section = section
130.6 -(QueryType=COMPLETION, NameKind=PREFIX)
130.7 -MODULE re [PRIVATE]
130.8 -CLASS ConfigParser
130.9 -CLASS DuplicateSectionError
130.10 -CLASS Error [PRIVATE]
130.11 -CLASS InterpolationDepthError
130.12 -CLASS InterpolationError
130.13 -CLASS InterpolationMissingOptionErro [PRIVATE]
130.14 -CLASS InterpolationSyntaxError
130.15 -CLASS MissingSectionHeaderError
130.16 -CLASS NoOptionError
130.17 -CLASS NoSectionError
130.18 -CLASS ParsingError
130.19 -CLASS RawConfigParser [PRIVATE]
130.20 -CLASS SafeConfigParser
130.21 -VARIABLE DEFAULTSECT
130.22 -VARIABLE MAX_INTERPOLATION_DEPTH
130.23 -VARIABLE __all__
130.24 -VARIABLE section
130.25 -VARIABLE self
130.26 -------------------------------------
130.27 -CLASS A
130.28 -CLASS ABCMeta
130.29 -CLASS AEServer
130.30 -CLASS AEText
130.31 -CLASS ASTVisitor
130.32 -CLASS AbstractBasicAuthHandler
130.33 -CLASS AbstractClassCode
130.34 -CLASS AbstractCompileMode
130.35 -CLASS AbstractDigestAuthHandler
130.36 -CLASS AbstractFormatter
130.37 -CLASS AbstractFunctionCode
130.38 -CLASS AbstractHTTPHandler
130.39 -CLASS AbstractWriter
130.40 -CLASS Add
130.41 -CLASS AddressList
130.42 -CLASS And
130.43 -CLASS Application
130.44 -CLASS ArgumentError
130.45 -CLASS ArithmeticError
130.46 -CLASS ArithmeticError
130.47 -CLASS Array
130.48 -CLASS ArrayInstance
130.49 -CLASS AssAttr
130.50 -CLASS AssList
130.51 -CLASS AssName
130.52 -CLASS AssTuple
130.53 -CLASS Assert
130.54 -CLASS AssertionError
130.55 -CLASS AssertionError
130.56 -CLASS Assign
130.57 -CLASS AsyncResult
130.58 -CLASS Attr
130.59 -CLASS AttributeError
130.60 -CLASS AttributeError
130.61 -CLASS AttributeList
130.62 -CLASS AttributeMap
130.63 -CLASS Attributes
130.64 -CLASS AttributesImpl
130.65 -CLASS AttributesNS
130.66 -CLASS AttributesNSImpl
130.67 -CLASS AugAssign
130.68 -CLASS AugGetattr
130.69 -CLASS AugName
130.70 -CLASS AugSlice
130.71 -CLASS AugSubscript
130.72 -CLASS AuthenticationError
130.73 -CLASS AutoGILError
130.74 -CLASS B
130.75 -CLASS BCPPCompiler
130.76 -CLASS BCPTestCase
130.77 -CLASS BZ2Compressor
130.78 -CLASS BZ2Decompressor
130.79 -CLASS BZ2File
130.80 -CLASS Babyl
130.81 -CLASS BabylMailbox
130.82 -CLASS BabylMessage
130.83 -CLASS Backquote
130.84 -CLASS BadBoundaryPointsErr
130.85 -CLASS BadFutureParser
130.86 -CLASS BadOptionError
130.87 -CLASS BadStatusLine
130.88 -CLASS BadZipfile
130.89 -CLASS Balloon
130.90 -CLASS Bar
130.91 -CLASS BaseCGIHandler
130.92 -CLASS BaseCookie
130.93 -CLASS BaseException
130.94 -CLASS BaseException
130.95 -CLASS BaseHTTPRequestHandler
130.96 -CLASS BaseHandler
130.97 -CLASS BaseIncrementalParser
130.98 -CLASS BaseManager
130.99 -CLASS BaseProxy
130.100 -CLASS BaseRequestHandler
130.101 -CLASS BaseRotatingHandler
130.102 -CLASS BaseSet
130.103 -CLASS BasicModuleImporter
130.104 -CLASS BasicModuleLoader
130.105 -CLASS BastionClass
130.106 -CLASS Baz
130.107 -CLASS Bdb
130.108 -CLASS BdbQuit
130.109 -CLASS BigEndianStructure
130.110 -CLASS Binary
130.111 -CLASS Bitand
130.112 -CLASS Bitor
130.113 -CLASS Bitxor
130.114 -CLASS Block
130.115 -CLASS BlockFinder
130.116 -CLASS BlockingIOError
130.117 -CLASS Boolean
130.118 -CLASS BoundaryError
130.119 -CLASS BoundedSemaphore
130.120 -CLASS Break
130.121 -CLASS Breakpoint
130.122 -CLASS BsdDbShelf
130.123 -CLASS BufferTooShort
130.124 -CLASS BufferedIOBase
130.125 -CLASS BufferedRWPair
130.126 -CLASS BufferedRandom
130.127 -CLASS BufferedReader
130.128 -CLASS BufferedWriter
130.129 -CLASS BufferingFormatter
130.130 -CLASS BufferingHandler
130.131 -CLASS BuildPyTestCase
130.132 -CLASS BuildScriptsTestCase
130.133 -CLASS BuiltinImporter
130.134 -CLASS Bulkcopy
130.135 -CLASS ButtonBox
130.136 -CLASS BytesIO
130.137 -CLASS C
130.138 -CLASS CAB
130.139 -CLASS CCompiler
130.140 -CLASS CCompilerError
130.141 -CLASS CDATASection
130.142 -CLASS CDLL
130.143 -CLASS CGIHTTPRequestHandler
130.144 -CLASS CGIHandler
130.145 -CLASS CGIXMLRPCRequestHandler
130.146 -CLASS CacheFTPHandler
130.147 -CLASS CallFunc
130.148 -CLASS CalledProcessError
130.149 -CLASS CannotSendHeader
130.150 -CLASS CannotSendRequest
130.151 -CLASS Canonizer
130.152 -CLASS CharacterData
130.153 -CLASS Charset
130.154 -CLASS CharsetError
130.155 -CLASS CheckList
130.156 -CLASS Childless
130.157 -CLASS Chunk
130.158 -CLASS Clamped
130.159 -CLASS Class
130.160 -CLASS ClassCodeGenerator
130.161 -CLASS ClassScope
130.162 -CLASS Cmd
130.163 -CLASS CodeGenerator
130.164 -CLASS Codec
130.165 -CLASS CodecRegistryError
130.166 -CLASS ComboBox
130.167 -CLASS Command
130.168 -CLASS CommandCompiler
130.169 -CLASS Comment
130.170 -CLASS Compare
130.171 -CLASS Comparison
130.172 -CLASS Compile
130.173 -CLASS CompileError
130.174 -CLASS Completer
130.175 -CLASS Complex
130.176 -CLASS ComponentItem
130.177 -CLASS Condition
130.178 -CLASS ConfigParser
130.179 -CLASS Connection
130.180 -CLASS Const
130.181 -CLASS ContentGenerator
130.182 -CLASS ContentHandler
130.183 -CLASS Context
130.184 -CLASS Continue
130.185 -CLASS Control
130.186 -CLASS ControlsWindow
130.187 -CLASS ConversionError
130.188 -CLASS Cookie
130.189 -CLASS CookieError
130.190 -CLASS CookieJar
130.191 -CLASS CookiePolicy
130.192 -CLASS CoverageResults
130.193 -CLASS Cursor
130.194 -CLASS CygwinCCompiler
130.195 -CLASS D
130.196 -CLASS DOMBuilder
130.197 -CLASS DOMEntityResolver
130.198 -CLASS DOMError
130.199 -CLASS DOMEventStream
130.200 -CLASS DOMException
130.201 -CLASS DOMImplementation
130.202 -CLASS DOMInputSource
130.203 -CLASS DOMStringSizeErr
130.204 -CLASS DTDHandler
130.205 -CLASS Data
130.206 -CLASS Database
130.207 -CLASS DatagramHandler
130.208 -CLASS DatagramRequestHandler
130.209 -CLASS DateTime
130.210 -CLASS DbfilenameShelf
130.211 -CLASS DebugRunner
130.212 -CLASS DebuggingServer
130.213 -CLASS Decimal
130.214 -CLASS DecimalException
130.215 -CLASS DeclHandler
130.216 -CLASS DecodedGenerator
130.217 -CLASS Decorators
130.218 -CLASS DefaultCookiePolicy
130.219 -CLASS DefaultHandler
130.220 -CLASS Delegator
130.221 -CLASS DeprecationWarning
130.222 -CLASS DeprecationWarning
130.223 -CLASS Dialect
130.224 -CLASS Dialog
130.225 -CLASS DialogWindow
130.226 -CLASS Dict
130.227 -CLASS DictMixin
130.228 -CLASS DictReader
130.229 -CLASS DictWriter
130.230 -CLASS Differ
130.231 -CLASS DirList
130.232 -CLASS DirSelectBox
130.233 -CLASS DirSelectDialog
130.234 -CLASS DirTree
130.235 -CLASS Directory
130.236 -CLASS Discard
130.237 -CLASS Distribution
130.238 -CLASS DistributionMetadata
130.239 -CLASS DistributionTestCase
130.240 -CLASS DistutilsArgError
130.241 -CLASS DistutilsClassError
130.242 -CLASS DistutilsError
130.243 -CLASS DistutilsExecError
130.244 -CLASS DistutilsFileError
130.245 -CLASS DistutilsGetoptError
130.246 -CLASS DistutilsInternalError
130.247 -CLASS DistutilsModuleError
130.248 -CLASS DistutilsOptionError
130.249 -CLASS DistutilsPlatformError
130.250 -CLASS DistutilsSetupError
130.251 -CLASS DistutilsTemplateError
130.252 -CLASS Div
130.253 -CLASS DivisionByZero
130.254 -CLASS Doc
130.255 -CLASS DocCGIXMLRPCRequestHandler
130.256 -CLASS DocTest
130.257 -CLASS DocTestFailure
130.258 -CLASS DocTestFinder
130.259 -CLASS DocTestParser
130.260 -CLASS DocTestRunner
130.261 -CLASS DocXMLRPCRequestHandler
130.262 -CLASS DocXMLRPCServer
130.263 -CLASS Document
130.264 -CLASS DocumentFragment
130.265 -CLASS DocumentHandler
130.266 -CLASS DocumentType
130.267 -CLASS DomstringSizeErr
130.268 -CLASS DumbWriter
130.269 -CLASS DummyCommand
130.270 -CLASS DuplicateSectionError
130.271 -CLASS DynLoadSuffixImporter
130.272 -CLASS EMXCCompiler
130.273 -CLASS EOFError
130.274 -CLASS EOFError
130.275 -CLASS ESISDocHandler
130.276 -CLASS Element
130.277 -CLASS ElementInfo
130.278 -CLASS ElementTree
130.279 -CLASS Ellipsis
130.280 -CLASS Empty
130.281 -CLASS EmptyNode
130.282 -CLASS EndOfBlock
130.283 -CLASS Entity
130.284 -CLASS EntityResolver
130.285 -CLASS Enum
130.286 -CLASS EnvironmentError
130.287 -CLASS EnvironmentError
130.288 -CLASS Error
130.289 -CLASS ErrorDuringImport
130.290 -CLASS ErrorHandler
130.291 -CLASS ErrorPrinter
130.292 -CLASS ErrorRaiser
130.293 -CLASS Event
130.294 -CLASS EventBroadcaster
130.295 -CLASS EventException
130.296 -CLASS ExFileSelectBox
130.297 -CLASS Example
130.298 -CLASS ExampleASTVisitor
130.299 -CLASS Exception
130.300 -CLASS Exception
130.301 -CLASS Exec
130.302 -CLASS ExitNow
130.303 -CLASS ExpatError
130.304 -CLASS ExpatParser
130.305 -CLASS Expression
130.306 -CLASS ExpressionCodeGenerator
130.307 -CLASS Extension
130.308 -CLASS F
130.309 -CLASS FTP
130.310 -CLASS FTPHandler
130.311 -CLASS Factory
130.312 -CLASS FancyGetopt
130.313 -CLASS FancyModuleLoader
130.314 -CLASS FancyURLopener
130.315 -CLASS Fault
130.316 -CLASS Feature
130.317 -CLASS FeedParser
130.318 -CLASS FieldStorage
130.319 -CLASS FileCookieJar
130.320 -CLASS FileEntry
130.321 -CLASS FileHandler
130.322 -CLASS FileIO
130.323 -CLASS FileInput
130.324 -CLASS FileList
130.325 -CLASS FileSelectBox
130.326 -CLASS FileWrapper
130.327 -CLASS Filter
130.328 -CLASS Filterer
130.329 -CLASS FingerHandler
130.330 -CLASS FirstHeaderLineIsContinuationD
130.331 -CLASS FloatingPointError
130.332 -CLASS FloatingPointError
130.333 -CLASS FloorDiv
130.334 -CLASS FlowGraph
130.335 -CLASS Folder
130.336 -CLASS Foo
130.337 -CLASS For
130.338 -CLASS ForkingMixIn
130.339 -CLASS ForkingTCPServer
130.340 -CLASS ForkingUDPServer
130.341 -CLASS Form
130.342 -CLASS FormContent
130.343 -CLASS FormContentDict
130.344 -CLASS Formatter
130.345 -CLASS Fraction
130.346 -CLASS From
130.347 -CLASS FtException
130.348 -CLASS Full
130.349 -CLASS FuncPtr
130.350 -CLASS Function
130.351 -CLASS FunctionCodeGenerator
130.352 -CLASS FunctionScope
130.353 -CLASS FunctionTestCase
130.354 -CLASS FutureParser
130.355 -CLASS FutureWarning
130.356 -CLASS FutureWarning
130.357 -CLASS GNUTranslations
130.358 -CLASS GenExpr
130.359 -CLASS GenExprFor
130.360 -CLASS GenExprIf
130.361 -CLASS GenExprInner
130.362 -CLASS GenExprScope
130.363 -CLASS Generator
130.364 -CLASS GeneratorExit
130.365 -CLASS GeneratorExit
130.366 -CLASS Getattr
130.367 -CLASS GetattrMagic
130.368 -CLASS GetoptError
130.369 -CLASS Global
130.370 -CLASS GopherError
130.371 -CLASS GopherHandler
130.372 -CLASS GridBag
130.373 -CLASS GzipFile
130.374 -CLASS HList
130.375 -CLASS HMAC
130.376 -CLASS HRESULT
130.377 -CLASS HTMLDoc
130.378 -CLASS HTMLParseError
130.379 -CLASS HTMLParser
130.380 -CLASS HTMLRepr
130.381 -CLASS HTTP
130.382 -CLASS HTTPBasicAuthHandler
130.383 -CLASS HTTPConnection
130.384 -CLASS HTTPCookieProcessor
130.385 -CLASS HTTPDefaultErrorHandler
130.386 -CLASS HTTPDigestAuthHandler
130.387 -CLASS HTTPError
130.388 -CLASS HTTPErrorProcessor
130.389 -CLASS HTTPException
130.390 -CLASS HTTPHandler
130.391 -CLASS HTTPPasswordMgr
130.392 -CLASS HTTPPasswordMgrWithDefaultReal
130.393 -CLASS HTTPRedirectHandler
130.394 -CLASS HTTPResponse
130.395 -CLASS HTTPSConnection
130.396 -CLASS HTTPSHandler
130.397 -CLASS HTTPServer
130.398 -CLASS Handler
130.399 -CLASS HandlerBase
130.400 -CLASS Header
130.401 -CLASS HeaderParseError
130.402 -CLASS HeaderParser
130.403 -CLASS Headers
130.404 -CLASS HelpFormatter
130.405 -CLASS Helper
130.406 -CLASS HierarchyRequestErr
130.407 -CLASS Hook
130.408 -CLASS Hooks
130.409 -CLASS HtmlDiff
130.410 -CLASS IC
130.411 -CLASS IMAP4
130.412 -CLASS IMAP4_SSL
130.413 -CLASS IMAP4_stream
130.414 -CLASS IOBase
130.415 -CLASS IOError
130.416 -CLASS IOError
130.417 -CLASS Identified
130.418 -CLASS If
130.419 -CLASS IfExp
130.420 -CLASS Ignore
130.421 -CLASS IllegalMonthError
130.422 -CLASS IllegalWeekdayError
130.423 -CLASS ImmutableSet
130.424 -CLASS ImpImporter
130.425 -CLASS ImpLoader
130.426 -CLASS Import
130.427 -CLASS ImportError
130.428 -CLASS ImportError
130.429 -CLASS ImportManager
130.430 -CLASS ImportWarning
130.431 -CLASS ImportWarning
130.432 -CLASS Importer
130.433 -CLASS ImproperConnectionState
130.434 -CLASS Incomplete
130.435 -CLASS IncompleteRead
130.436 -CLASS IncrementalDecoder
130.437 -CLASS IncrementalEncoder
130.438 -CLASS IncrementalNewlineDecoder
130.439 -CLASS IncrementalParser
130.440 -CLASS IndentedHelpFormatter
130.441 -CLASS IndexError
130.442 -CLASS IndexError
130.443 -CLASS IndexSizeErr
130.444 -CLASS Inexact
130.445 -CLASS IniParser
130.446 -CLASS InputOnly
130.447 -CLASS InputSource
130.448 -CLASS InsertionLoc
130.449 -CLASS InstallScriptsTestCase
130.450 -CLASS InstallTestCase
130.451 -CLASS Integral
130.452 -CLASS Interactive
130.453 -CLASS InteractiveCodeGenerator
130.454 -CLASS InteractiveConsole
130.455 -CLASS InteractiveInterpreter
130.456 -CLASS InterpFormContentDict
130.457 -CLASS InterpolationDepthError
130.458 -CLASS InterpolationError
130.459 -CLASS InterpolationSyntaxError
130.460 -CLASS IntlText
130.461 -CLASS IntlWritingCode
130.462 -CLASS InuseAttributeErr
130.463 -CLASS InvalidAccessErr
130.464 -CLASS InvalidCharacterErr
130.465 -CLASS InvalidModificationErr
130.466 -CLASS InvalidNodeTypeErr
130.467 -CLASS InvalidOperation
130.468 -CLASS InvalidStateErr
130.469 -CLASS InvalidURL
130.470 -CLASS Invert
130.471 -CLASS IsqlCmd
130.472 -CLASS IsqlExit
130.473 -CLASS IterableUserDict
130.474 -CLASS JSONDecoder
130.475 -CLASS JSONEncoder
130.476 -CLASS JavaSAXParser
130.477 -CLASS JoinableQueue
130.478 -CLASS JyDTDHandlerWrapper
130.479 -CLASS JyEntityResolverWrapper
130.480 -CLASS JyErrorHandlerWrapper
130.481 -CLASS JyInputSourceWrapper
130.482 -CLASS JythonCompiler
130.483 -CLASS JythonSignalHandler
130.484 -CLASS KeyError
130.485 -CLASS KeyError
130.486 -CLASS KeyboardInterrupt
130.487 -CLASS KeyboardInterrupt
130.488 -CLASS Keyword
130.489 -CLASS LOBTestCase
130.490 -CLASS LWPCookieJar
130.491 -CLASS LabelEntry
130.492 -CLASS LabelFrame
130.493 -CLASS Lambda
130.494 -CLASS LambdaScope
130.495 -CLASS LargeZipFile
130.496 -CLASS LeftShift
130.497 -CLASS LexicalHandler
130.498 -CLASS LexicalXMLGenerator
130.499 -CLASS LibError
130.500 -CLASS LibraryLoader
130.501 -CLASS LineAddrTable
130.502 -CLASS LinkError
130.503 -CLASS List
130.504 -CLASS ListComp
130.505 -CLASS ListCompFor
130.506 -CLASS ListCompIf
130.507 -CLASS ListNoteBook
130.508 -CLASS Listener
130.509 -CLASS LittleEndianStructure
130.510 -CLASS LoadError
130.511 -CLASS LocalNameFinder
130.512 -CLASS Location
130.513 -CLASS Locator
130.514 -CLASS Lock
130.515 -CLASS Log
130.516 -CLASS LogRecord
130.517 -CLASS Logger
130.518 -CLASS LoggingSilencer
130.519 -CLASS Logical
130.520 -CLASS LookupError
130.521 -CLASS LookupError
130.522 -CLASS LooseVersion
130.523 -CLASS MH
130.524 -CLASS MHMailbox
130.525 -CLASS MHMessage
130.526 -CLASS MIMEApplication
130.527 -CLASS MIMEAudio
130.528 -CLASS MIMEBase
130.529 -CLASS MIMEImage
130.530 -CLASS MIMEMessage
130.531 -CLASS MIMEMultipart
130.532 -CLASS MIMENonMultipart
130.533 -CLASS MIMEText
130.534 -CLASS MMDF
130.535 -CLASS MMDFMessage
130.536 -CLASS MSVCCompiler
130.537 -CLASS MWerksCompiler
130.538 -CLASS MacroExpander
130.539 -CLASS Mailbox
130.540 -CLASS Maildir
130.541 -CLASS MaildirMessage
130.542 -CLASS MailmanProxy
130.543 -CLASS MalformedHeaderDefect
130.544 -CLASS Manager
130.545 -CLASS Marshaller
130.546 -CLASS MemoryError
130.547 -CLASS MemoryError
130.548 -CLASS MemoryHandler
130.549 -CLASS Message
130.550 -CLASS MessageDefect
130.551 -CLASS MessageError
130.552 -CLASS MessageParseError
130.553 -CLASS MetadataTestCase
130.554 -CLASS Meter
130.555 -CLASS MimeWriter
130.556 -CLASS Mingw32CCompiler
130.557 -CLASS MiniApplication
130.558 -CLASS MiniFieldStorage
130.559 -CLASS MisplacedEnvelopeHeaderDefect
130.560 -CLASS MissingSectionHeaderError
130.561 -CLASS MmdfMailbox
130.562 -CLASS Mod
130.563 -CLASS Model
130.564 -CLASS Module
130.565 -CLASS ModuleCodeGenerator
130.566 -CLASS ModuleFinder
130.567 -CLASS ModuleImporter
130.568 -CLASS ModuleLoader
130.569 -CLASS ModuleScanner
130.570 -CLASS ModuleScope
130.571 -CLASS MozillaCookieJar
130.572 -CLASS Mul
130.573 -CLASS MultiCall
130.574 -CLASS MultiCallIterator
130.575 -CLASS MultiFile
130.576 -CLASS MultipartConversionError
130.577 -CLASS MultipartInvariantViolationDef
130.578 -CLASS MutableString
130.579 -CLASS MyClass
130.580 -CLASS MyTest
130.581 -CLASS NNTP
130.582 -CLASS NNTPDataError
130.583 -CLASS NNTPPermanentError
130.584 -CLASS NNTPProtocolError
130.585 -CLASS NNTPReplyError
130.586 -CLASS NNTPTemporaryError
130.587 -CLASS NProperty
130.588 -CLASS NTEventLogHandler
130.589 -CLASS NULL
130.590 -CLASS Name
130.591 -CLASS NameError
130.592 -CLASS NameError
130.593 -CLASS NamedNodeMap
130.594 -CLASS NamespaceErr
130.595 -CLASS NannyNag
130.596 -CLASS NestedScopeMixin
130.597 -CLASS Netrc
130.598 -CLASS NetrcParseError
130.599 -CLASS NewStyle
130.600 -CLASS NoBoundaryInMultipartDefect
130.601 -CLASS NoDataAllowedErr
130.602 -CLASS NoModificationAllowedErr
130.603 -CLASS NoOpMetaClass
130.604 -CLASS NoOptionError
130.605 -CLASS NoSectionError
130.606 -CLASS Node
130.607 -CLASS NodeFilter
130.608 -CLASS NodeTransformer
130.609 -CLASS NodeVisitor
130.610 -CLASS Not
130.611 -CLASS NotANumber
130.612 -CLASS NotConnected
130.613 -CLASS NotFoundErr
130.614 -CLASS NotImplementedError
130.615 -CLASS NotImplementedError
130.616 -CLASS NotSupportedErr
130.617 -CLASS Notation
130.618 -CLASS NoteBook
130.619 -CLASS NullFormatter
130.620 -CLASS NullImporter
130.621 -CLASS NullTranslations
130.622 -CLASS NullWriter
130.623 -CLASS Number
130.624 -CLASS OSError
130.625 -CLASS OSError
130.626 -CLASS OSSAudioError
130.627 -CLASS ObjectSpecifier
130.628 -CLASS OleDLL
130.629 -CLASS OpFinder
130.630 -CLASS OpenerDirector
130.631 -CLASS OptParseError
130.632 -CLASS Option
130.633 -CLASS OptionConflictError
130.634 -CLASS OptionContainer
130.635 -CLASS OptionDummy
130.636 -CLASS OptionError
130.637 -CLASS OptionGroup
130.638 -CLASS OptionMenu
130.639 -CLASS OptionParser
130.640 -CLASS OptionValueError
130.641 -CLASS Or
130.642 -CLASS OracleSPTest
130.643 -CLASS Ordinal
130.644 -CLASS OutputChecker
130.645 -CLASS Overflow
130.646 -CLASS OverflowError
130.647 -CLASS OverflowError
130.648 -CLASS POP3
130.649 -CLASS POP3_SSL
130.650 -CLASS Packer
130.651 -CLASS PanedWindow
130.652 -CLASS Panel
130.653 -CLASS Parser
130.654 -CLASS ParserBase
130.655 -CLASS ParserError
130.656 -CLASS ParsingError
130.657 -CLASS Pass
130.658 -CLASS Pattern
130.659 -CLASS Pdb
130.660 -CLASS PendingDeprecationWarning
130.661 -CLASS PendingDeprecationWarning
130.662 -CLASS PickleError
130.663 -CLASS Pickler
130.664 -CLASS PicklingError
130.665 -CLASS PlaceHolder
130.666 -CLASS Popen
130.667 -CLASS Popen3
130.668 -CLASS Popen4
130.669 -CLASS PopupMenu
130.670 -CLASS PortableUnixMailbox
130.671 -CLASS Power
130.672 -CLASS PreprocessError
130.673 -CLASS PrettyPrinter
130.674 -CLASS Print
130.675 -CLASS Printnl
130.676 -CLASS Process
130.677 -CLASS ProcessingInstruction
130.678 -CLASS Profile
130.679 -CLASS ProgressBar
130.680 -CLASS Prompt
130.681 -CLASS ProtocolError
130.682 -CLASS ProxyBasicAuthHandler
130.683 -CLASS ProxyDigestAuthHandler
130.684 -CLASS ProxyHandler
130.685 -CLASS PullDOM
130.686 -CLASS PureProxy
130.687 -CLASS PyCompileError
130.688 -CLASS PyDLL
130.689 -CLASS PyDialog
130.690 -CLASS PyFlowGraph
130.691 -CLASS PyHKEY
130.692 -CLASS PyZipFile
130.693 -CLASS QDPoint
130.694 -CLASS QDRectangle
130.695 -CLASS QName
130.696 -CLASS Queue
130.697 -CLASS RExec
130.698 -CLASS RGBColor
130.699 -CLASS RLock
130.700 -CLASS RadioButtonGroup
130.701 -CLASS Raise
130.702 -CLASS Random
130.703 -CLASS Range
130.704 -CLASS RangeException
130.705 -CLASS Rational
130.706 -CLASS RawConfigParser
130.707 -CLASS RawIOBase
130.708 -CLASS RawTurtle
130.709 -CLASS ReadOnlySequentialNamedNodeMap
130.710 -CLASS Real
130.711 -CLASS Record
130.712 -CLASS ReferenceError
130.713 -CLASS ReferenceError
130.714 -CLASS Repr
130.715 -CLASS Request
130.716 -CLASS ResponseError
130.717 -CLASS ResponseNotReady
130.718 -CLASS ResultSet
130.719 -CLASS ResultSetRow
130.720 -CLASS Return
130.721 -CLASS RightShift
130.722 -CLASS RobotFileParser
130.723 -CLASS RootLogger
130.724 -CLASS RotatingFileHandler
130.725 -CLASS Rounded
130.726 -CLASS Row
130.727 -CLASS RuntimeError
130.728 -CLASS RuntimeError
130.729 -CLASS RuntimeWarning
130.730 -CLASS RuntimeWarning
130.731 -CLASS SAX2DOM
130.732 -CLASS SAXException
130.733 -CLASS SAXNotRecognizedException
130.734 -CLASS SAXNotSupportedException
130.735 -CLASS SAXParseException
130.736 -CLASS SAXReaderNotAvailable
130.737 -CLASS SGMLParseError
130.738 -CLASS SGMLParser
130.739 -CLASS SMTP
130.740 -CLASS SMTPAuthenticationError
130.741 -CLASS SMTPConnectError
130.742 -CLASS SMTPDataError
130.743 -CLASS SMTPException
130.744 -CLASS SMTPHandler
130.745 -CLASS SMTPHeloError
130.746 -CLASS SMTPRecipientsRefused
130.747 -CLASS SMTPResponseException
130.748 -CLASS SMTPSenderRefused
130.749 -CLASS SMTPServer
130.750 -CLASS SMTPServerDisconnected
130.751 -CLASS SQLServerSPTest
130.752 -CLASS SQLTestCase
130.753 -CLASS SSLError
130.754 -CLASS SSLSocket
130.755 -CLASS ST
130.756 -CLASS SafeConfigParser
130.757 -CLASS SafeTransport
130.758 -CLASS Schema
130.759 -CLASS Scope
130.760 -CLASS Screen
130.761 -CLASS ScrolledCavas
130.762 -CLASS ScrolledText
130.763 -CLASS ScrolledWindow
130.764 -CLASS Select
130.765 -CLASS Semaphore
130.766 -CLASS SequenceMatcher
130.767 -CLASS SerialCookie
130.768 -CLASS Server
130.769 -CLASS ServerHTMLDoc
130.770 -CLASS ServerProxy
130.771 -CLASS Set
130.772 -CLASS SgmlopParser
130.773 -CLASS Shape
130.774 -CLASS Shelf
130.775 -CLASS SimpleCookie
130.776 -CLASS SimpleHTTPRequestHandler
130.777 -CLASS SimpleHandler
130.778 -CLASS SimpleLocator
130.779 -CLASS SimpleXMLRPCDispatcher
130.780 -CLASS SimpleXMLRPCRequestHandler
130.781 -CLASS SimpleXMLRPCServer
130.782 -CLASS Slice
130.783 -CLASS Sliceobj
130.784 -CLASS SlowParser
130.785 -CLASS SmartCookie
130.786 -CLASS Sniffer
130.787 -CLASS SocketHandler
130.788 -CLASS SocketType
130.789 -CLASS Stack
130.790 -CLASS StackDepthTracker
130.791 -CLASS StandardError
130.792 -CLASS StandardError
130.793 -CLASS StartBoundaryNotFoundDefect
130.794 -CLASS Stats
130.795 -CLASS StdButtonBox
130.796 -CLASS Stmt
130.797 -CLASS StopIteration
130.798 -CLASS StopIteration
130.799 -CLASS StopTokenizing
130.800 -CLASS Strange
130.801 -CLASS StreamConverter
130.802 -CLASS StreamHandler
130.803 -CLASS StreamReader
130.804 -CLASS StreamRequestHandler
130.805 -CLASS StreamWriter
130.806 -CLASS StrictVersion
130.807 -CLASS StringIO
130.808 -CLASS Struct
130.809 -CLASS Structure
130.810 -CLASS StyledText
130.811 -CLASS Sub
130.812 -CLASS SubPattern
130.813 -CLASS Subnormal
130.814 -CLASS Subscript
130.815 -CLASS SummaryInformation
130.816 -CLASS Super
130.817 -CLASS SuperSuper
130.818 -CLASS SvFormContentDict
130.819 -CLASS Symbol
130.820 -CLASS SymbolTable
130.821 -CLASS SymbolVisitor
130.822 -CLASS SyncManager
130.823 -CLASS SyntaxErr
130.824 -CLASS SyntaxError
130.825 -CLASS SyntaxError
130.826 -CLASS SyntaxErrorChecker
130.827 -CLASS SyntaxWarning
130.828 -CLASS SyntaxWarning
130.829 -CLASS SysLogHandler
130.830 -CLASS SystemError
130.831 -CLASS SystemError
130.832 -CLASS SystemExit
130.833 -CLASS SystemExit
130.834 -CLASS SystemRandom
130.835 -CLASS TCPServer
130.836 -CLASS TList
130.837 -CLASS TalkTo
130.838 -CLASS TarError
130.839 -CLASS TarFile
130.840 -CLASS TarInfo
130.841 -CLASS Telnet
130.842 -CLASS TempdirManager
130.843 -CLASS Template
130.844 -CLASS Test
130.845 -CLASS TestCase
130.846 -CLASS TestClass
130.847 -CLASS TestCrispinTorture
130.848 -CLASS TestDistribution
130.849 -CLASS TestLoader
130.850 -CLASS TestResult
130.851 -CLASS TestSuite
130.852 -CLASS TestThread
130.853 -CLASS TestXMLParser
130.854 -CLASS Testcase
130.855 -CLASS Tester
130.856 -CLASS Text
130.857 -CLASS TextDoc
130.858 -CLASS TextFile
130.859 -CLASS TextIOBase
130.860 -CLASS TextIOWrapper
130.861 -CLASS TextRepr
130.862 -CLASS TextTestRunner
130.863 -CLASS TextWrapper
130.864 -CLASS Textbox
130.865 -CLASS Thread
130.866 -CLASS ThreadingMixIn
130.867 -CLASS ThreadingTCPServer
130.868 -CLASS ThreadingUDPServer
130.869 -CLASS ThreadingUnixDatagramServer
130.870 -CLASS ThreadingUnixStreamServer
130.871 -CLASS TimedRotatingFileHandler
130.872 -CLASS Timer
130.873 -CLASS TitledHelpFormatter
130.874 -CLASS Tix
130.875 -CLASS Tk
130.876 -CLASS TokenError
130.877 -CLASS Tokenizer
130.878 -CLASS TortureBase
130.879 -CLASS Trace
130.880 -CLASS Transformer
130.881 -CLASS Transport
130.882 -CLASS Tree
130.883 -CLASS TreeBuilder
130.884 -CLASS TryExcept
130.885 -CLASS TryFinally
130.886 -CLASS Tuple
130.887 -CLASS TupleArg
130.888 -CLASS Turtle
130.889 -CLASS TurtleScreen
130.890 -CLASS Type
130.891 -CLASS TypeError
130.892 -CLASS TypeError
130.893 -CLASS TypeInfo
130.894 -CLASS UDPServer
130.895 -CLASS URLError
130.896 -CLASS URLopener
130.897 -CLASS UUID
130.898 -CLASS UnaryAdd
130.899 -CLASS UnarySub
130.900 -CLASS UnboundLocalError
130.901 -CLASS UnboundLocalError
130.902 -CLASS Underflow
130.903 -CLASS UnexpectedException
130.904 -CLASS UnicodeDecodeError
130.905 -CLASS UnicodeDecodeError
130.906 -CLASS UnicodeEncodeError
130.907 -CLASS UnicodeEncodeError
130.908 -CLASS UnicodeError
130.909 -CLASS UnicodeError
130.910 -CLASS UnicodeTranslateError
130.911 -CLASS UnicodeTranslateError
130.912 -CLASS UnicodeWarning
130.913 -CLASS UnicodeWarning
130.914 -CLASS UnimplementedFileMode
130.915 -CLASS Union
130.916 -CLASS UnixCCompiler
130.917 -CLASS UnixDatagramServer
130.918 -CLASS UnixMailbox
130.919 -CLASS UnixStreamServer
130.920 -CLASS Unknown
130.921 -CLASS UnknownFileError
130.922 -CLASS UnknownHandler
130.923 -CLASS UnknownProtocol
130.924 -CLASS UnknownTransferEncoding
130.925 -CLASS Unload
130.926 -CLASS Unmarshaller
130.927 -CLASS Unpacker
130.928 -CLASS Unpickler
130.929 -CLASS UnpicklingError
130.930 -CLASS UnspecifiedEventTypeErr
130.931 -CLASS UnsupportedOperation
130.932 -CLASS UserDataHandler
130.933 -CLASS UserDict
130.934 -CLASS UserList
130.935 -CLASS UserString
130.936 -CLASS UserWarning
130.937 -CLASS UserWarning
130.938 -CLASS ValidationErr
130.939 -CLASS ValueError
130.940 -CLASS ValueError
130.941 -CLASS Values
130.942 -CLASS Vec2D
130.943 -CLASS Vendor
130.944 -CLASS Version
130.945 -CLASS VersionPredicate
130.946 -CLASS View
130.947 -CLASS WSGIRequestHandler
130.948 -CLASS WSGIServer
130.949 -CLASS Warning
130.950 -CLASS Warning
130.951 -CLASS Wave_read
130.952 -CLASS Wave_write
130.953 -CLASS WeakKeyDictionary
130.954 -CLASS WeakValueDictionary
130.955 -CLASS While
130.956 -CLASS WichmannHill
130.957 -CLASS WinDLL
130.958 -CLASS Window
130.959 -CLASS WindowsError
130.960 -CLASS WindowsError
130.961 -CLASS With
130.962 -CLASS WrongDocumentErr
130.963 -CLASS X
130.964 -CLASS XMLFilter
130.965 -CLASS XMLFilterBase
130.966 -CLASS XMLFilterImpl
130.967 -CLASS XMLGenerator
130.968 -CLASS XMLParser
130.969 -CLASS XMLRPCDocGenerator
130.970 -CLASS XMLReader
130.971 -CLASS XMLTreeBuilder
130.972 -CLASS XmlParseErr
130.973 -CLASS Yield
130.974 -CLASS Yuck
130.975 -CLASS ZeroDivisionError
130.976 -CLASS ZeroDivisionError
130.977 -CLASS ZipFile
130.978 -CLASS ZipImportError
130.979 -CLASS ZipInfo
130.980 -CLASS _CData [PROTECTE
130.981 -CLASS _FuncPtr [PROTECTE
130.982 -CLASS _SimpleCData [PROTECTE
130.983 -CLASS _posixfile_
130.984 -CLASS array
130.985 -CLASS async_chat
130.986 -CLASS bdist
130.987 -CLASS bdist_dumb
130.988 -CLASS bdist_msi
130.989 -CLASS bdist_rpm
130.990 -CLASS bdist_wininst
130.991 -CLASS bool
130.992 -CLASS bsddbobject
130.993 -CLASS build
130.994 -CLASS build_clib
130.995 -CLASS build_ext
130.996 -CLASS build_py
130.997 -CLASS build_scripts
130.998 -CLASS c_bool
130.999 -CLASS c_byte
130.1000 -CLASS c_char
130.1001 -CLASS c_char_p
130.1002 -CLASS c_double
130.1003 -CLASS c_float
130.1004 -CLASS c_int
130.1005 -CLASS c_int16
130.1006 -CLASS c_int32
130.1007 -CLASS c_int64
130.1008 -CLASS c_int8
130.1009 -CLASS c_long
130.1010 -CLASS c_longdouble
130.1011 -CLASS c_longlong
130.1012 -CLASS c_short
130.1013 -CLASS c_size_t
130.1014 -CLASS c_ubyte
130.1015 -CLASS c_uint
130.1016 -CLASS c_uint16
130.1017 -CLASS c_uint32
130.1018 -CLASS c_uint64
130.1019 -CLASS c_uint8
130.1020 -CLASS c_ulong
130.1021 -CLASS c_ulonglong
130.1022 -CLASS c_ushort
130.1023 -CLASS c_void_p
130.1024 -CLASS c_wchar
130.1025 -CLASS c_wchar_p
130.1026 -CLASS class
130.1027 -CLASS class
130.1028 -CLASS clean
130.1029 -CLASS closing
130.1030 -CLASS complex
130.1031 -CLASS compressobj
130.1032 -CLASS config
130.1033 -CLASS container
130.1034 -CLASS container
130.1035 -CLASS contextmanager
130.1036 -CLASS contextmanager
130.1037 -CLASS controller
130.1038 -CLASS date
130.1039 -CLASS datetime
130.1040 -CLASS dbexts
130.1041 -CLASS dbextsTestCase
130.1042 -CLASS dbhash
130.1043 -CLASS decompressobj
130.1044 -CLASS deque
130.1045 -CLASS dict
130.1046 -CLASS dict
130.1047 -CLASS dircmp
130.1048 -CLASS dispatcher
130.1049 -CLASS dispatcher_with_send
130.1050 -CLASS dl
130.1051 -CLASS error
130.1052 -CLASS error_data
130.1053 -CLASS error_reply
130.1054 -CLASS excel
130.1055 -CLASS excel_tab
130.1056 -CLASS executor
130.1057 -CLASS fifo
130.1058 -CLASS file
130.1059 -CLASS file
130.1060 -CLASS file_dispatcher
130.1061 -CLASS file_wrapper
130.1062 -CLASS float
130.1063 -CLASS float
130.1064 -CLASS foo
130.1065 -CLASS gaierror
130.1066 -CLASS herror
130.1067 -CLASS install
130.1068 -CLASS install_data
130.1069 -CLASS install_egg_info
130.1070 -CLASS install_headers
130.1071 -CLASS install_lib
130.1072 -CLASS install_misc
130.1073 -CLASS install_scripts
130.1074 -CLASS instance
130.1075 -CLASS instance
130.1076 -CLASS int
130.1077 -CLASS iterator
130.1078 -CLASS iterator
130.1079 -CLASS list
130.1080 -CLASS local
130.1081 -CLASS lock
130.1082 -CLASS long
130.1083 -CLASS main
130.1084 -CLASS mbox
130.1085 -CLASS mboxMessage
130.1086 -CLASS mllib
130.1087 -CLASS mmap
130.1088 -CLASS multiprocessing.Pool
130.1089 -CLASS mutex
130.1090 -CLASS mxODBCProxy
130.1091 -CLASS netrc
130.1092 -CLASS object
130.1093 -CLASS object
130.1094 -CLASS oss_audio_device
130.1095 -CLASS oss_mixer_device
130.1096 -CLASS poll
130.1097 -CLASS py_object
130.1098 -CLASS register
130.1099 -CLASS scheduler
130.1100 -CLASS sdist
130.1101 -CLASS set
130.1102 -CLASS set
130.1103 -CLASS shlex
130.1104 -CLASS simple_producer
130.1105 -CLASS socket
130.1106 -CLASS stat_result
130.1107 -CLASS str
130.1108 -CLASS str
130.1109 -CLASS test_dist
130.1110 -CLASS test_zxjdbc
130.1111 -CLASS time
130.1112 -CLASS timedelta
130.1113 -CLASS timeout
130.1114 -CLASS tixCommand
130.1115 -CLASS tmxxx
130.1116 -CLASS tuple
130.1117 -CLASS tzinfo
130.1118 -CLASS unicode
130.1119 -CLASS unicode
130.1120 -CLASS upload
130.1121 -CLASS window
130.1122 -CLASS xmlparser
130.1123 -CLASS zipimporter
130.1124 -CLASS zxAPITestCase
130.1125 -CLASS zxCoreTestCase
130.1126 -CLASS zxJDBCTestCase
130.1127 -METHOD __import__(name, globals, loca
130.1128 -METHOD abs(x)
130.1129 -METHOD all(iterable)
130.1130 -METHOD any(iterable)
130.1131 -METHOD ---apply(function, args, ke---
130.1132 -METHOD basestring()
130.1133 -METHOD bin(x)
130.1134 -METHOD bool(x)
130.1135 -METHOD buffer(object, offset, size)
130.1136 -METHOD callable(object)
130.1137 -METHOD chr(i)
130.1138 -METHOD classmethod(function)
130.1139 -METHOD cmp(x, y)
130.1140 -METHOD coerce(x, y)
130.1141 -METHOD compile(source, filename, mode
130.1142 -METHOD complex(real, imag)
130.1143 -METHOD delattr(object, name)
130.1144 -METHOD dict(arg)
130.1145 -METHOD dir(object)
130.1146 -METHOD divmod(a, b)
130.1147 -METHOD enumerate(sequence, start)
130.1148 -METHOD eval(expression, globals, loca
130.1149 -METHOD execfile(filename, globals, lo
130.1150 -METHOD exit(code)
130.1151 -METHOD file(filename, mode, bufsize)
130.1152 -METHOD filter(function, iterable)
130.1153 -METHOD float(x)
130.1154 -METHOD frozenset(iterable)
130.1155 -METHOD getattr(object, name, default)
130.1156 -METHOD globals()
130.1157 -METHOD hasattr(object, name)
130.1158 -METHOD hash(object)
130.1159 -METHOD help(object)
130.1160 -METHOD hex(x)
130.1161 -METHOD id(object)
130.1162 -METHOD input(prompt)
130.1163 -METHOD int(x, radix)
130.1164 -METHOD intern(string)
130.1165 -METHOD isinstance(object, classinfo)
130.1166 -METHOD issubclass(class, classinfo)
130.1167 -METHOD iter(o, sentinel)
130.1168 -METHOD len(s)
130.1169 -METHOD list(iterable)
130.1170 -METHOD locals()
130.1171 -METHOD long(x, radix)
130.1172 -METHOD map(function, iterable)
130.1173 -METHOD max(iterable, argskey)
130.1174 -METHOD min(iterable, argskey)
130.1175 -METHOD next(iterator, default)
130.1176 -METHOD object()
130.1177 -METHOD oct(x)
130.1178 -METHOD open(filename, mode, bufsize)
130.1179 -METHOD ord(c)
130.1180 -METHOD pow(x, y, z)
130.1181 -METHOD print(object, sep, end, file)
130.1182 -METHOD property(fget, fset, fdel, doc
130.1183 -METHOD quit(code)
130.1184 -METHOD range(start, stop, step)
130.1185 -METHOD raw_input(prompt)
130.1186 -METHOD reduce(function, iterable, ini
130.1187 -METHOD reload(module)
130.1188 -METHOD repr(object)
130.1189 -METHOD reversed(seq)
130.1190 -METHOD round(x, n)
130.1191 -METHOD set(iterable)
130.1192 -METHOD setattr(object, name, value)
130.1193 -METHOD slice(start, stop, step)
130.1194 -METHOD sorted(iterable, cmp, key, rev
130.1195 -METHOD staticmethod(function)
130.1196 -METHOD str(object)
130.1197 -METHOD sum(iterable, start)
130.1198 -METHOD super(type, object-or-type)
130.1199 -METHOD tuple(iterable)
130.1200 -METHOD type(name, bases, dict)
130.1201 -METHOD type(object)
130.1202 -METHOD unichr(i)
130.1203 -METHOD unicode(object, encoding, erro
130.1204 -METHOD vars(object)
130.1205 -METHOD xrange(start, stop, step)
130.1206 -METHOD zip(iterable)
130.1207 -VARIABLE Ellipsis
130.1208 -VARIABLE False
130.1209 -VARIABLE None
130.1210 -VARIABLE NotImplemented
130.1211 -VARIABLE True
130.1212 -VARIABLE __debug__
130.1213 -VARIABLE copyright
130.1214 -KEYWORD and
130.1215 -KEYWORD as
130.1216 -KEYWORD assert
130.1217 -KEYWORD break
130.1218 -KEYWORD class
130.1219 -KEYWORD continue
130.1220 -KEYWORD def
130.1221 -KEYWORD del
130.1222 -KEYWORD elif
130.1223 -KEYWORD else
130.1224 -KEYWORD except
130.1225 -KEYWORD exec
130.1226 -KEYWORD finally
130.1227 -KEYWORD for
130.1228 -KEYWORD from
130.1229 -KEYWORD global
130.1230 -KEYWORD if
130.1231 -KEYWORD import
130.1232 -KEYWORD in
130.1233 -KEYWORD is
130.1234 -KEYWORD lambda
130.1235 -KEYWORD not
130.1236 -KEYWORD or
130.1237 -KEYWORD pass
130.1238 -KEYWORD print
130.1239 -KEYWORD raise
130.1240 -KEYWORD return
130.1241 -KEYWORD try
130.1242 -KEYWORD while
130.1243 -KEYWORD with
130.1244 -KEYWORD yield
131.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testClasses2.completion Sun Jan 04 13:11:53 2015 -0600
131.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
131.3 @@ -1,26 +0,0 @@
131.4 -Code completion result for source line:
131.5 -raise D|uplicateSectionError(section)
131.6 -(QueryType=COMPLETION, NameKind=PREFIX)
131.7 -------------------------------------
131.8 -CLASS DOMException
131.9 -CLASS DOMStringSizeErr
131.10 -CLASS DecimalException
131.11 -CLASS DeprecationWarning
131.12 -CLASS DistutilsArgError
131.13 -CLASS DistutilsClassError
131.14 -CLASS DistutilsError
131.15 -CLASS DistutilsExecError
131.16 -CLASS DistutilsFileError
131.17 -CLASS DistutilsGetoptError
131.18 -CLASS DistutilsInternalError
131.19 -CLASS DistutilsModuleError
131.20 -CLASS DistutilsOptionError
131.21 -CLASS DistutilsPlatformError
131.22 -CLASS DistutilsSetupError
131.23 -CLASS DistutilsTemplateError
131.24 -CLASS DivisionByZero
131.25 -CLASS DivisionImpossible [PRIVATE]
131.26 -CLASS DivisionUndefined [PRIVATE]
131.27 -CLASS DocTestFailure
131.28 -CLASS DomstringSizeErr
131.29 -CLASS DuplicateSectionError
132.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testFix8.fixed Sun Jan 04 13:11:53 2015 -0600
132.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
132.3 @@ -1,621 +0,0 @@
132.4 -"""Configuration file parser.
132.5 -
132.6 -A setup file consists of sections, lead by a "[section]" header,
132.7 -and followed by "name: value" entries, with continuations and such in
132.8 -the style of RFC 822.
132.9 -
132.10 - the same section, or values in a special [DEFAULT] section.
132.11 -
132.12 -For example:
132.13 -
132.14 - something: %(dir)s/whatever
132.15 -
132.16 -would resolve the "%(dir)s" to the value of dir. All reference
132.17 -expansions are done late, on demand.
132.18 -
132.19 -Intrinsic defaults can be specified by passing them into the
132.20 -ConfigParser constructor as a dictionary.
132.21 -
132.22 -class:
132.23 -
132.24 -ConfigParser -- responsible for parsing a list of
132.25 - configuration files, and managing the parsed database.
132.26 -
132.27 - methods:
132.28 -
132.29 - __init__(defaults=None)
132.30 - create the parser and specify a dictionary of intrinsic defaults. The
132.31 - keys must be strings, the values must be appropriate for %()s string
132.32 - interpolation. Note that `__name__' is always an intrinsic default;
132.33 - it's value is the section's name.
132.34 -
132.35 - sections()
132.36 - return all the configuration section names, sans DEFAULT
132.37 -
132.38 - has_section(section)
132.39 - return whether the given section exists
132.40 -
132.41 - has_option(section, option)
132.42 - return whether the given option exists in the given section
132.43 -
132.44 - options(section)
132.45 - return list of configuration options for the named section
132.46 -
132.47 - read(filenames)
132.48 - read and parse the list of named configuration files, given by
132.49 - name. A single filename is also allowed. Non-existing files
132.50 - are ignored.
132.51 -
132.52 - readfp(fp, filename=None)
132.53 - read and parse one configuration file, given as a file object.
132.54 - The filename defaults to fp.name; it is only used in error
132.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
132.56 -
132.57 - get(section, option, raw=False, vars=None)
132.58 - return a string value for the named option. All % interpolations are
132.59 - expanded in the return values, based on the defaults passed into the
132.60 - constructor and the DEFAULT section. Additional substitutions may be
132.61 - provided using the `vars' argument, which must be a dictionary whose
132.62 - contents override any pre-existing defaults.
132.63 -
132.64 - getint(section, options)
132.65 - like get(), but convert value to an integer
132.66 -
132.67 - getfloat(section, options)
132.68 - like get(), but convert value to a float
132.69 -
132.70 - getboolean(section, options)
132.71 - like get(), but convert value to a boolean (currently case
132.72 - insensitively defined as 0, false, no, off for False, and 1, true,
132.73 - yes, on for True). Returns False or True.
132.74 -
132.75 - items(section, raw=False, vars=None)
132.76 - return a list of tuples with (name, value) for each option
132.77 - in the section.
132.78 -
132.79 - remove_section(section)
132.80 - remove the given file section and all its options
132.81 -
132.82 - remove_option(section, option)
132.83 - remove the given option from the given section
132.84 -
132.85 - set(section, option, value)
132.86 - set the given option
132.87 -
132.88 - write(fp)
132.89 - write the configuration state in .ini format
132.90 -"""
132.91 -
132.92 -import re
132.93 -
132.94 -__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
132.95 - "InterpolationError", "InterpolationDepthError",
132.96 - "InterpolationSyntaxError", "ParsingError",
132.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
132.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
132.99 -
132.100 -DEFAULTSECT = "DEFAULT"
132.101 -
132.102 -MAX_INTERPOLATION_DEPTH = 10
132.103 -
132.104 -
132.105 -
132.106 -# exception classes
132.107 -class Error(Exception):
132.108 - """Base class for ConfigParser exceptions."""
132.109 -
132.110 - def __init__(self, msg=''):
132.111 - self.message = msg
132.112 - Exception.__init__(self, msg)
132.113 -
132.114 - def __repr__(self):
132.115 - return self.message
132.116 -
132.117 - __str__ = __repr__
132.118 -
132.119 -class NoSectionError(Error):
132.120 - """Rasssised when no section matches a requested option."""
132.121 -
132.122 - def __init__(self, section):
132.123 - Error.__init__(self, 'No section: ' + `section`)
132.124 - self.section = section
132.125 -
132.126 -class DuplicateSectionError(Error):
132.127 - """Raised when a section is multiply-created."""
132.128 -
132.129 - def __init__(self, section):
132.130 - Error.__init__(self, "Section %r already exists" % section)
132.131 - self.section = section
132.132 -
132.133 -class NoOptionError(Error):
132.134 - """A requested option was not found."""
132.135 -
132.136 - def __init__(self, option, section):
132.137 - Error.__init__(self, "No option %r in section: %r" %
132.138 - (option, section))
132.139 - self.option = option
132.140 - self.section = section
132.141 -
132.142 -class InterpolationError(Error):
132.143 - """Base class for interpolation-related exceptions."""
132.144 -
132.145 - def __init__(self, option, section, msg):
132.146 - Error.__init__(self, msg)
132.147 - self.option = option
132.148 - self.section = section
132.149 -
132.150 -class InterpolationMissingOptionError(InterpolationError):
132.151 - """A string substitution required a setting which was not available."""
132.152 -
132.153 - def __init__(self, option, section, rawval, reference):
132.154 - msg = ("Bad value substitution:\n"
132.155 - "\tsection: [%s]\n"
132.156 - "\toption : %s\n"
132.157 - "\tkey : %s\n"
132.158 - "\trawval : %s\n"
132.159 - % (section, option, reference, rawval))
132.160 - InterpolationError.__init__(self, option, section, msg)
132.161 - self.reference = reference
132.162 -
132.163 -class InterpolationSyntaxError(InterpolationError):
132.164 - """Raised when the source text into which substitutions are made
132.165 - does not conform to the required syntax."""
132.166 -
132.167 -class InterpolationDepthError(InterpolationError):
132.168 - """Raised when substitutions are nested too deeply."""
132.169 -
132.170 - def __init__(self, option, section, rawval):
132.171 - msg = ("Value interpolation too deeply recursive:\n"
132.172 - "\tsection: [%s]\n"
132.173 - "\toption : %s\n"
132.174 - "\trawval : %s\n"
132.175 - % (section, option, rawval))
132.176 - InterpolationError.__init__(self, option, section, msg)
132.177 -
132.178 -class ParsingError(Error):
132.179 - """Raised when a configuration file does not follow legal syntax."""
132.180 -
132.181 - def __init__(self, filename):
132.182 - Error.__init__(self, 'File contains parsing errors: %s' % filename)
132.183 - self.filename = filename
132.184 - self.errors = []
132.185 -
132.186 - def append(self, lineno, line):
132.187 - self.errors.append((lineno, line))
132.188 - self.message += '\n\t[line %2d]: %s' % (lineno, line)
132.189 -
132.190 -class MissingSectionHeaderError(ParsingError):
132.191 - """Raised when a key-value pair is found before any section header."""
132.192 -
132.193 - def __init__(self, filename, lineno, line):
132.194 - Error.__init__(
132.195 - self,
132.196 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
132.197 - (filename, lineno, line))
132.198 - self.filename = filename
132.199 - self.lineno = lineno
132.200 - self.line = line
132.201 -
132.202 -
132.203 -
132.204 -class RawConfigParser:
132.205 - def __init__(self, defaults=None):
132.206 - self._sections = {}
132.207 - if defaults is None:
132.208 - self._defaults = {}
132.209 - else:
132.210 - self._defaults = defaults
132.211 -
132.212 - def defaults(self):
132.213 - return self._defaults
132.214 -
132.215 - def sections(self):
132.216 - """Return a list of section names, excluding [DEFAULT]"""
132.217 - # self._sections will never have [DEFAULT] in it
132.218 - return self._sections.keys()
132.219 -
132.220 - def add_section(self, section):
132.221 - """Create a new section in the configuration.
132.222 -
132.223 - Raise DuplicateSectionError if a section by the specified name
132.224 - already exists.
132.225 - """
132.226 - if section in self._sections:
132.227 - raise DuplicateSectionError(section)
132.228 - self._sections[section] = {}
132.229 -
132.230 - def has_section(self, section):
132.231 - """Indicate whether the named section is present in the configuration.
132.232 -
132.233 - The DEFAULT section is not acknowledged.
132.234 - """
132.235 - return section in self._sections
132.236 -
132.237 - def options(self, section):
132.238 - """Return a list of option names for the given section name."""
132.239 - opts = |>new_name<|(self, section, self)
132.240 - opts.update(self._defaults)
132.241 - if '__name__' in opts:
132.242 - del opts['__name__']
132.243 - return opts.keys()
132.244 -
132.245 -
132.246 - def |>^new_name<|(self, section, self):
132.247 - try:
132.248 - opts = self._sections[section].copy()
132.249 - except KeyError:
132.250 - raise NoSectionError(section)
132.251 -
132.252 - return opts
132.253 -
132.254 - def read(self, filenames):
132.255 - """Read and parse a filename or a list of filenames.
132.256 -
132.257 - Files that cannot be opened are silently ignored; this is
132.258 - designed so that you can specify a list of potential
132.259 - configuration file locations (e.g. current directory, user's
132.260 - home directory, systemwide directory), and all existing
132.261 - configuration files in the list will be read. A single
132.262 - filename may also be given.
132.263 - """
132.264 - if isinstance(filenames, basestring):
132.265 - filenames = [filenames]
132.266 - for filename in filenames:
132.267 - try:
132.268 - fp = open(filename)
132.269 - except IOError:
132.270 - continue
132.271 - self._read(fp, filename)
132.272 - fp.close()
132.273 -
132.274 - def readfp(self, fp, filename=None):
132.275 - """Like read() but the argument must be a file-like object.
132.276 -
132.277 - The `fp' argument must have a `readline' method. Optional
132.278 - second argument is the `filename', which if not given, is
132.279 - taken from fp.name. If fp has no `name' attribute, `<???>' is
132.280 - used.
132.281 -
132.282 - """
132.283 - if filename is None:
132.284 - try:
132.285 - filename = fp.name
132.286 - except AttributeError:
132.287 - filename = '<???>'
132.288 - self._read(fp, filename)
132.289 -
132.290 - def get(self, section, option):
132.291 - opt = self.optionxform(option)
132.292 - if section not in self._sections:
132.293 - if section != DEFAULTSECT:
132.294 - raise NoSectionError(section)
132.295 - if opt in self._defaults:
132.296 - return self._defaults[opt]
132.297 - else:
132.298 - raise NoOptionError(option, section)
132.299 - elif opt in self._sections[section]:
132.300 - return self._sections[section][opt]
132.301 - elif opt in self._defaults:
132.302 - return self._defaults[opt]
132.303 - else:
132.304 - raise NoOptionError(option, section)
132.305 -
132.306 - def items(self, section):
132.307 - try:
132.308 - d2 = self._sections[section]
132.309 - except KeyError:
132.310 - if section != DEFAULTSECT:
132.311 - raise NoSectionError(section)
132.312 - d2 = {}
132.313 - d = self._defaults.copy()
132.314 - d.update(d2)
132.315 - if "__name__" in d:
132.316 - del d["__name__"]
132.317 - return d.items()
132.318 -
132.319 - def _get(self, section, conv, option):
132.320 - return conv(self.get(section, option))
132.321 -
132.322 - def getint(self, section, option):
132.323 - return self._get(section, int, option)
132.324 -
132.325 - def getfloat(self, section, option):
132.326 - return self._get(section, float, option)
132.327 -
132.328 - _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
132.329 - '0': False, 'no': False, 'false': False, 'off': False}
132.330 -
132.331 - def getboolean(self, section, option):
132.332 - v = self.get(section, option)
132.333 - if v.lower() not in self._boolean_states:
132.334 - raise ValueError, 'Not a boolean: %s' % v
132.335 - return self._boolean_states[v.lower()]
132.336 -
132.337 - def optionxform(self, optionstr):
132.338 - return optionstr.lower()
132.339 -
132.340 - def has_option(self, section, option):
132.341 - """Check for the existence of a given option in a given section."""
132.342 - if not section or section == DEFAULTSECT:
132.343 - option = self.optionxform(option)
132.344 - return option in self._defaults
132.345 - elif section not in self._sections:
132.346 - return False
132.347 - else:
132.348 - option = self.optionxform(option)
132.349 - return (option in self._sections[section]
132.350 - or option in self._defaults)
132.351 -
132.352 - def set(self, section, option, value):
132.353 - """Set an option."""
132.354 - if not section or section == DEFAULTSECT:
132.355 - sectdict = self._defaults
132.356 - else:
132.357 - try:
132.358 - sectdict = self._sections[section]
132.359 - except KeyError:
132.360 - raise NoSectionError(section)
132.361 - sectdict[self.optionxform(option)] = value
132.362 -
132.363 - def write(self, fp):
132.364 - """Write an .ini-format representation of the configuration state."""
132.365 - if self._defaults:
132.366 - fp.write("[%s]\n" % DEFAULTSECT)
132.367 - for (key, value) in self._defaults.items():
132.368 - fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
132.369 - fp.write("\n")
132.370 - for section in self._sections:
132.371 - fp.write("[%s]\n" % section)
132.372 - for (key, value) in self._sections[section].items():
132.373 - if key != "__name__":
132.374 - fp.write("%s = %s\n" %
132.375 - (key, str(value).replace('\n', '\n\t')))
132.376 - fp.write("\n")
132.377 -
132.378 - def remove_option(self, section, option):
132.379 - """Remove an option."""
132.380 - if not section or section == DEFAULTSECT:
132.381 - sectdict = self._defaults
132.382 - else:
132.383 - try:
132.384 - sectdict = self._sections[section]
132.385 - except KeyError:
132.386 - raise NoSectionError(section)
132.387 - option = self.optionxform(option)
132.388 - existed = option in sectdict
132.389 - if existed:
132.390 - del sectdict[option]
132.391 - return existed
132.392 -
132.393 - def remove_section(self, section):
132.394 - """Remove a file section."""
132.395 - existed = section in self._sections
132.396 - if existed:
132.397 - del self._sections[section]
132.398 - return existed
132.399 -
132.400 - #
132.401 - # Regular expressions for parsing section headers and options.
132.402 - #
132.403 - SECTCRE = re.compile(
132.404 - r'\[' # [
132.405 - r'(?P<header>[^]]+)' # very permissive!
132.406 - r'\]' # ]
132.407 - )
132.408 - OPTCRE = re.compile(
132.409 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
132.410 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
132.411 - # followed by separator
132.412 - # (either : or =), followed
132.413 - # by any # space/tab
132.414 - r'(?P<value>.*)$' # everything up to eol
132.415 - )
132.416 -
132.417 - def _read(self, fp, fpname):
132.418 - """Parse a sectioned setup file.
132.419 -
132.420 - The sections in setup file contains a title line at the top,
132.421 - indicated by a name in square brackets (`[]'), plus key/value
132.422 - options lines, indicated by `name: value' format lines.
132.423 - Continuations are represented by an embedded newline then
132.424 - leading whitespace. Blank lines, lines beginning with a '#',
132.425 - and just about everything else are ignored.
132.426 - """
132.427 - cursect = None # None, or a dictionary
132.428 - optname = None
132.429 - lineno = 0
132.430 - e = None # None, or an exception
132.431 - while True:
132.432 - line = fp.readline()
132.433 - if not line:
132.434 - break
132.435 - lineno = lineno + 1
132.436 - # comment or blank line?
132.437 - if line.strip() == '' or line[0] in '#;':
132.438 - continue
132.439 - if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
132.440 - # no leading whitespace
132.441 - continue
132.442 - # continuation line?
132.443 - if line[0].isspace() and cursect is not None and optname:
132.444 - value = line.strip()
132.445 - if value:
132.446 - cursect[optname] = "%s\n%s" % (cursect[optname], value)
132.447 - # a section header or option header?
132.448 - else:
132.449 - # is it a section header?
132.450 - mo = self.SECTCRE.match(line)
132.451 - if mo:
132.452 - sectname = mo.group('header')
132.453 - if sectname in self._sections:
132.454 - cursect = self._sections[sectname]
132.455 - elif sectname == DEFAULTSECT:
132.456 - cursect = self._defaults
132.457 - else:
132.458 - cursect = {'__name__': sectname}
132.459 - self._sections[sectname] = cursect
132.460 - # So sections can't start with a continuation line
132.461 - optname = None
132.462 - # no section header in the file?
132.463 - elif cursect is None:
132.464 - raise MissingSectionHeaderError(fpname, lineno, `line`)
132.465 - # an option line?
132.466 - else:
132.467 - mo = self.OPTCRE.match(line)
132.468 - if mo:
132.469 - optname, vi, optval = mo.group('option', 'vi', 'value')
132.470 - if vi in ('=', ':') and ';' in optval:
132.471 - # ';' is a comment delimiter only if it follows
132.472 - # a spacing character
132.473 - pos = optval.find(';')
132.474 - if pos != -1 and optval[pos-1].isspace():
132.475 - optval = optval[:pos]
132.476 - optval = optval.strip()
132.477 - # allow empty values
132.478 - if optval == '""':
132.479 - optval = ''
132.480 - optname = self.optionxform(optname.rstrip())
132.481 - cursect[optname] = optval
132.482 - else:
132.483 - # a non-fatal parsing error occurred. set up the
132.484 - # exception but keep going. the exception will be
132.485 - # raised at the end of the file and will contain a
132.486 - # list of all bogus lines
132.487 - if not e:
132.488 - e = ParsingError(fpname)
132.489 - e.append(lineno, `line`)
132.490 - # if any parsing errors occurred, raise an exception
132.491 - if e:
132.492 - raise e
132.493 -
132.494 -
132.495 -class ConfigParser(RawConfigParser):
132.496 -
132.497 - def get(self, section, option, raw=False, vars=None):
132.498 - """Get an option value for a given section.
132.499 -
132.500 - All % interpolations are expanded in the return values, based on the
132.501 - defaults passed into the constructor, unless the optional argument
132.502 - `raw' is true. Additional substitutions may be provided using the
132.503 - `vars' argument, which must be a dictionary whose contents overrides
132.504 - any pre-existing defaults.
132.505 -
132.506 - The section DEFAULT is special.
132.507 - """
132.508 - d = self._defaults.copy()
132.509 - try:
132.510 - d.update(self._sections[section])
132.511 - except KeyError:
132.512 - if section != DEFAULTSECT:
132.513 - raise NoSectionError(section)
132.514 - # Update with the entry specific variables
132.515 - if vars is not None:
132.516 - d.update(vars)
132.517 - option = self.optionxform(option)
132.518 - try:
132.519 - value = d[option]
132.520 - except KeyError:
132.521 - raise NoOptionError(option, section)
132.522 -
132.523 - if raw:
132.524 - return value
132.525 - else:
132.526 - return self._interpolate(section, option, value, d)
132.527 -
132.528 - def items(self, section, raw=False, vars=None):
132.529 - """Return a list of tuples with (name, value) for each option
132.530 - in the section.
132.531 -
132.532 - All % interpolations are expanded in the return values, based on the
132.533 - defaults passed into the constructor, unless the optional argument
132.534 - `raw' is true. Additional substitutions may be provided using the
132.535 - `vars' argument, which must be a dictionary whose contents overrides
132.536 - any pre-existing defaults.
132.537 -
132.538 - The section DEFAULT is special.
132.539 - """
132.540 - d = self._defaults.copy()
132.541 - try:
132.542 - d.update(self._sections[section])
132.543 - except KeyError:
132.544 - if section != DEFAULTSECT:
132.545 - raise NoSectionError(section)
132.546 - # Update with the entry specific variables
132.547 - if vars:
132.548 - d.update(vars)
132.549 - options = d.keys()
132.550 - if "__name__" in options:
132.551 - options.remove("__name__")
132.552 - if raw:
132.553 - return [(option, d[option])
132.554 - for option in options]
132.555 - else:
132.556 - return [(option, self._interpolate(section, option, d[option], d))
132.557 - for option in options]
132.558 -
132.559 - def _interpolate(self, section, option, rawval, vars):
132.560 - # do the string interpolation
132.561 - value = rawval
132.562 - depth = MAX_INTERPOLATION_DEPTH
132.563 - while depth: # Loop through this until it's done
132.564 - depth -= 1
132.565 - if value.find("%(") != -1:
132.566 - try:
132.567 - value = value % vars
132.568 - except KeyError, e:
132.569 - raise InterpolationMissingOptionError(
132.570 - option, section, rawval, e[0])
132.571 - else:
132.572 - break
132.573 - if value.find("%(") != -1:
132.574 - raise InterpolationDepthError(option, section, rawval)
132.575 - return value
132.576 -
132.577 -
132.578 -class SafeConfigParser(ConfigParser):
132.579 -
132.580 - def _interpolate(self, section, option, rawval, vars):
132.581 - # do the string interpolation
132.582 - L = []
132.583 - self._interpolate_some(option, L, rawval, section, vars, 1)
132.584 - return ''.join(L)
132.585 -
132.586 - _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
132.587 -
132.588 - def _interpolate_some(self, option, accum, rest, section, map, depth):
132.589 - if depth > MAX_INTERPOLATION_DEPTH:
132.590 - raise InterpolationDepthError(option, section, rest)
132.591 - while rest:
132.592 - p = rest.find("%")
132.593 - if p < 0:
132.594 - accum.append(rest)
132.595 - return
132.596 - if p > 0:
132.597 - accum.append(rest[:p])
132.598 - rest = rest[p:]
132.599 - # p is no longer used
132.600 - c = rest[1:2]
132.601 - if c == "%":
132.602 - accum.append("%")
132.603 - rest = rest[2:]
132.604 - elif c == "(":
132.605 - m = self._interpvar_match(rest)
132.606 - if m is None:
132.607 - raise InterpolationSyntaxError(option, section,
132.608 - "bad interpolation variable reference %r" % rest)
132.609 - var = m.group(1)
132.610 - rest = rest[m.end():]
132.611 - try:
132.612 - v = map[var]
132.613 - except KeyError:
132.614 - raise InterpolationMissingOptionError(
132.615 - option, section, rest, var)
132.616 - if "%" in v:
132.617 - self._interpolate_some(option, accum, v,
132.618 - section, map, depth + 1)
132.619 - else:
132.620 - accum.append(v)
132.621 - else:
132.622 - raise InterpolationSyntaxError(
132.623 - option, section,
132.624 - "'%' must be followed by '%' or '(', found: " + `ret`)
133.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testGetByCaretOffset.path Sun Jan 04 13:11:53 2015 -0600
133.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
133.3 @@ -1,6 +0,0 @@
133.4 -Module:OffsetRange[0,22066>
133.5 -ClassDef:OffsetRange[3844,4067>
133.6 -FunctionDef:OffsetRange[3938,4067>
133.7 -Expr:OffsetRange[3975,4034>
133.8 -Call:OffsetRange[3975,4034>
133.9 -Name:OffsetRange[3990,3994>
134.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testGetByNode1.path Sun Jan 04 13:11:53 2015 -0600
134.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
134.3 @@ -1,6 +0,0 @@
134.4 -Module:OffsetRange[0,22066>
134.5 -ClassDef:OffsetRange[3844,4067>
134.6 -FunctionDef:OffsetRange[3938,4067>
134.7 -Expr:OffsetRange[3975,4034>
134.8 -Call:OffsetRange[3975,4034>
134.9 -Name:OffsetRange[3990,3994>
135.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testGetByNode2.path Sun Jan 04 13:11:53 2015 -0600
135.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
135.3 @@ -1,5 +0,0 @@
135.4 -Module:OffsetRange[0,22066>
135.5 -ClassDef:OffsetRange[3844,4067>
135.6 -FunctionDef:OffsetRange[3938,4067>
135.7 -Expr:OffsetRange[3975,4034>
135.8 -Call:OffsetRange[3975,4034>
136.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testImports1.completion Sun Jan 04 13:11:53 2015 -0600
136.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
136.3 @@ -1,638 +0,0 @@
136.4 -Code completion result for source line:
136.5 -import |re
136.6 -(QueryType=COMPLETION, NameKind=PREFIX)
136.7 -------------------------------------
136.8 -KEYWORD BaseHTTPServer
136.9 -KEYWORD ---Bastion ---
136.10 -KEYWORD CGIHTTPServer
136.11 -KEYWORD ---Carbon.AE ---
136.12 -KEYWORD ---Carbon.AH ---
136.13 -KEYWORD ---Carbon.App ---
136.14 -KEYWORD ---Carbon.CF ---
136.15 -KEYWORD ---Carbon.CG ---
136.16 -KEYWORD ---Carbon.CarbonEvt ---
136.17 -KEYWORD ---Carbon.Cm ---
136.18 -KEYWORD ---Carbon.Ctl ---
136.19 -KEYWORD ---Carbon.Dlg ---
136.20 -KEYWORD ---Carbon.Evt ---
136.21 -KEYWORD ---Carbon.Fm ---
136.22 -KEYWORD ---Carbon.Folder ---
136.23 -KEYWORD ---Carbon.Help ---
136.24 -KEYWORD ---Carbon.List ---
136.25 -KEYWORD ---Carbon.Menu ---
136.26 -KEYWORD ---Carbon.Mlte ---
136.27 -KEYWORD ---Carbon.Qd ---
136.28 -KEYWORD ---Carbon.Qdoffs ---
136.29 -KEYWORD ---Carbon.Qt ---
136.30 -KEYWORD ---Carbon.Res ---
136.31 -KEYWORD ---Carbon.Scrap ---
136.32 -KEYWORD ---Carbon.Snd ---
136.33 -KEYWORD ---Carbon.TE ---
136.34 -KEYWORD ---Carbon.Win ---
136.35 -KEYWORD ---ColorPicker ---
136.36 -KEYWORD ConfigParser
136.37 -KEYWORD Cookie
136.38 -KEYWORD DocXMLRPCServer
136.39 -KEYWORD ---EasyDialogs ---
136.40 -KEYWORD ---FrameWork ---
136.41 -KEYWORD HTMLParser
136.42 -KEYWORD ---MacOS ---
136.43 -KEYWORD ---MimeWriter ---
136.44 -KEYWORD MiniAEFrame
136.45 -KEYWORD ---Nav ---
136.46 -KEYWORD ---PixMapWrapper ---
136.47 -KEYWORD Queue
136.48 -KEYWORD ScrolledText
136.49 -KEYWORD SimpleHTTPServer
136.50 -KEYWORD SimpleXMLRPCServer
136.51 -KEYWORD SocketServer
136.52 -KEYWORD StringIO
136.53 -KEYWORD Tix
136.54 -KEYWORD Tkinter
136.55 -KEYWORD UserDict
136.56 -KEYWORD UserList
136.57 -KEYWORD UserString
136.58 -KEYWORD ---W ---
136.59 -KEYWORD _LWPCookieJar
136.60 -KEYWORD _MozillaCookieJar
136.61 -KEYWORD __builtin__
136.62 -KEYWORD __future__
136.63 -KEYWORD __main__
136.64 -KEYWORD _ast
136.65 -KEYWORD _rawffi
136.66 -KEYWORD _strptime
136.67 -KEYWORD _threading_local
136.68 -KEYWORD _winreg
136.69 -KEYWORD abc
136.70 -KEYWORD ---aepack ---
136.71 -KEYWORD ---aetools ---
136.72 -KEYWORD ---aetypes ---
136.73 -KEYWORD aifc
136.74 -KEYWORD anydbm
136.75 -KEYWORD ---applesingle ---
136.76 -KEYWORD array
136.77 -KEYWORD ast
136.78 -KEYWORD asynchat
136.79 -KEYWORD asyncore
136.80 -KEYWORD atexit
136.81 -KEYWORD audioop
136.82 -KEYWORD ---autoGIL ---
136.83 -KEYWORD base64
136.84 -KEYWORD bdb
136.85 -KEYWORD binascii
136.86 -KEYWORD binhex
136.87 -KEYWORD bisect
136.88 -KEYWORD bsddb
136.89 -KEYWORD ---buildtools ---
136.90 -KEYWORD bz2
136.91 -KEYWORD calendar
136.92 -KEYWORD ---cfmfile ---
136.93 -KEYWORD cgi
136.94 -KEYWORD cgitb
136.95 -KEYWORD chunk
136.96 -KEYWORD cmath
136.97 -KEYWORD cmd
136.98 -KEYWORD code
136.99 -KEYWORD codecs
136.100 -KEYWORD codeop
136.101 -KEYWORD collections
136.102 -KEYWORD colorsys
136.103 -KEYWORD commands
136.104 -KEYWORD compileall
136.105 -KEYWORD compiler
136.106 -KEYWORD compiler.ast
136.107 -KEYWORD compiler.consts
136.108 -KEYWORD compiler.future
136.109 -KEYWORD compiler.misc
136.110 -KEYWORD compiler.pyassem
136.111 -KEYWORD compiler.pycodegen
136.112 -KEYWORD compiler.symbols
136.113 -KEYWORD compiler.syntax
136.114 -KEYWORD compiler.transformer
136.115 -KEYWORD compiler.visitor
136.116 -KEYWORD compl
136.117 -KEYWORD compl2
136.118 -KEYWORD compl3
136.119 -KEYWORD compl4
136.120 -KEYWORD compl5
136.121 -KEYWORD constants
136.122 -KEYWORD contextlib
136.123 -KEYWORD cookielib
136.124 -KEYWORD copy
136.125 -KEYWORD copy_reg
136.126 -KEYWORD crypt
136.127 -KEYWORD csv
136.128 -KEYWORD ctypes
136.129 -KEYWORD curses
136.130 -KEYWORD curses.ascii
136.131 -KEYWORD curses.panel
136.132 -KEYWORD curses.textpad
136.133 -KEYWORD curses.wrapper
136.134 -KEYWORD datetime
136.135 -KEYWORD dbexts
136.136 -KEYWORD dbhash
136.137 -KEYWORD dbm
136.138 -KEYWORD decimal
136.139 -KEYWORD difflib
136.140 -KEYWORD dircache
136.141 -KEYWORD dis
136.142 -KEYWORD distutils
136.143 -KEYWORD distutils.archive_util
136.144 -KEYWORD distutils.bcppcompiler
136.145 -KEYWORD distutils.ccompiler
136.146 -KEYWORD distutils.cmd
136.147 -KEYWORD distutils.command
136.148 -KEYWORD distutils.command.bdist
136.149 -KEYWORD distutils.command.bdist_dumb
136.150 -KEYWORD distutils.command.bdist_msi
136.151 -KEYWORD distutils.command.bdist_rpm
136.152 -KEYWORD distutils.command.bdist_winins
136.153 -KEYWORD distutils.command.build
136.154 -KEYWORD distutils.command.build_clib
136.155 -KEYWORD distutils.command.build_ext
136.156 -KEYWORD distutils.command.build_py
136.157 -KEYWORD distutils.command.build_script
136.158 -KEYWORD distutils.command.clean
136.159 -KEYWORD distutils.command.config
136.160 -KEYWORD distutils.command.install
136.161 -KEYWORD distutils.command.install_data
136.162 -KEYWORD distutils.command.install_egg_
136.163 -KEYWORD distutils.command.install_head
136.164 -KEYWORD distutils.command.install_lib
136.165 -KEYWORD distutils.command.install_scri
136.166 -KEYWORD distutils.command.register
136.167 -KEYWORD distutils.command.sdist
136.168 -KEYWORD distutils.command.upload
136.169 -KEYWORD distutils.core
136.170 -KEYWORD distutils.cygwinccompiler
136.171 -KEYWORD distutils.debug
136.172 -KEYWORD distutils.dep_util
136.173 -KEYWORD distutils.dir_util
136.174 -KEYWORD distutils.dist
136.175 -KEYWORD distutils.emxccompiler
136.176 -KEYWORD distutils.errors
136.177 -KEYWORD distutils.extension
136.178 -KEYWORD distutils.fancy_getopt
136.179 -KEYWORD distutils.file_util
136.180 -KEYWORD distutils.filelist
136.181 -KEYWORD distutils.jythoncompiler
136.182 -KEYWORD distutils.log
136.183 -KEYWORD distutils.msvccompiler
136.184 -KEYWORD distutils.mwerkscompiler
136.185 -KEYWORD distutils.spawn
136.186 -KEYWORD distutils.sysconfig
136.187 -KEYWORD distutils.tests
136.188 -KEYWORD distutils.tests.support
136.189 -KEYWORD distutils.tests.test_build_py
136.190 -KEYWORD distutils.tests.test_build_scr
136.191 -KEYWORD distutils.tests.test_dist
136.192 -KEYWORD distutils.tests.test_install
136.193 -KEYWORD distutils.tests.test_install_s
136.194 -KEYWORD distutils.tests.test_versionpr
136.195 -KEYWORD distutils.text_file
136.196 -KEYWORD distutils.unixccompiler
136.197 -KEYWORD distutils.util
136.198 -KEYWORD distutils.version
136.199 -KEYWORD distutils.versionpredicate
136.200 -KEYWORD ---dl ---
136.201 -KEYWORD doctest
136.202 -KEYWORD dumbdbm
136.203 -KEYWORD dummy_thread
136.204 -KEYWORD dummy_threading
136.205 -KEYWORD email
136.206 -KEYWORD email._parseaddr
136.207 -KEYWORD email.base64mime
136.208 -KEYWORD email.charset
136.209 -KEYWORD email.encoders
136.210 -KEYWORD email.errors
136.211 -KEYWORD email.feedparser
136.212 -KEYWORD email.generator
136.213 -KEYWORD email.header
136.214 -KEYWORD email.iterators
136.215 -KEYWORD email.message
136.216 -KEYWORD email.mime
136.217 -KEYWORD email.mime.application
136.218 -KEYWORD email.mime.audio
136.219 -KEYWORD email.mime.base
136.220 -KEYWORD email.mime.image
136.221 -KEYWORD email.mime.message
136.222 -KEYWORD email.mime.multipart
136.223 -KEYWORD email.mime.nonmultipart
136.224 -KEYWORD email.mime.text
136.225 -KEYWORD email.parser
136.226 -KEYWORD email.quoprimime
136.227 -KEYWORD email.test.test_email_torture
136.228 -KEYWORD email.utils
136.229 -KEYWORD empty
136.230 -KEYWORD encodings
136.231 -KEYWORD encodings.aliases
136.232 -KEYWORD encodings.ascii
136.233 -KEYWORD encodings.base64_codec
136.234 -KEYWORD encodings.big5
136.235 -KEYWORD encodings.big5hkscs
136.236 -KEYWORD encodings.bz2_codec
136.237 -KEYWORD encodings.charmap
136.238 -KEYWORD encodings.cp037
136.239 -KEYWORD encodings.cp1006
136.240 -KEYWORD encodings.cp1026
136.241 -KEYWORD encodings.cp1140
136.242 -KEYWORD encodings.cp1250
136.243 -KEYWORD encodings.cp1251
136.244 -KEYWORD encodings.cp1252
136.245 -KEYWORD encodings.cp1253
136.246 -KEYWORD encodings.cp1254
136.247 -KEYWORD encodings.cp1255
136.248 -KEYWORD encodings.cp1256
136.249 -KEYWORD encodings.cp1257
136.250 -KEYWORD encodings.cp1258
136.251 -KEYWORD encodings.cp424
136.252 -KEYWORD encodings.cp437
136.253 -KEYWORD encodings.cp500
136.254 -KEYWORD encodings.cp737
136.255 -KEYWORD encodings.cp775
136.256 -KEYWORD encodings.cp850
136.257 -KEYWORD encodings.cp852
136.258 -KEYWORD encodings.cp855
136.259 -KEYWORD encodings.cp856
136.260 -KEYWORD encodings.cp857
136.261 -KEYWORD encodings.cp860
136.262 -KEYWORD encodings.cp861
136.263 -KEYWORD encodings.cp862
136.264 -KEYWORD encodings.cp863
136.265 -KEYWORD encodings.cp864
136.266 -KEYWORD encodings.cp865
136.267 -KEYWORD encodings.cp866
136.268 -KEYWORD encodings.cp869
136.269 -KEYWORD encodings.cp874
136.270 -KEYWORD encodings.cp875
136.271 -KEYWORD encodings.cp932
136.272 -KEYWORD encodings.cp949
136.273 -KEYWORD encodings.cp950
136.274 -KEYWORD encodings.euc_jis_2004
136.275 -KEYWORD encodings.euc_jisx0213
136.276 -KEYWORD encodings.euc_jp
136.277 -KEYWORD encodings.euc_kr
136.278 -KEYWORD encodings.gb18030
136.279 -KEYWORD encodings.gb2312
136.280 -KEYWORD encodings.gbk
136.281 -KEYWORD encodings.hex_codec
136.282 -KEYWORD encodings.hp_roman8
136.283 -KEYWORD encodings.hz
136.284 -KEYWORD encodings.idna
136.285 -KEYWORD encodings.iso2022_jp
136.286 -KEYWORD encodings.iso2022_jp_1
136.287 -KEYWORD encodings.iso2022_jp_2
136.288 -KEYWORD encodings.iso2022_jp_2004
136.289 -KEYWORD encodings.iso2022_jp_3
136.290 -KEYWORD encodings.iso2022_jp_ext
136.291 -KEYWORD encodings.iso2022_kr
136.292 -KEYWORD encodings.iso8859_1
136.293 -KEYWORD encodings.iso8859_10
136.294 -KEYWORD encodings.iso8859_11
136.295 -KEYWORD encodings.iso8859_13
136.296 -KEYWORD encodings.iso8859_14
136.297 -KEYWORD encodings.iso8859_15
136.298 -KEYWORD encodings.iso8859_16
136.299 -KEYWORD encodings.iso8859_2
136.300 -KEYWORD encodings.iso8859_3
136.301 -KEYWORD encodings.iso8859_4
136.302 -KEYWORD encodings.iso8859_5
136.303 -KEYWORD encodings.iso8859_6
136.304 -KEYWORD encodings.iso8859_7
136.305 -KEYWORD encodings.iso8859_8
136.306 -KEYWORD encodings.iso8859_9
136.307 -KEYWORD encodings.johab
136.308 -KEYWORD encodings.koi8_r
136.309 -KEYWORD encodings.koi8_u
136.310 -KEYWORD encodings.latin_1
136.311 -KEYWORD encodings.mac_arabic
136.312 -KEYWORD encodings.mac_centeuro
136.313 -KEYWORD encodings.mac_croatian
136.314 -KEYWORD encodings.mac_cyrillic
136.315 -KEYWORD encodings.mac_farsi
136.316 -KEYWORD encodings.mac_greek
136.317 -KEYWORD encodings.mac_iceland
136.318 -KEYWORD encodings.mac_latin2
136.319 -KEYWORD encodings.mac_roman
136.320 -KEYWORD encodings.mac_romanian
136.321 -KEYWORD encodings.mac_turkish
136.322 -KEYWORD encodings.mbcs
136.323 -KEYWORD encodings.palmos
136.324 -KEYWORD encodings.ptcp154
136.325 -KEYWORD encodings.punycode
136.326 -KEYWORD encodings.quopri_codec
136.327 -KEYWORD encodings.raw_unicode_escape
136.328 -KEYWORD encodings.rot_13
136.329 -KEYWORD encodings.shift_jis
136.330 -KEYWORD encodings.shift_jis_2004
136.331 -KEYWORD encodings.shift_jisx0213
136.332 -KEYWORD encodings.string_escape
136.333 -KEYWORD encodings.tis_620
136.334 -KEYWORD encodings.undefined
136.335 -KEYWORD encodings.unicode_escape
136.336 -KEYWORD encodings.unicode_internal
136.337 -KEYWORD encodings.utf_16
136.338 -KEYWORD encodings.utf_16_be
136.339 -KEYWORD encodings.utf_16_le
136.340 -KEYWORD encodings.utf_7
136.341 -KEYWORD encodings.utf_8
136.342 -KEYWORD encodings.utf_8_sig
136.343 -KEYWORD encodings.uu_codec
136.344 -KEYWORD encodings.zlib_codec
136.345 -KEYWORD errno
136.346 -KEYWORD exceptions
136.347 -KEYWORD fcntl
136.348 -KEYWORD filecmp
136.349 -KEYWORD fileinput
136.350 -KEYWORD findertools
136.351 -KEYWORD fnmatch
136.352 -KEYWORD formatter
136.353 -KEYWORD fpectl
136.354 -KEYWORD fpformat
136.355 -KEYWORD fractions
136.356 -KEYWORD ftplib
136.357 -KEYWORD functions
136.358 -KEYWORD functools
136.359 -KEYWORD future_builtins
136.360 -KEYWORD gc
136.361 -KEYWORD gdbm
136.362 -KEYWORD gensuitemodule
136.363 -KEYWORD getopt
136.364 -KEYWORD getpass
136.365 -KEYWORD gettext
136.366 -KEYWORD glob
136.367 -KEYWORD ---gopherlib ---
136.368 -KEYWORD grp
136.369 -KEYWORD gzip
136.370 -KEYWORD hashlib
136.371 -KEYWORD heapq
136.372 -KEYWORD hmac
136.373 -KEYWORD hotshot
136.374 -KEYWORD hotshot.stats
136.375 -KEYWORD htmlentitydefs
136.376 -KEYWORD htmllib
136.377 -KEYWORD httplib
136.378 -KEYWORD ---ic ---
136.379 -KEYWORD ---icopen ---
136.380 -KEYWORD ihooks
136.381 -KEYWORD ---imageop ---
136.382 -KEYWORD imaplib
136.383 -KEYWORD imghdr
136.384 -KEYWORD imp
136.385 -KEYWORD imports3
136.386 -KEYWORD imports4
136.387 -KEYWORD imports5
136.388 -KEYWORD imports6
136.389 -KEYWORD imports7
136.390 -KEYWORD imports8
136.391 -KEYWORD imports9
136.392 -KEYWORD ---imputil ---
136.393 -KEYWORD inspect
136.394 -KEYWORD io
136.395 -KEYWORD isql
136.396 -KEYWORD itertools
136.397 -KEYWORD javapath
136.398 -KEYWORD javashell
136.399 -KEYWORD jreload
136.400 -KEYWORD json
136.401 -KEYWORD keyword
136.402 -KEYWORD lib2to3
136.403 -KEYWORD linecache
136.404 -KEYWORD locale
136.405 -KEYWORD logging
136.406 -KEYWORD logging.config
136.407 -KEYWORD logging.handlers
136.408 -KEYWORD ---macerrors ---
136.409 -KEYWORD ---macostools ---
136.410 -KEYWORD macpath
136.411 -KEYWORD ---macresource ---
136.412 -KEYWORD macurl2path
136.413 -KEYWORD mailbox
136.414 -KEYWORD mailcap
136.415 -KEYWORD markupbase
136.416 -KEYWORD marshal
136.417 -KEYWORD math
136.418 -KEYWORD ---md5 ---
136.419 -KEYWORD mhlib
136.420 -KEYWORD ---mimetools ---
136.421 -KEYWORD mimetypes
136.422 -KEYWORD ---mimify ---
136.423 -KEYWORD mmap
136.424 -KEYWORD modulefinder
136.425 -KEYWORD msilib
136.426 -KEYWORD msvcrt
136.427 -KEYWORD ---multifile ---
136.428 -KEYWORD multiprocessing
136.429 -KEYWORD multiprocessing.connection
136.430 -KEYWORD multiprocessing.dummy
136.431 -KEYWORD multiprocessing.managers
136.432 -KEYWORD multiprocessing.pool
136.433 -KEYWORD multiprocessing.sharedctypes
136.434 -KEYWORD mutex
136.435 -KEYWORD netrc
136.436 -KEYWORD new
136.437 -KEYWORD nis
136.438 -KEYWORD nntplib
136.439 -KEYWORD ntpath
136.440 -KEYWORD nturl2path
136.441 -KEYWORD numbers
136.442 -KEYWORD occurrences2
136.443 -KEYWORD opcode
136.444 -KEYWORD operator
136.445 -KEYWORD optparse
136.446 -KEYWORD os
136.447 -KEYWORD os.path
136.448 -KEYWORD ossaudiodev
136.449 -KEYWORD parser
136.450 -KEYWORD pawt
136.451 -KEYWORD pawt.colors
136.452 -KEYWORD pawt.swing
136.453 -KEYWORD pdb
136.454 -KEYWORD pickle
136.455 -KEYWORD pickletools
136.456 -KEYWORD pipes
136.457 -KEYWORD pkgutil
136.458 -KEYWORD platform
136.459 -KEYWORD plistlib
136.460 -KEYWORD popen2
136.461 -KEYWORD poplib
136.462 -KEYWORD posix
136.463 -KEYWORD ---posixfile ---
136.464 -KEYWORD posixpath
136.465 -KEYWORD pprint
136.466 -KEYWORD profile
136.467 -KEYWORD pstats
136.468 -KEYWORD pty
136.469 -KEYWORD pwd
136.470 -KEYWORD py_compile
136.471 -KEYWORD pyclbr
136.472 -KEYWORD pydoc
136.473 -KEYWORD quopri
136.474 -KEYWORD random
136.475 -KEYWORD re
136.476 -KEYWORD readline
136.477 -KEYWORD repr
136.478 -KEYWORD resource
136.479 -KEYWORD ---rexec ---
136.480 -KEYWORD ---rfc822 ---
136.481 -KEYWORD rlcompleter
136.482 -KEYWORD robotparser
136.483 -KEYWORD runpy
136.484 -KEYWORD sched
136.485 -KEYWORD select
136.486 -KEYWORD ---sets ---
136.487 -KEYWORD sgmllib
136.488 -KEYWORD ---sha ---
136.489 -KEYWORD shelve
136.490 -KEYWORD shlex
136.491 -KEYWORD shutil
136.492 -KEYWORD signal
136.493 -KEYWORD site
136.494 -KEYWORD smtpd
136.495 -KEYWORD smtplib
136.496 -KEYWORD sndhdr
136.497 -KEYWORD socket
136.498 -KEYWORD spwd
136.499 -KEYWORD sqlite3
136.500 -KEYWORD sre
136.501 -KEYWORD sre_compile
136.502 -KEYWORD sre_constants
136.503 -KEYWORD sre_parse
136.504 -KEYWORD ssl
136.505 -KEYWORD stat
136.506 -KEYWORD ---statvfs ---
136.507 -KEYWORD stdtypes
136.508 -KEYWORD string
136.509 -KEYWORD ---stringprep ---
136.510 -KEYWORD struct
136.511 -KEYWORD subprocess
136.512 -KEYWORD symbol
136.513 -KEYWORD symtable
136.514 -KEYWORD sys
136.515 -KEYWORD syslog
136.516 -KEYWORD tabnanny
136.517 -KEYWORD tarfile
136.518 -KEYWORD telnetlib
136.519 -KEYWORD tempfile
136.520 -KEYWORD termios
136.521 -KEYWORD test.bugs.bugs100
136.522 -KEYWORD test.bugs.bugs101
136.523 -KEYWORD test.bugs.jdkbugs
136.524 -KEYWORD test.bugs.pr101
136.525 -KEYWORD test.bugs.pr104
136.526 -KEYWORD test.bugs.pr112
136.527 -KEYWORD test.bugs.pr119
136.528 -KEYWORD test.bugs.pr127
136.529 -KEYWORD test.bugs.pr133
136.530 -KEYWORD test.bugs.pr133.test
136.531 -KEYWORD test.bugs.pr134
136.532 -KEYWORD test.bugs.pr139
136.533 -KEYWORD test.bugs.pr142
136.534 -KEYWORD test.bugs.pr144
136.535 -KEYWORD test.bugs.pr148
136.536 -KEYWORD test.bugs.pr149
136.537 -KEYWORD test.bugs.pr155
136.538 -KEYWORD test.bugs.pr170
136.539 -KEYWORD test.bugs.pr171
136.540 -KEYWORD test.bugs.pr174
136.541 -KEYWORD test.bugs.pr178
136.542 -KEYWORD test.bugs.pr183
136.543 -KEYWORD test.bugs.pr186
136.544 -KEYWORD test.bugs.pr191
136.545 -KEYWORD test.bugs.pr192
136.546 -KEYWORD test.bugs.pr195
136.547 -KEYWORD test.bugs.pr208
136.548 -KEYWORD test.bugs.pr233
136.549 -KEYWORD test.bugs.pr234
136.550 -KEYWORD test.bugs.pr235
136.551 -KEYWORD test.bugs.pr239
136.552 -KEYWORD test.bugs.pr241
136.553 -KEYWORD test.bugs.pr242
136.554 -KEYWORD test.crashers.bogus_code_obj
136.555 -KEYWORD test.crashers.borrowed_ref_1
136.556 -KEYWORD test.crashers.borrowed_ref_2
136.557 -KEYWORD test.crashers.gc_inspection
136.558 -KEYWORD test.crashers.infinite_rec_1
136.559 -KEYWORD test.crashers.infinite_rec_2
136.560 -KEYWORD test.crashers.infinite_rec_4
136.561 -KEYWORD test.crashers.infinite_rec_5
136.562 -KEYWORD test.crashers.loosing_dict_ref
136.563 -KEYWORD test.crashers.nasty_eq_vs_dict
136.564 -KEYWORD test.crashers.recursion_limit_
136.565 -KEYWORD test.crashers.recursive_call
136.566 -KEYWORD test.leakers
136.567 -KEYWORD test.leakers.test_ctypes
136.568 -KEYWORD test.leakers.test_gestalt
136.569 -KEYWORD test.leakers.test_selftype
136.570 -KEYWORD test.test_metaclass_support
136.571 -KEYWORD test.test_metaclass_support.me
136.572 -KEYWORD test.test_metaclass_support.si
136.573 -KEYWORD test.xmltests
136.574 -KEYWORD test.zxjdbc.dbextstest
136.575 -KEYWORD test.zxjdbc.jndi
136.576 -KEYWORD test.zxjdbc.runner
136.577 -KEYWORD test.zxjdbc.sptest
136.578 -KEYWORD test.zxjdbc.test_zxjdbc_dbapi2
136.579 -KEYWORD test.zxjdbc.zxtest
136.580 -KEYWORD textwrap
136.581 -KEYWORD this
136.582 -KEYWORD thread
136.583 -KEYWORD threading
136.584 -KEYWORD time
136.585 -KEYWORD timeit
136.586 -KEYWORD token
136.587 -KEYWORD tokenize
136.588 -KEYWORD trace
136.589 -KEYWORD traceback
136.590 -KEYWORD tty
136.591 -KEYWORD turtle
136.592 -KEYWORD types
136.593 -KEYWORD unicodedata
136.594 -KEYWORD unittest
136.595 -KEYWORD urllib
136.596 -KEYWORD urllib2
136.597 -KEYWORD urlparse
136.598 -KEYWORD user
136.599 -KEYWORD uu
136.600 -KEYWORD uuid
136.601 -KEYWORD ---videoreader ---
136.602 -KEYWORD warnings
136.603 -KEYWORD wave
136.604 -KEYWORD weakref
136.605 -KEYWORD webbrowser
136.606 -KEYWORD whichdb
136.607 -KEYWORD winsound
136.608 -KEYWORD wsgiref
136.609 -KEYWORD wsgiref.handlers
136.610 -KEYWORD wsgiref.headers
136.611 -KEYWORD wsgiref.simple_server
136.612 -KEYWORD wsgiref.util
136.613 -KEYWORD wsgiref.validate
136.614 -KEYWORD xdrlib
136.615 -KEYWORD xml
136.616 -KEYWORD xml.FtCore
136.617 -KEYWORD xml.Uri
136.618 -KEYWORD xml.dom
136.619 -KEYWORD xml.dom.MessageSource
136.620 -KEYWORD xml.dom.NodeFilter
136.621 -KEYWORD xml.dom.domreg
136.622 -KEYWORD xml.dom.minicompat
136.623 -KEYWORD xml.dom.minidom
136.624 -KEYWORD xml.dom.pulldom
136.625 -KEYWORD xml.dom.xmlbuilder
136.626 -KEYWORD xml.etree
136.627 -KEYWORD xml.etree.ElementTree
136.628 -KEYWORD xml.parsers.expat
136.629 -KEYWORD xml.sax
136.630 -KEYWORD xml.sax._exceptions
136.631 -KEYWORD xml.sax.drivers2
136.632 -KEYWORD xml.sax.drivers2.drv_javasax
136.633 -KEYWORD xml.sax.handler
136.634 -KEYWORD xml.sax.saxlib
136.635 -KEYWORD xml.sax.saxutils
136.636 -KEYWORD xml.sax.xmlreader
136.637 -KEYWORD xmllib
136.638 -KEYWORD xmlrpclib
136.639 -KEYWORD zipfile
136.640 -KEYWORD zipimport
136.641 -KEYWORD zlib
137.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testImports2.completion Sun Jan 04 13:11:53 2015 -0600
137.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
137.3 @@ -1,14 +0,0 @@
137.4 -Code completion result for source line:
137.5 -import r|e
137.6 -(QueryType=COMPLETION, NameKind=PREFIX)
137.7 -------------------------------------
137.8 -KEYWORD random
137.9 -KEYWORD re
137.10 -KEYWORD readline
137.11 -KEYWORD repr
137.12 -KEYWORD resource
137.13 -KEYWORD ---rexec ---
137.14 -KEYWORD ---rfc822 ---
137.15 -KEYWORD rlcompleter
137.16 -KEYWORD robotparser
137.17 -KEYWORD runpy
138.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testLocals1.completion Sun Jan 04 13:11:53 2015 -0600
138.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
138.3 @@ -1,16 +0,0 @@
138.4 -Code completion result for source line:
138.5 -s|elf.section = section
138.6 -(QueryType=COMPLETION, NameKind=PREFIX)
138.7 -VARIABLE section
138.8 -VARIABLE self
138.9 -------------------------------------
138.10 -CLASS set
138.11 -CLASS str
138.12 -METHOD set(iterable)
138.13 -METHOD setattr(object, name, value)
138.14 -METHOD slice(start, stop, step)
138.15 -METHOD sorted(iterable, cmp, key, rev
138.16 -METHOD staticmethod(function)
138.17 -METHOD str(object)
138.18 -METHOD sum(iterable, start)
138.19 -METHOD super(type, object-or-type)
139.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testMarks1.occurrences Sun Jan 04 13:11:53 2015 -0600
139.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
139.3 @@ -1,3 +0,0 @@
139.4 - def __init__(self, |>MARK_OCCURRENCES:m^sg<|=''):
139.5 - self.message = |>MARK_OCCURRENCES:msg<|
139.6 - Exception.__init__(self, |>MARK_OCCURRENCES:msg<|)
140.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testMarks2.occurrences Sun Jan 04 13:11:53 2015 -0600
140.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
140.3 @@ -1,5 +0,0 @@
140.4 - for (|>MARK_OCCURRENCES:key<|, value) in self._defaults.items():
140.5 - fp.write("%s = %s\n" % (|>MARK_OCCURRENCES:key<|, str(value).replace('\n', '\n\t')))
140.6 - for (|>MARK_OCCURRENCES:ke^y<|, value) in self._sections[section].items():
140.7 - if |>MARK_OCCURRENCES:key<| != "__name__":
140.8 - (|>MARK_OCCURRENCES:key<|, str(value).replace('\n', '\n\t')))
141.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testRename1.rename Sun Jan 04 13:11:53 2015 -0600
141.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
141.3 @@ -1,3 +0,0 @@
141.4 -107: def __init__(self, |>msg<|=''):
141.5 -108: self.message = |>msg<|
141.6 -109: Exception.__init__(self, |>msg<|)
142.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testRename2.rename Sun Jan 04 13:11:53 2015 -0600
142.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
142.3 @@ -1,5 +0,0 @@
142.4 -358: for (|>key<|, value) in self._defaults.items():
142.5 -359: fp.write("%s = %s\n" % (|>key<|, str(value).replace('\n', '\n\t')))
142.6 -363: for (|>key<|, value) in self._sections[section].items():
142.7 -364: if |>key<| != "__name__":
142.8 -366: (|>key<|, str(value).replace('\n', '\n\t')))
143.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testRename3.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/ConfigParser.py.testStringCompletion.completion Sun Jan 04 13:11:53 2015 -0600
144.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
144.3 @@ -1,19 +0,0 @@
144.4 -Code completion result for source line:
144.5 -if line.split(None, 1)[0].lower() == 'rem' and line[0] in "|rR":
144.6 -(QueryType=COMPLETION, NameKind=PREFIX)
144.7 -------------------------------------
144.8 -KEYWORD ' Single quote (')
144.9 -KEYWORD \" Double quote (")
144.10 -KEYWORD \N{name} Character named name
144.11 -KEYWORD \Uxxxxxxxx Character with 32-b
144.12 -KEYWORD \\ Backslash (\)
144.13 -KEYWORD \a ASCII Bell (BEL)
144.14 -KEYWORD \b ASCII Backspace (BS)
144.15 -KEYWORD \f ASCII Formfeed (FF)
144.16 -KEYWORD \n ASCII Linefeed (LF)
144.17 -KEYWORD \ooo Character with octal valu
144.18 -KEYWORD \r ASCII Carriage Return (CR)
144.19 -KEYWORD \t ASCII Horizontal Tab (TAB)
144.20 -KEYWORD \uxxxx Character with 16-bit h
144.21 -KEYWORD \v ASCII Vertical Tab (VT)
144.22 -KEYWORD \xhh Character with hex value
145.1 --- a/python.editor/test/unit/data/testfiles/SocketServer.py Sun Jan 04 13:11:53 2015 -0600
145.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
145.3 @@ -1,588 +0,0 @@
145.4 -"""Generic socket server classes.
145.5 -
145.6 -This module tries to capture the various aspects of defining a server:
145.7 -
145.8 -For socket-based servers:
145.9 -
145.10 -- address family:
145.11 - - AF_INET{,6}: IP (Internet Protocol) sockets (default)
145.12 - - AF_UNIX: Unix domain sockets
145.13 - - others, e.g. AF_DECNET are conceivable (see <socket.h>
145.14 -- socket type:
145.15 - - SOCK_STREAM (reliable stream, e.g. TCP)
145.16 - - SOCK_DGRAM (datagrams, e.g. UDP)
145.17 -
145.18 -For request-based servers (including socket-based):
145.19 -
145.20 -- client address verification before further looking at the request
145.21 - (This is actually a hook for any processing that needs to look
145.22 - at the request before anything else, e.g. logging)
145.23 -- how to handle multiple requests:
145.24 - - synchronous (one request is handled at a time)
145.25 - - forking (each request is handled by a new process)
145.26 - - threading (each request is handled by a new thread)
145.27 -
145.28 -The classes in this module favor the server type that is simplest to
145.29 -write: a synchronous TCP/IP server. This is bad class design, but
145.30 -save some typing. (There's also the issue that a deep class hierarchy
145.31 -slows down method lookups.)
145.32 -
145.33 -There are five classes in an inheritance diagram, four of which represent
145.34 -synchronous servers of four types:
145.35 -
145.36 - +------------+
145.37 - | BaseServer |
145.38 - +------------+
145.39 - |
145.40 - v
145.41 - +-----------+ +------------------+
145.42 - | TCPServer |------->| UnixStreamServer |
145.43 - +-----------+ +------------------+
145.44 - |
145.45 - v
145.46 - +-----------+ +--------------------+
145.47 - | UDPServer |------->| UnixDatagramServer |
145.48 - +-----------+ +--------------------+
145.49 -
145.50 -Note that UnixDatagramServer derives from UDPServer, not from
145.51 -UnixStreamServer -- the only difference between an IP and a Unix
145.52 -stream server is the address family, which is simply repeated in both
145.53 -unix server classes.
145.54 -
145.55 -Forking and threading versions of each type of server can be created
145.56 -using the ForkingMixIn and ThreadingMixIn mix-in classes. For
145.57 -instance, a threading UDP server class is created as follows:
145.58 -
145.59 - class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
145.60 -
145.61 -The Mix-in class must come first, since it overrides a method defined
145.62 -in UDPServer! Setting the various member variables also changes
145.63 -the behavior of the underlying server mechanism.
145.64 -
145.65 -To implement a service, you must derive a class from
145.66 -BaseRequestHandler and redefine its handle() method. You can then run
145.67 -various versions of the service by combining one of the server classes
145.68 -with your request handler class.
145.69 -
145.70 -The request handler class must be different for datagram or stream
145.71 -services. This can be hidden by using the request handler
145.72 -subclasses StreamRequestHandler or DatagramRequestHandler.
145.73 -
145.74 -Of course, you still have to use your head!
145.75 -
145.76 -For instance, it makes no sense to use a forking server if the service
145.77 -contains state in memory that can be modified by requests (since the
145.78 -modifications in the child process would never reach the initial state
145.79 -kept in the parent process and passed to each child). In this case,
145.80 -you can use a threading server, but you will probably have to use
145.81 -locks to avoid two requests that come in nearly simultaneous to apply
145.82 -conflicting changes to the server state.
145.83 -
145.84 -On the other hand, if you are building e.g. an HTTP server, where all
145.85 -data is stored externally (e.g. in the file system), a synchronous
145.86 -class will essentially render the service "deaf" while one request is
145.87 -being handled -- which may be for a very long time if a client is slow
145.88 -to reqd all the data it has requested. Here a threading or forking
145.89 -server is appropriate.
145.90 -
145.91 -In some cases, it may be appropriate to process part of a request
145.92 -synchronously, but to finish processing in a forked child depending on
145.93 -the request data. This can be implemented by using a synchronous
145.94 -server and doing an explicit fork in the request handler class
145.95 -handle() method.
145.96 -
145.97 -Another approach to handling multiple simultaneous requests in an
145.98 -environment that supports neither threads nor fork (or where these are
145.99 -too expensive or inappropriate for the service) is to maintain an
145.100 -explicit table of partially finished requests and to use select() to
145.101 -decide which request to work on next (or whether to handle a new
145.102 -incoming request). This is particularly important for stream services
145.103 -where each client can potentially be connected for a long time (if
145.104 -threads or subprocesses cannot be used).
145.105 -
145.106 -Future work:
145.107 -- Standard classes for Sun RPC (which uses either UDP or TCP)
145.108 -- Standard mix-in classes to implement various authentication
145.109 - and encryption schemes
145.110 -- Standard framework for select-based multiplexing
145.111 -
145.112 -XXX Open problems:
145.113 -- What to do with out-of-band data?
145.114 -
145.115 -BaseServer:
145.116 -- split generic "request" functionality out into BaseServer class.
145.117 - Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org>
145.118 -
145.119 - example: read entries from a SQL database (requires overriding
145.120 - get_request() to return a table entry from the database).
145.121 - entry is processed by a RequestHandlerClass.
145.122 -
145.123 -"""
145.124 -
145.125 -# Author of the BaseServer patch: Luke Kenneth Casson Leighton
145.126 -
145.127 -# XXX Warning!
145.128 -# There is a test suite for this module, but it cannot be run by the
145.129 -# standard regression test.
145.130 -# To run it manually, run Lib/test/test_socketserver.py.
145.131 -
145.132 -__version__ = "0.4"
145.133 -
145.134 -
145.135 -import socket
145.136 -import sys
145.137 -import os
145.138 -
145.139 -__all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
145.140 - "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
145.141 - "StreamRequestHandler","DatagramRequestHandler",
145.142 - "ThreadingMixIn", "ForkingMixIn"]
145.143 -if hasattr(socket, "AF_UNIX"):
145.144 - __all__.extend(["UnixStreamServer","UnixDatagramServer",
145.145 - "ThreadingUnixStreamServer",
145.146 - "ThreadingUnixDatagramServer"])
145.147 -
145.148 -class BaseServer:
145.149 -
145.150 - """Base class for server classes.
145.151 -
145.152 - Methods for the caller:
145.153 -
145.154 - - __init__(server_address, RequestHandlerClass)
145.155 - - serve_forever()
145.156 - - handle_request() # if you do not use serve_forever()
145.157 - - fileno() -> int # for select()
145.158 -
145.159 - Methods that may be overridden:
145.160 -
145.161 - - server_bind()
145.162 - - server_activate()
145.163 - - get_request() -> request, client_address
145.164 - - verify_request(request, client_address)
145.165 - - server_close()
145.166 - - process_request(request, client_address)
145.167 - - close_request(request)
145.168 - - handle_error()
145.169 -
145.170 - Methods for derived classes:
145.171 -
145.172 - - finish_request(request, client_address)
145.173 -
145.174 - Class variables that may be overridden by derived classes or
145.175 - instances:
145.176 -
145.177 - - address_family
145.178 - - socket_type
145.179 - - allow_reuse_address
145.180 -
145.181 - Instance variables:
145.182 -
145.183 - - RequestHandlerClass
145.184 - - socket
145.185 -
145.186 - """
145.187 -
145.188 - def __init__(self, server_address, RequestHandlerClass):
145.189 - """Constructor. May be extended, do not override."""
145.190 - self.server_address = server_address
145.191 - self.RequestHandlerClass = RequestHandlerClass
145.192 -
145.193 - def server_activate(self):
145.194 - """Called by constructor to activate the server.
145.195 -
145.196 - May be overridden.
145.197 -
145.198 - """
145.199 - pass
145.200 -
145.201 - def serve_forever(self):
145.202 - """Handle one request at a time until doomsday."""
145.203 - while 1:
145.204 - self.handle_request()
145.205 -
145.206 - # The distinction between handling, getting, processing and
145.207 - # finishing a request is fairly arbitrary. Remember:
145.208 - #
145.209 - # - handle_request() is the top-level call. It calls
145.210 - # get_request(), verify_request() and process_request()
145.211 - # - get_request() is different for stream or datagram sockets
145.212 - # - process_request() is the place that may fork a new process
145.213 - # or create a new thread to finish the request
145.214 - # - finish_request() instantiates the request handler class;
145.215 - # this constructor will handle the request all by itself
145.216 -
145.217 - def handle_request(self):
145.218 - """Handle one request, possibly blocking."""
145.219 - try:
145.220 - request, client_address = self.get_request()
145.221 - except socket.error:
145.222 - return
145.223 - if self.verify_request(request, client_address):
145.224 - try:
145.225 - self.process_request(request, client_address)
145.226 - except:
145.227 - self.handle_error(request, client_address)
145.228 - self.close_request(request)
145.229 -
145.230 - def verify_request(self, request, client_address):
145.231 - """Verify the request. May be overridden.
145.232 -
145.233 - Return True if we should proceed with this request.
145.234 -
145.235 - """
145.236 - return True
145.237 -
145.238 - def process_request(self, request, client_address):
145.239 - """Call finish_request.
145.240 -
145.241 - Overridden by ForkingMixIn and ThreadingMixIn.
145.242 -
145.243 - """
145.244 - self.finish_request(request, client_address)
145.245 - self.close_request(request)
145.246 -
145.247 - def server_close(self):
145.248 - """Called to clean-up the server.
145.249 -
145.250 - May be overridden.
145.251 -
145.252 - """
145.253 - pass
145.254 -
145.255 - def finish_request(self, request, client_address):
145.256 - """Finish one request by instantiating RequestHandlerClass."""
145.257 - self.RequestHandlerClass(request, client_address, self)
145.258 -
145.259 - def close_request(self, request):
145.260 - """Called to clean up an individual request."""
145.261 - pass
145.262 -
145.263 - def handle_error(self, request, client_address):
145.264 - """Handle an error gracefully. May be overridden.
145.265 -
145.266 - The default is to print a traceback and continue.
145.267 -
145.268 - """
145.269 - print '-'*40
145.270 - print 'Exception happened during processing of request from',
145.271 - print client_address
145.272 - import traceback
145.273 - traceback.print_exc() # XXX But this goes to stderr!
145.274 - print '-'*40
145.275 -
145.276 -
145.277 -class TCPServer(BaseServer):
145.278 -
145.279 - """Base class for various socket-based server classes.
145.280 -
145.281 - Defaults to synchronous IP stream (i.e., TCP).
145.282 -
145.283 - Methods for the caller:
145.284 -
145.285 - - __init__(server_address, RequestHandlerClass)
145.286 - - serve_forever()
145.287 - - handle_request() # if you don't use serve_forever()
145.288 - - fileno() -> int # for select()
145.289 -
145.290 - Methods that may be overridden:
145.291 -
145.292 - - server_bind()
145.293 - - server_activate()
145.294 - - get_request() -> request, client_address
145.295 - - verify_request(request, client_address)
145.296 - - process_request(request, client_address)
145.297 - - close_request(request)
145.298 - - handle_error()
145.299 -
145.300 - Methods for derived classes:
145.301 -
145.302 - - finish_request(request, client_address)
145.303 -
145.304 - Class variables that may be overridden by derived classes or
145.305 - instances:
145.306 -
145.307 - - address_family
145.308 - - socket_type
145.309 - - request_queue_size (only for stream sockets)
145.310 - - allow_reuse_address
145.311 -
145.312 - Instance variables:
145.313 -
145.314 - - server_address
145.315 - - RequestHandlerClass
145.316 - - socket
145.317 -
145.318 - """
145.319 -
145.320 - address_family = socket.AF_INET
145.321 -
145.322 - socket_type = socket.SOCK_STREAM
145.323 -
145.324 - request_queue_size = 5
145.325 -
145.326 - allow_reuse_address = False
145.327 -
145.328 - def __init__(self, server_address, RequestHandlerClass):
145.329 - """Constructor. May be extended, do not override."""
145.330 - BaseServer.__init__(self, server_address, RequestHandlerClass)
145.331 - self.socket = socket.socket(self.address_family,
145.332 - self.socket_type)
145.333 - self.server_bind()
145.334 - self.server_activate()
145.335 -
145.336 - def server_bind(self):
145.337 - """Called by constructor to bind the socket.
145.338 -
145.339 - May be overridden.
145.340 -
145.341 - """
145.342 - if self.allow_reuse_address:
145.343 - self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
145.344 - self.socket.bind(self.server_address)
145.345 - self.server_address = self.socket.getsockname()
145.346 -
145.347 - def server_activate(self):
145.348 - """Called by constructor to activate the server.
145.349 -
145.350 - May be overridden.
145.351 -
145.352 - """
145.353 - self.socket.listen(self.request_queue_size)
145.354 -
145.355 - def server_close(self):
145.356 - """Called to clean-up the server.
145.357 -
145.358 - May be overridden.
145.359 -
145.360 - """
145.361 - self.socket.close()
145.362 -
145.363 - def fileno(self):
145.364 - """Return socket file number.
145.365 -
145.366 - Interface required by select().
145.367 -
145.368 - """
145.369 - return self.socket.fileno()
145.370 -
145.371 - def get_request(self):
145.372 - """Get the request and client address from the socket.
145.373 -
145.374 - May be overridden.
145.375 -
145.376 - """
145.377 - return self.socket.accept()
145.378 -
145.379 - def close_request(self, request):
145.380 - """Called to clean up an individual request."""
145.381 - request.close()
145.382 -
145.383 -
145.384 -class UDPServer(TCPServer):
145.385 -
145.386 - """UDP server class."""
145.387 -
145.388 - allow_reuse_address = False
145.389 -
145.390 - socket_type = socket.SOCK_DGRAM
145.391 -
145.392 - max_packet_size = 8192
145.393 -
145.394 - def get_request(self):
145.395 - data, client_addr = self.socket.recvfrom(self.max_packet_size)
145.396 - return (data, self.socket), client_addr
145.397 -
145.398 - def server_activate(self):
145.399 - # No need to call listen() for UDP.
145.400 - pass
145.401 -
145.402 - def close_request(self, request):
145.403 - # No need to close anything.
145.404 - pass
145.405 -
145.406 -class ForkingMixIn:
145.407 -
145.408 - """Mix-in class to handle each request in a new process."""
145.409 -
145.410 - active_children = None
145.411 - max_children = 40
145.412 -
145.413 - def collect_children(self):
145.414 - """Internal routine to wait for died children."""
145.415 - while self.active_children:
145.416 - if len(self.active_children) < self.max_children:
145.417 - options = os.WNOHANG
145.418 - else:
145.419 - # If the maximum number of children are already
145.420 - # running, block while waiting for a child to exit
145.421 - options = 0
145.422 - try:
145.423 - pid, status = os.waitpid(0, options)
145.424 - except os.error:
145.425 - pid = None
145.426 - if not pid: break
145.427 - self.active_children.remove(pid)
145.428 -
145.429 - def process_request(self, request, client_address):
145.430 - """Fork a new subprocess to process the request."""
145.431 - self.collect_children()
145.432 - pid = os.fork()
145.433 - if pid:
145.434 - # Parent process
145.435 - if self.active_children is None:
145.436 - self.active_children = []
145.437 - self.active_children.append(pid)
145.438 - self.close_request(request)
145.439 - return
145.440 - else:
145.441 - # Child process.
145.442 - # This must never return, hence os._exit()!
145.443 - try:
145.444 - self.finish_request(request, client_address)
145.445 - os._exit(0)
145.446 - except:
145.447 - try:
145.448 - self.handle_error(request, client_address)
145.449 - finally:
145.450 - os._exit(1)
145.451 -
145.452 -
145.453 -class ThreadingMixIn:
145.454 - """Mix-in class to handle each request in a new thread."""
145.455 -
145.456 - # Decides how threads will act upon termination of the
145.457 - # main process
145.458 - daemon_threads = False
145.459 -
145.460 - def process_request_thread(self, request, client_address):
145.461 - """Same as in BaseServer but as a thread.
145.462 -
145.463 - In addition, exception handling is done here.
145.464 -
145.465 - """
145.466 - try:
145.467 - self.finish_request(request, client_address)
145.468 - self.close_request(request)
145.469 - except:
145.470 - self.handle_error(request, client_address)
145.471 - self.close_request(request)
145.472 -
145.473 - def process_request(self, request, client_address):
145.474 - """Start a new thread to process the request."""
145.475 - import threading
145.476 - t = threading.Thread(target = self.process_request_thread,
145.477 - args = (request, client_address))
145.478 - if self.daemon_threads:
145.479 - t.setDaemon (1)
145.480 - t.start()
145.481 -
145.482 -
145.483 -class ForkingUDPServer(ForkingMixIn, UDPServer): pass
145.484 -class ForkingTCPServer(ForkingMixIn, TCPServer): pass
145.485 -
145.486 -class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
145.487 -class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
145.488 -
145.489 -if hasattr(socket, 'AF_UNIX'):
145.490 -
145.491 - class UnixStreamServer(TCPServer):
145.492 - address_family = socket.AF_UNIX
145.493 -
145.494 - class UnixDatagramServer(UDPServer):
145.495 - address_family = socket.AF_UNIX
145.496 -
145.497 - class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
145.498 -
145.499 - class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
145.500 -
145.501 -class BaseRequestHandler:
145.502 -
145.503 - """Base class for request handler classes.
145.504 -
145.505 - This class is instantiated for each request to be handled. The
145.506 - constructor sets the instance variables request, client_address
145.507 - and server, and then calls the handle() method. To implement a
145.508 - specific service, all you need to do is to derive a class which
145.509 - defines a handle() method.
145.510 -
145.511 - The handle() method can find the request as self.request, the
145.512 - client address as self.client_address, and the server (in case it
145.513 - needs access to per-server information) as self.server. Since a
145.514 - separate instance is created for each request, the handle() method
145.515 - can define arbitrary other instance variariables.
145.516 -
145.517 - """
145.518 -
145.519 - def __init__(self, request, client_address, server):
145.520 - self.request = request
145.521 - self.client_address = client_address
145.522 - self.server = server
145.523 - try:
145.524 - self.setup()
145.525 - self.handle()
145.526 - self.finish()
145.527 - finally:
145.528 - sys.exc_traceback = None # Help garbage collection
145.529 -
145.530 - def setup(self):
145.531 - pass
145.532 -
145.533 - def handle(self):
145.534 - pass
145.535 -
145.536 - def finish(self):
145.537 - pass
145.538 -
145.539 -
145.540 -# The following two classes make it possible to use the same service
145.541 -# class for stream or datagram servers.
145.542 -# Each class sets up these instance variables:
145.543 -# - rfile: a file object from which receives the request is read
145.544 -# - wfile: a file object to which the reply is written
145.545 -# When the handle() method returns, wfile is flushed properly
145.546 -
145.547 -
145.548 -class StreamRequestHandler(BaseRequestHandler):
145.549 -
145.550 - """Define self.rfile and self.wfile for stream sockets."""
145.551 -
145.552 - # Default buffer sizes for rfile, wfile.
145.553 - # We default rfile to buffered because otherwise it could be
145.554 - # really slow for large data (a getc() call per byte); we make
145.555 - # wfile unbuffered because (a) often after a write() we want to
145.556 - # read and we need to flush the line; (b) big writes to unbuffered
145.557 - # files are typically optimized by stdio even when big reads
145.558 - # aren't.
145.559 - rbufsize = -1
145.560 - wbufsize = 0
145.561 -
145.562 - def setup(self):
145.563 - self.connection = self.request
145.564 - self.rfile = self.connection.makefile('rb', self.rbufsize)
145.565 - self.wfile = self.connection.makefile('wb', self.wbufsize)
145.566 -
145.567 - def finish(self):
145.568 - if not self.wfile.closed:
145.569 - self.wfile.flush()
145.570 - self.wfile.close()
145.571 - self.rfile.close()
145.572 -
145.573 -
145.574 -class DatagramRequestHandler(BaseRequestHandler):
145.575 -
145.576 - # XXX Regrettably, I cannot get this working on Linux;
145.577 - # s.recvfrom() doesn't return a meaningful client address.
145.578 -
145.579 - """Define self.rfile and self.wfile for datagram sockets."""
145.580 -
145.581 - def setup(self):
145.582 - try:
145.583 - from cStringIO import StringIO
145.584 - except ImportError:
145.585 - from StringIO import StringIO
145.586 - self.packet, self.socket = self.request
145.587 - self.rfile = StringIO(self.packet)
145.588 - self.wfile = StringIO()
145.589 -
145.590 - def finish(self):
145.591 - self.socket.sendto(self.wfile.getvalue(), self.client_address)
146.1 --- a/python.editor/test/unit/data/testfiles/SocketServer.py.testDoc1.html Sun Jan 04 13:11:53 2015 -0600
146.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
146.3 @@ -1,57 +0,0 @@
146.4 -<html><body>
146.5 -<pre>Code completion result for source line:
146.6 -class TCPServer(BaseSer|ver):
146.7 -(QueryType=COMPLETION, NameKind=PREFIX)
146.8 -------------------------------------
146.9 -CLASS BaseServer [PRIVATE] SocketServer
146.10 -</pre><h2>Documentation:</h2><pre><b>BaseServer</b></pre>
146.11 -
146.12 -<hr>
146.13 -Base class for server classes.
146.14 -
146.15 -<br><br>
146.16 - Methods for the caller:
146.17 -
146.18 -<br><br>
146.19 - - __init__(server_address, RequestHandlerClass)
146.20 -<br> - serve_forever()
146.21 -<br> - handle_request() # if you do not use serve_forever()
146.22 -<br> - fileno() -> int # for select()
146.23 -
146.24 -<br><br>
146.25 - Methods that may be overridden:
146.26 -
146.27 -<br><br>
146.28 - - server_bind()
146.29 -<br> - server_activate()
146.30 -<br> - get_request() -> request, client_address
146.31 -<br> - verify_request(request, client_address)
146.32 -<br> - server_close()
146.33 -<br> - process_request(request, client_address)
146.34 -<br> - close_request(request)
146.35 -<br> - handle_error()
146.36 -
146.37 -<br><br>
146.38 - Methods for derived classes:
146.39 -
146.40 -<br><br>
146.41 - - finish_request(request, client_address)
146.42 -
146.43 -<br><br>
146.44 - Class variables that may be overridden by derived classes or
146.45 - instances:
146.46 -
146.47 -<br><br>
146.48 - - address_family
146.49 -<br> - socket_type
146.50 -<br> - allow_reuse_address
146.51 -
146.52 -<br><br>
146.53 - Instance variables:
146.54 -
146.55 -<br><br>
146.56 - - RequestHandlerClass
146.57 -<br> - socket
146.58 -
146.59 -<br><br>
146.60 -</body></html>
147.1 --- a/python.editor/test/unit/data/testfiles/SocketServer.py.testDoc2.html Sun Jan 04 13:11:53 2015 -0600
147.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
147.3 @@ -1,27 +0,0 @@
147.4 -<html><body>
147.5 -<pre>Code completion result for source line:
147.6 -class BaseRequestHandler|:
147.7 -(QueryType=COMPLETION, NameKind=PREFIX)
147.8 -------------------------------------
147.9 -CLASS BaseRequestHandler SocketServer
147.10 -</pre><h2>Documentation:</h2><pre><b>BaseRequestHandler</b></pre>
147.11 -
147.12 -<hr>
147.13 -Base class for request handler classes.
147.14 -
147.15 -<br><br>
147.16 - This class is instantiated for each request to be handled. The
147.17 - constructor sets the instance variables request, client_address
147.18 - and server, and then calls the handle() method. To implement a
147.19 - specific service, all you need to do is to derive a class which
147.20 - defines a handle() method.
147.21 -
147.22 -<br><br>
147.23 - The handle() method can find the request as self.request, the
147.24 - client address as self.client_address, and the server (in case it
147.25 - needs access to per-server information) as self.server. Since a
147.26 - separate instance is created for each request, the handle() method
147.27 - can define arbitrary other instance variariables.
147.28 -
147.29 -<br><br>
147.30 -</body></html>
148.1 --- a/python.editor/test/unit/data/testfiles/SocketServer.py.testDoc4.html 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 -<html><body>
148.5 -<pre>Code completion result for source line:
148.6 -def serve_fore|ver(self):
148.7 -(QueryType=COMPLETION, NameKind=PREFIX)
148.8 -METHOD serve_forever() [PRIVATE] SocketServer
148.9 -</pre><h2>Documentation:</h2><pre><i>SocketServer</i><br><b>serve_forever</b>(<font color="#808080">self</font>)</pre>
148.10 -
148.11 -<hr>
148.12 -Handle one request at a time until doomsday.
148.13 -</body></html>
149.1 --- a/python.editor/test/unit/data/testfiles/all.py Sun Jan 04 13:11:53 2015 -0600
149.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
149.3 @@ -1,9 +0,0 @@
149.4 -__all__ = [ "MyPublikClass", "MyPublicClass" ]
149.5 -
149.6 -class MyPublicClass:
149.7 - def mymethod(self):
149.8 - pass
149.9 -
149.10 -class MyPrivateClass:
149.11 - def mymethod2(self):
149.12 - pass
150.1 --- a/python.editor/test/unit/data/testfiles/all.py.testAssign1.hints Sun Jan 04 13:11:53 2015 -0600
150.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
150.3 @@ -1,3 +0,0 @@
150.4 -__all__ = [ "MyPublikClass", "MyPublicClass" ]
150.5 - ---------------
150.6 -HINT:"MyPublikClass" defined in __all__ does not exist!
151.1 --- a/python.editor/test/unit/data/testfiles/all2.py Sun Jan 04 13:11:53 2015 -0600
151.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
151.3 @@ -1,13 +0,0 @@
151.4 -__all__ = [ "MyPublikClass", "MyPublicClass" ]
151.5 -__all__.extend(["makedirs", "removedirs", "renames"])
151.6 -__all__.append("three")
151.7 -
151.8 -class MyPublicClass:
151.9 - def mymethod(self):
151.10 - pass
151.11 -
151.12 -class MyPrivateClass:
151.13 - def mymethod2(self):
151.14 - pass
151.15 -
151.16 -
152.1 --- a/python.editor/test/unit/data/testfiles/all2.py.testAssign2.hints Sun Jan 04 13:11:53 2015 -0600
152.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
152.3 @@ -1,11 +0,0 @@
152.4 -__all__ = [ "MyPublikClass", "MyPublicClass" ]
152.5 - ---------------
152.6 -HINT:"MyPublikClass" defined in __all__ does not exist!
152.7 -__all__.extend(["makedirs", "removedirs", "renames"])
152.8 - ---------
152.9 -HINT:"makedirs" defined in __all__ does not exist!
152.10 -HINT:"removedirs" defined in __all__ does not exist!
152.11 -HINT:"renames" defined in __all__ does not exist!
152.12 -__all__.append("three")
152.13 - -------
152.14 -HINT:"three" defined in __all__ does not exist!
153.1 Binary file python.editor/test/unit/data/testfiles/antlr_python_runtime-3.1.1-py2.5.egg has changed
154.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
154.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
154.3 @@ -1,1728 +0,0 @@
154.4 -
154.5 -
154.6 -Document 0
154.7 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/__init__.py
154.8 -Searchable Keys:
154.9 - item : __version__;D;;
154.10 - item : runtime_version;D;;
154.11 - item : runtime_version_str;D;;
154.12 - item : version_str_to_tuple;F;;version_str;
154.13 - module : __init__
154.14 -
154.15 -Not Searchable Keys:
154.16 -
154.17 -
154.18 -Document 1
154.19 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/compat.py
154.20 -Searchable Keys:
154.21 - item : frozenset;I;;
154.22 - item : reversed;F;;l;
154.23 - item : set;I;;
154.24 - module : compat
154.25 -
154.26 -Not Searchable Keys:
154.27 -
154.28 -
154.29 -Document 2
154.30 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/constants.py
154.31 -Searchable Keys:
154.32 - item : DEFAULT_CHANNEL;D;;
154.33 - item : DOWN;D;;
154.34 - item : EOF;D;;
154.35 - item : EOR_TOKEN_TYPE;D;;
154.36 - item : HIDDEN_CHANNEL;D;;
154.37 - item : INVALID_TOKEN_TYPE;D;;
154.38 - item : MIN_TOKEN_TYPE;D;;
154.39 - item : UP;D;;
154.40 - module : constants
154.41 -
154.42 -Not Searchable Keys:
154.43 -
154.44 -
154.45 -Document 3
154.46 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/dfa.py
154.47 -Searchable Keys:
154.48 - class : DFA
154.49 - class-ig : dfa
154.50 - extends : object
154.51 - in : dfa
154.52 - member : __init__;c;|CONSTRUCTOR|;self,recognizer,decisionNumber,eot,eof,min,max,accept,special,transition;
154.53 - member : accept;D;;
154.54 - member : decisionNumber;D;;
154.55 - member : eof;D;;
154.56 - member : eot;D;;
154.57 - member : error;F;;self,nvae;
154.58 - member : getDescription;F;;self;
154.59 - member : max;D;;
154.60 - member : min;D;;
154.61 - member : noViableAlt;F;;self,s,input;
154.62 - member : predict;F;;self,input;
154.63 - member : recognizer;D;;
154.64 - member : special;D;;
154.65 - member : specialStateTransition;F;;self,s,input;
154.66 - member : transition;D;;
154.67 - member : unpack;F;;cls,string;
154.68 -
154.69 -Not Searchable Keys:
154.70 -
154.71 -
154.72 -Document 4
154.73 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/dfa.py
154.74 -Searchable Keys:
154.75 - item : BacktrackingFailed;I;;
154.76 - item : DFA;C;;
154.77 - item : EOF;I;;
154.78 - item : NoViableAltException;I;;
154.79 - module : dfa
154.80 -
154.81 -Not Searchable Keys:
154.82 -
154.83 -
154.84 -Document 5
154.85 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/dottreegen.py
154.86 -Searchable Keys:
154.87 - class : DOTTreeGenerator
154.88 - class-ig : dottreegenerator
154.89 - extends : object
154.90 - in : dottreegen
154.91 - member : __init__;c;|CONSTRUCTOR|;self;
154.92 - member : _edgeST;D;|PRIVATE|;
154.93 - member : _nodeST;D;|PRIVATE|;
154.94 - member : _treeST;D;|PRIVATE|;
154.95 - member : getNodeNumber;F;;self,t;
154.96 - member : getNodeST;F;;self,adaptor,t;
154.97 - member : nodeNumber;D;;
154.98 - member : nodeToNumberMap;D;;
154.99 - member : toDOT;F;;self,tree,adaptor,treeST,edgeST;
154.100 - member : toDOTDefineEdges;F;;self,tree,adaptor,treeST,edgeST;
154.101 - member : toDOTDefineNodes;F;;self,tree,adaptor,treeST,knownNodes;
154.102 -
154.103 -Not Searchable Keys:
154.104 -
154.105 -
154.106 -Document 6
154.107 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/dottreegen.py
154.108 -Searchable Keys:
154.109 - item : CommonTreeAdaptor;I;;
154.110 - item : DOTTreeGenerator;C;;
154.111 - item : stringtemplate3;I;;
154.112 - item : toDOT;F;;tree,adaptor,treeST,edgeST;
154.113 - module : dottreegen
154.114 -
154.115 -Not Searchable Keys:
154.116 -
154.117 -
154.118 -Document 7
154.119 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
154.120 -Searchable Keys:
154.121 - class : BacktrackingFailed
154.122 - class-ig : backtrackingfailed
154.123 - extends : Exception
154.124 - in : exceptions
154.125 -
154.126 -Not Searchable Keys:
154.127 -
154.128 -
154.129 -Document 8
154.130 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
154.131 -Searchable Keys:
154.132 - class : EarlyExitException
154.133 - class-ig : earlyexitexception
154.134 - extends : RecognitionException
154.135 - in : exceptions
154.136 - member : __init__;c;|CONSTRUCTOR|;self,decisionNumber,input;
154.137 - member : decisionNumber;D;;
154.138 -
154.139 -Not Searchable Keys:
154.140 -
154.141 -
154.142 -Document 9
154.143 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
154.144 -Searchable Keys:
154.145 - class : FailedPredicateException
154.146 - class-ig : failedpredicateexception
154.147 - extends : RecognitionException
154.148 - in : exceptions
154.149 - member : __init__;c;|CONSTRUCTOR|;self,input,ruleName,predicateText;
154.150 - member : __repr__;F;;self;
154.151 - member : __str__;F;;self;
154.152 - member : predicateText;D;;
154.153 - member : ruleName;D;;
154.154 -
154.155 -Not Searchable Keys:
154.156 -
154.157 -
154.158 -Document 10
154.159 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
154.160 -Searchable Keys:
154.161 - class : MismatchedNotSetException
154.162 - class-ig : mismatchednotsetexception
154.163 - extends : MismatchedSetException
154.164 - in : exceptions
154.165 - member : __repr__;F;;self;
154.166 - member : __str__;F;;self;
154.167 -
154.168 -Not Searchable Keys:
154.169 -
154.170 -
154.171 -Document 11
154.172 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
154.173 -Searchable Keys:
154.174 - class : MismatchedRangeException
154.175 - class-ig : mismatchedrangeexception
154.176 - extends : RecognitionException
154.177 - in : exceptions
154.178 - member : __init__;c;|CONSTRUCTOR|;self,a,b,input;
154.179 - member : __repr__;F;;self;
154.180 - member : __str__;F;;self;
154.181 - member : a;D;;
154.182 - member : b;D;;
154.183 -
154.184 -Not Searchable Keys:
154.185 -
154.186 -
154.187 -Document 12
154.188 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
154.189 -Searchable Keys:
154.190 - class : MismatchedSetException
154.191 - class-ig : mismatchedsetexception
154.192 - extends : RecognitionException
154.193 - in : exceptions
154.194 - member : __init__;c;|CONSTRUCTOR|;self,expecting,input;
154.195 - member : __repr__;F;;self;
154.196 - member : __str__;F;;self;
154.197 - member : expecting;D;;
154.198 -
154.199 -Not Searchable Keys:
154.200 -
154.201 -
154.202 -Document 13
154.203 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
154.204 -Searchable Keys:
154.205 - class : MismatchedTokenException
154.206 - class-ig : mismatchedtokenexception
154.207 - extends : RecognitionException
154.208 - in : exceptions
154.209 - member : __init__;c;|CONSTRUCTOR|;self,expecting,input;
154.210 - member : __repr__;F;;self;
154.211 - member : __str__;F;;self;
154.212 - member : expecting;D;;
154.213 -
154.214 -Not Searchable Keys:
154.215 -
154.216 -
154.217 -Document 14
154.218 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
154.219 -Searchable Keys:
154.220 - class : MismatchedTreeNodeException
154.221 - class-ig : mismatchedtreenodeexception
154.222 - extends : RecognitionException
154.223 - in : exceptions
154.224 - member : __init__;c;|CONSTRUCTOR|;self,expecting,input;
154.225 - member : __repr__;F;;self;
154.226 - member : __str__;F;;self;
154.227 - member : expecting;D;;
154.228 -
154.229 -Not Searchable Keys:
154.230 -
154.231 -
154.232 -Document 15
154.233 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
154.234 -Searchable Keys:
154.235 - class : MissingTokenException
154.236 - class-ig : missingtokenexception
154.237 - extends : MismatchedTokenException
154.238 - in : exceptions
154.239 - member : __init__;c;|CONSTRUCTOR|;self,expecting,input,inserted;
154.240 - member : __repr__;F;;self;
154.241 - member : __str__;F;;self;
154.242 - member : getMissingType;F;;self;
154.243 - member : inserted;D;;
154.244 -
154.245 -Not Searchable Keys:
154.246 -
154.247 -
154.248 -Document 16
154.249 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
154.250 -Searchable Keys:
154.251 - class : NoViableAltException
154.252 - class-ig : noviablealtexception
154.253 - extends : RecognitionException
154.254 - in : exceptions
154.255 - member : __init__;c;|CONSTRUCTOR|;self,grammarDecisionDescription,decisionNumber,stateNumber,input;
154.256 - member : __repr__;F;;self;
154.257 - member : __str__;F;;self;
154.258 - member : decisionNumber;D;;
154.259 - member : grammarDecisionDescription;D;;
154.260 - member : stateNumber;D;;
154.261 -
154.262 -Not Searchable Keys:
154.263 -
154.264 -
154.265 -Document 17
154.266 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
154.267 -Searchable Keys:
154.268 - class : RecognitionException
154.269 - class-ig : recognitionexception
154.270 - extends : Exception
154.271 - in : exceptions
154.272 - member : __init__;c;|CONSTRUCTOR|;self,input;
154.273 - member : approximateLineInfo;D;;
154.274 - member : c;D;;
154.275 - member : charPositionInLine;D;;
154.276 - member : extractInformationFromTreeNodeStream;F;;self,nodes;
154.277 - member : getUnexpectedType;F;;self;
154.278 - member : index;D;;
154.279 - member : input;D;;
154.280 - member : line;D;;
154.281 - member : node;D;;
154.282 - member : token;D;;
154.283 - member : unexpectedType;D;;
154.284 -
154.285 -Not Searchable Keys:
154.286 -
154.287 -
154.288 -Document 18
154.289 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
154.290 -Searchable Keys:
154.291 - class : UnwantedTokenException
154.292 - class-ig : unwantedtokenexception
154.293 - extends : MismatchedTokenException
154.294 - in : exceptions
154.295 - member : __repr__;F;;self;
154.296 - member : __str__;F;;self;
154.297 - member : getUnexpectedToken;F;;self;
154.298 -
154.299 -Not Searchable Keys:
154.300 -
154.301 -
154.302 -Document 19
154.303 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
154.304 -Searchable Keys:
154.305 - item : BacktrackingFailed;C;;
154.306 - item : EarlyExitException;C;;
154.307 - item : FailedPredicateException;C;;
154.308 - item : INVALID_TOKEN_TYPE;I;;
154.309 - item : MismatchedNotSetException;C;;
154.310 - item : MismatchedRangeException;C;;
154.311 - item : MismatchedSetException;C;;
154.312 - item : MismatchedTokenException;C;;
154.313 - item : MismatchedTreeNodeException;C;;
154.314 - item : MissingTokenException;C;;
154.315 - item : NoViableAltException;C;;
154.316 - item : RecognitionException;C;;
154.317 - item : UnwantedTokenException;C;;
154.318 - module : exceptions
154.319 -
154.320 -Not Searchable Keys:
154.321 -
154.322 -
154.323 -Document 20
154.324 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/extras.py
154.325 -Searchable Keys:
154.326 - item : TreeWizard;I;;
154.327 - item : exc;D;;
154.328 - item : toDOT;F;;args,kwargs;
154.329 - module : extras
154.330 -
154.331 -Not Searchable Keys:
154.332 -
154.333 -
154.334 -Document 21
154.335 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/main.py
154.336 -Searchable Keys:
154.337 - class : LexerMain
154.338 - class-ig : lexermain
154.339 - extends : _Main
154.340 - in : main
154.341 - member : __init__;c;|CONSTRUCTOR|;self,lexerClass;
154.342 - member : lexerClass;D;;
154.343 - member : parseStream;F;;self,options,inStream;
154.344 -
154.345 -Not Searchable Keys:
154.346 -
154.347 -
154.348 -Document 22
154.349 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/main.py
154.350 -Searchable Keys:
154.351 - class : ParserMain
154.352 - class-ig : parsermain
154.353 - extends : _Main
154.354 - in : main
154.355 - member : __init__;c;|CONSTRUCTOR|;self,lexerClassName,parserClass;
154.356 - member : lexerClass;D;;
154.357 - member : lexerClassName;D;;
154.358 - member : parseStream;F;;self,options,inStream;
154.359 - member : parserClass;D;;
154.360 - member : setUp;F;;self,options;
154.361 - member : setupOptions;F;;self,optParser;
154.362 -
154.363 -Not Searchable Keys:
154.364 -
154.365 -
154.366 -Document 23
154.367 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/main.py
154.368 -Searchable Keys:
154.369 - class : WalkerMain
154.370 - class-ig : walkermain
154.371 - extends : _Main
154.372 - in : main
154.373 - member : __init__;c;|CONSTRUCTOR|;self,walkerClass;
154.374 - member : lexerClass;D;;
154.375 - member : parseStream;F;;self,options,inStream;
154.376 - member : parserClass;D;;
154.377 - member : setUp;F;;self,options;
154.378 - member : setupOptions;F;;self,optParser;
154.379 - member : walkerClass;D;;
154.380 -
154.381 -Not Searchable Keys:
154.382 -
154.383 -
154.384 -Document 24
154.385 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/main.py
154.386 -Searchable Keys:
154.387 - class : _Main
154.388 - class-ig : _main
154.389 - extends : object
154.390 - in : main
154.391 - member : __init__;c;|CONSTRUCTOR|;self;
154.392 - member : execute;F;;self,argv;
154.393 - member : parseOptions;F;;self,argv;
154.394 - member : parseStream;F;;self,options,inStream;
154.395 - member : setUp;F;;self,options;
154.396 - member : setupOptions;F;;self,optParser;
154.397 - member : stderr;D;;
154.398 - member : stdin;D;;
154.399 - member : stdout;D;;
154.400 - member : write;F;;self,options,text;
154.401 - member : writeln;F;;self,options,text;
154.402 -
154.403 -Not Searchable Keys:
154.404 - clzattrs : ;|PRIVATE|;
154.405 -
154.406 -
154.407 -Document 25
154.408 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/main.py
154.409 -Searchable Keys:
154.410 - item : LexerMain;C;;
154.411 - item : ParserMain;C;;
154.412 - item : WalkerMain;C;;
154.413 - item : _Main;C;|PRIVATE|;
154.414 - item : antlr3;I;;
154.415 - item : optparse;I;;
154.416 - item : sys;I;;
154.417 - module : main
154.418 -
154.419 -Not Searchable Keys:
154.420 -
154.421 -
154.422 -Document 26
154.423 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
154.424 -Searchable Keys:
154.425 - class : BaseRecognizer
154.426 - class-ig : baserecognizer
154.427 - extends : object
154.428 - in : recognizers
154.429 - member : DEFAULT_TOKEN_CHANNEL;D;;
154.430 - member : HIDDEN;D;;
154.431 - member : MEMO_RULE_FAILED;D;;
154.432 - member : MEMO_RULE_UNKNOWN;D;;
154.433 - member : __init__;c;|CONSTRUCTOR|;self,state;
154.434 - member : _getRuleInvocationStack;F;|PRIVATE|;cls,module;
154.435 - member : _state;D;|PRIVATE|;
154.436 - member : alreadyParsedRule;F;;self,input,ruleIndex;
154.437 - member : antlr_version;D;;
154.438 - member : antlr_version_str;D;;
154.439 - member : beginResync;F;;self;
154.440 - member : combineFollows;F;;self,exact;
154.441 - member : computeContextSensitiveRuleFOLLOW;F;;self;
154.442 - member : computeErrorRecoverySet;F;;self;
154.443 - member : consumeUntil;F;;self,input,tokenTypes;
154.444 - member : displayRecognitionError;F;;self,tokenNames,e;
154.445 - member : emitErrorMessage;F;;self,msg;
154.446 - member : endResync;F;;self;
154.447 - member : getBacktrackingLevel;F;;self;
154.448 - member : getCurrentInputSymbol;F;;self,input;
154.449 - member : getErrorHeader;F;;self,e;
154.450 - member : getErrorMessage;F;;self,e,tokenNames;
154.451 - member : getGrammarFileName;F;;self;
154.452 - member : getMissingSymbol;F;;self,input,e,expectedTokenType,follow;
154.453 - member : getNumberOfSyntaxErrors;F;;self;
154.454 - member : getRuleInvocationStack;F;;self;
154.455 - member : getRuleMemoization;F;;self,ruleIndex,ruleStartIndex;
154.456 - member : getSourceName;F;;self;
154.457 - member : getTokenErrorDisplay;F;;self,t;
154.458 - member : input;D;;
154.459 - member : match;F;;self,input,ttype,follow;
154.460 - member : matchAny;F;;self,input;
154.461 - member : memoize;F;;self,input,ruleIndex,ruleStartIndex,success;
154.462 - member : mismatch;F;;self,input,ttype,follow;
154.463 - member : mismatchIsMissingToken;F;;self,input,follow;
154.464 - member : mismatchIsUnwantedToken;F;;self,input,ttype;
154.465 - member : recover;F;;self,input,re;
154.466 - member : recoverFromMismatchedSet;F;;self,input,e,follow;
154.467 - member : recoverFromMismatchedToken;F;;self,input,ttype,follow;
154.468 - member : reportError;F;;self,e;
154.469 - member : reset;F;;self;
154.470 - member : setInput;F;;self,input;
154.471 - member : toStrings;F;;self,tokens;
154.472 - member : tokenNames;D;;
154.473 - member : traceIn;F;;self,ruleName,ruleIndex,inputSymbol;
154.474 - member : traceOut;F;;self,ruleName,ruleIndex,inputSymbol;
154.475 -
154.476 -Not Searchable Keys:
154.477 -
154.478 -
154.479 -Document 27
154.480 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
154.481 -Searchable Keys:
154.482 - class : Lexer
154.483 - class-ig : lexer
154.484 - extends : BaseRecognizer
154.485 - extends : TokenSource
154.486 - in : recognizers
154.487 - member : __init__;c;|CONSTRUCTOR|;self,input,state;
154.488 - member : emit;F;;self,token;
154.489 - member : getCharErrorDisplay;F;;self,c;
154.490 - member : getCharIndex;F;;self;
154.491 - member : getCharPositionInLine;F;;self;
154.492 - member : getErrorMessage;F;;self,e,tokenNames;
154.493 - member : getLine;F;;self;
154.494 - member : getSourceName;F;;self;
154.495 - member : getText;F;;self;
154.496 - member : input;D;;
154.497 - member : mTokens;F;;self;
154.498 - member : match;F;;self,s;
154.499 - member : matchAny;F;;self;
154.500 - member : matchRange;F;;self,a,b;
154.501 - member : nextToken;F;;self;
154.502 - member : recover;F;;self,re;
154.503 - member : reportError;F;;self,e;
154.504 - member : reset;F;;self;
154.505 - member : setCharStream;F;;self,input;
154.506 - member : setText;F;;self,text;
154.507 - member : skip;F;;self;
154.508 - member : text;D;;
154.509 - member : traceIn;F;;self,ruleName,ruleIndex;
154.510 - member : traceOut;F;;self,ruleName,ruleIndex;
154.511 -
154.512 -Not Searchable Keys:
154.513 -
154.514 -
154.515 -Document 28
154.516 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
154.517 -Searchable Keys:
154.518 - class : Parser
154.519 - class-ig : parser
154.520 - extends : BaseRecognizer
154.521 - in : recognizers
154.522 - member : __init__;c;|CONSTRUCTOR|;self,lexer,state;
154.523 - member : getCurrentInputSymbol;F;;self,input;
154.524 - member : getMissingSymbol;F;;self,input,e,expectedTokenType,follow;
154.525 - member : getSourceName;F;;self;
154.526 - member : getTokenStream;F;;self;
154.527 - member : input;D;;
154.528 - member : reset;F;;self;
154.529 - member : setTokenStream;F;;self,input;
154.530 - member : traceIn;F;;self,ruleName,ruleIndex;
154.531 - member : traceOut;F;;self,ruleName,ruleIndex;
154.532 -
154.533 -Not Searchable Keys:
154.534 -
154.535 -
154.536 -Document 29
154.537 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
154.538 -Searchable Keys:
154.539 - class : ParserRuleReturnScope
154.540 - class-ig : parserrulereturnscope
154.541 - extends : RuleReturnScope
154.542 - in : recognizers
154.543 - member : __init__;c;|CONSTRUCTOR|;self;
154.544 - member : getStart;F;;self;
154.545 - member : getStop;F;;self;
154.546 - member : start;D;;
154.547 - member : stop;D;;
154.548 -
154.549 -Not Searchable Keys:
154.550 -
154.551 -
154.552 -Document 30
154.553 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
154.554 -Searchable Keys:
154.555 - class : RecognizerSharedState
154.556 - class-ig : recognizersharedstate
154.557 - extends : object
154.558 - in : recognizers
154.559 - member : __init__;c;|CONSTRUCTOR|;self;
154.560 - member : backtracking;D;;
154.561 - member : channel;D;;
154.562 - member : errorRecovery;D;;
154.563 - member : following;D;;
154.564 - member : lastErrorIndex;D;;
154.565 - member : ruleMemo;D;;
154.566 - member : syntaxErrors;D;;
154.567 - member : text;D;;
154.568 - member : token;D;;
154.569 - member : tokenStartCharIndex;D;;
154.570 - member : tokenStartCharPositionInLine;D;;
154.571 - member : tokenStartLine;D;;
154.572 - member : type;D;;
154.573 -
154.574 -Not Searchable Keys:
154.575 -
154.576 -
154.577 -Document 31
154.578 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
154.579 -Searchable Keys:
154.580 - class : RuleReturnScope
154.581 - class-ig : rulereturnscope
154.582 - extends : object
154.583 - in : recognizers
154.584 - member : getStart;F;;self;
154.585 - member : getStop;F;;self;
154.586 - member : getTemplate;F;;self;
154.587 - member : getTree;F;;self;
154.588 -
154.589 -Not Searchable Keys:
154.590 -
154.591 -
154.592 -Document 32
154.593 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
154.594 -Searchable Keys:
154.595 - class : TokenSource
154.596 - class-ig : tokensource
154.597 - extends : object
154.598 - in : recognizers
154.599 - member : __iter__;F;;self;
154.600 - member : next;F;;self;
154.601 - member : nextToken;F;;self;
154.602 -
154.603 -Not Searchable Keys:
154.604 -
154.605 -
154.606 -Document 33
154.607 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
154.608 -Searchable Keys:
154.609 - item : BacktrackingFailed;I;;
154.610 - item : BaseRecognizer;C;;
154.611 - item : CommonToken;I;;
154.612 - item : DEFAULT_CHANNEL;I;;
154.613 - item : EOF;I;;
154.614 - item : EOF_TOKEN;I;;
154.615 - item : EOR_TOKEN_TYPE;I;;
154.616 - item : EarlyExitException;I;;
154.617 - item : FailedPredicateException;I;;
154.618 - item : HIDDEN_CHANNEL;I;;
154.619 - item : INVALID_TOKEN_TYPE;I;;
154.620 - item : Lexer;C;;
154.621 - item : MismatchedNotSetException;I;;
154.622 - item : MismatchedRangeException;I;;
154.623 - item : MismatchedSetException;I;;
154.624 - item : MismatchedTokenException;I;;
154.625 - item : MismatchedTreeNodeException;I;;
154.626 - item : MissingTokenException;I;;
154.627 - item : NoViableAltException;I;;
154.628 - item : Parser;C;;
154.629 - item : ParserRuleReturnScope;C;;
154.630 - item : RecognitionException;I;;
154.631 - item : RecognizerSharedState;C;;
154.632 - item : RuleReturnScope;C;;
154.633 - item : SKIP_TOKEN;I;;
154.634 - item : TokenSource;C;;
154.635 - item : UnwantedTokenException;I;;
154.636 - item : frozenset;I;;
154.637 - item : inspect;I;;
154.638 - item : reversed;I;;
154.639 - item : runtime_version;I;;
154.640 - item : runtime_version_str;I;;
154.641 - item : set;I;;
154.642 - item : sys;I;;
154.643 - module : recognizers
154.644 -
154.645 -Not Searchable Keys:
154.646 -
154.647 -
154.648 -Document 34
154.649 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.650 -Searchable Keys:
154.651 - class : ANTLRFileStream
154.652 - class-ig : antlrfilestream
154.653 - extends : ANTLRStringStream
154.654 - in : streams
154.655 - member : __init__;c;|CONSTRUCTOR|;self,fileName,encoding;
154.656 - member : fileName;D;;
154.657 - member : getSourceName;F;;self;
154.658 -
154.659 -Not Searchable Keys:
154.660 -
154.661 -
154.662 -Document 35
154.663 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.664 -Searchable Keys:
154.665 - class : ANTLRInputStream
154.666 - class-ig : antlrinputstream
154.667 - extends : ANTLRStringStream
154.668 - in : streams
154.669 - member : __init__;c;|CONSTRUCTOR|;self,file,encoding;
154.670 -
154.671 -Not Searchable Keys:
154.672 -
154.673 -
154.674 -Document 36
154.675 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.676 -Searchable Keys:
154.677 - class : ANTLRStringStream
154.678 - class-ig : antlrstringstream
154.679 - extends : CharStream
154.680 - in : streams
154.681 - member : LA;F;;self,i;
154.682 - member : LT;F;;self,i;
154.683 - member : __init__;c;|CONSTRUCTOR|;self,data;
154.684 - member : _markers;D;|PRIVATE|;
154.685 - member : charPositionInLine;D;;
154.686 - member : consume;F;;self;
154.687 - member : data;D;;
154.688 - member : getCharPositionInLine;F;;self;
154.689 - member : getLine;F;;self;
154.690 - member : getSourceName;F;;self;
154.691 - member : index;F;;self;
154.692 - member : lastMarker;D;;
154.693 - member : line;D;;
154.694 - member : mark;F;;self;
154.695 - member : markDepth;D;;
154.696 - member : n;D;;
154.697 - member : name;D;;
154.698 - member : p;D;;
154.699 - member : release;F;;self,marker;
154.700 - member : reset;F;;self;
154.701 - member : rewind;F;;self,marker;
154.702 - member : seek;F;;self,index;
154.703 - member : setCharPositionInLine;F;;self,pos;
154.704 - member : setLine;F;;self,line;
154.705 - member : size;F;;self;
154.706 - member : strdata;D;;
154.707 - member : substring;F;;self,start,stop;
154.708 -
154.709 -Not Searchable Keys:
154.710 -
154.711 -
154.712 -Document 37
154.713 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.714 -Searchable Keys:
154.715 - class : CharStream
154.716 - class-ig : charstream
154.717 - extends : IntStream
154.718 - in : streams
154.719 - member : EOF;D;;
154.720 - member : LT;F;;self,i;
154.721 - member : getCharPositionInLine;F;;self;
154.722 - member : getLine;F;;self;
154.723 - member : setCharPositionInLine;F;;self,pos;
154.724 - member : setLine;F;;self,line;
154.725 - member : substring;F;;self,start,stop;
154.726 -
154.727 -Not Searchable Keys:
154.728 -
154.729 -
154.730 -Document 38
154.731 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.732 -Searchable Keys:
154.733 - class : CommonTokenStream
154.734 - class-ig : commontokenstream
154.735 - extends : TokenStream
154.736 - in : streams
154.737 - member : LA;F;;self,i;
154.738 - member : LB;F;;self,k;
154.739 - member : LT;F;;self,k;
154.740 - member : __init__;c;|CONSTRUCTOR|;self,tokenSource,channel;
154.741 - member : channel;D;;
154.742 - member : channelOverrideMap;D;;
154.743 - member : consume;F;;self;
154.744 - member : discardOffChannelTokens;D;;
154.745 - member : discardSet;D;;
154.746 - member : discardTokenType;F;;self,ttype;
154.747 - member : fillBuffer;F;;self;
154.748 - member : get;F;;self,i;
154.749 - member : getSourceName;F;;self;
154.750 - member : getTokenSource;F;;self;
154.751 - member : getTokens;F;;self,start,stop,types;
154.752 - member : index;F;;self;
154.753 - member : lastMarker;D;;
154.754 - member : mark;F;;self;
154.755 - member : p;D;;
154.756 - member : release;F;;self,marker;
154.757 - member : reset;F;;self;
154.758 - member : rewind;F;;self,marker;
154.759 - member : seek;F;;self,index;
154.760 - member : setTokenSource;F;;self,tokenSource;
154.761 - member : setTokenTypeChannel;F;;self,ttype,channel;
154.762 - member : size;F;;self;
154.763 - member : skipOffTokenChannels;F;;self,i;
154.764 - member : skipOffTokenChannelsReverse;F;;self,i;
154.765 - member : toString;F;;self,start,stop;
154.766 - member : tokenSource;D;;
154.767 - member : tokens;D;;
154.768 -
154.769 -Not Searchable Keys:
154.770 -
154.771 -
154.772 -Document 39
154.773 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.774 -Searchable Keys:
154.775 - class : DeleteOp
154.776 - class-ig : deleteop
154.777 - extends : ReplaceOp
154.778 - in : streams
154.779 - member : __init__;c;|CONSTRUCTOR|;self,stream,first,last;
154.780 - member : __repr__;F;;self;
154.781 - member : __str__;F;;self;
154.782 - member : toString;F;;self;
154.783 -
154.784 -Not Searchable Keys:
154.785 -
154.786 -
154.787 -Document 40
154.788 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.789 -Searchable Keys:
154.790 - class : FileStream
154.791 - class-ig : filestream
154.792 - extends : ANTLRStringStream
154.793 - in : streams
154.794 - member : __init__;c;|CONSTRUCTOR|;self,fileName,encoding;
154.795 - member : fileName;D;;
154.796 - member : getSourceName;F;;self;
154.797 -
154.798 -Not Searchable Keys:
154.799 -
154.800 -
154.801 -Document 41
154.802 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.803 -Searchable Keys:
154.804 - class : InputStream
154.805 - class-ig : inputstream
154.806 - extends : ANTLRStringStream
154.807 - in : streams
154.808 - member : __init__;c;|CONSTRUCTOR|;self,file,encoding;
154.809 -
154.810 -Not Searchable Keys:
154.811 -
154.812 -
154.813 -Document 42
154.814 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.815 -Searchable Keys:
154.816 - class : InsertBeforeOp
154.817 - class-ig : insertbeforeop
154.818 - extends : RewriteOperation
154.819 - in : streams
154.820 - member : execute;F;;self,buf;
154.821 -
154.822 -Not Searchable Keys:
154.823 -
154.824 -
154.825 -Document 43
154.826 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.827 -Searchable Keys:
154.828 - class : IntStream
154.829 - class-ig : intstream
154.830 - extends : object
154.831 - in : streams
154.832 - member : LA;F;;self,i;
154.833 - member : consume;F;;self;
154.834 - member : getSourceName;F;;self;
154.835 - member : index;F;;self;
154.836 - member : mark;F;;self;
154.837 - member : release;F;;self,marker;
154.838 - member : rewind;F;;self,marker;
154.839 - member : seek;F;;self,index;
154.840 - member : size;F;;self;
154.841 -
154.842 -Not Searchable Keys:
154.843 -
154.844 -
154.845 -Document 44
154.846 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.847 -Searchable Keys:
154.848 - class : ReplaceOp
154.849 - class-ig : replaceop
154.850 - extends : RewriteOperation
154.851 - in : streams
154.852 - member : __init__;c;|CONSTRUCTOR|;self,stream,first,last,text;
154.853 - member : __repr__;F;;self;
154.854 - member : __str__;F;;self;
154.855 - member : execute;F;;self,buf;
154.856 - member : lastIndex;D;;
154.857 - member : toString;F;;self;
154.858 -
154.859 -Not Searchable Keys:
154.860 -
154.861 -
154.862 -Document 45
154.863 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.864 -Searchable Keys:
154.865 - class : RewriteOperation
154.866 - class-ig : rewriteoperation
154.867 - extends : object
154.868 - in : streams
154.869 - member : __init__;c;|CONSTRUCTOR|;self,stream,index,text;
154.870 - member : __repr__;F;;self;
154.871 - member : __str__;F;;self;
154.872 - member : execute;F;;self,buf;
154.873 - member : index;D;;
154.874 - member : stream;D;;
154.875 - member : text;D;;
154.876 - member : toString;F;;self;
154.877 -
154.878 -Not Searchable Keys:
154.879 -
154.880 -
154.881 -Document 46
154.882 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.883 -Searchable Keys:
154.884 - class : StringStream
154.885 - class-ig : stringstream
154.886 - extends : CharStream
154.887 - in : streams
154.888 - member : LA;F;;self,i;
154.889 - member : LT;F;;self,i;
154.890 - member : __init__;c;|CONSTRUCTOR|;self,data;
154.891 - member : _markers;D;|PRIVATE|;
154.892 - member : charPositionInLine;D;;
154.893 - member : consume;F;;self;
154.894 - member : data;D;;
154.895 - member : getCharPositionInLine;F;;self;
154.896 - member : getLine;F;;self;
154.897 - member : getSourceName;F;;self;
154.898 - member : index;F;;self;
154.899 - member : lastMarker;D;;
154.900 - member : line;D;;
154.901 - member : mark;F;;self;
154.902 - member : markDepth;D;;
154.903 - member : n;D;;
154.904 - member : name;D;;
154.905 - member : p;D;;
154.906 - member : release;F;;self,marker;
154.907 - member : reset;F;;self;
154.908 - member : rewind;F;;self,marker;
154.909 - member : seek;F;;self,index;
154.910 - member : setCharPositionInLine;F;;self,pos;
154.911 - member : setLine;F;;self,line;
154.912 - member : size;F;;self;
154.913 - member : strdata;D;;
154.914 - member : substring;F;;self,start,stop;
154.915 -
154.916 -Not Searchable Keys:
154.917 -
154.918 -
154.919 -Document 47
154.920 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.921 -Searchable Keys:
154.922 - class : TokenRewriteStream
154.923 - class-ig : tokenrewritestream
154.924 - extends : CommonTokenStream
154.925 - in : streams
154.926 - member : DEFAULT_PROGRAM_NAME;D;;
154.927 - member : MIN_TOKEN_INDEX;D;;
154.928 - member : __init__;c;|CONSTRUCTOR|;self,tokenSource,channel;
154.929 - member : __str__;F;;self,args;
154.930 - member : catOpText;F;;self,a,b;
154.931 - member : delete;F;;self,args;
154.932 - member : deleteProgram;F;;self,programName;
154.933 - member : getKindOfOps;F;;self,rewrites,kind,before;
154.934 - member : getLastRewriteTokenIndex;F;;self,programName;
154.935 - member : getProgram;F;;self,name;
154.936 - member : initializeProgram;F;;self,name;
154.937 - member : insertAfter;F;;self,args;
154.938 - member : insertBefore;F;;self,args;
154.939 - member : lastRewriteTokenIndexes;D;;
154.940 - member : programs;D;;
154.941 - member : reduceToSingleOperationPerIndex;F;;self,rewrites;
154.942 - member : replace;F;;self,args;
154.943 - member : rollback;F;;self,args;
154.944 - member : setLastRewriteTokenIndex;F;;self,programName,i;
154.945 - member : toDebugString;F;;self,start,end;
154.946 - member : toOriginalString;F;;self,start,end;
154.947 - member : toString;F;;self,args;
154.948 -
154.949 -Not Searchable Keys:
154.950 -
154.951 -
154.952 -Document 48
154.953 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.954 -Searchable Keys:
154.955 - class : TokenStream
154.956 - class-ig : tokenstream
154.957 - extends : IntStream
154.958 - in : streams
154.959 - member : LT;F;;self,k;
154.960 - member : get;F;;self,i;
154.961 - member : getTokenSource;F;;self;
154.962 - member : toString;F;;self,start,stop;
154.963 -
154.964 -Not Searchable Keys:
154.965 -
154.966 -
154.967 -Document 49
154.968 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
154.969 -Searchable Keys:
154.970 - item : ANTLRFileStream;C;;
154.971 - item : ANTLRInputStream;C;;
154.972 - item : ANTLRStringStream;C;;
154.973 - item : CharStream;C;;
154.974 - item : CommonTokenStream;C;;
154.975 - item : DEFAULT_CHANNEL;I;;
154.976 - item : DeleteOp;C;;
154.977 - item : EOF;I;;
154.978 - item : EOF_TOKEN;I;;
154.979 - item : FileStream;C;;
154.980 - item : InputStream;C;;
154.981 - item : InsertBeforeOp;C;;
154.982 - item : IntStream;C;;
154.983 - item : ReplaceOp;C;;
154.984 - item : RewriteOperation;C;;
154.985 - item : StringIO;I;;
154.986 - item : StringStream;C;;
154.987 - item : Token;I;;
154.988 - item : TokenRewriteStream;C;;
154.989 - item : TokenStream;C;;
154.990 - item : codecs;I;;
154.991 - module : streams
154.992 -
154.993 -Not Searchable Keys:
154.994 -
154.995 -
154.996 -Document 50
154.997 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tokens.py
154.998 -Searchable Keys:
154.999 - class : ClassicToken
154.1000 - class-ig : classictoken
154.1001 - extends : Token
154.1002 - in : tokens
154.1003 - member : __init__;c;|CONSTRUCTOR|;self,type,text,channel,oldToken;
154.1004 - member : __repr__;F;;self;
154.1005 - member : __str__;F;;self;
154.1006 - member : channel;D;;
154.1007 - member : charPositionInLine;D;;
154.1008 - member : getChannel;F;;self;
154.1009 - member : getCharPositionInLine;F;;self;
154.1010 - member : getInputStream;F;;self;
154.1011 - member : getLine;F;;self;
154.1012 - member : getText;F;;self;
154.1013 - member : getTokenIndex;F;;self;
154.1014 - member : getType;F;;self;
154.1015 - member : index;D;;
154.1016 - member : line;D;;
154.1017 - member : setChannel;F;;self,channel;
154.1018 - member : setCharPositionInLine;F;;self,pos;
154.1019 - member : setInputStream;F;;self,input;
154.1020 - member : setLine;F;;self,line;
154.1021 - member : setText;F;;self,text;
154.1022 - member : setTokenIndex;F;;self,index;
154.1023 - member : setType;F;;self,ttype;
154.1024 - member : text;D;;
154.1025 - member : toString;F;;self;
154.1026 - member : type;D;;
154.1027 -
154.1028 -Not Searchable Keys:
154.1029 -
154.1030 -
154.1031 -Document 51
154.1032 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tokens.py
154.1033 -Searchable Keys:
154.1034 - class : CommonToken
154.1035 - class-ig : commontoken
154.1036 - extends : Token
154.1037 - in : tokens
154.1038 - member : __init__;c;|CONSTRUCTOR|;self,type,channel,text,input,start,stop,oldToken;
154.1039 - member : __str__;F;;self;
154.1040 - member : _text;D;|PRIVATE|;
154.1041 - member : channel;D;;
154.1042 - member : charPositionInLine;D;;
154.1043 - member : getChannel;F;;self;
154.1044 - member : getCharPositionInLine;F;;self;
154.1045 - member : getInputStream;F;;self;
154.1046 - member : getLine;F;;self;
154.1047 - member : getText;F;;self;
154.1048 - member : getTokenIndex;F;;self;
154.1049 - member : getType;F;;self;
154.1050 - member : index;D;;
154.1051 - member : input;D;;
154.1052 - member : line;D;;
154.1053 - member : setChannel;F;;self,channel;
154.1054 - member : setCharPositionInLine;F;;self,pos;
154.1055 - member : setInputStream;F;;self,input;
154.1056 - member : setLine;F;;self,line;
154.1057 - member : setText;F;;self,text;
154.1058 - member : setTokenIndex;F;;self,index;
154.1059 - member : setType;F;;self,ttype;
154.1060 - member : start;D;;
154.1061 - member : stop;D;;
154.1062 - member : text;D;;
154.1063 - member : type;D;;
154.1064 -
154.1065 -Not Searchable Keys:
154.1066 -
154.1067 -
154.1068 -Document 52
154.1069 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tokens.py
154.1070 -Searchable Keys:
154.1071 - class : Token
154.1072 - class-ig : token
154.1073 - extends : object
154.1074 - in : tokens
154.1075 - member : getChannel;F;;self;
154.1076 - member : getCharPositionInLine;F;;self;
154.1077 - member : getInputStream;F;;self;
154.1078 - member : getLine;F;;self;
154.1079 - member : getText;F;;self;
154.1080 - member : getTokenIndex;F;;self;
154.1081 - member : getType;F;;self;
154.1082 - member : setChannel;F;;self,channel;
154.1083 - member : setCharPositionInLine;F;;self,pos;
154.1084 - member : setInputStream;F;;self,input;
154.1085 - member : setLine;F;;self,line;
154.1086 - member : setText;F;;self,text;
154.1087 - member : setTokenIndex;F;;self,index;
154.1088 - member : setType;F;;self,ttype;
154.1089 -
154.1090 -Not Searchable Keys:
154.1091 -
154.1092 -
154.1093 -Document 53
154.1094 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tokens.py
154.1095 -Searchable Keys:
154.1096 - item : ClassicToken;C;;
154.1097 - item : CommonToken;C;;
154.1098 - item : DEFAULT_CHANNEL;I;;
154.1099 - item : EOF;I;;
154.1100 - item : EOF_TOKEN;D;;
154.1101 - item : INVALID_TOKEN;D;;
154.1102 - item : INVALID_TOKEN_TYPE;I;;
154.1103 - item : SKIP_TOKEN;D;;
154.1104 - item : Token;C;;
154.1105 - module : tokens
154.1106 -
154.1107 -Not Searchable Keys:
154.1108 -
154.1109 -
154.1110 -Document 54
154.1111 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1112 -Searchable Keys:
154.1113 - class : BaseTree
154.1114 - class-ig : basetree
154.1115 - extends : Tree
154.1116 - in : tree
154.1117 - member : __init__;c;|CONSTRUCTOR|;self,node;
154.1118 - member : addChild;F;;self,childTree;
154.1119 - member : addChildren;F;;self,children;
154.1120 - member : childIndex;D;;
154.1121 - member : children;D;;
154.1122 - member : deleteChild;F;;self,i;
154.1123 - member : freshenParentAndChildIndexes;F;;self,offset;
154.1124 - member : getCharPositionInLine;F;;self;
154.1125 - member : getChild;F;;self,i;
154.1126 - member : getChildCount;F;;self;
154.1127 - member : getChildIndex;F;;self;
154.1128 - member : getChildren;F;;self;
154.1129 - member : getFirstChildWithType;F;;self,treeType;
154.1130 - member : getLine;F;;self;
154.1131 - member : getParent;F;;self;
154.1132 - member : isNil;F;;self;
154.1133 - member : parent;D;;
154.1134 - member : replaceChildren;F;;self,startChildIndex,stopChildIndex,newTree;
154.1135 - member : sanityCheckParentAndChildIndexes;F;;self,parent,i;
154.1136 - member : setChild;F;;self,i,t;
154.1137 - member : setChildIndex;F;;self,index;
154.1138 - member : setParent;F;;self,t;
154.1139 - member : toString;F;;self;
154.1140 - member : toStringTree;F;;self;
154.1141 -
154.1142 -Not Searchable Keys:
154.1143 -
154.1144 -
154.1145 -Document 55
154.1146 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1147 -Searchable Keys:
154.1148 - class : BaseTreeAdaptor
154.1149 - class-ig : basetreeadaptor
154.1150 - extends : TreeAdaptor
154.1151 - in : tree
154.1152 - member : addChild;F;;self,tree,child;
154.1153 - member : becomeRoot;F;;self,newRoot,oldRoot;
154.1154 - member : createFromToken;F;;self,tokenType,fromToken,text;
154.1155 - member : createFromType;F;;self,tokenType,text;
154.1156 - member : createToken;F;;self,fromToken,tokenType,text;
154.1157 - member : deleteChild;F;;self,t,i;
154.1158 - member : dupTree;F;;self,t,parent;
154.1159 - member : errorNode;F;;self,input,start,stop,exc;
154.1160 - member : getChild;F;;self,t,i;
154.1161 - member : getChildCount;F;;self,t;
154.1162 - member : getText;F;;self,t;
154.1163 - member : getType;F;;self,t;
154.1164 - member : getUniqueID;F;;self,node;
154.1165 - member : isNil;F;;self,tree;
154.1166 - member : nil;F;;self;
154.1167 - member : rulePostProcessing;F;;self,root;
154.1168 - member : setChild;F;;self,t,i,child;
154.1169 - member : setText;F;;self,t,text;
154.1170 - member : setType;F;;self,t,type;
154.1171 -
154.1172 -Not Searchable Keys:
154.1173 -
154.1174 -
154.1175 -Document 56
154.1176 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1177 -Searchable Keys:
154.1178 - class : CommonErrorNode
154.1179 - class-ig : commonerrornode
154.1180 - extends : CommonTree
154.1181 - in : tree
154.1182 - member : __init__;c;|CONSTRUCTOR|;self,input,start,stop,exc;
154.1183 - member : getText;F;;self;
154.1184 - member : getType;F;;self;
154.1185 - member : input;D;;
154.1186 - member : isNil;F;;self;
154.1187 - member : start;D;;
154.1188 - member : stop;D;;
154.1189 - member : toString;F;;self;
154.1190 - member : trappedException;D;;
154.1191 -
154.1192 -Not Searchable Keys:
154.1193 -
154.1194 -
154.1195 -Document 57
154.1196 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1197 -Searchable Keys:
154.1198 - class : CommonTree
154.1199 - class-ig : commontree
154.1200 - extends : BaseTree
154.1201 - in : tree
154.1202 - member : __init__;c;|CONSTRUCTOR|;self,payload;
154.1203 - member : __str__;F;;self;
154.1204 - member : charPositionInLine;D;;
154.1205 - member : childIndex;D;;
154.1206 - member : dupNode;F;;self;
154.1207 - member : getCharPositionInLine;F;;self;
154.1208 - member : getChildIndex;F;;self;
154.1209 - member : getLine;F;;self;
154.1210 - member : getParent;F;;self;
154.1211 - member : getText;F;;self;
154.1212 - member : getToken;F;;self;
154.1213 - member : getTokenStartIndex;F;;self;
154.1214 - member : getTokenStopIndex;F;;self;
154.1215 - member : getType;F;;self;
154.1216 - member : isNil;F;;self;
154.1217 - member : line;D;;
154.1218 - member : parent;D;;
154.1219 - member : setChildIndex;F;;self,idx;
154.1220 - member : setParent;F;;self,t;
154.1221 - member : setTokenStartIndex;F;;self,index;
154.1222 - member : setTokenStopIndex;F;;self,index;
154.1223 - member : startIndex;D;;
154.1224 - member : stopIndex;D;;
154.1225 - member : text;D;;
154.1226 - member : toString;F;;self;
154.1227 - member : toStringTree;F;;self;
154.1228 - member : token;D;;
154.1229 - member : tokenStartIndex;D;;
154.1230 - member : tokenStopIndex;D;;
154.1231 - member : type;D;;
154.1232 -
154.1233 -Not Searchable Keys:
154.1234 -
154.1235 -
154.1236 -Document 58
154.1237 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1238 -Searchable Keys:
154.1239 - class : CommonTreeAdaptor
154.1240 - class-ig : commontreeadaptor
154.1241 - extends : BaseTreeAdaptor
154.1242 - in : tree
154.1243 - member : createToken;F;;self,fromToken,tokenType,text;
154.1244 - member : createWithPayload;F;;self,payload;
154.1245 - member : dupNode;F;;self,treeNode;
154.1246 - member : getChild;F;;self,t,i;
154.1247 - member : getChildCount;F;;self,t;
154.1248 - member : getChildIndex;F;;self,t;
154.1249 - member : getParent;F;;self,t;
154.1250 - member : getText;F;;self,t;
154.1251 - member : getToken;F;;self,t;
154.1252 - member : getTokenStartIndex;F;;self,t;
154.1253 - member : getTokenStopIndex;F;;self,t;
154.1254 - member : getType;F;;self,t;
154.1255 - member : replaceChildren;F;;self,parent,startChildIndex,stopChildIndex,t;
154.1256 - member : setChildIndex;F;;self,t,index;
154.1257 - member : setParent;F;;self,t,parent;
154.1258 - member : setTokenBoundaries;F;;self,t,startToken,stopToken;
154.1259 -
154.1260 -Not Searchable Keys:
154.1261 -
154.1262 -
154.1263 -Document 59
154.1264 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1265 -Searchable Keys:
154.1266 - class : CommonTreeNodeStream
154.1267 - class-ig : commontreenodestream
154.1268 - extends : TreeNodeStream
154.1269 - in : tree
154.1270 - member : LA;F;;self,i;
154.1271 - member : LB;F;;self,k;
154.1272 - member : LT;F;;self,k;
154.1273 - member : __init__;c;|CONSTRUCTOR|;self,args;
154.1274 - member : __iter__;F;;self;
154.1275 - member : __str__;F;;self;
154.1276 - member : _fillBuffer;F;|PRIVATE|;self,t;
154.1277 - member : adaptor;D;;
154.1278 - member : addNavigationNode;F;;self,ttype;
154.1279 - member : calls;D;;
154.1280 - member : consume;F;;self;
154.1281 - member : down;D;;
154.1282 - member : eof;D;;
154.1283 - member : fillBuffer;F;;self;
154.1284 - member : get;F;;self,i;
154.1285 - member : getCurrentSymbol;F;;self;
154.1286 - member : getNodeIndex;F;;self,node;
154.1287 - member : getSourceName;F;;self;
154.1288 - member : getTokenStream;F;;self;
154.1289 - member : getTreeAdaptor;F;;self;
154.1290 - member : getTreeSource;F;;self;
154.1291 - member : hasUniqueNavigationNodes;F;;self;
154.1292 - member : index;F;;self;
154.1293 - member : lastMarker;D;;
154.1294 - member : mark;F;;self;
154.1295 - member : nodes;D;;
154.1296 - member : p;D;;
154.1297 - member : pop;F;;self;
154.1298 - member : push;F;;self,index;
154.1299 - member : release;F;;self,marker;
154.1300 - member : replaceChildren;F;;self,parent,startChildIndex,stopChildIndex,t;
154.1301 - member : reset;F;;self;
154.1302 - member : rewind;F;;self,marker;
154.1303 - member : root;D;;
154.1304 - member : seek;F;;self,index;
154.1305 - member : setTokenStream;F;;self,tokens;
154.1306 - member : setUniqueNavigationNodes;F;;self,uniqueNavigationNodes;
154.1307 - member : size;F;;self;
154.1308 - member : toString;F;;self,start,stop;
154.1309 - member : tokens;D;;
154.1310 - member : uniqueNavigationNodes;D;;
154.1311 - member : up;D;;
154.1312 -
154.1313 -Not Searchable Keys:
154.1314 -
154.1315 -
154.1316 -Document 60
154.1317 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1318 -Searchable Keys:
154.1319 - class : RewriteCardinalityException
154.1320 - class-ig : rewritecardinalityexception
154.1321 - extends : RuntimeError
154.1322 - in : tree
154.1323 - member : __init__;c;|CONSTRUCTOR|;self,elementDescription;
154.1324 - member : elementDescription;D;;
154.1325 - member : getMessage;F;;self;
154.1326 -
154.1327 -Not Searchable Keys:
154.1328 -
154.1329 -
154.1330 -Document 61
154.1331 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1332 -Searchable Keys:
154.1333 - class : RewriteEarlyExitException
154.1334 - class-ig : rewriteearlyexitexception
154.1335 - extends : RewriteCardinalityException
154.1336 - in : tree
154.1337 - member : __init__;c;|CONSTRUCTOR|;self,elementDescription;
154.1338 -
154.1339 -Not Searchable Keys:
154.1340 -
154.1341 -
154.1342 -Document 62
154.1343 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1344 -Searchable Keys:
154.1345 - class : RewriteEmptyStreamException
154.1346 - class-ig : rewriteemptystreamexception
154.1347 - extends : RewriteCardinalityException
154.1348 - in : tree
154.1349 -
154.1350 -Not Searchable Keys:
154.1351 -
154.1352 -
154.1353 -Document 63
154.1354 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1355 -Searchable Keys:
154.1356 - class : RewriteRuleElementStream
154.1357 - class-ig : rewriteruleelementstream
154.1358 - extends : object
154.1359 - in : tree
154.1360 - member : __init__;c;|CONSTRUCTOR|;self,adaptor,elementDescription,elements;
154.1361 - member : __len__;F;;self;
154.1362 - member : _next;F;|PRIVATE|;self;
154.1363 - member : adaptor;D;;
154.1364 - member : add;F;;self,el;
154.1365 - member : cursor;D;;
154.1366 - member : dirty;D;;
154.1367 - member : dup;F;;self,el;
154.1368 - member : elementDescription;D;;
154.1369 - member : elements;D;;
154.1370 - member : getDescription;F;;self;
154.1371 - member : hasNext;F;;self;
154.1372 - member : nextTree;F;;self;
154.1373 - member : reset;F;;self;
154.1374 - member : singleElement;D;;
154.1375 - member : size;F;;self;
154.1376 - member : toTree;F;;self,el;
154.1377 -
154.1378 -Not Searchable Keys:
154.1379 -
154.1380 -
154.1381 -Document 64
154.1382 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1383 -Searchable Keys:
154.1384 - class : RewriteRuleNodeStream
154.1385 - class-ig : rewriterulenodestream
154.1386 - extends : RewriteRuleElementStream
154.1387 - in : tree
154.1388 - member : dup;F;;self,el;
154.1389 - member : nextNode;F;;self;
154.1390 - member : toTree;F;;self,el;
154.1391 -
154.1392 -Not Searchable Keys:
154.1393 -
154.1394 -
154.1395 -Document 65
154.1396 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1397 -Searchable Keys:
154.1398 - class : RewriteRuleSubtreeStream
154.1399 - class-ig : rewriterulesubtreestream
154.1400 - extends : RewriteRuleElementStream
154.1401 - in : tree
154.1402 - member : dup;F;;self,el;
154.1403 - member : nextNode;F;;self;
154.1404 -
154.1405 -Not Searchable Keys:
154.1406 -
154.1407 -
154.1408 -Document 66
154.1409 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1410 -Searchable Keys:
154.1411 - class : RewriteRuleTokenStream
154.1412 - class-ig : rewriteruletokenstream
154.1413 - extends : RewriteRuleElementStream
154.1414 - in : tree
154.1415 - member : dup;F;;self,el;
154.1416 - member : nextNode;F;;self;
154.1417 - member : nextToken;F;;self;
154.1418 - member : toTree;F;;self,el;
154.1419 -
154.1420 -Not Searchable Keys:
154.1421 -
154.1422 -
154.1423 -Document 67
154.1424 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1425 -Searchable Keys:
154.1426 - class : Tree
154.1427 - class-ig : tree
154.1428 - extends : object
154.1429 - in : tree
154.1430 - member : addChild;F;;self,t;
154.1431 - member : deleteChild;F;;self,i;
154.1432 - member : dupNode;F;;self;
154.1433 - member : freshenParentAndChildIndexes;F;;self;
154.1434 - member : getCharPositionInLine;F;;self;
154.1435 - member : getChild;F;;self,i;
154.1436 - member : getChildCount;F;;self;
154.1437 - member : getChildIndex;F;;self;
154.1438 - member : getLine;F;;self;
154.1439 - member : getParent;F;;self;
154.1440 - member : getText;F;;self;
154.1441 - member : getTokenStartIndex;F;;self;
154.1442 - member : getTokenStopIndex;F;;self;
154.1443 - member : getType;F;;self;
154.1444 - member : isNil;F;;self;
154.1445 - member : replaceChildren;F;;self,startChildIndex,stopChildIndex,t;
154.1446 - member : setChild;F;;self,i,t;
154.1447 - member : setChildIndex;F;;self,index;
154.1448 - member : setParent;F;;self,t;
154.1449 - member : setTokenStartIndex;F;;self,index;
154.1450 - member : setTokenStopIndex;F;;self,index;
154.1451 - member : toString;F;;self;
154.1452 - member : toStringTree;F;;self;
154.1453 -
154.1454 -Not Searchable Keys:
154.1455 -
154.1456 -
154.1457 -Document 68
154.1458 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1459 -Searchable Keys:
154.1460 - class : TreeAdaptor
154.1461 - class-ig : treeadaptor
154.1462 - extends : object
154.1463 - in : tree
154.1464 - member : addChild;F;;self,t,child;
154.1465 - member : becomeRoot;F;;self,newRoot,oldRoot;
154.1466 - member : create;F;;self,args;
154.1467 - member : createFromToken;F;;self,tokenType,fromToken,text;
154.1468 - member : createFromType;F;;self,tokenType,text;
154.1469 - member : createWithPayload;F;;self,payload;
154.1470 - member : deleteChild;F;;self,t,i;
154.1471 - member : dupNode;F;;self,treeNode;
154.1472 - member : dupTree;F;;self,tree;
154.1473 - member : errorNode;F;;self,input,start,stop,exc;
154.1474 - member : getChild;F;;self,t,i;
154.1475 - member : getChildCount;F;;self,t;
154.1476 - member : getChildIndex;F;;self,t;
154.1477 - member : getParent;F;;self,t;
154.1478 - member : getText;F;;self,t;
154.1479 - member : getToken;F;;self,t;
154.1480 - member : getTokenStartIndex;F;;self,t;
154.1481 - member : getTokenStopIndex;F;;self,t;
154.1482 - member : getType;F;;self,t;
154.1483 - member : getUniqueID;F;;self,node;
154.1484 - member : isNil;F;;self,tree;
154.1485 - member : nil;F;;self;
154.1486 - member : replaceChildren;F;;self,parent,startChildIndex,stopChildIndex,t;
154.1487 - member : rulePostProcessing;F;;self,root;
154.1488 - member : setChild;F;;self,t,i,child;
154.1489 - member : setChildIndex;F;;self,t,index;
154.1490 - member : setParent;F;;self,t,parent;
154.1491 - member : setText;F;;self,t,text;
154.1492 - member : setTokenBoundaries;F;;self,t,startToken,stopToken;
154.1493 - member : setType;F;;self,t,type;
154.1494 -
154.1495 -Not Searchable Keys:
154.1496 -
154.1497 -
154.1498 -Document 69
154.1499 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1500 -Searchable Keys:
154.1501 - class : TreeNodeStream
154.1502 - class-ig : treenodestream
154.1503 - extends : IntStream
154.1504 - in : tree
154.1505 - member : LT;F;;self,k;
154.1506 - member : get;F;;self,i;
154.1507 - member : getTokenStream;F;;self;
154.1508 - member : getTreeAdaptor;F;;self;
154.1509 - member : getTreeSource;F;;self;
154.1510 - member : replaceChildren;F;;self,parent,startChildIndex,stopChildIndex,t;
154.1511 - member : setUniqueNavigationNodes;F;;self,uniqueNavigationNodes;
154.1512 - member : toString;F;;self,start,stop;
154.1513 -
154.1514 -Not Searchable Keys:
154.1515 -
154.1516 -
154.1517 -Document 70
154.1518 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1519 -Searchable Keys:
154.1520 - class : TreeParser
154.1521 - class-ig : treeparser
154.1522 - extends : BaseRecognizer
154.1523 - in : tree
154.1524 - member : __init__;c;|CONSTRUCTOR|;self,input,state;
154.1525 - member : getCurrentInputSymbol;F;;self,input;
154.1526 - member : getErrorHeader;F;;self,e;
154.1527 - member : getErrorMessage;F;;self,e,tokenNames;
154.1528 - member : getMissingSymbol;F;;self,input,e,expectedTokenType,follow;
154.1529 - member : getSourceName;F;;self;
154.1530 - member : getTreeNodeStream;F;;self;
154.1531 - member : input;D;;
154.1532 - member : matchAny;F;;self,ignore;
154.1533 - member : mismatch;F;;self,input,ttype,follow;
154.1534 - member : reset;F;;self;
154.1535 - member : setTreeNodeStream;F;;self,input;
154.1536 - member : traceIn;F;;self,ruleName,ruleIndex;
154.1537 - member : traceOut;F;;self,ruleName,ruleIndex;
154.1538 -
154.1539 -Not Searchable Keys:
154.1540 -
154.1541 -
154.1542 -Document 71
154.1543 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1544 -Searchable Keys:
154.1545 - class : TreeRuleReturnScope
154.1546 - class-ig : treerulereturnscope
154.1547 - extends : RuleReturnScope
154.1548 - in : tree
154.1549 - member : __init__;c;|CONSTRUCTOR|;self;
154.1550 - member : getStart;F;;self;
154.1551 - member : getTree;F;;self;
154.1552 - member : start;D;;
154.1553 - member : tree;D;;
154.1554 -
154.1555 -Not Searchable Keys:
154.1556 -
154.1557 -
154.1558 -Document 72
154.1559 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
154.1560 -Searchable Keys:
154.1561 - item : BaseRecognizer;I;;
154.1562 - item : BaseTree;C;;
154.1563 - item : BaseTreeAdaptor;C;;
154.1564 - item : CommonErrorNode;C;;
154.1565 - item : CommonToken;I;;
154.1566 - item : CommonTree;C;;
154.1567 - item : CommonTreeAdaptor;C;;
154.1568 - item : CommonTreeNodeStream;C;;
154.1569 - item : DOWN;I;;
154.1570 - item : EOF;I;;
154.1571 - item : INVALID_NODE;D;;
154.1572 - item : INVALID_TOKEN;I;;
154.1573 - item : INVALID_TOKEN_TYPE;I;;
154.1574 - item : IntStream;I;;
154.1575 - item : MismatchedTokenException;I;;
154.1576 - item : MismatchedTreeNodeException;I;;
154.1577 - item : MissingTokenException;I;;
154.1578 - item : NoViableAltException;I;;
154.1579 - item : RewriteCardinalityException;C;;
154.1580 - item : RewriteEarlyExitException;C;;
154.1581 - item : RewriteEmptyStreamException;C;;
154.1582 - item : RewriteRuleElementStream;C;;
154.1583 - item : RewriteRuleNodeStream;C;;
154.1584 - item : RewriteRuleSubtreeStream;C;;
154.1585 - item : RewriteRuleTokenStream;C;;
154.1586 - item : RuleReturnScope;I;;
154.1587 - item : Token;I;;
154.1588 - item : Tree;C;;
154.1589 - item : TreeAdaptor;C;;
154.1590 - item : TreeNodeStream;C;;
154.1591 - item : TreeParser;C;;
154.1592 - item : TreeRuleReturnScope;C;;
154.1593 - item : UP;I;;
154.1594 - item : UnwantedTokenException;I;;
154.1595 - module : tree
154.1596 -
154.1597 -Not Searchable Keys:
154.1598 -
154.1599 -
154.1600 -Document 73
154.1601 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
154.1602 -Searchable Keys:
154.1603 - class : TreePattern
154.1604 - class-ig : treepattern
154.1605 - extends : CommonTree
154.1606 - in : treewizard
154.1607 - member : __init__;c;|CONSTRUCTOR|;self,payload;
154.1608 - member : hasTextArg;D;;
154.1609 - member : label;D;;
154.1610 - member : toString;F;;self;
154.1611 -
154.1612 -Not Searchable Keys:
154.1613 -
154.1614 -
154.1615 -Document 74
154.1616 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
154.1617 -Searchable Keys:
154.1618 - class : TreePatternLexer
154.1619 - class-ig : treepatternlexer
154.1620 - extends : object
154.1621 - in : treewizard
154.1622 - member : __idChar;D;|PRIVATE|;
154.1623 - member : __idStartChar;D;|PRIVATE|;
154.1624 - member : __init__;c;|CONSTRUCTOR|;self,pattern;
154.1625 - member : c;D;;
154.1626 - member : consume;F;;self;
154.1627 - member : error;D;;
154.1628 - member : n;D;;
154.1629 - member : nextToken;F;;self;
154.1630 - member : p;D;;
154.1631 - member : pattern;D;;
154.1632 - member : sval;D;;
154.1633 -
154.1634 -Not Searchable Keys:
154.1635 -
154.1636 -
154.1637 -Document 75
154.1638 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
154.1639 -Searchable Keys:
154.1640 - class : TreePatternParser
154.1641 - class-ig : treepatternparser
154.1642 - extends : object
154.1643 - in : treewizard
154.1644 - member : __init__;c;|CONSTRUCTOR|;self,tokenizer,wizard,adaptor;
154.1645 - member : adaptor;D;;
154.1646 - member : parseNode;F;;self;
154.1647 - member : parseTree;F;;self;
154.1648 - member : pattern;F;;self;
154.1649 - member : tokenizer;D;;
154.1650 - member : ttype;D;;
154.1651 - member : wizard;D;;
154.1652 -
154.1653 -Not Searchable Keys:
154.1654 -
154.1655 -
154.1656 -Document 76
154.1657 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
154.1658 -Searchable Keys:
154.1659 - class : TreePatternTreeAdaptor
154.1660 - class-ig : treepatterntreeadaptor
154.1661 - extends : CommonTreeAdaptor
154.1662 - in : treewizard
154.1663 - member : createWithPayload;F;;self,payload;
154.1664 -
154.1665 -Not Searchable Keys:
154.1666 -
154.1667 -
154.1668 -Document 77
154.1669 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
154.1670 -Searchable Keys:
154.1671 - class : TreeWizard
154.1672 - class-ig : treewizard
154.1673 - extends : object
154.1674 - in : treewizard
154.1675 - member : __init__;c;|CONSTRUCTOR|;self,adaptor,tokenNames,typeMap;
154.1676 - member : _equals;F;|PRIVATE|;self,t1,t2,adaptor;
154.1677 - member : _findPattern;F;|PRIVATE|;self,t,pattern;
154.1678 - member : _findTokenType;F;|PRIVATE|;self,t,ttype;
154.1679 - member : _index;F;|PRIVATE|;self,t,m;
154.1680 - member : _parse;F;|PRIVATE|;self,t1,t2,labels;
154.1681 - member : _visitPattern;F;|PRIVATE|;self,tree,pattern,visitor;
154.1682 - member : _visitType;F;|PRIVATE|;self,t,parent,childIndex,ttype,visitor;
154.1683 - member : adaptor;D;;
154.1684 - member : create;F;;self,pattern;
154.1685 - member : equals;F;;self,t1,t2,adaptor;
154.1686 - member : find;F;;self,tree,what;
154.1687 - member : getTokenType;F;;self,tokenName;
154.1688 - member : index;F;;self,tree;
154.1689 - member : parse;F;;self,t,pattern,labels;
154.1690 - member : tokenNameToTypeMap;D;;
154.1691 - member : visit;F;;self,tree,what,visitor;
154.1692 -
154.1693 -Not Searchable Keys:
154.1694 -
154.1695 -
154.1696 -Document 78
154.1697 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
154.1698 -Searchable Keys:
154.1699 - class : WildcardTreePattern
154.1700 - class-ig : wildcardtreepattern
154.1701 - extends : TreePattern
154.1702 - in : treewizard
154.1703 -
154.1704 -Not Searchable Keys:
154.1705 -
154.1706 -
154.1707 -Document 79
154.1708 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
154.1709 -Searchable Keys:
154.1710 - item : ARG;D;;
154.1711 - item : BEGIN;D;;
154.1712 - item : COLON;D;;
154.1713 - item : CommonToken;I;;
154.1714 - item : CommonTree;I;;
154.1715 - item : CommonTreeAdaptor;I;;
154.1716 - item : DOT;D;;
154.1717 - item : END;D;;
154.1718 - item : EOF;D;;
154.1719 - item : ID;D;;
154.1720 - item : INVALID_TOKEN_TYPE;I;;
154.1721 - item : PERCENT;D;;
154.1722 - item : TreePattern;C;;
154.1723 - item : TreePatternLexer;C;;
154.1724 - item : TreePatternParser;C;;
154.1725 - item : TreePatternTreeAdaptor;C;;
154.1726 - item : TreeWizard;C;;
154.1727 - item : WildcardTreePattern;C;;
154.1728 - item : computeTokenTypes;F;;tokenNames;
154.1729 - module : treewizard
154.1730 -
154.1731 -Not Searchable Keys:
155.1 --- a/python.editor/test/unit/data/testfiles/assign.py Sun Jan 04 13:11:53 2015 -0600
155.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
155.3 @@ -1,7 +0,0 @@
155.4 -if __name__ == "__main__":
155.5 - print "Hello";
155.6 - "foo"
155.7 - 3+1
155.8 - preprocess1(foo, source, output_file, macros, include_dirs, extra_preargs, extra_postargs);
155.9 - get_preprocess2(self, source, output_file, macros, include_dirs, extra_preargs, extra_postargs)
155.10 -
156.1 --- a/python.editor/test/unit/data/testfiles/assign.py.testAssign1.hints Sun Jan 04 13:11:53 2015 -0600
156.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
156.3 @@ -1,4 +0,0 @@
156.4 - ^"foo"
156.5 - -----
156.6 -HINT:Assign expression to a variable
156.7 -FIX:Assign expression to a variable
157.1 --- a/python.editor/test/unit/data/testfiles/assign.py.testAssign2.hints Sun Jan 04 13:11:53 2015 -0600
157.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
157.3 @@ -1,4 +0,0 @@
157.4 - 3+1^
157.5 - ---
157.6 -HINT:Assign expression to a variable
157.7 -FIX:Assign expression to a variable
158.1 --- a/python.editor/test/unit/data/testfiles/assign.py.testAssign3.hints Sun Jan 04 13:11:53 2015 -0600
158.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
158.3 @@ -1,4 +0,0 @@
158.4 - ^get_preprocess2(self, source, output_file, macros, include_dirs, extra_preargs, extra_postargs)
158.5 - -----------------------------------------------------------------------------------------------
158.6 -HINT:Assign expression to a variable
158.7 -FIX:Assign expression to a variable
159.1 --- a/python.editor/test/unit/data/testfiles/assign.py.testFixAssign.fixed Sun Jan 04 13:11:53 2015 -0600
159.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
159.3 @@ -1,7 +0,0 @@
159.4 -if __name__ == "__main__":
159.5 - print "Hello";
159.6 - "foo"
159.7 - name = 3+1
159.8 - preprocess1(foo, source, output_file, macros, include_dirs, extra_preargs, extra_postargs);
159.9 - get_preprocess2(self, source, output_file, macros, include_dirs, extra_preargs, extra_postargs)
159.10 -
160.1 --- a/python.editor/test/unit/data/testfiles/assign2.py Sun Jan 04 13:11:53 2015 -0600
160.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
160.3 @@ -1,4 +0,0 @@
160.4 -def _is_leap(year):
160.5 - "year -> 1 if leap year, else 0."
160.6 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
160.7 -
161.1 --- a/python.editor/test/unit/data/testfiles/attribute.py Sun Jan 04 13:11:53 2015 -0600
161.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
161.3 @@ -1,6 +0,0 @@
161.4 -# Test 1
161.5 -foo.bar
161.6 -
161.7 -# Test 2
161.8 -foo.bar()
161.9 -
162.1 --- a/python.editor/test/unit/data/testfiles/attribute.py.offsets Sun Jan 04 13:11:53 2015 -0600
162.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
162.3 @@ -1,7 +0,0 @@
162.4 -
162.5 -# Test 1
162.6 -<Module><Expr><Attribute><Name>foo</Name>.bar</Attribute></Expr>
162.7 -
162.8 -# Test 2
162.9 -<Expr><Call><Attribute><Name>foo</Name>.bar</Attribute>()</Call></Expr></Module>
162.10 -
163.1 --- a/python.editor/test/unit/data/testfiles/attributes.py Sun Jan 04 13:11:53 2015 -0600
163.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
163.3 @@ -1,20 +0,0 @@
163.4 -
163.5 -class AttributeTest:
163.6 - def __init__(self):
163.7 - self.okay = true;
163.8 - self._private = true;
163.9 -
163.10 - def notconstructor(self):
163.11 - self.notokay = true;
163.12 -
163.13 -
163.14 - print self.okay
163.15 - print self.notokay
163.16 -
163.17 -
163.18 - def usage(self):
163.19 - other.notokay = true;
163.20 - other._notokay = true;
163.21 - print other._notokay
163.22 -
163.23 -
164.1 --- a/python.editor/test/unit/data/testfiles/attributes.py.scopes Sun Jan 04 13:11:53 2015 -0600
164.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
164.3 @@ -1,33 +0,0 @@
164.4 - =============================================
164.5 - class AttributeTest: ClassDef : OffsetRange[1,361>
164.6 - __init__ [bound][function][def][node=FunctionDef]
164.7 - notconstructor [bound][function][def][node=FunctionDef]
164.8 - usage [bound][function][def][node=FunctionDef]
164.9 - ------ Attributes ---------------------------------------
164.10 - _private : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
164.11 - notokay : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
164.12 - okay : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
164.13 -
164.14 -=============================================
164.15 -<file-top>: Module : OffsetRange[1,361>
164.16 -AttributeTest [bound][class][def][node=ClassDef]
164.17 -
164.18 - =============================================
164.19 - __init__: FunctionDef : OffsetRange[26,106>
164.20 - self [bound][param][data][read][node=Name]
164.21 - true [free][read][node=Name]
164.22 -
164.23 - =============================================
164.24 - notconstructor: FunctionDef : OffsetRange[107,244>
164.25 - self [bound][param][data][read][node=Name]
164.26 - true [free][read][node=Name]
164.27 - ------ Attributes ---------------------------------------
164.28 - notokay : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
164.29 - okay : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
164.30 -
164.31 - =============================================
164.32 - usage: FunctionDef : OffsetRange[245,361>
164.33 - other [free][read][node=Name]
164.34 - self [bound][param][data][unused][node=Name]
164.35 - true [free][read][node=Name]
164.36 -
165.1 --- a/python.editor/test/unit/data/testfiles/attributes.py.testAccessToProtected.hints Sun Jan 04 13:11:53 2015 -0600
165.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
165.3 @@ -1,6 +0,0 @@
165.4 - other._notokay = true;
165.5 - --------------
165.6 -HINT:Access to protected variable "_notokay"
165.7 - print other._notokay
165.8 - --------------
165.9 -HINT:Access to protected variable "_notokay"
166.1 --- a/python.editor/test/unit/data/testfiles/attributes.py.testAttributeDefinedOutsideInit.hints Sun Jan 04 13:11:53 2015 -0600
166.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
166.3 @@ -1,3 +0,0 @@
166.4 - self.notokay = true;
166.5 - ------------
166.6 -HINT:Attribute Defined Outside __init__ "notokay"
167.1 --- a/python.editor/test/unit/data/testfiles/attributes.py.testRename9.rename Sun Jan 04 13:11:53 2015 -0600
167.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
167.3 @@ -1,1 +0,0 @@
167.4 -Requires Interactive Refactoring
168.1 --- a/python.editor/test/unit/data/testfiles/circularredundancy.py Sun Jan 04 13:11:53 2015 -0600
168.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
168.3 @@ -1,23 +0,0 @@
168.4 -#
168.5 -# checking redundancy cycling
168.6 -#
168.7 -
168.8 -# circular
168.9 -class First (Third ):
168.10 - pass
168.11 -
168.12 -class Second (First) :
168.13 - pass
168.14 -
168.15 -class Third (Second) :
168.16 - pass
168.17 -
168.18 -# not circular
168.19 -class Fourth :
168.20 - pass
168.21 -
168.22 -class Fifth(Fourth):
168.23 - pass
168.24 -
168.25 -
168.26 -
169.1 --- a/python.editor/test/unit/data/testfiles/circularredundancy.py.testCircularRedundancy.hints Sun Jan 04 13:11:53 2015 -0600
169.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
169.3 @@ -1,9 +0,0 @@
169.4 -class First (Third ):
169.5 - -----
169.6 -HINT:Parent/child First/Third inheritance circular redundancy
169.7 -class Second (First) :
169.8 - ------
169.9 -HINT:Parent/child Second/First inheritance circular redundancy
169.10 -class Third (Second) :
169.11 - -----
169.12 -HINT:Parent/child Third/Second inheritance circular redundancy
170.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/nbproject/project.properties 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 -java.lib.path=
170.5 -main.file=md5driver.py
170.6 -platform.active=Python_2.5.1
170.7 -python.lib.path=
170.8 -src.dir=src
171.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
171.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
171.3 @@ -1,13 +0,0 @@
171.4 -<?xml version="1.0" encoding="UTF-8"?>
171.5 -<project xmlns="http://www.netbeans.org/ns/project/1">
171.6 - <type>org.netbeans.modules.python.project</type>
171.7 - <configuration>
171.8 - <data xmlns="http://nbpython.dev.java.net/ns/php-project/1">
171.9 - <name>CoveragePrj</name>
171.10 - <sources>
171.11 - <root id="src.dir"/>
171.12 - </sources>
171.13 - <tests/>
171.14 - </data>
171.15 - </configuration>
171.16 -</project>
172.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/coverageprj.py Sun Jan 04 13:11:53 2015 -0600
172.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
172.3 @@ -1,10 +0,0 @@
172.4 -# To change this template, choose Tools | Templates
172.5 -# and open the template in the editor.
172.6 -
172.7 -__author__="tor"
172.8 -__date__ ="$Dec 15, 2008 12:29:43 PM$"
172.9 -
172.10 -if __name__ == "__mmain__":
172.11 - print "Hello World";
172.12 -
172.13 -print "Bye"
173.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/coverageprj.py.coverage.html Sun Jan 04 13:11:53 2015 -0600
173.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
173.3 @@ -1,25 +0,0 @@
173.4 -<html>
173.5 -<head>
173.6 -<style>
173.7 -div { white-space: pre; font-family: monospace; margin: 0px; padding: 0px }
173.8 -.covered { background-color: CCFFCC }
173.9 -.partial { background-color: FFFFCC }
173.10 -.not_covered { background-color: FFCCCC }
173.11 -.inferred { background-color: E0FFE0 }
173.12 -.unknown { background-color: EEEEEE }
173.13 -</style>
173.14 -</head>
173.15 -<body>
173.16 -<h1>File Coverage for coverageprj.py</h1>
173.17 -<div class="inferred"># To change this template, choose Tools | Templates</div>
173.18 -<div class="inferred"># and open the template in the editor.</div>
173.19 -<div class="inferred"></div>
173.20 -<div class="covered">__author__="tor"</div>
173.21 -<div class="covered">__date__ ="$Dec 15, 2008 12:29:43 PM$"</div>
173.22 -<div class="inferred"></div>
173.23 -<div class="covered">if __name__ == "__mmain__":</div>
173.24 -<div class="not_covered"> print "Hello World";</div>
173.25 -<div class="not_covered"></div>
173.26 -<div class="covered">print "Bye"</div>
173.27 -
173.28 -</body></html>
174.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/coverageprj2.py Sun Jan 04 13:11:53 2015 -0600
174.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
174.3 @@ -1,13 +0,0 @@
174.4 -#import
174.5 -__author__="tor"
174.6 -__date__ ="$Nov 1, 2008 4:43:31 PM$"
174.7 -
174.8 -
174.9 -
174.10 -if __name__ == "__mmain__":
174.11 - print "Hello";
174.12 -
174.13 -
174.14 - def fenamme():
174.15 - pass
174.16 -
175.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/coverageprj2.py.coverage.html Sun Jan 04 13:11:53 2015 -0600
175.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
175.3 @@ -1,28 +0,0 @@
175.4 -<html>
175.5 -<head>
175.6 -<style>
175.7 -div { white-space: pre; font-family: monospace; margin: 0px; padding: 0px }
175.8 -.covered { background-color: CCFFCC }
175.9 -.partial { background-color: FFFFCC }
175.10 -.not_covered { background-color: FFCCCC }
175.11 -.inferred { background-color: E0FFE0 }
175.12 -.unknown { background-color: EEEEEE }
175.13 -</style>
175.14 -</head>
175.15 -<body>
175.16 -<h1>File Coverage for coverageprj2.py</h1>
175.17 -<div class="inferred">#import</div>
175.18 -<div class="covered">__author__="tor"</div>
175.19 -<div class="covered">__date__ ="$Nov 1, 2008 4:43:31 PM$"</div>
175.20 -<div class="inferred"></div>
175.21 -<div class="inferred"></div>
175.22 -<div class="inferred"></div>
175.23 -<div class="covered">if __name__ == "__mmain__":</div>
175.24 -<div class="not_covered"> print "Hello";</div>
175.25 -<div class="not_covered"></div>
175.26 -<div class="not_covered"></div>
175.27 -<div class="not_covered"> def fenamme():</div>
175.28 -<div class="not_covered"> pass</div>
175.29 -<div class="not_covered"></div>
175.30 -
175.31 -</body></html>
176.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/coverageprj3.py Sun Jan 04 13:11:53 2015 -0600
176.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
176.3 @@ -1,12 +0,0 @@
176.4 -#import
176.5 -__author__="tor"
176.6 -__date__ ="$Nov 1, 2008 4:43:31 PM$"
176.7 -
176.8 -
176.9 -
176.10 -if __name__ == "__main__":
176.11 - print "Hello";
176.12 -
176.13 -# This line is inferred to be executed
176.14 -# This one too
176.15 -
177.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/coverageprj3.py.coverage.html Sun Jan 04 13:11:53 2015 -0600
177.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
177.3 @@ -1,27 +0,0 @@
177.4 -<html>
177.5 -<head>
177.6 -<style>
177.7 -div { white-space: pre; font-family: monospace; margin: 0px; padding: 0px }
177.8 -.covered { background-color: CCFFCC }
177.9 -.partial { background-color: FFFFCC }
177.10 -.not_covered { background-color: FFCCCC }
177.11 -.inferred { background-color: E0FFE0 }
177.12 -.unknown { background-color: EEEEEE }
177.13 -</style>
177.14 -</head>
177.15 -<body>
177.16 -<h1>File Coverage for coverageprj3.py</h1>
177.17 -<div class="inferred">#import</div>
177.18 -<div class="covered">__author__="tor"</div>
177.19 -<div class="covered">__date__ ="$Nov 1, 2008 4:43:31 PM$"</div>
177.20 -<div class="inferred"></div>
177.21 -<div class="inferred"></div>
177.22 -<div class="inferred"></div>
177.23 -<div class="covered">if __name__ == "__main__":</div>
177.24 -<div class="covered"> print "Hello";</div>
177.25 -<div class="inferred"></div>
177.26 -<div class="inferred"># This line is inferred to be executed</div>
177.27 -<div class="inferred"># This one too</div>
177.28 -<div class="inferred"></div>
177.29 -
177.30 -</body></html>
178.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/foo Sun Jan 04 13:11:53 2015 -0600
178.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
178.3 @@ -1,1 +0,0 @@
178.4 -Hello World
179.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/md5driver.py Sun Jan 04 13:11:53 2015 -0600
179.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
179.3 @@ -1,126 +0,0 @@
179.4 -import string
179.5 -import md5
179.6 -from sys import argv
179.7 -
179.8 -def MDPrint(str):
179.9 - outstr = ''
179.10 - for i in str:
179.11 - o = ord(i)
179.12 - outstr = (outstr
179.13 - + string.hexdigits[(o >> 4) & 0xF]
179.14 - + string.hexdigits[o & 0xF])
179.15 - print outstr,
179.16 -
179.17 -
179.18 -from time import time
179.19 -
179.20 -def makestr(start, end):
179.21 - result = ''
179.22 -
179.23 - for i in range(start, end + 1):
179.24 - result = result + chr(i)
179.25 -
179.26 - return result
179.27 -
179.28 -
179.29 -def MDTimeTrial():
179.30 - TEST_BLOCK_SIZE = 1000
179.31 - TEST_BLOCKS = 10000
179.32 -
179.33 - TEST_BYTES = TEST_BLOCK_SIZE * TEST_BLOCKS
179.34 -
179.35 - # initialize test data, need temporary string filler
179.36 -
179.37 - filsiz = 1 << 8
179.38 - filler = makestr(0, filsiz-1)
179.39 - data = filler * (TEST_BLOCK_SIZE // filsiz)
179.40 - data = data + filler[:(TEST_BLOCK_SIZE % filsiz)]
179.41 -
179.42 - del filsiz, filler
179.43 -
179.44 -
179.45 - # start timer
179.46 - print 'MD5 time trial. Processing', TEST_BYTES, 'characters...'
179.47 - t1 = time()
179.48 -
179.49 - mdContext = md5.new()
179.50 -
179.51 - for i in range(TEST_BLOCKS):
179.52 - mdContext.update(data)
179.53 -
179.54 - str = mdContext.digest()
179.55 - t2 = time()
179.56 -
179.57 - MDPrint(str)
179.58 - print 'is digest of test input.'
179.59 - print 'Seconds to process test input:', t2 - t1
179.60 - print 'Characters processed per second:', TEST_BYTES / (t2 - t1)
179.61 -
179.62 -
179.63 -def MDString(str):
179.64 - MDPrint(md5.new(str).digest())
179.65 - print '"' + str + '"'
179.66 -
179.67 -
179.68 -def MDFile(filename):
179.69 - f = open(filename, 'rb')
179.70 - mdContext = md5.new()
179.71 -
179.72 - while 1:
179.73 - data = f.read(1024)
179.74 - if not data:
179.75 - break
179.76 - mdContext.update(data)
179.77 -
179.78 - MDPrint(mdContext.digest())
179.79 - print filename
179.80 -
179.81 -
179.82 -import sys
179.83 -
179.84 -# This comment should be
179.85 -# inferred as part of the previous one
179.86 -def MDFilter():
179.87 - mdContext = md5.new()
179.88 -
179.89 - while 1:
179.90 - data = sys.stdin.read(16)
179.91 - if not data:
179.92 - break
179.93 - mdContext.update(data)
179.94 -
179.95 - MDPrint(mdContext.digest())
179.96 - print
179.97 -
179.98 -
179.99 -def MDTestSuite():
179.100 - print 'MD5 test suite results:'
179.101 - MDString('')
179.102 - MDString('a')
179.103 - MDString('abc')
179.104 - MDString('message digest')
179.105 - MDString(makestr(ord('a'), ord('z')))
179.106 - MDString(makestr(ord('A'), ord('Z'))
179.107 - + makestr(ord('a'), ord('z'))
179.108 - + makestr(ord('0'), ord('9')))
179.109 - MDString((makestr(ord('1'), ord('9')) + '0') * 8)
179.110 -
179.111 - # Contents of file foo are "abc"
179.112 - MDFile('foo')
179.113 -
179.114 -
179.115 -# I don't wanna use getopt(), since I want to use the same i/f...
179.116 -def main():
179.117 - if len(argv) == 1:
179.118 - MDFilter()
179.119 - for arg in argv[1:]:
179.120 - if arg[:2] == '-s':
179.121 - MDString(arg[2:])
179.122 - elif arg == '-t':
179.123 - MDTimeTrial()
179.124 - elif arg == '-x':
179.125 - MDTestSuite()
179.126 - else:
179.127 - MDFile(arg)
179.128 -
179.129 -main()
180.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/md5driver.py.coverage.html Sun Jan 04 13:11:53 2015 -0600
180.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
180.3 @@ -1,141 +0,0 @@
180.4 -<html>
180.5 -<head>
180.6 -<style>
180.7 -div { white-space: pre; font-family: monospace; margin: 0px; padding: 0px }
180.8 -.covered { background-color: CCFFCC }
180.9 -.partial { background-color: FFFFCC }
180.10 -.not_covered { background-color: FFCCCC }
180.11 -.inferred { background-color: E0FFE0 }
180.12 -.unknown { background-color: EEEEEE }
180.13 -</style>
180.14 -</head>
180.15 -<body>
180.16 -<h1>File Coverage for md5driver.py</h1>
180.17 -<div class="covered">import string</div>
180.18 -<div class="covered">import md5</div>
180.19 -<div class="covered">from sys import argv</div>
180.20 -<div class="unknown"></div>
180.21 -<div class="covered">def MDPrint(str):</div>
180.22 -<div class="covered"> outstr = ''</div>
180.23 -<div class="covered"> for i in str:</div>
180.24 -<div class="covered"> o = ord(i)</div>
180.25 -<div class="covered"> outstr = (outstr</div>
180.26 -<div class="unknown"> + string.hexdigits[(o >> 4) & 0xF]</div>
180.27 -<div class="unknown"> + string.hexdigits[o & 0xF])</div>
180.28 -<div class="covered"> print outstr,</div>
180.29 -<div class="inferred"></div>
180.30 -<div class="inferred"></div>
180.31 -<div class="covered">from time import time</div>
180.32 -<div class="unknown"></div>
180.33 -<div class="covered">def makestr(start, end):</div>
180.34 -<div class="not_covered"> result = ''</div>
180.35 -<div class="not_covered"> </div>
180.36 -<div class="not_covered"> for i in range(start, end + 1):</div>
180.37 -<div class="not_covered"> result = result + chr(i)</div>
180.38 -<div class="not_covered"></div>
180.39 -<div class="not_covered"> return result</div>
180.40 -<div class="not_covered"></div>
180.41 -<div class="not_covered"></div>
180.42 -<div class="covered">def MDTimeTrial():</div>
180.43 -<div class="not_covered"> TEST_BLOCK_SIZE = 1000</div>
180.44 -<div class="not_covered"> TEST_BLOCKS = 10000</div>
180.45 -<div class="not_covered"></div>
180.46 -<div class="not_covered"> TEST_BYTES = TEST_BLOCK_SIZE * TEST_BLOCKS</div>
180.47 -<div class="not_covered"></div>
180.48 -<div class="not_covered"> # initialize test data, need temporary string filler</div>
180.49 -<div class="not_covered"></div>
180.50 -<div class="not_covered"> filsiz = 1 << 8</div>
180.51 -<div class="not_covered"> filler = makestr(0, filsiz-1)</div>
180.52 -<div class="not_covered"> data = filler * (TEST_BLOCK_SIZE // filsiz)</div>
180.53 -<div class="not_covered"> data = data + filler[:(TEST_BLOCK_SIZE % filsiz)]</div>
180.54 -<div class="not_covered"></div>
180.55 -<div class="not_covered"> del filsiz, filler</div>
180.56 -<div class="not_covered"></div>
180.57 -<div class="not_covered"></div>
180.58 -<div class="not_covered"> # start timer</div>
180.59 -<div class="not_covered"> print 'MD5 time trial. Processing', TEST_BYTES, 'characters...'</div>
180.60 -<div class="not_covered"> t1 = time()</div>
180.61 -<div class="not_covered"></div>
180.62 -<div class="not_covered"> mdContext = md5.new()</div>
180.63 -<div class="not_covered"></div>
180.64 -<div class="not_covered"> for i in range(TEST_BLOCKS):</div>
180.65 -<div class="not_covered"> mdContext.update(data)</div>
180.66 -<div class="not_covered"></div>
180.67 -<div class="not_covered"> str = mdContext.digest()</div>
180.68 -<div class="not_covered"> t2 = time()</div>
180.69 -<div class="not_covered"></div>
180.70 -<div class="not_covered"> MDPrint(str)</div>
180.71 -<div class="not_covered"> print 'is digest of test input.'</div>
180.72 -<div class="not_covered"> print 'Seconds to process test input:', t2 - t1</div>
180.73 -<div class="not_covered"> print 'Characters processed per second:', TEST_BYTES / (t2 - t1)</div>
180.74 -<div class="not_covered"></div>
180.75 -<div class="not_covered"></div>
180.76 -<div class="covered">def MDString(str):</div>
180.77 -<div class="not_covered"> MDPrint(md5.new(str).digest())</div>
180.78 -<div class="not_covered"> print '"' + str + '"'</div>
180.79 -<div class="not_covered"></div>
180.80 -<div class="not_covered"></div>
180.81 -<div class="covered">def MDFile(filename):</div>
180.82 -<div class="not_covered"> f = open(filename, 'rb')</div>
180.83 -<div class="not_covered"> mdContext = md5.new()</div>
180.84 -<div class="not_covered"></div>
180.85 -<div class="not_covered"> while 1:</div>
180.86 -<div class="not_covered"> data = f.read(1024)</div>
180.87 -<div class="not_covered"> if not data:</div>
180.88 -<div class="not_covered"> break</div>
180.89 -<div class="not_covered"> mdContext.update(data)</div>
180.90 -<div class="not_covered"></div>
180.91 -<div class="not_covered"> MDPrint(mdContext.digest())</div>
180.92 -<div class="not_covered"> print filename</div>
180.93 -<div class="not_covered"></div>
180.94 -<div class="not_covered"></div>
180.95 -<div class="covered">import sys</div>
180.96 -<div class="inferred"></div>
180.97 -<div class="inferred"># This comment should be</div>
180.98 -<div class="inferred"># inferred as part of the previous one</div>
180.99 -<div class="covered">def MDFilter():</div>
180.100 -<div class="covered"> mdContext = md5.new()</div>
180.101 -<div class="inferred"></div>
180.102 -<div class="covered"> while 1:</div>
180.103 -<div class="covered"> data = sys.stdin.read(16)</div>
180.104 -<div class="covered"> if not data:</div>
180.105 -<div class="not_covered"> break</div>
180.106 -<div class="not_covered"> mdContext.update(data)</div>
180.107 -<div class="not_covered"></div>
180.108 -<div class="covered"> MDPrint(mdContext.digest())</div>
180.109 -<div class="covered"> print</div>
180.110 -<div class="unknown"></div>
180.111 -<div class="unknown"></div>
180.112 -<div class="covered">def MDTestSuite():</div>
180.113 -<div class="not_covered"> print 'MD5 test suite results:'</div>
180.114 -<div class="not_covered"> MDString('')</div>
180.115 -<div class="not_covered"> MDString('a')</div>
180.116 -<div class="not_covered"> MDString('abc')</div>
180.117 -<div class="not_covered"> MDString('message digest')</div>
180.118 -<div class="not_covered"> MDString(makestr(ord('a'), ord('z')))</div>
180.119 -<div class="not_covered"> MDString(makestr(ord('A'), ord('Z'))</div>
180.120 -<div class="not_covered"> + makestr(ord('a'), ord('z'))</div>
180.121 -<div class="not_covered"> + makestr(ord('0'), ord('9')))</div>
180.122 -<div class="not_covered"> MDString((makestr(ord('1'), ord('9')) + '0') * 8)</div>
180.123 -<div class="not_covered"></div>
180.124 -<div class="not_covered"> # Contents of file foo are "abc"</div>
180.125 -<div class="not_covered"> MDFile('foo')</div>
180.126 -<div class="not_covered"></div>
180.127 -<div class="not_covered"></div>
180.128 -<div class="inferred"># I don't wanna use getopt(), since I want to use the same i/f...</div>
180.129 -<div class="covered">def main():</div>
180.130 -<div class="covered"> if len(argv) == 1:</div>
180.131 -<div class="covered"> MDFilter()</div>
180.132 -<div class="covered"> for arg in argv[1:]:</div>
180.133 -<div class="not_covered"> if arg[:2] == '-s':</div>
180.134 -<div class="not_covered"> MDString(arg[2:])</div>
180.135 -<div class="not_covered"> elif arg == '-t':</div>
180.136 -<div class="not_covered"> MDTimeTrial()</div>
180.137 -<div class="not_covered"> elif arg == '-x':</div>
180.138 -<div class="not_covered"> MDTestSuite()</div>
180.139 -<div class="not_covered"> else:</div>
180.140 -<div class="not_covered"> MDFile(arg)</div>
180.141 -<div class="not_covered"></div>
180.142 -<div class="covered">main()</div>
180.143 -
180.144 -</body></html>
181.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj2/nbproject/project.properties Sun Jan 04 13:11:53 2015 -0600
181.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
181.3 @@ -1,5 +0,0 @@
181.4 -java.lib.path=
181.5 -main.file=md5driver.py
181.6 -platform.active=Python_2.5.1
181.7 -python.lib.path=
181.8 -src.dir=src
182.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj2/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
182.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
182.3 @@ -1,13 +0,0 @@
182.4 -<?xml version="1.0" encoding="UTF-8"?>
182.5 -<project xmlns="http://www.netbeans.org/ns/project/1">
182.6 - <type>org.netbeans.modules.python.project</type>
182.7 - <configuration>
182.8 - <data xmlns="http://nbpython.dev.java.net/ns/php-project/1">
182.9 - <name>CoveragePrj2</name>
182.10 - <sources>
182.11 - <root id="src.dir"/>
182.12 - </sources>
182.13 - <tests/>
182.14 - </data>
182.15 - </configuration>
182.16 -</project>
183.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj2/src/roman9.py Sun Jan 04 13:11:53 2015 -0600
183.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
183.3 @@ -1,83 +0,0 @@
183.4 -"""Convert to and from Roman numerals
183.5 -
183.6 -This program is part of "Dive Into Python", a free Python book for
183.7 -experienced programmers. Visit http://diveintopython.org/ for the
183.8 -latest version.
183.9 -"""
183.10 -
183.11 -__author__ = "Steve Lamm, Mark Pilgrim (mark@diveintopython.org)"
183.12 -__version__ = "$Revision: 1.3 $"
183.13 -__date__ = "$Date: 2004/05/05 21:57:20 $"
183.14 -__copyright__ = "Copyright (c) 2001 Steve Lamm, Copyright (c) 2001 Mark Pilgrim"
183.15 -__license__ = "Python"
183.16 -
183.17 -import re
183.18 -
183.19 -#Define exceptions
183.20 -class RomanError(Exception): pass
183.21 -class OutOfRangeError(RomanError): pass
183.22 -class NotIntegerError(RomanError): pass
183.23 -class InvalidRomanNumeralError(RomanError): pass
183.24 -
183.25 -#Roman numerals must be less than 5000
183.26 -MAX_ROMAN_NUMERAL = 4999
183.27 -
183.28 -#Define digit mapping
183.29 -romanNumeralMap = (('M', 1000),
183.30 - ('CM', 900),
183.31 - ('D', 500),
183.32 - ('CD', 300),
183.33 - ('C', 100),
183.34 - ('XC', 90),
183.35 - ('L', 50),
183.36 - ('XL', 40),
183.37 - ('X', 10),
183.38 - ('IX', 9),
183.39 - ('V', 5),
183.40 - ('IV', 4),
183.41 - ('I', 1))
183.42 -
183.43 -#Create tables for fast conversion of roman numerals.
183.44 -#See fillLookupTables() below.
183.45 -toRomanTable = [ None ] # Skip an index since Roman numerals have no zero
183.46 -fromRomanTable = {}
183.47 -
183.48 -def toRoman(n):
183.49 - """convert integer to Roman numeral"""
183.50 - if not (0 < n <= MAX_ROMAN_NUMERAL):
183.51 - raise OutOfRangeError, "number out of range (must be 1..4999)"
183.52 - if int(n) <> n:
183.53 - raise NotIntegerError, "non-integers can not be converted"
183.54 - return toRomanTable[n]
183.55 -
183.56 -def fromRoman(s):
183.57 - """convert Roman numeral to integer"""
183.58 - if not s:
183.59 - raise InvalidRomanNumeralError, 'Input can not be blank'
183.60 - if not fromRomanTable.has_key(s):
183.61 - raise InvalidRomanNumeralError, 'Invalid Roman numeral: %s' % s
183.62 - return fromRomanTable[s]
183.63 -
183.64 -def toRomanDynamic(n):
183.65 - """convert integer to Roman numeral using dynamic programming"""
183.66 - assert(0 < n <= MAX_ROMAN_NUMERAL)
183.67 - assert(int(n) == n)
183.68 - result = ""
183.69 - for numeral, integer in romanNumeralMap:
183.70 - if n >= integer:
183.71 - result = numeral
183.72 - n -= integer
183.73 - break
183.74 - if n > 0:
183.75 - result += toRomanTable[n]
183.76 - return result
183.77 -
183.78 -def fillLookupTables():
183.79 - """compute all the possible roman numerals"""
183.80 - #Save the values in two global tables to convert to and from integers.
183.81 - for integer in range(1, MAX_ROMAN_NUMERAL + 1):
183.82 - romanNumber = toRomanDynamic(integer)
183.83 - toRomanTable.append(romanNumber)
183.84 - fromRomanTable[romanNumber] = integer
183.85 -
183.86 -fillLookupTables()
184.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj2/src/roman9.py.coverage.html Sun Jan 04 13:11:53 2015 -0600
184.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
184.3 @@ -1,98 +0,0 @@
184.4 -<html>
184.5 -<head>
184.6 -<style>
184.7 -div { white-space: pre; font-family: monospace; margin: 0px; padding: 0px }
184.8 -.covered { background-color: CCFFCC }
184.9 -.partial { background-color: FFFFCC }
184.10 -.not_covered { background-color: FFCCCC }
184.11 -.inferred { background-color: E0FFE0 }
184.12 -.unknown { background-color: EEEEEE }
184.13 -</style>
184.14 -</head>
184.15 -<body>
184.16 -<h1>File Coverage for roman9.py</h1>
184.17 -<div class="inferred">"""Convert to and from Roman numerals</div>
184.18 -<div class="inferred"></div>
184.19 -<div class="inferred">This program is part of "Dive Into Python", a free Python book for</div>
184.20 -<div class="inferred">experienced programmers. Visit http://diveintopython.org/ for the</div>
184.21 -<div class="inferred">latest version.</div>
184.22 -<div class="inferred">"""</div>
184.23 -<div class="inferred"></div>
184.24 -<div class="covered">__author__ = "Steve Lamm, Mark Pilgrim (mark@diveintopython.org)"</div>
184.25 -<div class="covered">__version__ = "$Revision: 1.3 $"</div>
184.26 -<div class="covered">__date__ = "$Date: 2004/05/05 21:57:20 $"</div>
184.27 -<div class="covered">__copyright__ = "Copyright (c) 2001 Steve Lamm, Copyright (c) 2001 Mark Pilgrim"</div>
184.28 -<div class="covered">__license__ = "Python"</div>
184.29 -<div class="inferred"></div>
184.30 -<div class="covered">import re</div>
184.31 -<div class="inferred"></div>
184.32 -<div class="inferred">#Define exceptions</div>
184.33 -<div class="covered">class RomanError(Exception): pass</div>
184.34 -<div class="covered">class OutOfRangeError(RomanError): pass</div>
184.35 -<div class="covered">class NotIntegerError(RomanError): pass</div>
184.36 -<div class="covered">class InvalidRomanNumeralError(RomanError): pass</div>
184.37 -<div class="inferred"></div>
184.38 -<div class="inferred">#Roman numerals must be less than 5000</div>
184.39 -<div class="covered">MAX_ROMAN_NUMERAL = 4999</div>
184.40 -<div class="inferred"></div>
184.41 -<div class="inferred">#Define digit mapping</div>
184.42 -<div class="covered">romanNumeralMap = (('M', 1000),</div>
184.43 -<div class="unknown"> ('CM', 900),</div>
184.44 -<div class="unknown"> ('D', 500),</div>
184.45 -<div class="unknown"> ('CD', 300),</div>
184.46 -<div class="unknown"> ('C', 100),</div>
184.47 -<div class="unknown"> ('XC', 90),</div>
184.48 -<div class="unknown"> ('L', 50),</div>
184.49 -<div class="unknown"> ('XL', 40),</div>
184.50 -<div class="unknown"> ('X', 10),</div>
184.51 -<div class="unknown"> ('IX', 9),</div>
184.52 -<div class="unknown"> ('V', 5),</div>
184.53 -<div class="unknown"> ('IV', 4),</div>
184.54 -<div class="unknown"> ('I', 1))</div>
184.55 -<div class="inferred"></div>
184.56 -<div class="inferred">#Create tables for fast conversion of roman numerals.</div>
184.57 -<div class="inferred">#See fillLookupTables() below.</div>
184.58 -<div class="covered">toRomanTable = [ None ] # Skip an index since Roman numerals have no zero</div>
184.59 -<div class="covered">fromRomanTable = {}</div>
184.60 -<div class="unknown"></div>
184.61 -<div class="covered">def toRoman(n):</div>
184.62 -<div class="covered"> """convert integer to Roman numeral"""</div>
184.63 -<div class="covered"> if not (0 < n <= MAX_ROMAN_NUMERAL):</div>
184.64 -<div class="covered"> raise OutOfRangeError, "number out of range (must be 1..4999)"</div>
184.65 -<div class="covered"> if int(n) <> n:</div>
184.66 -<div class="covered"> raise NotIntegerError, "non-integers can not be converted"</div>
184.67 -<div class="covered"> return toRomanTable[n]</div>
184.68 -<div class="unknown"></div>
184.69 -<div class="covered">def fromRoman(s):</div>
184.70 -<div class="covered"> """convert Roman numeral to integer"""</div>
184.71 -<div class="covered"> if not s:</div>
184.72 -<div class="covered"> raise InvalidRomanNumeralError, 'Input can not be blank'</div>
184.73 -<div class="covered"> if not fromRomanTable.has_key(s):</div>
184.74 -<div class="covered"> raise InvalidRomanNumeralError, 'Invalid Roman numeral: %s' % s</div>
184.75 -<div class="covered"> return fromRomanTable[s]</div>
184.76 -<div class="unknown"></div>
184.77 -<div class="covered">def toRomanDynamic(n):</div>
184.78 -<div class="covered"> """convert integer to Roman numeral using dynamic programming"""</div>
184.79 -<div class="covered"> assert(0 < n <= MAX_ROMAN_NUMERAL)</div>
184.80 -<div class="covered"> assert(int(n) == n)</div>
184.81 -<div class="covered"> result = ""</div>
184.82 -<div class="covered"> for numeral, integer in romanNumeralMap:</div>
184.83 -<div class="covered"> if n >= integer:</div>
184.84 -<div class="covered"> result = numeral</div>
184.85 -<div class="covered"> n -= integer</div>
184.86 -<div class="not_covered"> break </div>
184.87 -<div class="covered"> if n > 0:</div>
184.88 -<div class="covered"> result += toRomanTable[n]</div>
184.89 -<div class="covered"> return result</div>
184.90 -<div class="unknown"></div>
184.91 -<div class="covered">def fillLookupTables():</div>
184.92 -<div class="covered"> """compute all the possible roman numerals"""</div>
184.93 -<div class="inferred"> #Save the values in two global tables to convert to and from integers.</div>
184.94 -<div class="covered"> for integer in range(1, MAX_ROMAN_NUMERAL + 1):</div>
184.95 -<div class="covered"> romanNumber = toRomanDynamic(integer)</div>
184.96 -<div class="covered"> toRomanTable.append(romanNumber)</div>
184.97 -<div class="covered"> fromRomanTable[romanNumber] = integer</div>
184.98 -<div class="inferred"> </div>
184.99 -<div class="covered">fillLookupTables()</div>
184.100 -
184.101 -</body></html>
185.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj2/src/romantest9.py Sun Jan 04 13:11:53 2015 -0600
185.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
185.3 @@ -1,153 +0,0 @@
185.4 -"""Unit test for roman9.py
185.5 -
185.6 -This program is part of "Dive Into Python", a free Python book for
185.7 -experienced programmers. Visit http://diveintopython.org/ for the
185.8 -latest version.
185.9 -"""
185.10 -
185.11 -__author__ = "Mark Pilgrim (mark@diveintopython.org)"
185.12 -__version__ = "$Revision: 1.3 $"
185.13 -__date__ = "$Date: 2004/05/05 21:57:20 $"
185.14 -__copyright__ = "Copyright (c) 2001 Mark Pilgrim"
185.15 -__license__ = "Python"
185.16 -
185.17 -import roman9
185.18 -import unittest
185.19 -
185.20 -class KnownValues(unittest.TestCase):
185.21 - knownValues = ((1, 'I'),
185.22 - (2, 'II'),
185.23 - (3, 'III'),
185.24 - (4, 'IV'),
185.25 - (5, 'V'),
185.26 - (6, 'VI'),
185.27 - (7, 'VII'),
185.28 - (8, 'VIII'),
185.29 - (9, 'IX'),
185.30 - (10, 'X'),
185.31 - (50, 'L'),
185.32 - (100, 'C'),
185.33 - (500, 'D'),
185.34 - (1000, 'M'),
185.35 - (31, 'XXXI'),
185.36 - (148, 'CXLVIII'),
185.37 - (294, 'CCXCIV'),
185.38 - (312, 'CCCXII'),
185.39 - (421, 'CDXXI'),
185.40 - (528, 'DXXVIII'),
185.41 - (621, 'DCXXI'),
185.42 - (782, 'DCCLXXXII'),
185.43 - (870, 'DCCCLXX'),
185.44 - (941, 'CMXLI'),
185.45 - (1043, 'MXLIII'),
185.46 - (1110, 'MCX'),
185.47 - (1226, 'MCCXXVI'),
185.48 - (1301, 'MCCCI'),
185.49 - (1485, 'MCDLXXXV'),
185.50 - (1509, 'MDIX'),
185.51 - (1607, 'MDCVII'),
185.52 - (1754, 'MDCCLIV'),
185.53 - (1832, 'MDCCCXXXII'),
185.54 - (1993, 'MCMXCIII'),
185.55 - (2074, 'MMLXXIV'),
185.56 - (2152, 'MMCLII'),
185.57 - (2212, 'MMCCXII'),
185.58 - (2343, 'MMCCCXLIII'),
185.59 - (2499, 'MMCDXCIX'),
185.60 - (2574, 'MMDLXXIV'),
185.61 - (2646, 'MMDCXLVI'),
185.62 - (2723, 'MMDCCXXIII'),
185.63 - (2892, 'MMDCCCXCII'),
185.64 - (2975, 'MMCMLXXV'),
185.65 - (3051, 'MMMLI'),
185.66 - (3185, 'MMMCLXXXV'),
185.67 - (3250, 'MMMCCL'),
185.68 - (3313, 'MMMCCCXIII'),
185.69 - (3408, 'MMMCDVIII'),
185.70 - (3501, 'MMMDI'),
185.71 - (3610, 'MMMDCX'),
185.72 - (3743, 'MMMDCCXLIII'),
185.73 - (3844, 'MMMDCCCXLIV'),
185.74 - (3888, 'MMMDCCCLXXXVIII'),
185.75 - (3940, 'MMMCMXL'),
185.76 - (3999, 'MMMCMXCIX'),
185.77 - (4000, 'MMMM'),
185.78 - (4500, 'MMMMD'),
185.79 - (4888, 'MMMMDCCCLXXXVIII'),
185.80 - (4999, 'MMMMCMXCIX'))
185.81 -
185.82 - def testToRomanKnownValues(self):
185.83 - """toRoman should give known result with known input"""
185.84 - for integer, numeral in self.knownValues:
185.85 - result = roman9.toRoman(integer)
185.86 - self.assertEqual(numeral, result)
185.87 -
185.88 - def testFromRomanKnownValues(self):
185.89 - """fromRoman should give known result with known input"""
185.90 - for integer, numeral in self.knownValues:
185.91 - result = roman9.fromRoman(numeral)
185.92 - self.assertEqual(integer, result)
185.93 -
185.94 -class ToRomanBadInput(unittest.TestCase):
185.95 - def testTooLarge(self):
185.96 - """toRoman should fail with large input"""
185.97 - self.assertRaises(roman9.OutOfRangeError, roman9.toRoman, 5000)
185.98 -
185.99 - def testZero(self):
185.100 - """toRoman should fail with 0 input"""
185.101 - self.assertRaises(roman9.OutOfRangeError, roman9.toRoman, 0)
185.102 -
185.103 - def testNegative(self):
185.104 - """toRoman should fail with negative input"""
185.105 - self.assertRaises(roman9.OutOfRangeError, roman9.toRoman, -1)
185.106 -
185.107 - def testNonInteger(self):
185.108 - """toRoman should fail with non-integer input"""
185.109 - self.assertRaises(roman9.NotIntegerError, roman9.toRoman, 0.5)
185.110 -
185.111 -class FromRomanBadInput(unittest.TestCase):
185.112 - def testTooManyRepeatedNumerals(self):
185.113 - """fromRoman should fail with too many repeated numerals"""
185.114 - for s in ('MMMMM', 'DD', 'CCCC', 'LL', 'XXXX', 'VV', 'IIII'):
185.115 - self.assertRaises(roman9.InvalidRomanNumeralError, roman9.fromRoman, s)
185.116 -
185.117 - def testRepeatedPairs(self):
185.118 - """fromRoman should fail with repeated pairs of numerals"""
185.119 - for s in ('CMCM', 'CDCD', 'XCXC', 'XLXL', 'IXIX', 'IVIV'):
185.120 - self.assertRaises(roman9.InvalidRomanNumeralError, roman9.fromRoman, s)
185.121 -
185.122 - def testMalformedAntecedent(self):
185.123 - """fromRoman should fail with malformed antecedents"""
185.124 - for s in ('IIMXCC', 'VX', 'DCM', 'CMM', 'IXIV',
185.125 - 'MCMC', 'XCX', 'IVI', 'LM', 'LD', 'LC'):
185.126 - self.assertRaises(roman9.InvalidRomanNumeralError, roman9.fromRoman, s)
185.127 -
185.128 - def testBlank(self):
185.129 - """fromRoman should fail with blank string"""
185.130 - self.assertRaises(roman9.InvalidRomanNumeralError, roman9.fromRoman, "")
185.131 -
185.132 -class SanityCheck(unittest.TestCase):
185.133 - def testSanity(self):
185.134 - """fromRoman(toRoman(n))==n for all n"""
185.135 - for integer in range(1, 5000):
185.136 - numeral = roman9.toRoman(integer)
185.137 - result = roman9.fromRoman(numeral)
185.138 - self.assertEqual(integer, result)
185.139 -
185.140 -class CaseCheck(unittest.TestCase):
185.141 - def testToRomanCase(self):
185.142 - """toRoman should always return uppercase"""
185.143 - for integer in range(1, 5000):
185.144 - numeral = roman9.toRoman(integer)
185.145 - self.assertEqual(numeral, numeral.upper())
185.146 -
185.147 - def testFromRomanCase(self):
185.148 - """fromRoman should only accept uppercase input"""
185.149 - for integer in range(1, 5000):
185.150 - numeral = roman9.toRoman(integer)
185.151 - roman9.fromRoman(numeral.upper())
185.152 - self.assertRaises(roman9.InvalidRomanNumeralError,
185.153 - roman9.fromRoman, numeral.lower())
185.154 -
185.155 -if __name__ == "__main__":
185.156 - unittest.main()
186.1 --- a/python.editor/test/unit/data/testfiles/compl.py Sun Jan 04 13:11:53 2015 -0600
186.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
186.3 @@ -1,19 +0,0 @@
186.4 -class SuperSuper:
186.5 - def mysupersupermethod(self):
186.6 - print "World"
186.7 -
186.8 -class Super(SuperSuper):
186.9 - def mysupermethod(self):
186.10 - print "Hello"
186.11 -
186.12 -
186.13 -
186.14 -class MyClass(Super):
186.15 - def mymethod(self):
186.16 - print "Hello World"
186.17 - self.mysupersupermethod()
186.18 - print dir()
186.19 -
186.20 -x = MyClass()
186.21 -x.mymethod()
186.22 -
187.1 --- a/python.editor/test/unit/data/testfiles/compl.py.scopes Sun Jan 04 13:11:53 2015 -0600
187.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
187.3 @@ -1,34 +0,0 @@
187.4 -=============================================
187.5 -<file-top>: Module : OffsetRange[0,309>
187.6 -MyClass [bound][class][def][read][called][node=ClassDef]
187.7 -Super [bound][class][def][read][node=ClassDef]
187.8 -SuperSuper [bound][class][def][read][node=ClassDef]
187.9 -x [bound][data][read][node=Name]
187.10 -
187.11 - =============================================
187.12 - class SuperSuper: ClassDef : OffsetRange[0,75>
187.13 - mysupersupermethod [bound][function][def][node=FunctionDef]
187.14 -
187.15 - =============================================
187.16 - mysupersupermethod: FunctionDef : OffsetRange[22,75>
187.17 - self [bound][param][data][unused][node=Name]
187.18 -
187.19 - =============================================
187.20 - class Super: ClassDef : OffsetRange[75,154>
187.21 - mysupermethod [bound][function][def][node=FunctionDef]
187.22 -
187.23 - =============================================
187.24 - mysupermethod: FunctionDef : OffsetRange[104,154>
187.25 - self [bound][param][data][unused][node=Name]
187.26 -
187.27 - =============================================
187.28 - class MyClass: ClassDef : OffsetRange[154,283>
187.29 - mymethod [bound][function][def][node=FunctionDef]
187.30 -
187.31 - =============================================
187.32 - mymethod: FunctionDef : OffsetRange[180,283>
187.33 - dir [free][read][called][node=Name]
187.34 - self [bound][param][data][read][node=Name]
187.35 - ------ Attributes ---------------------------------------
187.36 - mysupersupermethod : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
187.37 -
188.1 --- a/python.editor/test/unit/data/testfiles/compl.py.testObjMethodCompletion1.completion Sun Jan 04 13:11:53 2015 -0600
188.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
188.3 @@ -1,1225 +0,0 @@
188.4 -Code completion result for source line:
188.5 -|self.mysupersupermethod()
188.6 -(QueryType=COMPLETION, NameKind=PREFIX)
188.7 -CLASS MyClass
188.8 -CLASS Super
188.9 -CLASS SuperSuper
188.10 -VARIABLE self
188.11 -VARIABLE x
188.12 -------------------------------------
188.13 -CLASS A
188.14 -CLASS ABCMeta
188.15 -CLASS AEServer
188.16 -CLASS AEText
188.17 -CLASS ASTVisitor
188.18 -CLASS AbstractBasicAuthHandler
188.19 -CLASS AbstractClassCode
188.20 -CLASS AbstractCompileMode
188.21 -CLASS AbstractDigestAuthHandler
188.22 -CLASS AbstractFormatter
188.23 -CLASS AbstractFunctionCode
188.24 -CLASS AbstractHTTPHandler
188.25 -CLASS AbstractWriter
188.26 -CLASS Add
188.27 -CLASS AddressList
188.28 -CLASS And
188.29 -CLASS Application
188.30 -CLASS ArgumentError
188.31 -CLASS ArithmeticError
188.32 -CLASS ArithmeticError
188.33 -CLASS Array
188.34 -CLASS ArrayInstance
188.35 -CLASS AssAttr
188.36 -CLASS AssList
188.37 -CLASS AssName
188.38 -CLASS AssTuple
188.39 -CLASS Assert
188.40 -CLASS AssertionError
188.41 -CLASS AssertionError
188.42 -CLASS Assign
188.43 -CLASS AsyncResult
188.44 -CLASS Attr
188.45 -CLASS AttributeError
188.46 -CLASS AttributeError
188.47 -CLASS AttributeList
188.48 -CLASS AttributeMap
188.49 -CLASS Attributes
188.50 -CLASS AttributesImpl
188.51 -CLASS AttributesNS
188.52 -CLASS AttributesNSImpl
188.53 -CLASS AugAssign
188.54 -CLASS AugGetattr
188.55 -CLASS AugName
188.56 -CLASS AugSlice
188.57 -CLASS AugSubscript
188.58 -CLASS AuthenticationError
188.59 -CLASS AutoGILError
188.60 -CLASS B
188.61 -CLASS BCPPCompiler
188.62 -CLASS BCPTestCase
188.63 -CLASS BZ2Compressor
188.64 -CLASS BZ2Decompressor
188.65 -CLASS BZ2File
188.66 -CLASS Babyl
188.67 -CLASS BabylMailbox
188.68 -CLASS BabylMessage
188.69 -CLASS Backquote
188.70 -CLASS BadBoundaryPointsErr
188.71 -CLASS BadFutureParser
188.72 -CLASS BadOptionError
188.73 -CLASS BadStatusLine
188.74 -CLASS BadZipfile
188.75 -CLASS Balloon
188.76 -CLASS Bar
188.77 -CLASS BaseCGIHandler
188.78 -CLASS BaseCookie
188.79 -CLASS BaseException
188.80 -CLASS BaseException
188.81 -CLASS BaseHTTPRequestHandler
188.82 -CLASS BaseHandler
188.83 -CLASS BaseIncrementalParser
188.84 -CLASS BaseManager
188.85 -CLASS BaseProxy
188.86 -CLASS BaseRequestHandler
188.87 -CLASS BaseRotatingHandler
188.88 -CLASS BaseSet
188.89 -CLASS BasicModuleImporter
188.90 -CLASS BasicModuleLoader
188.91 -CLASS BastionClass
188.92 -CLASS Baz
188.93 -CLASS Bdb
188.94 -CLASS BdbQuit
188.95 -CLASS BigEndianStructure
188.96 -CLASS Binary
188.97 -CLASS Bitand
188.98 -CLASS Bitor
188.99 -CLASS Bitxor
188.100 -CLASS Block
188.101 -CLASS BlockFinder
188.102 -CLASS BlockingIOError
188.103 -CLASS Boolean
188.104 -CLASS BoundaryError
188.105 -CLASS BoundedSemaphore
188.106 -CLASS Break
188.107 -CLASS Breakpoint
188.108 -CLASS BsdDbShelf
188.109 -CLASS BufferTooShort
188.110 -CLASS BufferedIOBase
188.111 -CLASS BufferedRWPair
188.112 -CLASS BufferedRandom
188.113 -CLASS BufferedReader
188.114 -CLASS BufferedWriter
188.115 -CLASS BufferingFormatter
188.116 -CLASS BufferingHandler
188.117 -CLASS BuildPyTestCase
188.118 -CLASS BuildScriptsTestCase
188.119 -CLASS BuiltinImporter
188.120 -CLASS Bulkcopy
188.121 -CLASS ButtonBox
188.122 -CLASS BytesIO
188.123 -CLASS C
188.124 -CLASS CAB
188.125 -CLASS CCompiler
188.126 -CLASS CCompilerError
188.127 -CLASS CDATASection
188.128 -CLASS CDLL
188.129 -CLASS CGIHTTPRequestHandler
188.130 -CLASS CGIHandler
188.131 -CLASS CGIXMLRPCRequestHandler
188.132 -CLASS CacheFTPHandler
188.133 -CLASS CallFunc
188.134 -CLASS CalledProcessError
188.135 -CLASS CannotSendHeader
188.136 -CLASS CannotSendRequest
188.137 -CLASS Canonizer
188.138 -CLASS CharacterData
188.139 -CLASS Charset
188.140 -CLASS CharsetError
188.141 -CLASS CheckList
188.142 -CLASS Childless
188.143 -CLASS Chunk
188.144 -CLASS Clamped
188.145 -CLASS Class
188.146 -CLASS ClassCodeGenerator
188.147 -CLASS ClassScope
188.148 -CLASS Cmd
188.149 -CLASS CodeGenerator
188.150 -CLASS Codec
188.151 -CLASS CodecRegistryError
188.152 -CLASS ComboBox
188.153 -CLASS Command
188.154 -CLASS CommandCompiler
188.155 -CLASS Comment
188.156 -CLASS Compare
188.157 -CLASS Comparison
188.158 -CLASS Compile
188.159 -CLASS CompileError
188.160 -CLASS Completer
188.161 -CLASS Complex
188.162 -CLASS ComponentItem
188.163 -CLASS Condition
188.164 -CLASS ConfigParser
188.165 -CLASS Connection
188.166 -CLASS Const
188.167 -CLASS ContentGenerator
188.168 -CLASS ContentHandler
188.169 -CLASS Context
188.170 -CLASS Continue
188.171 -CLASS Control
188.172 -CLASS ControlsWindow
188.173 -CLASS ConversionError
188.174 -CLASS Cookie
188.175 -CLASS CookieError
188.176 -CLASS CookieJar
188.177 -CLASS CookiePolicy
188.178 -CLASS CoverageResults
188.179 -CLASS Cursor
188.180 -CLASS CygwinCCompiler
188.181 -CLASS D
188.182 -CLASS DOMBuilder
188.183 -CLASS DOMEntityResolver
188.184 -CLASS DOMError
188.185 -CLASS DOMEventStream
188.186 -CLASS DOMException
188.187 -CLASS DOMImplementation
188.188 -CLASS DOMInputSource
188.189 -CLASS DOMStringSizeErr
188.190 -CLASS DTDHandler
188.191 -CLASS Data
188.192 -CLASS Database
188.193 -CLASS DatagramHandler
188.194 -CLASS DatagramRequestHandler
188.195 -CLASS DateTime
188.196 -CLASS DbfilenameShelf
188.197 -CLASS DebugRunner
188.198 -CLASS DebuggingServer
188.199 -CLASS Decimal
188.200 -CLASS DecimalException
188.201 -CLASS DeclHandler
188.202 -CLASS DecodedGenerator
188.203 -CLASS Decorators
188.204 -CLASS DefaultCookiePolicy
188.205 -CLASS DefaultHandler
188.206 -CLASS Delegator
188.207 -CLASS DeprecationWarning
188.208 -CLASS DeprecationWarning
188.209 -CLASS Dialect
188.210 -CLASS Dialog
188.211 -CLASS DialogWindow
188.212 -CLASS Dict
188.213 -CLASS DictMixin
188.214 -CLASS DictReader
188.215 -CLASS DictWriter
188.216 -CLASS Differ
188.217 -CLASS DirList
188.218 -CLASS DirSelectBox
188.219 -CLASS DirSelectDialog
188.220 -CLASS DirTree
188.221 -CLASS Directory
188.222 -CLASS Discard
188.223 -CLASS Distribution
188.224 -CLASS DistributionMetadata
188.225 -CLASS DistributionTestCase
188.226 -CLASS DistutilsArgError
188.227 -CLASS DistutilsClassError
188.228 -CLASS DistutilsError
188.229 -CLASS DistutilsExecError
188.230 -CLASS DistutilsFileError
188.231 -CLASS DistutilsGetoptError
188.232 -CLASS DistutilsInternalError
188.233 -CLASS DistutilsModuleError
188.234 -CLASS DistutilsOptionError
188.235 -CLASS DistutilsPlatformError
188.236 -CLASS DistutilsSetupError
188.237 -CLASS DistutilsTemplateError
188.238 -CLASS Div
188.239 -CLASS DivisionByZero
188.240 -CLASS Doc
188.241 -CLASS DocCGIXMLRPCRequestHandler
188.242 -CLASS DocTest
188.243 -CLASS DocTestFailure
188.244 -CLASS DocTestFinder
188.245 -CLASS DocTestParser
188.246 -CLASS DocTestRunner
188.247 -CLASS DocXMLRPCRequestHandler
188.248 -CLASS DocXMLRPCServer
188.249 -CLASS Document
188.250 -CLASS DocumentFragment
188.251 -CLASS DocumentHandler
188.252 -CLASS DocumentType
188.253 -CLASS DomstringSizeErr
188.254 -CLASS DumbWriter
188.255 -CLASS DummyCommand
188.256 -CLASS DuplicateSectionError
188.257 -CLASS DynLoadSuffixImporter
188.258 -CLASS EMXCCompiler
188.259 -CLASS EOFError
188.260 -CLASS EOFError
188.261 -CLASS ESISDocHandler
188.262 -CLASS Element
188.263 -CLASS ElementInfo
188.264 -CLASS ElementTree
188.265 -CLASS Ellipsis
188.266 -CLASS Empty
188.267 -CLASS EmptyNode
188.268 -CLASS EndOfBlock
188.269 -CLASS Entity
188.270 -CLASS EntityResolver
188.271 -CLASS Enum
188.272 -CLASS EnvironmentError
188.273 -CLASS EnvironmentError
188.274 -CLASS Error
188.275 -CLASS ErrorDuringImport
188.276 -CLASS ErrorHandler
188.277 -CLASS ErrorPrinter
188.278 -CLASS ErrorRaiser
188.279 -CLASS Event
188.280 -CLASS EventBroadcaster
188.281 -CLASS EventException
188.282 -CLASS ExFileSelectBox
188.283 -CLASS Example
188.284 -CLASS ExampleASTVisitor
188.285 -CLASS Exception
188.286 -CLASS Exception
188.287 -CLASS Exec
188.288 -CLASS ExitNow
188.289 -CLASS ExpatError
188.290 -CLASS ExpatParser
188.291 -CLASS Expression
188.292 -CLASS ExpressionCodeGenerator
188.293 -CLASS Extension
188.294 -CLASS F
188.295 -CLASS FTP
188.296 -CLASS FTPHandler
188.297 -CLASS Factory
188.298 -CLASS FancyGetopt
188.299 -CLASS FancyModuleLoader
188.300 -CLASS FancyURLopener
188.301 -CLASS Fault
188.302 -CLASS Feature
188.303 -CLASS FeedParser
188.304 -CLASS FieldStorage
188.305 -CLASS FileCookieJar
188.306 -CLASS FileEntry
188.307 -CLASS FileHandler
188.308 -CLASS FileIO
188.309 -CLASS FileInput
188.310 -CLASS FileList
188.311 -CLASS FileSelectBox
188.312 -CLASS FileWrapper
188.313 -CLASS Filter
188.314 -CLASS Filterer
188.315 -CLASS FingerHandler
188.316 -CLASS FirstHeaderLineIsContinuationD
188.317 -CLASS FloatingPointError
188.318 -CLASS FloatingPointError
188.319 -CLASS FloorDiv
188.320 -CLASS FlowGraph
188.321 -CLASS Folder
188.322 -CLASS Foo
188.323 -CLASS For
188.324 -CLASS ForkingMixIn
188.325 -CLASS ForkingTCPServer
188.326 -CLASS ForkingUDPServer
188.327 -CLASS Form
188.328 -CLASS FormContent
188.329 -CLASS FormContentDict
188.330 -CLASS Formatter
188.331 -CLASS Fraction
188.332 -CLASS From
188.333 -CLASS FtException
188.334 -CLASS Full
188.335 -CLASS FuncPtr
188.336 -CLASS Function
188.337 -CLASS FunctionCodeGenerator
188.338 -CLASS FunctionScope
188.339 -CLASS FunctionTestCase
188.340 -CLASS FutureParser
188.341 -CLASS FutureWarning
188.342 -CLASS FutureWarning
188.343 -CLASS GNUTranslations
188.344 -CLASS GenExpr
188.345 -CLASS GenExprFor
188.346 -CLASS GenExprIf
188.347 -CLASS GenExprInner
188.348 -CLASS GenExprScope
188.349 -CLASS Generator
188.350 -CLASS GeneratorExit
188.351 -CLASS GeneratorExit
188.352 -CLASS Getattr
188.353 -CLASS GetattrMagic
188.354 -CLASS GetoptError
188.355 -CLASS Global
188.356 -CLASS GopherError
188.357 -CLASS GopherHandler
188.358 -CLASS GridBag
188.359 -CLASS GzipFile
188.360 -CLASS HList
188.361 -CLASS HMAC
188.362 -CLASS HRESULT
188.363 -CLASS HTMLDoc
188.364 -CLASS HTMLParseError
188.365 -CLASS HTMLParser
188.366 -CLASS HTMLRepr
188.367 -CLASS HTTP
188.368 -CLASS HTTPBasicAuthHandler
188.369 -CLASS HTTPConnection
188.370 -CLASS HTTPCookieProcessor
188.371 -CLASS HTTPDefaultErrorHandler
188.372 -CLASS HTTPDigestAuthHandler
188.373 -CLASS HTTPError
188.374 -CLASS HTTPErrorProcessor
188.375 -CLASS HTTPException
188.376 -CLASS HTTPHandler
188.377 -CLASS HTTPPasswordMgr
188.378 -CLASS HTTPPasswordMgrWithDefaultReal
188.379 -CLASS HTTPRedirectHandler
188.380 -CLASS HTTPResponse
188.381 -CLASS HTTPSConnection
188.382 -CLASS HTTPSHandler
188.383 -CLASS HTTPServer
188.384 -CLASS Handler
188.385 -CLASS HandlerBase
188.386 -CLASS Header
188.387 -CLASS HeaderParseError
188.388 -CLASS HeaderParser
188.389 -CLASS Headers
188.390 -CLASS HelpFormatter
188.391 -CLASS Helper
188.392 -CLASS HierarchyRequestErr
188.393 -CLASS Hook
188.394 -CLASS Hooks
188.395 -CLASS HtmlDiff
188.396 -CLASS IC
188.397 -CLASS IMAP4
188.398 -CLASS IMAP4_SSL
188.399 -CLASS IMAP4_stream
188.400 -CLASS IOBase
188.401 -CLASS IOError
188.402 -CLASS IOError
188.403 -CLASS Identified
188.404 -CLASS If
188.405 -CLASS IfExp
188.406 -CLASS Ignore
188.407 -CLASS IllegalMonthError
188.408 -CLASS IllegalWeekdayError
188.409 -CLASS ImmutableSet
188.410 -CLASS ImpImporter
188.411 -CLASS ImpLoader
188.412 -CLASS Import
188.413 -CLASS ImportError
188.414 -CLASS ImportError
188.415 -CLASS ImportManager
188.416 -CLASS ImportWarning
188.417 -CLASS ImportWarning
188.418 -CLASS Importer
188.419 -CLASS ImproperConnectionState
188.420 -CLASS Incomplete
188.421 -CLASS IncompleteRead
188.422 -CLASS IncrementalDecoder
188.423 -CLASS IncrementalEncoder
188.424 -CLASS IncrementalNewlineDecoder
188.425 -CLASS IncrementalParser
188.426 -CLASS IndentedHelpFormatter
188.427 -CLASS IndexError
188.428 -CLASS IndexError
188.429 -CLASS IndexSizeErr
188.430 -CLASS Inexact
188.431 -CLASS IniParser
188.432 -CLASS InputOnly
188.433 -CLASS InputSource
188.434 -CLASS InsertionLoc
188.435 -CLASS InstallScriptsTestCase
188.436 -CLASS InstallTestCase
188.437 -CLASS Integral
188.438 -CLASS Interactive
188.439 -CLASS InteractiveCodeGenerator
188.440 -CLASS InteractiveConsole
188.441 -CLASS InteractiveInterpreter
188.442 -CLASS InterpFormContentDict
188.443 -CLASS InterpolationDepthError
188.444 -CLASS InterpolationError
188.445 -CLASS InterpolationSyntaxError
188.446 -CLASS IntlText
188.447 -CLASS IntlWritingCode
188.448 -CLASS InuseAttributeErr
188.449 -CLASS InvalidAccessErr
188.450 -CLASS InvalidCharacterErr
188.451 -CLASS InvalidModificationErr
188.452 -CLASS InvalidNodeTypeErr
188.453 -CLASS InvalidOperation
188.454 -CLASS InvalidStateErr
188.455 -CLASS InvalidURL
188.456 -CLASS Invert
188.457 -CLASS IsqlCmd
188.458 -CLASS IsqlExit
188.459 -CLASS IterableUserDict
188.460 -CLASS JSONDecoder
188.461 -CLASS JSONEncoder
188.462 -CLASS JavaSAXParser
188.463 -CLASS JoinableQueue
188.464 -CLASS JyDTDHandlerWrapper
188.465 -CLASS JyEntityResolverWrapper
188.466 -CLASS JyErrorHandlerWrapper
188.467 -CLASS JyInputSourceWrapper
188.468 -CLASS JythonCompiler
188.469 -CLASS JythonSignalHandler
188.470 -CLASS KeyError
188.471 -CLASS KeyError
188.472 -CLASS KeyboardInterrupt
188.473 -CLASS KeyboardInterrupt
188.474 -CLASS Keyword
188.475 -CLASS LOBTestCase
188.476 -CLASS LWPCookieJar
188.477 -CLASS LabelEntry
188.478 -CLASS LabelFrame
188.479 -CLASS Lambda
188.480 -CLASS LambdaScope
188.481 -CLASS LargeZipFile
188.482 -CLASS LeftShift
188.483 -CLASS LexicalHandler
188.484 -CLASS LexicalXMLGenerator
188.485 -CLASS LibError
188.486 -CLASS LibraryLoader
188.487 -CLASS LineAddrTable
188.488 -CLASS LinkError
188.489 -CLASS List
188.490 -CLASS ListComp
188.491 -CLASS ListCompFor
188.492 -CLASS ListCompIf
188.493 -CLASS ListNoteBook
188.494 -CLASS Listener
188.495 -CLASS LittleEndianStructure
188.496 -CLASS LoadError
188.497 -CLASS LocalNameFinder
188.498 -CLASS Location
188.499 -CLASS Locator
188.500 -CLASS Lock
188.501 -CLASS Log
188.502 -CLASS LogRecord
188.503 -CLASS Logger
188.504 -CLASS LoggingSilencer
188.505 -CLASS Logical
188.506 -CLASS LookupError
188.507 -CLASS LookupError
188.508 -CLASS LooseVersion
188.509 -CLASS MH
188.510 -CLASS MHMailbox
188.511 -CLASS MHMessage
188.512 -CLASS MIMEApplication
188.513 -CLASS MIMEAudio
188.514 -CLASS MIMEBase
188.515 -CLASS MIMEImage
188.516 -CLASS MIMEMessage
188.517 -CLASS MIMEMultipart
188.518 -CLASS MIMENonMultipart
188.519 -CLASS MIMEText
188.520 -CLASS MMDF
188.521 -CLASS MMDFMessage
188.522 -CLASS MSVCCompiler
188.523 -CLASS MWerksCompiler
188.524 -CLASS MacroExpander
188.525 -CLASS Mailbox
188.526 -CLASS Maildir
188.527 -CLASS MaildirMessage
188.528 -CLASS MailmanProxy
188.529 -CLASS MalformedHeaderDefect
188.530 -CLASS Manager
188.531 -CLASS Marshaller
188.532 -CLASS MemoryError
188.533 -CLASS MemoryError
188.534 -CLASS MemoryHandler
188.535 -CLASS Message
188.536 -CLASS MessageDefect
188.537 -CLASS MessageError
188.538 -CLASS MessageParseError
188.539 -CLASS MetadataTestCase
188.540 -CLASS Meter
188.541 -CLASS MimeWriter
188.542 -CLASS Mingw32CCompiler
188.543 -CLASS MiniApplication
188.544 -CLASS MiniFieldStorage
188.545 -CLASS MisplacedEnvelopeHeaderDefect
188.546 -CLASS MissingSectionHeaderError
188.547 -CLASS MmdfMailbox
188.548 -CLASS Mod
188.549 -CLASS Model
188.550 -CLASS Module
188.551 -CLASS ModuleCodeGenerator
188.552 -CLASS ModuleFinder
188.553 -CLASS ModuleImporter
188.554 -CLASS ModuleLoader
188.555 -CLASS ModuleScanner
188.556 -CLASS ModuleScope
188.557 -CLASS MozillaCookieJar
188.558 -CLASS Mul
188.559 -CLASS MultiCall
188.560 -CLASS MultiCallIterator
188.561 -CLASS MultiFile
188.562 -CLASS MultipartConversionError
188.563 -CLASS MultipartInvariantViolationDef
188.564 -CLASS MutableString
188.565 -CLASS MyClass
188.566 -CLASS MyTest
188.567 -CLASS NNTP
188.568 -CLASS NNTPDataError
188.569 -CLASS NNTPPermanentError
188.570 -CLASS NNTPProtocolError
188.571 -CLASS NNTPReplyError
188.572 -CLASS NNTPTemporaryError
188.573 -CLASS NProperty
188.574 -CLASS NTEventLogHandler
188.575 -CLASS NULL
188.576 -CLASS Name
188.577 -CLASS NameError
188.578 -CLASS NameError
188.579 -CLASS NamedNodeMap
188.580 -CLASS NamespaceErr
188.581 -CLASS NannyNag
188.582 -CLASS NestedScopeMixin
188.583 -CLASS Netrc
188.584 -CLASS NetrcParseError
188.585 -CLASS NewStyle
188.586 -CLASS NoBoundaryInMultipartDefect
188.587 -CLASS NoDataAllowedErr
188.588 -CLASS NoModificationAllowedErr
188.589 -CLASS NoOpMetaClass
188.590 -CLASS NoOptionError
188.591 -CLASS NoSectionError
188.592 -CLASS Node
188.593 -CLASS NodeFilter
188.594 -CLASS NodeTransformer
188.595 -CLASS NodeVisitor
188.596 -CLASS Not
188.597 -CLASS NotANumber
188.598 -CLASS NotConnected
188.599 -CLASS NotFoundErr
188.600 -CLASS NotImplementedError
188.601 -CLASS NotImplementedError
188.602 -CLASS NotSupportedErr
188.603 -CLASS Notation
188.604 -CLASS NoteBook
188.605 -CLASS NullFormatter
188.606 -CLASS NullImporter
188.607 -CLASS NullTranslations
188.608 -CLASS NullWriter
188.609 -CLASS Number
188.610 -CLASS OSError
188.611 -CLASS OSError
188.612 -CLASS OSSAudioError
188.613 -CLASS ObjectSpecifier
188.614 -CLASS OleDLL
188.615 -CLASS OpFinder
188.616 -CLASS OpenerDirector
188.617 -CLASS OptParseError
188.618 -CLASS Option
188.619 -CLASS OptionConflictError
188.620 -CLASS OptionContainer
188.621 -CLASS OptionDummy
188.622 -CLASS OptionError
188.623 -CLASS OptionGroup
188.624 -CLASS OptionMenu
188.625 -CLASS OptionParser
188.626 -CLASS OptionValueError
188.627 -CLASS Or
188.628 -CLASS OracleSPTest
188.629 -CLASS Ordinal
188.630 -CLASS OutputChecker
188.631 -CLASS Overflow
188.632 -CLASS OverflowError
188.633 -CLASS OverflowError
188.634 -CLASS POP3
188.635 -CLASS POP3_SSL
188.636 -CLASS Packer
188.637 -CLASS PanedWindow
188.638 -CLASS Panel
188.639 -CLASS Parser
188.640 -CLASS ParserBase
188.641 -CLASS ParserError
188.642 -CLASS ParsingError
188.643 -CLASS Pass
188.644 -CLASS Pattern
188.645 -CLASS Pdb
188.646 -CLASS PendingDeprecationWarning
188.647 -CLASS PendingDeprecationWarning
188.648 -CLASS PickleError
188.649 -CLASS Pickler
188.650 -CLASS PicklingError
188.651 -CLASS PlaceHolder
188.652 -CLASS Popen
188.653 -CLASS Popen3
188.654 -CLASS Popen4
188.655 -CLASS PopupMenu
188.656 -CLASS PortableUnixMailbox
188.657 -CLASS Power
188.658 -CLASS PreprocessError
188.659 -CLASS PrettyPrinter
188.660 -CLASS Print
188.661 -CLASS Printnl
188.662 -CLASS Process
188.663 -CLASS ProcessingInstruction
188.664 -CLASS Profile
188.665 -CLASS ProgressBar
188.666 -CLASS Prompt
188.667 -CLASS ProtocolError
188.668 -CLASS ProxyBasicAuthHandler
188.669 -CLASS ProxyDigestAuthHandler
188.670 -CLASS ProxyHandler
188.671 -CLASS PullDOM
188.672 -CLASS PureProxy
188.673 -CLASS PyCompileError
188.674 -CLASS PyDLL
188.675 -CLASS PyDialog
188.676 -CLASS PyFlowGraph
188.677 -CLASS PyHKEY
188.678 -CLASS PyZipFile
188.679 -CLASS QDPoint
188.680 -CLASS QDRectangle
188.681 -CLASS QName
188.682 -CLASS Queue
188.683 -CLASS RExec
188.684 -CLASS RGBColor
188.685 -CLASS RLock
188.686 -CLASS RadioButtonGroup
188.687 -CLASS Raise
188.688 -CLASS Random
188.689 -CLASS Range
188.690 -CLASS RangeException
188.691 -CLASS Rational
188.692 -CLASS RawIOBase
188.693 -CLASS RawTurtle
188.694 -CLASS ReadOnlySequentialNamedNodeMap
188.695 -CLASS Real
188.696 -CLASS Record
188.697 -CLASS ReferenceError
188.698 -CLASS ReferenceError
188.699 -CLASS Repr
188.700 -CLASS Request
188.701 -CLASS ResponseError
188.702 -CLASS ResponseNotReady
188.703 -CLASS ResultSet
188.704 -CLASS ResultSetRow
188.705 -CLASS Return
188.706 -CLASS RightShift
188.707 -CLASS RobotFileParser
188.708 -CLASS RootLogger
188.709 -CLASS RotatingFileHandler
188.710 -CLASS Rounded
188.711 -CLASS Row
188.712 -CLASS RuntimeError
188.713 -CLASS RuntimeError
188.714 -CLASS RuntimeWarning
188.715 -CLASS RuntimeWarning
188.716 -CLASS SAX2DOM
188.717 -CLASS SAXException
188.718 -CLASS SAXNotRecognizedException
188.719 -CLASS SAXNotSupportedException
188.720 -CLASS SAXParseException
188.721 -CLASS SAXReaderNotAvailable
188.722 -CLASS SGMLParseError
188.723 -CLASS SGMLParser
188.724 -CLASS SMTP
188.725 -CLASS SMTPAuthenticationError
188.726 -CLASS SMTPConnectError
188.727 -CLASS SMTPDataError
188.728 -CLASS SMTPException
188.729 -CLASS SMTPHandler
188.730 -CLASS SMTPHeloError
188.731 -CLASS SMTPRecipientsRefused
188.732 -CLASS SMTPResponseException
188.733 -CLASS SMTPSenderRefused
188.734 -CLASS SMTPServer
188.735 -CLASS SMTPServerDisconnected
188.736 -CLASS SQLServerSPTest
188.737 -CLASS SQLTestCase
188.738 -CLASS SSLError
188.739 -CLASS SSLSocket
188.740 -CLASS ST
188.741 -CLASS SafeConfigParser
188.742 -CLASS SafeTransport
188.743 -CLASS Scanner
188.744 -CLASS Schema
188.745 -CLASS Scope
188.746 -CLASS Screen
188.747 -CLASS ScrolledCavas
188.748 -CLASS ScrolledText
188.749 -CLASS ScrolledWindow
188.750 -CLASS Select
188.751 -CLASS Semaphore
188.752 -CLASS SequenceMatcher
188.753 -CLASS SerialCookie
188.754 -CLASS Server
188.755 -CLASS ServerHTMLDoc
188.756 -CLASS ServerProxy
188.757 -CLASS Set
188.758 -CLASS SgmlopParser
188.759 -CLASS Shape
188.760 -CLASS Shelf
188.761 -CLASS SimpleCookie
188.762 -CLASS SimpleHTTPRequestHandler
188.763 -CLASS SimpleHandler
188.764 -CLASS SimpleLocator
188.765 -CLASS SimpleXMLRPCDispatcher
188.766 -CLASS SimpleXMLRPCRequestHandler
188.767 -CLASS SimpleXMLRPCServer
188.768 -CLASS Slice
188.769 -CLASS Sliceobj
188.770 -CLASS SlowParser
188.771 -CLASS SmartCookie
188.772 -CLASS Sniffer
188.773 -CLASS SocketHandler
188.774 -CLASS SocketType
188.775 -CLASS Stack
188.776 -CLASS StackDepthTracker
188.777 -CLASS StandardError
188.778 -CLASS StandardError
188.779 -CLASS StartBoundaryNotFoundDefect
188.780 -CLASS Stats
188.781 -CLASS StdButtonBox
188.782 -CLASS Stmt
188.783 -CLASS StopIteration
188.784 -CLASS StopIteration
188.785 -CLASS StopTokenizing
188.786 -CLASS Strange
188.787 -CLASS StreamConverter
188.788 -CLASS StreamHandler
188.789 -CLASS StreamReader
188.790 -CLASS StreamRequestHandler
188.791 -CLASS StreamWriter
188.792 -CLASS StrictVersion
188.793 -CLASS StringIO
188.794 -CLASS Struct
188.795 -CLASS Structure
188.796 -CLASS StyledText
188.797 -CLASS Sub
188.798 -CLASS SubPattern
188.799 -CLASS Subnormal
188.800 -CLASS Subscript
188.801 -CLASS SummaryInformation
188.802 -CLASS Super
188.803 -CLASS SuperSuper
188.804 -CLASS SvFormContentDict
188.805 -CLASS Symbol
188.806 -CLASS SymbolTable
188.807 -CLASS SymbolVisitor
188.808 -CLASS SyncManager
188.809 -CLASS SyntaxErr
188.810 -CLASS SyntaxError
188.811 -CLASS SyntaxError
188.812 -CLASS SyntaxErrorChecker
188.813 -CLASS SyntaxWarning
188.814 -CLASS SyntaxWarning
188.815 -CLASS SysLogHandler
188.816 -CLASS SystemError
188.817 -CLASS SystemError
188.818 -CLASS SystemExit
188.819 -CLASS SystemExit
188.820 -CLASS SystemRandom
188.821 -CLASS TCPServer
188.822 -CLASS TList
188.823 -CLASS TalkTo
188.824 -CLASS TarError
188.825 -CLASS TarFile
188.826 -CLASS TarInfo
188.827 -CLASS Telnet
188.828 -CLASS TempdirManager
188.829 -CLASS Template
188.830 -CLASS Test
188.831 -CLASS TestCase
188.832 -CLASS TestClass
188.833 -CLASS TestCrispinTorture
188.834 -CLASS TestDistribution
188.835 -CLASS TestLoader
188.836 -CLASS TestResult
188.837 -CLASS TestSuite
188.838 -CLASS TestThread
188.839 -CLASS TestXMLParser
188.840 -CLASS Testcase
188.841 -CLASS Tester
188.842 -CLASS Text
188.843 -CLASS TextDoc
188.844 -CLASS TextFile
188.845 -CLASS TextIOBase
188.846 -CLASS TextIOWrapper
188.847 -CLASS TextRepr
188.848 -CLASS TextTestRunner
188.849 -CLASS TextWrapper
188.850 -CLASS Textbox
188.851 -CLASS Thread
188.852 -CLASS ThreadingMixIn
188.853 -CLASS ThreadingTCPServer
188.854 -CLASS ThreadingUDPServer
188.855 -CLASS ThreadingUnixDatagramServer
188.856 -CLASS ThreadingUnixStreamServer
188.857 -CLASS TimedRotatingFileHandler
188.858 -CLASS Timer
188.859 -CLASS TitledHelpFormatter
188.860 -CLASS Tix
188.861 -CLASS Tk
188.862 -CLASS TokenError
188.863 -CLASS Tokenizer
188.864 -CLASS TortureBase
188.865 -CLASS Trace
188.866 -CLASS Transformer
188.867 -CLASS Transport
188.868 -CLASS Tree
188.869 -CLASS TreeBuilder
188.870 -CLASS TryExcept
188.871 -CLASS TryFinally
188.872 -CLASS Tuple
188.873 -CLASS TupleArg
188.874 -CLASS Turtle
188.875 -CLASS TurtleScreen
188.876 -CLASS Type
188.877 -CLASS TypeError
188.878 -CLASS TypeError
188.879 -CLASS TypeInfo
188.880 -CLASS UDPServer
188.881 -CLASS URLError
188.882 -CLASS UUID
188.883 -CLASS UnaryAdd
188.884 -CLASS UnarySub
188.885 -CLASS UnboundLocalError
188.886 -CLASS UnboundLocalError
188.887 -CLASS Underflow
188.888 -CLASS UnexpectedException
188.889 -CLASS UnicodeDecodeError
188.890 -CLASS UnicodeDecodeError
188.891 -CLASS UnicodeEncodeError
188.892 -CLASS UnicodeEncodeError
188.893 -CLASS UnicodeError
188.894 -CLASS UnicodeError
188.895 -CLASS UnicodeTranslateError
188.896 -CLASS UnicodeTranslateError
188.897 -CLASS UnicodeWarning
188.898 -CLASS UnicodeWarning
188.899 -CLASS UnimplementedFileMode
188.900 -CLASS Union
188.901 -CLASS UnixCCompiler
188.902 -CLASS UnixDatagramServer
188.903 -CLASS UnixMailbox
188.904 -CLASS UnixStreamServer
188.905 -CLASS Unknown
188.906 -CLASS UnknownFileError
188.907 -CLASS UnknownHandler
188.908 -CLASS UnknownProtocol
188.909 -CLASS UnknownTransferEncoding
188.910 -CLASS Unload
188.911 -CLASS Unmarshaller
188.912 -CLASS Unpacker
188.913 -CLASS Unpickler
188.914 -CLASS UnpicklingError
188.915 -CLASS UnspecifiedEventTypeErr
188.916 -CLASS UnsupportedOperation
188.917 -CLASS UserDataHandler
188.918 -CLASS UserDict
188.919 -CLASS UserList
188.920 -CLASS UserString
188.921 -CLASS UserWarning
188.922 -CLASS UserWarning
188.923 -CLASS ValidationErr
188.924 -CLASS ValueError
188.925 -CLASS ValueError
188.926 -CLASS Values
188.927 -CLASS Vec2D
188.928 -CLASS Vendor
188.929 -CLASS Version
188.930 -CLASS VersionPredicate
188.931 -CLASS View
188.932 -CLASS WSGIRequestHandler
188.933 -CLASS WSGIServer
188.934 -CLASS Warning
188.935 -CLASS Warning
188.936 -CLASS Wave_read
188.937 -CLASS Wave_write
188.938 -CLASS WeakKeyDictionary
188.939 -CLASS WeakValueDictionary
188.940 -CLASS While
188.941 -CLASS WichmannHill
188.942 -CLASS WinDLL
188.943 -CLASS Window
188.944 -CLASS WindowsError
188.945 -CLASS WindowsError
188.946 -CLASS With
188.947 -CLASS WrongDocumentErr
188.948 -CLASS X
188.949 -CLASS XMLFilter
188.950 -CLASS XMLFilterBase
188.951 -CLASS XMLFilterImpl
188.952 -CLASS XMLGenerator
188.953 -CLASS XMLParser
188.954 -CLASS XMLRPCDocGenerator
188.955 -CLASS XMLReader
188.956 -CLASS XMLTreeBuilder
188.957 -CLASS XmlParseErr
188.958 -CLASS Yield
188.959 -CLASS Yuck
188.960 -CLASS ZeroDivisionError
188.961 -CLASS ZeroDivisionError
188.962 -CLASS ZipFile
188.963 -CLASS ZipImportError
188.964 -CLASS ZipInfo
188.965 -CLASS _CData [PROTECTE
188.966 -CLASS _FuncPtr [PROTECTE
188.967 -CLASS _SimpleCData [PROTECTE
188.968 -CLASS _posixfile_
188.969 -CLASS array
188.970 -CLASS async_chat
188.971 -CLASS bdist
188.972 -CLASS bdist_dumb
188.973 -CLASS bdist_msi
188.974 -CLASS bdist_rpm
188.975 -CLASS bdist_wininst
188.976 -CLASS bool
188.977 -CLASS bsddbobject
188.978 -CLASS build
188.979 -CLASS build_clib
188.980 -CLASS build_ext
188.981 -CLASS build_py
188.982 -CLASS build_scripts
188.983 -CLASS c_bool
188.984 -CLASS c_byte
188.985 -CLASS c_char
188.986 -CLASS c_char_p
188.987 -CLASS c_double
188.988 -CLASS c_float
188.989 -CLASS c_int
188.990 -CLASS c_int16
188.991 -CLASS c_int32
188.992 -CLASS c_int64
188.993 -CLASS c_int8
188.994 -CLASS c_long
188.995 -CLASS c_longdouble
188.996 -CLASS c_longlong
188.997 -CLASS c_short
188.998 -CLASS c_size_t
188.999 -CLASS c_ubyte
188.1000 -CLASS c_uint
188.1001 -CLASS c_uint16
188.1002 -CLASS c_uint32
188.1003 -CLASS c_uint64
188.1004 -CLASS c_uint8
188.1005 -CLASS c_ulong
188.1006 -CLASS c_ulonglong
188.1007 -CLASS c_ushort
188.1008 -CLASS c_void_p
188.1009 -CLASS c_wchar
188.1010 -CLASS c_wchar_p
188.1011 -CLASS class
188.1012 -CLASS class
188.1013 -CLASS clean
188.1014 -CLASS closing
188.1015 -CLASS complex
188.1016 -CLASS compressobj
188.1017 -CLASS config
188.1018 -CLASS container
188.1019 -CLASS container
188.1020 -CLASS contextmanager
188.1021 -CLASS contextmanager
188.1022 -CLASS controller
188.1023 -CLASS date
188.1024 -CLASS datetime
188.1025 -CLASS dbexts
188.1026 -CLASS dbextsTestCase
188.1027 -CLASS dbhash
188.1028 -CLASS decompressobj
188.1029 -CLASS deque
188.1030 -CLASS dict
188.1031 -CLASS dict
188.1032 -CLASS dircmp
188.1033 -CLASS dispatcher
188.1034 -CLASS dispatcher_with_send
188.1035 -CLASS dl
188.1036 -CLASS error
188.1037 -CLASS error_data
188.1038 -CLASS excel
188.1039 -CLASS excel_tab
188.1040 -CLASS executor
188.1041 -CLASS fifo
188.1042 -CLASS file
188.1043 -CLASS file
188.1044 -CLASS file_dispatcher
188.1045 -CLASS file_wrapper
188.1046 -CLASS float
188.1047 -CLASS float
188.1048 -CLASS foo
188.1049 -CLASS gaierror
188.1050 -CLASS herror
188.1051 -CLASS install
188.1052 -CLASS install_data
188.1053 -CLASS install_egg_info
188.1054 -CLASS install_headers
188.1055 -CLASS install_lib
188.1056 -CLASS install_misc
188.1057 -CLASS install_scripts
188.1058 -CLASS instance
188.1059 -CLASS instance
188.1060 -CLASS int
188.1061 -CLASS iterator
188.1062 -CLASS iterator
188.1063 -CLASS list
188.1064 -CLASS local
188.1065 -CLASS lock
188.1066 -CLASS long
188.1067 -CLASS main
188.1068 -CLASS mbox
188.1069 -CLASS mboxMessage
188.1070 -CLASS mllib
188.1071 -CLASS mmap
188.1072 -CLASS multiprocessing.Pool
188.1073 -CLASS mutex
188.1074 -CLASS mxODBCProxy
188.1075 -CLASS netrc
188.1076 -CLASS object
188.1077 -CLASS object
188.1078 -CLASS oss_audio_device
188.1079 -CLASS oss_mixer_device
188.1080 -CLASS poll
188.1081 -CLASS py_object
188.1082 -CLASS register
188.1083 -CLASS scheduler
188.1084 -CLASS sdist
188.1085 -CLASS set
188.1086 -CLASS set
188.1087 -CLASS shlex
188.1088 -CLASS simple_producer
188.1089 -CLASS socket
188.1090 -CLASS stat_result
188.1091 -CLASS str
188.1092 -CLASS str
188.1093 -CLASS test_dist
188.1094 -CLASS test_zxjdbc
188.1095 -CLASS time
188.1096 -CLASS timedelta
188.1097 -CLASS timeout
188.1098 -CLASS tixCommand
188.1099 -CLASS tmxxx
188.1100 -CLASS tuple
188.1101 -CLASS tzinfo
188.1102 -CLASS unicode
188.1103 -CLASS unicode
188.1104 -CLASS upload
188.1105 -CLASS window
188.1106 -CLASS xmlparser
188.1107 -CLASS zipimporter
188.1108 -CLASS zxAPITestCase
188.1109 -CLASS zxCoreTestCase
188.1110 -CLASS zxJDBCTestCase
188.1111 -METHOD __import__(name, globals, loca
188.1112 -METHOD abs(x)
188.1113 -METHOD all(iterable)
188.1114 -METHOD any(iterable)
188.1115 -METHOD ---apply(function, args, ke---
188.1116 -METHOD basestring()
188.1117 -METHOD bin(x)
188.1118 -METHOD bool(x)
188.1119 -METHOD buffer(object, offset, size)
188.1120 -METHOD callable(object)
188.1121 -METHOD chr(i)
188.1122 -METHOD classmethod(function)
188.1123 -METHOD cmp(x, y)
188.1124 -METHOD coerce(x, y)
188.1125 -METHOD compile(source, filename, mode
188.1126 -METHOD complex(real, imag)
188.1127 -METHOD delattr(object, name)
188.1128 -METHOD dict(arg)
188.1129 -METHOD dir(object)
188.1130 -METHOD divmod(a, b)
188.1131 -METHOD enumerate(sequence, start)
188.1132 -METHOD eval(expression, globals, loca
188.1133 -METHOD execfile(filename, globals, lo
188.1134 -METHOD exit(code)
188.1135 -METHOD file(filename, mode, bufsize)
188.1136 -METHOD filter(function, iterable)
188.1137 -METHOD float(x)
188.1138 -METHOD frozenset(iterable)
188.1139 -METHOD getattr(object, name, default)
188.1140 -METHOD globals()
188.1141 -METHOD hasattr(object, name)
188.1142 -METHOD hash(object)
188.1143 -METHOD help(object)
188.1144 -METHOD hex(x)
188.1145 -METHOD id(object)
188.1146 -METHOD input(prompt)
188.1147 -METHOD int(x, radix)
188.1148 -METHOD intern(string)
188.1149 -METHOD isinstance(object, classinfo)
188.1150 -METHOD issubclass(class, classinfo)
188.1151 -METHOD iter(o, sentinel)
188.1152 -METHOD len(s)
188.1153 -METHOD list(iterable)
188.1154 -METHOD locals()
188.1155 -METHOD long(x, radix)
188.1156 -METHOD map(function, iterable)
188.1157 -METHOD max(iterable, argskey)
188.1158 -METHOD min(iterable, argskey)
188.1159 -METHOD next(iterator, default)
188.1160 -METHOD object()
188.1161 -METHOD oct(x)
188.1162 -METHOD open(filename, mode, bufsize)
188.1163 -METHOD ord(c)
188.1164 -METHOD pow(x, y, z)
188.1165 -METHOD print(object, sep, end, file)
188.1166 -METHOD property(fget, fset, fdel, doc
188.1167 -METHOD quit(code)
188.1168 -METHOD range(start, stop, step)
188.1169 -METHOD raw_input(prompt)
188.1170 -METHOD reduce(function, iterable, ini
188.1171 -METHOD reload(module)
188.1172 -METHOD repr(object)
188.1173 -METHOD reversed(seq)
188.1174 -METHOD round(x, n)
188.1175 -METHOD set(iterable)
188.1176 -METHOD setattr(object, name, value)
188.1177 -METHOD slice(start, stop, step)
188.1178 -METHOD sorted(iterable, cmp, key, rev
188.1179 -METHOD staticmethod(function)
188.1180 -METHOD str(object)
188.1181 -METHOD sum(iterable, start)
188.1182 -METHOD super(type, object-or-type)
188.1183 -METHOD tuple(iterable)
188.1184 -METHOD type(name, bases, dict)
188.1185 -METHOD type(object)
188.1186 -METHOD unichr(i)
188.1187 -METHOD unicode(object, encoding, erro
188.1188 -METHOD vars(object)
188.1189 -METHOD xrange(start, stop, step)
188.1190 -METHOD zip(iterable)
188.1191 -VARIABLE Ellipsis
188.1192 -VARIABLE False
188.1193 -VARIABLE None
188.1194 -VARIABLE NotImplemented
188.1195 -VARIABLE True
188.1196 -VARIABLE __debug__
188.1197 -VARIABLE copyright
188.1198 -KEYWORD and
188.1199 -KEYWORD as
188.1200 -KEYWORD assert
188.1201 -KEYWORD break
188.1202 -KEYWORD class
188.1203 -KEYWORD continue
188.1204 -KEYWORD def
188.1205 -KEYWORD del
188.1206 -KEYWORD elif
188.1207 -KEYWORD else
188.1208 -KEYWORD except
188.1209 -KEYWORD exec
188.1210 -KEYWORD finally
188.1211 -KEYWORD for
188.1212 -KEYWORD from
188.1213 -KEYWORD global
188.1214 -KEYWORD if
188.1215 -KEYWORD import
188.1216 -KEYWORD in
188.1217 -KEYWORD is
188.1218 -KEYWORD lambda
188.1219 -KEYWORD not
188.1220 -KEYWORD or
188.1221 -KEYWORD pass
188.1222 -KEYWORD print
188.1223 -KEYWORD raise
188.1224 -KEYWORD return
188.1225 -KEYWORD try
188.1226 -KEYWORD while
188.1227 -KEYWORD with
188.1228 -KEYWORD yield
189.1 --- a/python.editor/test/unit/data/testfiles/compl.py.testObjMethodCompletion2.completion Sun Jan 04 13:11:53 2015 -0600
189.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
189.3 @@ -1,10 +0,0 @@
189.4 -Code completion result for source line:
189.5 -self.|mysupersupermethod()
189.6 -(QueryType=COMPLETION, NameKind=PREFIX)
189.7 -METHOD mymethod()
189.8 -METHOD mysupermethod()
189.9 -METHOD mysupersupermethod()
189.10 -------------------------------------
189.11 -ATTRIBUTE __dict__
189.12 -ATTRIBUTE ---__members__ ---
189.13 -ATTRIBUTE ---__methods__ ---
190.1 --- a/python.editor/test/unit/data/testfiles/compl2.py Sun Jan 04 13:11:53 2015 -0600
190.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
190.3 @@ -1,15 +0,0 @@
190.4 -import sys as whatever
190.5 -import os
190.6 -
190.7 -print whatever.r
190.8 -print os.r
190.9 -print sys.getfilesysteme
190.10 -
190.11 -myvar = file()
190.12 -myvar.close()
190.13 -
190.14 -myothervar = ZipFile()
190.15 -myothervar.x
190.16 -
190.17 -unknown.fai
190.18 -
191.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodCompletion3.completion Sun Jan 04 13:11:53 2015 -0600
191.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
191.3 @@ -1,7 +0,0 @@
191.4 -Code completion result for source line:
191.5 -print w|hatever.r
191.6 -(QueryType=COMPLETION, NameKind=PREFIX)
191.7 -MODULE whatever
191.8 -------------------------------------
191.9 -KEYWORD while
191.10 -KEYWORD with
192.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodCompletion4.completion Sun Jan 04 13:11:53 2015 -0600
192.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
192.3 @@ -1,58 +0,0 @@
192.4 -Code completion result for source line:
192.5 -print whatever.|r
192.6 -(QueryType=COMPLETION, NameKind=PREFIX)
192.7 -METHOD displayhook(value)
192.8 -METHOD exc_clear()
192.9 -METHOD exc_info()
192.10 -METHOD excepthook(type, value, traceb
192.11 -METHOD exit(arg)
192.12 -METHOD getcheckinterval()
192.13 -METHOD getdefaultencoding()
192.14 -METHOD getdlopenflags()
192.15 -METHOD getfilesystemencoding()
192.16 -METHOD getprofile()
192.17 -METHOD getrecursionlimit()
192.18 -METHOD getrefcount(object)
192.19 -METHOD getsizeof(object, default)
192.20 -METHOD gettrace()
192.21 -METHOD getwindowsversion()
192.22 -METHOD setcheckinterval(interval)
192.23 -METHOD setdefaultencoding(name)
192.24 -METHOD setdlopenflags(n)
192.25 -METHOD setprofile(profilefunc)
192.26 -METHOD setrecursionlimit(limit)
192.27 -METHOD settrace(tracefunc)
192.28 -METHOD settscdump(on_flag)
192.29 -VARIABLE __displayhook__
192.30 -VARIABLE __stdin__
192.31 -VARIABLE api_version
192.32 -VARIABLE argv
192.33 -VARIABLE builtin_module_names
192.34 -VARIABLE byteorder
192.35 -VARIABLE copyright
192.36 -VARIABLE dllhandle
192.37 -VARIABLE dont_write_bytecode
192.38 -VARIABLE ---exc_type ---
192.39 -VARIABLE exec_prefix
192.40 -VARIABLE executable
192.41 -VARIABLE ---exitfunc ---
192.42 -VARIABLE flags
192.43 -VARIABLE float_info
192.44 -VARIABLE hexversion
192.45 -VARIABLE last_type
192.46 -VARIABLE maxint
192.47 -VARIABLE maxsize
192.48 -VARIABLE maxunicode
192.49 -VARIABLE modules
192.50 -VARIABLE path
192.51 -VARIABLE platform
192.52 -VARIABLE prefix
192.53 -VARIABLE ps1
192.54 -VARIABLE py3kwarning
192.55 -VARIABLE stdin
192.56 -VARIABLE subversion
192.57 -VARIABLE tracebacklimit
192.58 -VARIABLE version
192.59 -VARIABLE version_info
192.60 -VARIABLE warnoptions
192.61 -VARIABLE winver
193.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodCompletion5.completion Sun Jan 04 13:11:53 2015 -0600
193.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
193.3 @@ -1,492 +0,0 @@
193.4 -Code completion result for source line:
193.5 -print whatever.r|
193.6 -(QueryType=COMPLETION, NameKind=PREFIX)
193.7 -------------------------------------
193.8 -METHOD r_eval(code)
193.9 -METHOD r_exec(code)
193.10 -METHOD r_execfile(filename)
193.11 -METHOD r_import(modulename, globals,
193.12 -METHOD r_open(filename, mode, bufsize
193.13 -METHOD r_reload(module)
193.14 -METHOD r_unload(module)
193.15 -METHOD radiogroup(name, x, y, width,
193.16 -METHOD radix()
193.17 -METHOD radix()
193.18 -METHOD raise_exc(exc_class, message)
193.19 -METHOD raise_stmt(nodelist)
193.20 -METHOD randint(a, b)
193.21 -METHOD random()
193.22 -METHOD random()
193.23 -METHOD randrange(start, stop, step, i
193.24 -METHOD ratio()
193.25 -METHOD raw(sql, params, bindings, del
193.26 -METHOD raw_decode(s)
193.27 -METHOD raw_input(prompt)
193.28 -METHOD rawq_getchar()
193.29 -METHOD rcpt(recip, options)
193.30 -METHOD read()
193.31 -METHOD read()
193.32 -METHOD read()
193.33 -METHOD read(amt)
193.34 -METHOD read(args)
193.35 -METHOD ---read(f, n) ---
193.36 -METHOD read(filenames)
193.37 -METHOD read(n)
193.38 -METHOD read(n)
193.39 -METHOD read(n)
193.40 -METHOD read(n)
193.41 -METHOD read(n)
193.42 -METHOD read(n)
193.43 -METHOD read(n)
193.44 -METHOD read(name)
193.45 -METHOD read(nbytes)
193.46 -METHOD read(num)
193.47 -METHOD read(size)
193.48 -METHOD read(size)
193.49 -METHOD read(size)
193.50 -METHOD read(size)
193.51 -METHOD read(size)
193.52 -METHOD read(size)
193.53 -METHOD read(size)
193.54 -METHOD read(size)
193.55 -METHOD read1()
193.56 -METHOD read1(n)
193.57 -METHOD read_all()
193.58 -METHOD read_binary()
193.59 -METHOD read_byte()
193.60 -METHOD read_eager()
193.61 -METHOD read_file(filename, mode)
193.62 -METHOD read_lazy()
193.63 -METHOD read_lines()
193.64 -METHOD read_lines_to_eof()
193.65 -METHOD read_lines_to_outerboundary()
193.66 -METHOD read_manifest()
193.67 -METHOD read_module(modname, mode)
193.68 -METHOD read_multi(environ, keep_blank
193.69 -METHOD read_sb_data()
193.70 -METHOD read_single()
193.71 -METHOD read_some()
193.72 -METHOD read_template()
193.73 -METHOD read_token()
193.74 -METHOD read_until(match, timeout)
193.75 -METHOD read_urlencoded()
193.76 -METHOD read_very_eager()
193.77 -METHOD read_very_lazy()
193.78 -METHOD readable()
193.79 -METHOD readable()
193.80 -METHOD readable()
193.81 -METHOD readall()
193.82 -METHOD readall()
193.83 -METHOD readfp(fp, filename)
193.84 -METHOD readframes(n)
193.85 -METHOD readheaders()
193.86 -METHOD readinto(b)
193.87 -METHOD readinto(b)
193.88 -METHOD readline()
193.89 -METHOD readline()
193.90 -METHOD readline()
193.91 -METHOD readline()
193.92 -METHOD readline()
193.93 -METHOD readline()
193.94 -METHOD readline()
193.95 -METHOD readline()
193.96 -METHOD readline(length)
193.97 -METHOD readline(limit)
193.98 -METHOD readline(size)
193.99 -METHOD readline(size)
193.100 -METHOD readline(size)
193.101 -METHOD readlines()
193.102 -METHOD readlines()
193.103 -METHOD readlines()
193.104 -METHOD readlines(hint)
193.105 -METHOD readlines(size)
193.106 -METHOD readlines(sizehint)
193.107 -METHOD readlines(sizehint)
193.108 -METHOD readlines(sizehint)
193.109 -METHOD ready()
193.110 -METHOD real_quick_ratio()
193.111 -METHOD reccontrols()
193.112 -METHOD recent()
193.113 -METHOD recv()
193.114 -METHOD recv(args)
193.115 -METHOD recv(buffer_size)
193.116 -METHOD recv_bytes(maxlength)
193.117 -METHOD recv_bytes_into(buffer, offset
193.118 -METHOD redirect_internal(url, fp, err
193.119 -METHOD redirect_request(req, fp, code
193.120 -METHOD redrawln(beg, num)
193.121 -METHOD redrawwin()
193.122 -METHOD reduce_uri(uri, default_port)
193.123 -METHOD refilemessages(list, tofolder,
193.124 -METHOD refill_buffer()
193.125 -METHOD refresh(pminrow, pmincol, smin
193.126 -METHOD refuse_compilation(args, kwarg
193.127 -METHOD register(socket_object, mask)
193.128 -METHOD register(subclass)
193.129 -METHOD register(typeid, callable, pro
193.130 -METHOD register_function(function, na
193.131 -METHOD register_instance(instance, al
193.132 -METHOD register_introspection_functio
193.133 -METHOD register_multicall_functions()
193.134 -METHOD reinitialize_command(command,
193.135 -METHOD reinitialize_command(command,
193.136 -METHOD release()
193.137 -METHOD release()
193.138 -METHOD release()
193.139 -METHOD release()
193.140 -METHOD release_poll_object(pobj)
193.141 -METHOD reload(module)
193.142 -METHOD reload(module, path)
193.143 -METHOD remainder(a, b)
193.144 -METHOD remainder_near(a, b)
193.145 -METHOD remainder_near(other, context)
193.146 -METHOD remove()
193.147 -METHOD remove(elem)
193.148 -METHOD remove(element)
193.149 -METHOD remove(elt)
193.150 -METHOD remove(item)
193.151 -METHOD remove(key)
193.152 -METHOD remove(key)
193.153 -METHOD remove(key)
193.154 -METHOD remove(key)
193.155 -METHOD remove(x)
193.156 -METHOD removeAttribute(name)
193.157 -METHOD removeAttributeNS(namespaceURI
193.158 -METHOD removeAttributeNode(node)
193.159 -METHOD removeAttributeNodeNS(node)
193.160 -METHOD removeChild(oldChild)
193.161 -METHOD removeChild(oldChild)
193.162 -METHOD removeChild(oldChild)
193.163 -METHOD removeChild(oldChild)
193.164 -METHOD removeFilter(filter)
193.165 -METHOD removeHandler(hdlr)
193.166 -METHOD removeHandler(hdlr)
193.167 -METHOD removeNamedItem(name)
193.168 -METHOD removeNamedItem(name)
193.169 -METHOD removeNamedItem(name)
193.170 -METHOD removeNamedItemNS(namespaceURI
193.171 -METHOD removeNamedItemNS(namespaceURI
193.172 -METHOD removeNamedItemNS(namespaceURI
193.173 -METHOD remove_duplicates()
193.174 -METHOD remove_flag(flag)
193.175 -METHOD remove_folder(folder)
193.176 -METHOD remove_folder(folder)
193.177 -METHOD remove_label(label)
193.178 -METHOD remove_option(opt_str)
193.179 -METHOD remove_option(section, option)
193.180 -METHOD remove_pyc()
193.181 -METHOD remove_section(section)
193.182 -METHOD remove_sequence(sequence)
193.183 -METHOD removefromallsequences(list)
193.184 -METHOD removemessages(list)
193.185 -METHOD rename(fromname, toname)
193.186 -METHOD rename(oldmailbox, newmailbox)
193.187 -METHOD renameNode(n, namespaceURI, na
193.188 -METHOD repeat(repeat, number)
193.189 -METHOD replace(hour, minute, second,
193.190 -METHOD replace(hour, minute, second,
193.191 -METHOD replace(old, new)
193.192 -METHOD replace(old, new, count)
193.193 -METHOD replace(old, new, maxsplit)
193.194 -METHOD replace(win)
193.195 -METHOD replace(year, month, day)
193.196 -METHOD replace(year, month, day)
193.197 -METHOD replace(year, month, day, hour
193.198 -METHOD replaceChild(newChild, oldChil
193.199 -METHOD replaceChild(newChild, oldChil
193.200 -METHOD replaceChild(newChild, oldChil
193.201 -METHOD replaceData(offset, count, arg
193.202 -METHOD replaceWholeText(content)
193.203 -METHOD replace_header(_name, _value)
193.204 -METHOD replace_paths_in_code(co)
193.205 -METHOD report()
193.206 -METHOD report()
193.207 -METHOD report_404()
193.208 -METHOD report_failure(out, test, exam
193.209 -METHOD report_failure(out, test, exam
193.210 -METHOD report_full_closure()
193.211 -METHOD report_partial_closure()
193.212 -METHOD report_start(out, test, exampl
193.213 -METHOD report_success(out, test, exam
193.214 -METHOD report_unbalanced(tag)
193.215 -METHOD report_unexpected_exception(ou
193.216 -METHOD report_unexpected_exception(ou
193.217 -METHOD repr(object)
193.218 -METHOD repr(x)
193.219 -METHOD repr1(x, level)
193.220 -METHOD repr1(x, level)
193.221 -METHOD repr1(x, level)
193.222 -METHOD repr_array(x, level)
193.223 -METHOD repr_deque(x, level)
193.224 -METHOD repr_dict(x, level)
193.225 -METHOD repr_frozenset(x, level)
193.226 -METHOD repr_instance(x, level)
193.227 -METHOD repr_instance(x, level)
193.228 -METHOD repr_instance(x, level)
193.229 -METHOD repr_list(x, level)
193.230 -METHOD repr_long(x, level)
193.231 -METHOD repr_set(x, level)
193.232 -METHOD repr_str(x, level)
193.233 -METHOD repr_str(x, level)
193.234 -METHOD repr_str(x, level)
193.235 -METHOD repr_string(x, level)
193.236 -METHOD repr_string(x, level)
193.237 -METHOD repr_tuple(x, level)
193.238 -METHOD repr_unicode(x, level)
193.239 -METHOD request(host, handler, request
193.240 -METHOD request(method, url, body, hea
193.241 -METHOD reset()
193.242 -METHOD reset()
193.243 -METHOD reset()
193.244 -METHOD reset()
193.245 -METHOD reset()
193.246 -METHOD reset()
193.247 -METHOD reset()
193.248 -METHOD reset()
193.249 -METHOD reset()
193.250 -METHOD reset()
193.251 -METHOD reset()
193.252 -METHOD reset()
193.253 -METHOD reset()
193.254 -METHOD reset()
193.255 -METHOD reset()
193.256 -METHOD reset()
193.257 -METHOD reset()
193.258 -METHOD reset()
193.259 -METHOD reset(data)
193.260 -METHOD reset_retry_count()
193.261 -METHOD resetbuffer()
193.262 -METHOD resize(newsize)
193.263 -METHOD resolveEntity(pubId, sysId)
193.264 -METHOD resolveEntity(publicId, system
193.265 -METHOD resolveEntity(publicId, system
193.266 -METHOD resolveEntity(publicId, system
193.267 -METHOD resolveEntity(publicId, system
193.268 -METHOD response(code)
193.269 -METHOD result_is_file()
193.270 -METHOD results()
193.271 -METHOD retr(which)
193.272 -METHOD retrbinary(cmd, callback, bloc
193.273 -METHOD retrieve(url, filename, report
193.274 -METHOD retrlines(cmd, callback)
193.275 -METHOD retry_http_basic_auth(host, re
193.276 -METHOD retry_http_basic_auth(url, rea
193.277 -METHOD retry_http_digest_auth(req, au
193.278 -METHOD retry_https_basic_auth(url, re
193.279 -METHOD retry_proxy_http_basic_auth(ur
193.280 -METHOD retry_proxy_https_basic_auth(u
193.281 -METHOD return_ok(cookie, request)
193.282 -METHOD return_ok(cookie, request)
193.283 -METHOD return_ok_domain(cookie, reque
193.284 -METHOD return_ok_expires(cookie, requ
193.285 -METHOD return_ok_port(cookie, request
193.286 -METHOD return_ok_secure(cookie, reque
193.287 -METHOD return_ok_verifiability(cookie
193.288 -METHOD return_ok_version(cookie, requ
193.289 -METHOD return_stmt(nodelist)
193.290 -METHOD reverse()
193.291 -METHOD reverse()
193.292 -METHOD reverse()
193.293 -METHOD reverse_order()
193.294 -METHOD revert(filename, ignore_discar
193.295 -METHOD rewind()
193.296 -METHOD rewind()
193.297 -METHOD rewindbody()
193.298 -METHOD rfind(string, start, end)
193.299 -METHOD rfind(sub)
193.300 -METHOD rfind(sub, start, end)
193.301 -METHOD rfind(sub, start, end)
193.302 -METHOD rindex(sub)
193.303 -METHOD rindex(sub, start, end)
193.304 -METHOD rindex(sub, start, end)
193.305 -METHOD rjust(width)
193.306 -METHOD rjust(width, args)
193.307 -METHOD rjust(width, fillchar)
193.308 -METHOD rmd(dirname)
193.309 -METHOD rollback()
193.310 -METHOD rollback()
193.311 -METHOD rotate(a, b)
193.312 -METHOD rotate(other, context)
193.313 -METHOD rowxfer(line)
193.314 -METHOD rpartition(sep)
193.315 -METHOD rpartition(sep)
193.316 -METHOD rpartition(sep)
193.317 -METHOD rpop(user)
193.318 -METHOD rset()
193.319 -METHOD rset()
193.320 -METHOD rsplit()
193.321 -METHOD rsplit(sep, maxsplit)
193.322 -METHOD rsplit(sep, maxsplit)
193.323 -METHOD rstrip()
193.324 -METHOD rstrip(chars)
193.325 -METHOD rstrip(chars)
193.326 -METHOD run()
193.327 -METHOD run()
193.328 -METHOD run()
193.329 -METHOD run()
193.330 -METHOD run()
193.331 -METHOD run()
193.332 -METHOD run()
193.333 -METHOD run()
193.334 -METHOD run()
193.335 -METHOD run()
193.336 -METHOD run()
193.337 -METHOD run()
193.338 -METHOD run()
193.339 -METHOD run()
193.340 -METHOD run()
193.341 -METHOD run()
193.342 -METHOD run()
193.343 -METHOD run()
193.344 -METHOD run()
193.345 -METHOD run()
193.346 -METHOD run()
193.347 -METHOD run()
193.348 -METHOD run()
193.349 -METHOD run()
193.350 -METHOD run()
193.351 -METHOD run()
193.352 -METHOD run(application)
193.353 -METHOD run(callback, key, completer)
193.354 -METHOD run(cmd)
193.355 -METHOD run(cmd)
193.356 -METHOD run(cmd)
193.357 -METHOD run(cmd, globals, locals)
193.358 -METHOD run(result)
193.359 -METHOD run(result)
193.360 -METHOD run(test)
193.361 -METHOD run(test, compileflags, out, c
193.362 -METHOD run(test, compileflags, out, c
193.363 -METHOD runTest()
193.364 -METHOD run__test__(d, name)
193.365 -METHOD run_cgi()
193.366 -METHOD run_command(command)
193.367 -METHOD run_command(command)
193.368 -METHOD run_commands()
193.369 -METHOD run_script(pathname)
193.370 -METHOD runcall(func, *args, **keyword
193.371 -METHOD runcall(func, args, kw)
193.372 -METHOD runcall(func, args, kwds)
193.373 -METHOD runcode(code)
193.374 -METHOD runctx(cmd, globals, locals)
193.375 -METHOD runctx(cmd, globals, locals)
193.376 -METHOD runctx(cmd, globals, locals)
193.377 -METHOD runctx(cmd, globals, locals)
193.378 -METHOD rundict(d, name, module)
193.379 -METHOD rundoc(object, name, module)
193.380 -METHOD runeval(expr, globals, locals)
193.381 -METHOD runfunc(func, args, kw)
193.382 -METHOD runsource(source, filename, sy
193.383 -METHOD runstring(s, name)
193.384 -METHOD runtime_library_dir_option(dir
193.385 -METHOD runtime_library_dir_option(dir
193.386 -METHOD runtime_library_dir_option(dir
193.387 -METHOD runtime_library_dir_option(dir
193.388 -VARIABLE rargs
193.389 -VARIABLE raw
193.390 -VARIABLE raw_requestline
193.391 -VARIABLE raw_requestline
193.392 -VARIABLE rawdata
193.393 -VARIABLE rawdata
193.394 -VARIABLE rawdata
193.395 -VARIABLE rawq
193.396 -VARIABLE rbufsize
193.397 -VARIABLE rbufsize
193.398 -VARIABLE rc
193.399 -VARIABLE rcLines
193.400 -VARIABLE re_var
193.401 -VARIABLE read
193.402 -VARIABLE read
193.403 -VARIABLE read
193.404 -VARIABLE read
193.405 -VARIABLE read_func
193.406 -VARIABLE reader
193.407 -VARIABLE reader
193.408 -VARIABLE reader
193.409 -VARIABLE readfile
193.410 -VARIABLE readline
193.411 -VARIABLE readline
193.412 -VARIABLE readline
193.413 -VARIABLE readlines
193.414 -VARIABLE readlines
193.415 -VARIABLE realpos
193.416 -VARIABLE realsock
193.417 -VARIABLE reason
193.418 -VARIABLE reason
193.419 -VARIABLE recipients
193.420 -VARIABLE record
193.421 -VARIABLE records
193.422 -VARIABLE recv
193.423 -VARIABLE recvfrom
193.424 -VARIABLE reference
193.425 -VARIABLE relative
193.426 -VARIABLE relativeCreated
193.427 -VARIABLE release
193.428 -VARIABLE repeat
193.429 -VARIABLE replace_paths
193.430 -VARIABLE replace_whitespace
193.431 -VARIABLE repository
193.432 -VARIABLE repository
193.433 -VARIABLE repr
193.434 -VARIABLE request
193.435 -VARIABLE request_queue_size
193.436 -VARIABLE request_version
193.437 -VARIABLE requestline
193.438 -VARIABLE requires
193.439 -VARIABLE requires
193.440 -VARIABLE res_extension
193.441 -VARIABLE res_extension
193.442 -VARIABLE res_extension
193.443 -VARIABLE reserved
193.444 -VARIABLE response
193.445 -VARIABLE response_class
193.446 -VARIABLE responses
193.447 -VARIABLE restkey
193.448 -VARIABLE restval
193.449 -VARIABLE restype
193.450 -VARIABLE result
193.451 -VARIABLE results
193.452 -VARIABLE results
193.453 -VARIABLE retried
193.454 -VARIABLE retryFactor
193.455 -VARIABLE retryMax
193.456 -VARIABLE retryPeriod
193.457 -VARIABLE retryStart
193.458 -VARIABLE retryTime
193.459 -VARIABLE returncode
193.460 -VARIABLE returnframe
193.461 -VARIABLE rfc2109
193.462 -VARIABLE rfc2109_as_netscape
193.463 -VARIABLE rfc2965
193.464 -VARIABLE rfile
193.465 -VARIABLE right
193.466 -VARIABLE right
193.467 -VARIABLE right_list
193.468 -VARIABLE right_only
193.469 -VARIABLE rlen
193.470 -VARIABLE rng
193.471 -VARIABLE rng
193.472 -VARIABLE rolloverAt
193.473 -VARIABLE root
193.474 -VARIABLE root
193.475 -VARIABLE root
193.476 -VARIABLE root
193.477 -VARIABLE roots
193.478 -VARIABLE rounding
193.479 -VARIABLE row
193.480 -VARIABLE rows
193.481 -VARIABLE rpath
193.482 -VARIABLE rpc_paths
193.483 -VARIABLE rpm3_mode
193.484 -VARIABLE rpm_base
193.485 -VARIABLE rs
193.486 -VARIABLE rulelines
193.487 -VARIABLE ruler
193.488 -VARIABLE runtime_library_dirs
193.489 -VARIABLE runtime_library_dirs
193.490 -VARIABLE rx
193.491 -ATTRIBUTE real
193.492 -ATTRIBUTE real
193.493 -ATTRIBUTE restype
193.494 -ATTRIBUTE row_factory
193.495 -ATTRIBUTE rowcount
194.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodCompletion6.completion Sun Jan 04 13:11:53 2015 -0600
194.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
194.3 @@ -1,5 +0,0 @@
194.4 -Code completion result for source line:
194.5 -print sys.getfile|systeme
194.6 -(QueryType=COMPLETION, NameKind=PREFIX)
194.7 -------------------------------------
194.8 -METHOD getfile()
195.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodCompletion7.completion Sun Jan 04 13:11:53 2015 -0600
195.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
195.3 @@ -1,76 +0,0 @@
195.4 -Code completion result for source line:
195.5 -print os.|r
195.6 -(QueryType=COMPLETION, NameKind=PREFIX)
195.7 -MODULE altsep
195.8 -MODULE curdir
195.9 -MODULE defpath
195.10 -MODULE pardir
195.11 -MODULE path
195.12 -MODULE pathsep
195.13 -MODULE sep
195.14 -PACKAGE os.path
195.15 -CLASS stat_result
195.16 -METHOD access(path, mode)
195.17 -METHOD chdir(path)
195.18 -METHOD chmod(path, mode)
195.19 -METHOD close(fd)
195.20 -METHOD fdopen(fd, mode, bufsize)
195.21 -METHOD getcwd()
195.22 -METHOD getegid()
195.23 -METHOD getenv(key, default)
195.24 -METHOD geteuid()
195.25 -METHOD getgid()
195.26 -METHOD getlogin()
195.27 -METHOD getpgrp()
195.28 -METHOD getpid()
195.29 -METHOD getppid()
195.30 -METHOD getuid()
195.31 -METHOD isatty(fileno)
195.32 -METHOD listdir(path)
195.33 -METHOD lseek(fd, pos, how)
195.34 -METHOD lstat(path)
195.35 -METHOD makedirs(path, mode)
195.36 -METHOD mkdir(path, mode)
195.37 -METHOD open(filename, flag, mode)
195.38 -METHOD popen(args, kwargs)
195.39 -METHOD popen2(cmd, mode, bufsize)
195.40 -METHOD popen3(cmd, mode, bufsize)
195.41 -METHOD popen4(cmd, mode, bufsize)
195.42 -METHOD putenv(key, value)
195.43 -METHOD read(fd, buffersize)
195.44 -METHOD remove(path)
195.45 -METHOD removedirs(name)
195.46 -METHOD rename(path, newpath)
195.47 -METHOD renames(old, new)
195.48 -METHOD rmdir(path)
195.49 -METHOD setpgrp()
195.50 -METHOD setsid()
195.51 -METHOD stat(path)
195.52 -METHOD strerror(code)
195.53 -METHOD system(args, kwargs)
195.54 -METHOD unlink(path)
195.55 -METHOD unsetenv(key)
195.56 -METHOD utime(path, times)
195.57 -METHOD walk(top, topdown, onerror)
195.58 -METHOD write(fd, string)
195.59 -VARIABLE EX_OK
195.60 -VARIABLE F_OK
195.61 -VARIABLE O_APPEND
195.62 -VARIABLE O_CREAT
195.63 -VARIABLE O_EXCL
195.64 -VARIABLE O_RDONLY
195.65 -VARIABLE O_RDWR
195.66 -VARIABLE O_SYNC
195.67 -VARIABLE O_TRUNC
195.68 -VARIABLE O_WRONLY
195.69 -VARIABLE R_OK
195.70 -VARIABLE SEEK_CUR
195.71 -VARIABLE SEEK_END
195.72 -VARIABLE SEEK_SET
195.73 -VARIABLE W_OK
195.74 -VARIABLE X_OK
195.75 -VARIABLE __all__
195.76 -VARIABLE environ
195.77 -VARIABLE error
195.78 -VARIABLE linesep
195.79 -VARIABLE name
196.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodConstructors1.completion Sun Jan 04 13:11:53 2015 -0600
196.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
196.3 @@ -1,28 +0,0 @@
196.4 -Code completion result for source line:
196.5 -myvar.|close()
196.6 -(QueryType=COMPLETION, NameKind=PREFIX)
196.7 -METHOD close()
196.8 -METHOD fileno()
196.9 -METHOD flush()
196.10 -METHOD isatty()
196.11 -METHOD next()
196.12 -METHOD read(size)
196.13 -METHOD readline(size)
196.14 -METHOD readlines(sizehint)
196.15 -METHOD seek(offset, whence)
196.16 -METHOD tell()
196.17 -METHOD truncate(size)
196.18 -METHOD write(str)
196.19 -METHOD writelines(sequence)
196.20 -METHOD ---xreadlines() ---
196.21 -ATTRIBUTE closed
196.22 -ATTRIBUTE encoding
196.23 -ATTRIBUTE errors
196.24 -ATTRIBUTE mode
196.25 -ATTRIBUTE name
196.26 -ATTRIBUTE newlines
196.27 -ATTRIBUTE softspace
196.28 -------------------------------------
196.29 -ATTRIBUTE __dict__
196.30 -ATTRIBUTE ---__members__ ---
196.31 -ATTRIBUTE ---__methods__ ---
197.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodConstructors2.completion Sun Jan 04 13:11:53 2015 -0600
197.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
197.3 @@ -1,27 +0,0 @@
197.4 -Code completion result for source line:
197.5 -myothervar.|x
197.6 -(QueryType=COMPLETION, NameKind=PREFIX)
197.7 -METHOD close()
197.8 -METHOD getinfo(name)
197.9 -METHOD infolist()
197.10 -METHOD namelist()
197.11 -METHOD printdir()
197.12 -METHOD read(name)
197.13 -METHOD testzip()
197.14 -METHOD write(filename, arcname, compr
197.15 -METHOD writestr(zinfo_or_arcname, byt
197.16 -VARIABLE NameToInfo
197.17 -VARIABLE comment
197.18 -VARIABLE compression
197.19 -VARIABLE debug
197.20 -VARIABLE filelist
197.21 -VARIABLE filename
197.22 -VARIABLE fp
197.23 -VARIABLE mode
197.24 -VARIABLE start_dir
197.25 -------------------------------------
197.26 -CONSTRUCTO __init__(file, mode, compressi
197.27 -METHOD __del__()
197.28 -ATTRIBUTE __dict__
197.29 -ATTRIBUTE ---__members__ ---
197.30 -ATTRIBUTE ---__methods__ ---
198.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodConstructors3.completion Sun Jan 04 13:11:53 2015 -0600
198.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
198.3 @@ -1,18 +0,0 @@
198.4 -Code completion result for source line:
198.5 -unknown.fai|
198.6 -(QueryType=COMPLETION, NameKind=PREFIX)
198.7 -OTHER Specify type of <code>unknown<
198.8 -------------------------------------
198.9 -METHOD fail(msg)
198.10 -METHOD fail(object, name, args)
198.11 -METHOD failIf(expr, msg)
198.12 -METHOD failIfAlmostEqual(first, secon
198.13 -METHOD failIfEqual(first, second, msg
198.14 -METHOD failUnless(expr, msg)
198.15 -METHOD failUnlessAlmostEqual(first, s
198.16 -METHOD failUnlessEqual(first, second,
198.17 -METHOD failUnlessRaises(excClass, cal
198.18 -VARIABLE fail
198.19 -VARIABLE failureException
198.20 -VARIABLE failures
198.21 -VARIABLE failures
199.1 --- a/python.editor/test/unit/data/testfiles/compl3.py Sun Jan 04 13:11:53 2015 -0600
199.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
199.3 @@ -1,59 +0,0 @@
199.4 -#!/usr/bin/env python
199.5 -# Testcase from http://www.amk.ca/files/simple/fingerd.txt
199.6 -
199.7 -# fingerd.py
199.8 -# By A.M. Kuchling (amk@amk.ca)
199.9 -#
199.10 -# This little program illustrates how easy it is to write network
199.11 -# servers using the classes in the SocketServer module.
199.12 -#
199.13 -# The finger protocol is a very simple TCP-based protocol; the client
199.14 -# sends a single line containing the name of the user whose
199.15 -# information is being requested, followed by a newline.
199.16 -# Information about the user should then be sent over the socket
199.17 -# connection to the client. In this implementation, the server simply
199.18 -# tells you who you've fingered; you'd probably want it to retrieve
199.19 -# information from the user's home directory or a database of some sort.
199.20 -#
199.21 -
199.22 -import SocketServer
199.23 -
199.24 -class FingerHandler(SocketServer.StreamRequestHandler):
199.25 - def handle(self):
199.26 - # Read a line of text, limiting it to 512 bytes.
199.27 - # This will prevent someone trying to crash the server machine
199.28 - # by sending megabytes of data.
199.29 - username=self.rfile.readline(512)
199.30 -
199.31 - # Remove any leading and trailing whitespace, including the
199.32 - # trailing newline.
199.33 - import string
199.34 - username=string.strip(username)
199.35 -
199.36 - # Call the method to get the user's information, and return it
199.37 - # to the client. The SocketServer classes make self.wfile
199.38 - # available to send data to the client.
199.39 - info = self.find_user_info(username)
199.40 - self.wfile.write(info)
199.41 -
199.42 - # The following method takes a string containing the username,
199.43 - # and returns another string containing whatever information is
199.44 - # desired. You can subclass the FingerHandler class and override
199.45 - # this method with your own to produce customized output.
199.46 -
199.47 - def find_user_info(self, username):
199.48 - "Return a string containing the desired user information."
199.49 - return "You fingered the user %s\n" % (repr(username),)
199.50 -
199.51 -# If this script is being run directly, it'll start acting as a finger
199.52 -# daemon. If someone's importing it in order to subclass
199.53 -# FingerHandler, that shouldn't be done. The following "if" statement
199.54 -# is the usual Python idiom for running code only in a script.
199.55 -
199.56 -if __name__=='__main__':
199.57 - # Create an instance of our server class
199.58 - server=SocketServer.TCPServer( ('', 79), FingerHandler)
199.59 -
199.60 - # Enter an infinite loop, waiting for requests and then servicing them.
199.61 - server.serve_forever()
199.62 -
200.1 --- a/python.editor/test/unit/data/testfiles/compl3.py.testObjMethodCompletion8.completion Sun Jan 04 13:11:53 2015 -0600
200.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
200.3 @@ -1,19 +0,0 @@
200.4 -Code completion result for source line:
200.5 -server=SocketServer.|TCPServer( ('', 79), FingerHandler)
200.6 -(QueryType=COMPLETION, NameKind=PREFIX)
200.7 -CLASS BaseRequestHandler
200.8 -CLASS DatagramRequestHandler
200.9 -CLASS ForkingMixIn
200.10 -CLASS ForkingTCPServer
200.11 -CLASS ForkingUDPServer
200.12 -CLASS StreamRequestHandler
200.13 -CLASS TCPServer
200.14 -CLASS ThreadingMixIn
200.15 -CLASS ThreadingTCPServer
200.16 -CLASS ThreadingUDPServer
200.17 -CLASS ThreadingUnixDatagramServer
200.18 -CLASS ThreadingUnixStreamServer
200.19 -CLASS UDPServer
200.20 -CLASS UnixDatagramServer
200.21 -CLASS UnixStreamServer
200.22 -VARIABLE __all__
201.1 --- a/python.editor/test/unit/data/testfiles/compl4.py Sun Jan 04 13:11:53 2015 -0600
201.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
201.3 @@ -1,3 +0,0 @@
201.4 -import sys as faen
201.5 -faen.e
201.6 -
202.1 --- a/python.editor/test/unit/data/testfiles/compl4.py.testObjMethodCompletion9.completion Sun Jan 04 13:11:53 2015 -0600
202.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
202.3 @@ -1,11 +0,0 @@
202.4 -Code completion result for source line:
202.5 -faen.e|
202.6 -(QueryType=COMPLETION, NameKind=PREFIX)
202.7 -METHOD exc_clear()
202.8 -METHOD exc_info()
202.9 -METHOD excepthook(type, value, traceb
202.10 -METHOD exit(arg)
202.11 -VARIABLE ---exc_type ---
202.12 -VARIABLE exec_prefix
202.13 -VARIABLE executable
202.14 -VARIABLE ---exitfunc ---
203.1 --- a/python.editor/test/unit/data/testfiles/compl5.py Sun Jan 04 13:11:53 2015 -0600
203.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
203.3 @@ -1,19 +0,0 @@
203.4 -import unittest
203.5 -
203.6 -class MyTest(unittest.TestCase):
203.7 -
203.8 - def f(self)
203.9 - self.assertAlmostEquals(1,2)
203.10 - pass
203.11 -
203.12 -x = MyTest()
203.13 -x.r
203.14 -
203.15 -# @type os2 str
203.16 -os2.x
203.17 -# @type os3 int
203.18 -os3.x
203.19 -# @type os4 list
203.20 -os4.x
203.21 -os5.xhd
203.22 -
204.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testDoc6.html Sun Jan 04 13:11:53 2015 -0600
204.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
204.3 @@ -1,18 +0,0 @@
204.4 -<html><body>
204.5 -<pre>Code completion result for source line:
204.6 -self.assertA|lmostEquals(1,2)
204.7 -(QueryType=COMPLETION, NameKind=PREFIX)
204.8 -METHOD assertAlmostEquals(first, seco unittest
204.9 -</pre><h2>Documentation:</h2><pre><i>unittest</i><br><b>assertAlmostEquals</b>(<font color="#808080">self, first, second, places, msg</font>)</pre>
204.10 -
204.11 -<hr>
204.12 -Fail if the two objects are unequal as determined by their
204.13 - difference rounded to the given number of decimal places
204.14 - (default 7) and comparing to zero.
204.15 -
204.16 -<br><br>
204.17 - Note that decimal places (from zero) are usually not the same
204.18 - as significant digits (measured from the most signficant digit).
204.19 -
204.20 -<br><br>
204.21 -</body></html>
205.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testObjMethodCompletion10.completion Sun Jan 04 13:11:53 2015 -0600
205.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
205.3 @@ -1,8 +0,0 @@
205.4 -Code completion result for source line:
205.5 -class MyTest(unittest.T|estCase):
205.6 -(QueryType=COMPLETION, NameKind=PREFIX)
205.7 -CLASS TestCase
205.8 -CLASS TestLoader
205.9 -CLASS TestResult
205.10 -CLASS TestSuite
205.11 -CLASS TextTestRunner
206.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testObjMethodCompletion11.completion Sun Jan 04 13:11:53 2015 -0600
206.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
206.3 @@ -1,41 +0,0 @@
206.4 -Code completion result for source line:
206.5 -x.|r
206.6 -(QueryType=COMPLETION, NameKind=PREFIX)
206.7 -METHOD assertAlmostEqual(first, secon
206.8 -METHOD assertAlmostEquals(first, seco
206.9 -METHOD assertEqual(first, second, msg
206.10 -METHOD assertEquals(first, second, ms
206.11 -METHOD assertFalse(expr, msg)
206.12 -METHOD assertNotAlmostEqual(first, se
206.13 -METHOD assertNotAlmostEquals(first, s
206.14 -METHOD assertNotEqual(first, second,
206.15 -METHOD assertNotEquals(first, second,
206.16 -METHOD assertRaises(excClass, callabl
206.17 -METHOD assertTrue(expr, msg)
206.18 -METHOD assert_(expr, msg)
206.19 -METHOD countTestCases()
206.20 -METHOD debug()
206.21 -METHOD defaultTestResult()
206.22 -METHOD f()
206.23 -METHOD fail(msg)
206.24 -METHOD failIf(expr, msg)
206.25 -METHOD failIfAlmostEqual(first, secon
206.26 -METHOD failIfEqual(first, second, msg
206.27 -METHOD failUnless(expr, msg)
206.28 -METHOD failUnlessAlmostEqual(first, s
206.29 -METHOD failUnlessEqual(first, second,
206.30 -METHOD failUnlessRaises(excClass, cal
206.31 -METHOD id()
206.32 -METHOD run(result)
206.33 -METHOD setUp()
206.34 -METHOD shortDescription()
206.35 -METHOD tearDown()
206.36 -VARIABLE failureException
206.37 -------------------------------------
206.38 -CONSTRUCTO __init__(methodName)
206.39 -METHOD __call__(args, kwds)
206.40 -METHOD __repr__()
206.41 -METHOD __str__()
206.42 -ATTRIBUTE __dict__
206.43 -ATTRIBUTE ---__members__ ---
206.44 -ATTRIBUTE ---__methods__ ---
207.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testOverride1.completion Sun Jan 04 13:11:53 2015 -0600
207.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
207.3 @@ -1,38 +0,0 @@
207.4 -Code completion result for source line:
207.5 -class MyTest(unittest.TestCase):
207.6 - |
207.7 - def f(self)
207.8 -(QueryType=COMPLETION, NameKind=PREFIX)
207.9 -CONSTRUCTO __init__(methodName) - overrid
207.10 -METHOD __call__(args, kwds) - overrid
207.11 -METHOD __repr__() - override
207.12 -METHOD __str__() - override
207.13 -METHOD _exc_info() - override [PRIVATE]
207.14 -METHOD assertAlmostEqual(first, secon
207.15 -METHOD assertAlmostEquals(first, seco
207.16 -METHOD assertEqual(first, second, msg
207.17 -METHOD assertEquals(first, second, ms
207.18 -METHOD assertFalse(expr, msg) - overr
207.19 -METHOD assertNotAlmostEqual(first, se
207.20 -METHOD assertNotAlmostEquals(first, s
207.21 -METHOD assertNotEqual(first, second,
207.22 -METHOD assertNotEquals(first, second,
207.23 -METHOD assertRaises(excClass, callabl
207.24 -METHOD assertTrue(expr, msg) - overri
207.25 -METHOD assert_(expr, msg) - override
207.26 -METHOD countTestCases() - override
207.27 -METHOD debug() - override
207.28 -METHOD defaultTestResult() - override
207.29 -METHOD fail(msg) - override
207.30 -METHOD failIf(expr, msg) - override
207.31 -METHOD failIfAlmostEqual(first, secon
207.32 -METHOD failIfEqual(first, second, msg
207.33 -METHOD failUnless(expr, msg) - overri
207.34 -METHOD failUnlessAlmostEqual(first, s
207.35 -METHOD failUnlessEqual(first, second,
207.36 -METHOD failUnlessRaises(excClass, cal
207.37 -METHOD id() - override
207.38 -METHOD run(result) - override
207.39 -METHOD setUp() - override
207.40 -METHOD shortDescription() - override
207.41 -METHOD tearDown() - override
208.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testOverride2.completion Sun Jan 04 13:11:53 2015 -0600
208.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
208.3 @@ -1,36 +0,0 @@
208.4 -Code completion result for source line:
208.5 -def |f(self)
208.6 -(QueryType=COMPLETION, NameKind=PREFIX)
208.7 -CONSTRUCTO __init__(methodName) - overrid
208.8 -METHOD __call__(args, kwds) - overrid
208.9 -METHOD __repr__() - override
208.10 -METHOD __str__() - override
208.11 -METHOD _exc_info() - override [PRIVATE]
208.12 -METHOD assertAlmostEqual(first, secon
208.13 -METHOD assertAlmostEquals(first, seco
208.14 -METHOD assertEqual(first, second, msg
208.15 -METHOD assertEquals(first, second, ms
208.16 -METHOD assertFalse(expr, msg) - overr
208.17 -METHOD assertNotAlmostEqual(first, se
208.18 -METHOD assertNotAlmostEquals(first, s
208.19 -METHOD assertNotEqual(first, second,
208.20 -METHOD assertNotEquals(first, second,
208.21 -METHOD assertRaises(excClass, callabl
208.22 -METHOD assertTrue(expr, msg) - overri
208.23 -METHOD assert_(expr, msg) - override
208.24 -METHOD countTestCases() - override
208.25 -METHOD debug() - override
208.26 -METHOD defaultTestResult() - override
208.27 -METHOD fail(msg) - override
208.28 -METHOD failIf(expr, msg) - override
208.29 -METHOD failIfAlmostEqual(first, secon
208.30 -METHOD failIfEqual(first, second, msg
208.31 -METHOD failUnless(expr, msg) - overri
208.32 -METHOD failUnlessAlmostEqual(first, s
208.33 -METHOD failUnlessEqual(first, second,
208.34 -METHOD failUnlessRaises(excClass, cal
208.35 -METHOD id() - override
208.36 -METHOD run(result) - override
208.37 -METHOD setUp() - override
208.38 -METHOD shortDescription() - override
208.39 -METHOD tearDown() - override
209.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testTypedVars1.completion Sun Jan 04 13:11:53 2015 -0600
209.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
209.3 @@ -1,77 +0,0 @@
209.4 -Code completion result for source line:
209.5 -os2.|x
209.6 -(QueryType=COMPLETION, NameKind=PREFIX)
209.7 -METHOD capitalize()
209.8 -METHOD center(width, fillchar)
209.9 -METHOD count(sub, start, end)
209.10 -METHOD decode(encoding, errors)
209.11 -METHOD encode(encoding, errors)
209.12 -METHOD endswith(suffix, start, end)
209.13 -METHOD expandtabs(tabsize)
209.14 -METHOD find(sub, start, end)
209.15 -METHOD format(format_string, *args, *
209.16 -METHOD index(a)
209.17 -METHOD index(sub, start, end)
209.18 -METHOD isalnum()
209.19 -METHOD isalpha()
209.20 -METHOD isdigit()
209.21 -METHOD islower()
209.22 -METHOD isspace()
209.23 -METHOD istitle()
209.24 -METHOD isupper()
209.25 -METHOD join(seq)
209.26 -METHOD ljust(width, fillchar)
209.27 -METHOD lower()
209.28 -METHOD lstrip(chars)
209.29 -METHOD partition(sep)
209.30 -METHOD replace(old, new, count)
209.31 -METHOD rfind(sub, start, end)
209.32 -METHOD rindex(sub, start, end)
209.33 -METHOD rjust(width, fillchar)
209.34 -METHOD rpartition(sep)
209.35 -METHOD rsplit(sep, maxsplit)
209.36 -METHOD rstrip(chars)
209.37 -METHOD split(sep, maxsplit)
209.38 -METHOD splitlines(keepends)
209.39 -METHOD startswith(prefix, start, end)
209.40 -METHOD strip(chars)
209.41 -METHOD swapcase()
209.42 -METHOD title()
209.43 -METHOD translate(table, deletechars)
209.44 -METHOD upper()
209.45 -METHOD zfill(width)
209.46 -------------------------------------
209.47 -CONSTRUCTO __init__()
209.48 -METHOD __add__(a, b)
209.49 -METHOD __contains__(a, b)
209.50 -METHOD __delattr__(name)
209.51 -METHOD __eq__(a, b)
209.52 -METHOD __format__(format_spec)
209.53 -METHOD __ge__(a, b)
209.54 -METHOD __getattribute__(name)
209.55 -METHOD __getitem__(a, b)
209.56 -METHOD __getnewargs__()
209.57 -METHOD __getslice__(a, b, c)
209.58 -METHOD __gt__(a, b)
209.59 -METHOD __hash__()
209.60 -METHOD __le__(a, b)
209.61 -METHOD __len__()
209.62 -METHOD __lt__(a, b)
209.63 -METHOD __mod__(a, b)
209.64 -METHOD __mul__(a, b)
209.65 -METHOD __ne__(a, b)
209.66 -METHOD __new__(S, ___)
209.67 -METHOD __reduce__()
209.68 -METHOD __reduce_ex__()
209.69 -METHOD __repr__()
209.70 -METHOD __rmod__(y)
209.71 -METHOD __rmul__(n)
209.72 -METHOD __setattr__(name, value)
209.73 -METHOD __sizeof__()
209.74 -METHOD __str__()
209.75 -METHOD __subclasshook__()
209.76 -ATTRIBUTE __class__
209.77 -ATTRIBUTE __dict__
209.78 -ATTRIBUTE __doc__
209.79 -ATTRIBUTE ---__members__ ---
209.80 -ATTRIBUTE ---__methods__ ---
210.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testTypedVars2.completion Sun Jan 04 13:11:53 2015 -0600
210.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
210.3 @@ -1,70 +0,0 @@
210.4 -Code completion result for source line:
210.5 -os3.|x
210.6 -(QueryType=COMPLETION, NameKind=PREFIX)
210.7 -METHOD conjugate()
210.8 -ATTRIBUTE denominator
210.9 -ATTRIBUTE imag
210.10 -ATTRIBUTE numerator
210.11 -ATTRIBUTE real
210.12 -------------------------------------
210.13 -CONSTRUCTO __init__()
210.14 -METHOD __abs__(obj)
210.15 -METHOD __add__(a, b)
210.16 -METHOD __and__(a, b)
210.17 -METHOD __cmp__(y)
210.18 -METHOD __coerce__(y)
210.19 -METHOD __delattr__(name)
210.20 -METHOD __div__(a, b)
210.21 -METHOD __divmod__(y)
210.22 -METHOD __float__()
210.23 -METHOD __floordiv__(a, b)
210.24 -METHOD __format__()
210.25 -METHOD __getattribute__(name)
210.26 -METHOD __getnewargs__()
210.27 -METHOD __hash__()
210.28 -METHOD __hex__()
210.29 -METHOD __index__(a)
210.30 -METHOD __int__()
210.31 -METHOD __invert__(obj)
210.32 -METHOD __long__()
210.33 -METHOD __lshift__(a, b)
210.34 -METHOD __mod__(a, b)
210.35 -METHOD __mul__(a, b)
210.36 -METHOD __neg__(obj)
210.37 -METHOD __new__(S, ___)
210.38 -METHOD __nonzero__()
210.39 -METHOD __oct__()
210.40 -METHOD __or__(a, b)
210.41 -METHOD __pos__(obj)
210.42 -METHOD __pow__(a, b)
210.43 -METHOD __radd__(y)
210.44 -METHOD __rand__(y)
210.45 -METHOD __rdiv__(y)
210.46 -METHOD __rdivmod__(y)
210.47 -METHOD __reduce__()
210.48 -METHOD __reduce_ex__()
210.49 -METHOD __repr__()
210.50 -METHOD __rfloordiv__(y)
210.51 -METHOD __rlshift__(y)
210.52 -METHOD __rmod__(y)
210.53 -METHOD __rmul__(y)
210.54 -METHOD __ror__(y)
210.55 -METHOD __rpow__(x)
210.56 -METHOD __rrshift__(y)
210.57 -METHOD __rshift__(a, b)
210.58 -METHOD __rsub__(y)
210.59 -METHOD __rtruediv__(y)
210.60 -METHOD __rxor__(y)
210.61 -METHOD __setattr__(name, value)
210.62 -METHOD __sizeof__()
210.63 -METHOD __str__()
210.64 -METHOD __sub__(a, b)
210.65 -METHOD __subclasshook__()
210.66 -METHOD __truediv__(a, b)
210.67 -METHOD __trunc__()
210.68 -METHOD __xor__(a, b)
210.69 -ATTRIBUTE __class__
210.70 -ATTRIBUTE __dict__
210.71 -ATTRIBUTE __doc__
210.72 -ATTRIBUTE ---__members__ ---
210.73 -ATTRIBUTE ---__methods__ ---
211.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testTypedVars3.completion Sun Jan 04 13:11:53 2015 -0600
211.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
211.3 @@ -1,52 +0,0 @@
211.4 -Code completion result for source line:
211.5 -os4.|x
211.6 -(QueryType=COMPLETION, NameKind=PREFIX)
211.7 -METHOD append()
211.8 -METHOD count(value)
211.9 -METHOD extend()
211.10 -METHOD index(a)
211.11 -METHOD insert()
211.12 -METHOD pop()
211.13 -METHOD remove()
211.14 -METHOD reverse()
211.15 -METHOD sort(cmp, key, reverse)
211.16 -------------------------------------
211.17 -CONSTRUCTO __init__()
211.18 -METHOD __add__(a, b)
211.19 -METHOD __contains__(a, b)
211.20 -METHOD __delattr__(name)
211.21 -METHOD __delitem__(a, b)
211.22 -METHOD __delslice__(a, b, c)
211.23 -METHOD __eq__(a, b)
211.24 -METHOD __format__()
211.25 -METHOD __ge__(a, b)
211.26 -METHOD __getattribute__(name)
211.27 -METHOD __getitem__(a, b)
211.28 -METHOD __getslice__(a, b, c)
211.29 -METHOD __gt__(a, b)
211.30 -METHOD __iadd__(a, b)
211.31 -METHOD __imul__(a, b)
211.32 -METHOD __iter__()
211.33 -METHOD __le__(a, b)
211.34 -METHOD __len__()
211.35 -METHOD __lt__(a, b)
211.36 -METHOD __mul__(a, b)
211.37 -METHOD __ne__(a, b)
211.38 -METHOD __new__(S, ___)
211.39 -METHOD __reduce__()
211.40 -METHOD __reduce_ex__()
211.41 -METHOD __repr__()
211.42 -METHOD __reversed__()
211.43 -METHOD __rmul__(n)
211.44 -METHOD __setattr__(name, value)
211.45 -METHOD __setitem__(a, b, c)
211.46 -METHOD __setslice__(a, b, c, v)
211.47 -METHOD __sizeof__()
211.48 -METHOD __str__()
211.49 -METHOD __subclasshook__()
211.50 -ATTRIBUTE __class__
211.51 -ATTRIBUTE __dict__
211.52 -ATTRIBUTE __doc__
211.53 -ATTRIBUTE __hash__
211.54 -ATTRIBUTE ---__members__ ---
211.55 -ATTRIBUTE ---__methods__ ---
212.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testTypedVars4.completion Sun Jan 04 13:11:53 2015 -0600
212.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
212.3 @@ -1,6 +0,0 @@
212.4 -Code completion result for source line:
212.5 -os5.xhd|
212.6 -(QueryType=COMPLETION, NameKind=PREFIX)
212.7 -OTHER Specify type of <code>os5</cod
212.8 -------------------------------------
212.9 -METHOD xhdr(hdr, str, file)
213.1 --- a/python.editor/test/unit/data/testfiles/complete-calls.py Sun Jan 04 13:11:53 2015 -0600
213.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
213.3 @@ -1,23 +0,0 @@
213.4 -
213.5 -class _MyLocal():
213.6 - def __init__(self):
213.7 - pass
213.8 -
213.9 - def foo(self, param3, default=5):
213.10 - pass
213.11 -
213.12 - def bar(self):
213.13 - pass
213.14 -
213.15 -
213.16 -def functionfoo(param1,param2):
213.17 - """This is my documentation"""
213.18 - pass
213.19 -
213.20 -
213.21 -functionfoo(foo, bar)
213.22 -functionfoo("foo", "bar", invalid)
213.23 -y = _MyLocal()
213.24 -y.foo(xyz)
213.25 -y.foo(xyz, baz)
213.26 -
214.1 --- a/python.editor/test/unit/data/testfiles/complete-calls.py.testParameters1.completion Sun Jan 04 13:11:53 2015 -0600
214.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
214.3 @@ -1,4 +0,0 @@
214.4 -Code completion result for source line:
214.5 -functionfoo(foo|, bar)
214.6 -(QueryType=COMPLETION, NameKind=PREFIX)
214.7 -CALL functionfoo(param1, ...)
215.1 --- a/python.editor/test/unit/data/testfiles/complete-calls.py.testParameters2.completion Sun Jan 04 13:11:53 2015 -0600
215.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
215.3 @@ -1,4 +0,0 @@
215.4 -Code completion result for source line:
215.5 -functionfoo(foo, bar|)
215.6 -(QueryType=COMPLETION, NameKind=PREFIX)
215.7 -CALL functionfoo(... , param2)
216.1 --- a/python.editor/test/unit/data/testfiles/complete-calls.py.testParameters3.completion Sun Jan 04 13:11:53 2015 -0600
216.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
216.3 @@ -1,6 +0,0 @@
216.4 -Code completion result for source line:
216.5 -y.foo(x|yz)
216.6 -(QueryType=COMPLETION, NameKind=PREFIX)
216.7 -CALL foo(param3, ...)
216.8 -------------------------------------
216.9 -METHOD xrange(start, stop, step)
217.1 --- a/python.editor/test/unit/data/testfiles/complete-calls.py.testParameters4.completion Sun Jan 04 13:11:53 2015 -0600
217.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
217.3 @@ -1,10 +0,0 @@
217.4 -Code completion result for source line:
217.5 -y.foo(xyz, b|az)
217.6 -(QueryType=COMPLETION, NameKind=PREFIX)
217.7 -CALL foo(... , param3, ...)
217.8 -------------------------------------
217.9 -METHOD basestring()
217.10 -METHOD bin(x)
217.11 -METHOD bool(x)
217.12 -METHOD buffer(object, offset, size)
217.13 -KEYWORD break
218.1 --- a/python.editor/test/unit/data/testfiles/complete-calls.py.testParameters5.completion Sun Jan 04 13:11:53 2015 -0600
218.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
218.3 @@ -1,4 +0,0 @@
218.4 -Code completion result for source line:
218.5 -functionfoo("foo", "bar", inval|id)
218.6 -(QueryType=COMPLETION, NameKind=PREFIX)
218.7 -CALL functionfoo(param2)
219.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py Sun Jan 04 13:11:53 2015 -0600
219.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
219.3 @@ -1,14 +0,0 @@
219.4 -
219.5 -class DatagramRequestHandler(BaseRequestHandler):
219.6 - def setup(self):
219.7 - pass
219.8 -
219.9 - def handle(self):
219.10 - pass
219.11 -
219.12 - def finish(self):
219.13 - pass
219.14 -
219.15 - def already(self):
219.16 - """Already commented"""
219.17 -
220.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
220.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
220.3 @@ -1,15 +0,0 @@
220.4 -
220.5 -class DatagramRequestHandler(BaseRequestHandler):
220.6 - def setup(self):
220.7 - """"""
220.8 - pass
220.9 -
220.10 - def handle(self):
220.11 - pass
220.12 -
220.13 - def finish(self):
220.14 - pass
220.15 -
220.16 - def already(self):
220.17 - """Already commented"""
220.18 -
221.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
221.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
221.3 @@ -1,17 +0,0 @@
221.4 -
221.5 -class DatagramRequestHandler(BaseRequestHandler):
221.6 - def setup(self):
221.7 - """
221.8 -
221.9 - """
221.10 - pass
221.11 -
221.12 - def handle(self):
221.13 - pass
221.14 -
221.15 - def finish(self):
221.16 - pass
221.17 -
221.18 - def already(self):
221.19 - """Already commented"""
221.20 -
222.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py.testFix3.fixed Sun Jan 04 13:11:53 2015 -0600
222.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
222.3 @@ -1,15 +0,0 @@
222.4 -
222.5 -class DatagramRequestHandler(BaseRequestHandler):
222.6 - """"""
222.7 - def setup(self):
222.8 - pass
222.9 -
222.10 - def handle(self):
222.11 - pass
222.12 -
222.13 - def finish(self):
222.14 - pass
222.15 -
222.16 - def already(self):
222.17 - """Already commented"""
222.18 -
223.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py.testFix4.fixed Sun Jan 04 13:11:53 2015 -0600
223.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
223.3 @@ -1,17 +0,0 @@
223.4 -
223.5 -class DatagramRequestHandler(BaseRequestHandler):
223.6 - """
223.7 -
223.8 - """
223.9 - def setup(self):
223.10 - pass
223.11 -
223.12 - def handle(self):
223.13 - pass
223.14 -
223.15 - def finish(self):
223.16 - pass
223.17 -
223.18 - def already(self):
223.19 - """Already commented"""
223.20 -
224.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py.testHint1.hints Sun Jan 04 13:11:53 2015 -0600
224.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
224.3 @@ -1,5 +0,0 @@
224.4 - def set^up(self):
224.5 - -----
224.6 -HINT:Create document comment
224.7 -FIX:Add a one-liner docstring
224.8 -FIX:Add a multi-line docstring
225.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py.testHint3.hints Sun Jan 04 13:11:53 2015 -0600
225.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
225.3 @@ -1,5 +0,0 @@
225.4 -class Datagram^RequestHandler(BaseRequestHandler):
225.5 - ----------------------
225.6 -HINT:Create document comment
225.7 -FIX:Add a multi-line docstring
225.8 -FIX:Add a one-liner docstring
226.1 --- a/python.editor/test/unit/data/testfiles/create_docstring2.py Sun Jan 04 13:11:53 2015 -0600
226.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
226.3 @@ -1,3 +0,0 @@
226.4 -class Foo
226.5 - def faen(self)
226.6 - print hei
227.1 --- a/python.editor/test/unit/data/testfiles/create_docstring2.py.testFix5.fixed Sun Jan 04 13:11:53 2015 -0600
227.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
227.3 @@ -1,3 +0,0 @@
227.4 -class Foo
227.5 - def faen(self)
227.6 - print hei
228.1 --- a/python.editor/test/unit/data/testfiles/create_docstring3.py Sun Jan 04 13:11:53 2015 -0600
228.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
228.3 @@ -1,3 +0,0 @@
228.4 -class Foo
228.5 - def faen(self):
228.6 - print hei
229.1 --- a/python.editor/test/unit/data/testfiles/create_docstring3.py.testFix6.fixed 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 -class Foo
229.5 - def faen(self):
229.6 - """"""
229.7 - print hei
230.1 --- a/python.editor/test/unit/data/testfiles/create_docstring4.py Sun Jan 04 13:11:53 2015 -0600
230.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
230.3 @@ -1,10 +0,0 @@
230.4 -class Foo
230.5 - def faen(self):
230.6 - print hei
230.7 -
230.8 - def second(self):
230.9 - print hadet
230.10 -
230.11 - def ferdig(self):
230.12 - if true
230.13 -
231.1 --- a/python.editor/test/unit/data/testfiles/create_docstring4.py.testFix7.fixed Sun Jan 04 13:11:53 2015 -0600
231.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
231.3 @@ -1,11 +0,0 @@
231.4 -class Foo
231.5 - def faen(self):
231.6 - print hei
231.7 -
231.8 - def second(self):
231.9 - """"""
231.10 - print hadet
231.11 -
231.12 - def ferdig(self):
231.13 - if true
231.14 -
232.1 --- a/python.editor/test/unit/data/testfiles/datetime.py Sun Jan 04 13:11:53 2015 -0600
232.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
232.3 @@ -1,2008 +0,0 @@
232.4 -"""Concrete date/time and related types -- prototype implemented in Python.
232.5 -
232.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
232.7 -
232.8 -See also http://dir.yahoo.com/Reference/calendars/
232.9 -
232.10 -For a primer on DST, including many current DST rules, see
232.11 -http://webexhibits.org/daylightsaving/
232.12 -
232.13 -For more about DST than you ever wanted to know, see
232.14 -ftp://elsie.nci.nih.gov/pub/
232.15 -
232.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
232.17 -
232.18 -"""
232.19 -
232.20 -import time as _time
232.21 -import math as _math
232.22 -
232.23 -MINYEAR = 1
232.24 -MAXYEAR = 9999
232.25 -
232.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
232.27 -# also assumes the current Gregorian calendar indefinitely extended in
232.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
232.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
232.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
232.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
232.32 -# for all computations. See the book for algorithms for converting between
232.33 -# proleptic Gregorian ordinals and many other calendar systems.
232.34 -
232.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
232.36 -
232.37 -_DAYS_BEFORE_MONTH = [None]
232.38 -dbm = 0
232.39 -for dim in _DAYS_IN_MONTH[1:]:
232.40 - _DAYS_BEFORE_MONTH.append(dbm)
232.41 - dbm += dim
232.42 -del dbm, dim
232.43 -
232.44 -def _is_leap(year):
232.45 - "year -> 1 if leap year, else 0."
232.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
232.47 -
232.48 -def _days_in_year(year):
232.49 - "year -> number of days in year (366 if a leap year, else 365)."
232.50 - return 365 + _is_leap(year)
232.51 -
232.52 -def _days_before_year(year):
232.53 - "year -> number of days before January 1st of year."
232.54 - y = year - 1
232.55 - return y*365 + y//4 - y//100 + y//400
232.56 -
232.57 -def _days_in_month(year, month):
232.58 - "year, month -> number of days in that month in that year."
232.59 - assert 1 <= month <= 12, month
232.60 - if month == 2 and _is_leap(year):
232.61 - return 29
232.62 - return _DAYS_IN_MONTH[month]
232.63 -
232.64 -def _days_before_month(year, month):
232.65 - "year, month -> number of days in year preceeding first day of month."
232.66 - if not 1 <= month <= 12:
232.67 - raise ValueError('month must be in 1..12', month)
232.68 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
232.69 -
232.70 -def _ymd2ord(year, month, day):
232.71 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
232.72 - if not 1 <= month <= 12:
232.73 - raise ValueError('month must be in 1..12', month)
232.74 - dim = _days_in_month(year, month)
232.75 - if not 1 <= day <= dim:
232.76 - raise ValueError('day must be in 1..%d' % dim, day)
232.77 - return (_days_before_year(year) +
232.78 - _days_before_month(year, month) +
232.79 - day)
232.80 -
232.81 -_DI400Y = _days_before_year(401) # number of days in 400 years
232.82 -_DI100Y = _days_before_year(101) # " " " " 100 "
232.83 -_DI4Y = _days_before_year(5) # " " " " 4 "
232.84 -
232.85 -# A 4-year cycle has an extra leap day over what we'd get from pasting
232.86 -# together 4 single years.
232.87 -assert _DI4Y == 4 * 365 + 1
232.88 -
232.89 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
232.90 -# pasting together 4 100-year cycles.
232.91 -assert _DI400Y == 4 * _DI100Y + 1
232.92 -
232.93 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
232.94 -# pasting together 25 4-year cycles.
232.95 -assert _DI100Y == 25 * _DI4Y - 1
232.96 -
232.97 -def _ord2ymd(n):
232.98 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
232.99 -
232.100 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
232.101 - # repeats exactly every 400 years. The basic strategy is to find the
232.102 - # closest 400-year boundary at or before n, then work with the offset
232.103 - # from that boundary to n. Life is much clearer if we subtract 1 from
232.104 - # n first -- then the values of n at 400-year boundaries are exactly
232.105 - # those divisible by _DI400Y:
232.106 - #
232.107 - # D M Y n n-1
232.108 - # -- --- ---- ---------- ----------------
232.109 - # 31 Dec -400 -_DI400Y -_DI400Y -1
232.110 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
232.111 - # ...
232.112 - # 30 Dec 000 -1 -2
232.113 - # 31 Dec 000 0 -1
232.114 - # 1 Jan 001 1 0 400-year boundary
232.115 - # 2 Jan 001 2 1
232.116 - # 3 Jan 001 3 2
232.117 - # ...
232.118 - # 31 Dec 400 _DI400Y _DI400Y -1
232.119 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
232.120 - n -= 1
232.121 - n400, n = divmod(n, _DI400Y)
232.122 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
232.123 -
232.124 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
232.125 - # the desired date. Now compute how many 100-year cycles precede n.
232.126 - # Note that it's possible for n100 to equal 4! In that case 4 full
232.127 - # 100-year cycles precede the desired day, which implies the desired
232.128 - # day is December 31 at the end of a 400-year cycle.
232.129 - n100, n = divmod(n, _DI100Y)
232.130 -
232.131 - # Now compute how many 4-year cycles precede it.
232.132 - n4, n = divmod(n, _DI4Y)
232.133 -
232.134 - # And now how many single years. Again n1 can be 4, and again meaning
232.135 - # that the desired day is December 31 at the end of the 4-year cycle.
232.136 - n1, n = divmod(n, 365)
232.137 -
232.138 - year += n100 * 100 + n4 * 4 + n1
232.139 - if n1 == 4 or n100 == 4:
232.140 - assert n == 0
232.141 - return year-1, 12, 31
232.142 -
232.143 - # Now the year is correct, and n is the offset from January 1. We find
232.144 - # the month via an estimate that's either exact or one too large.
232.145 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
232.146 - assert leapyear == _is_leap(year)
232.147 - month = (n + 50) >> 5
232.148 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
232.149 - if preceding > n: # estimate is too large
232.150 - month -= 1
232.151 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
232.152 - n -= preceding
232.153 - assert 0 <= n < _days_in_month(year, month)
232.154 -
232.155 - # Now the year and month are correct, and n is the offset from the
232.156 - # start of that month: we're done!
232.157 - return year, month, n+1
232.158 -
232.159 -# Month and day names. For localized versions, see the calendar module.
232.160 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
232.161 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
232.162 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
232.163 -
232.164 -
232.165 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
232.166 - wday = (_ymd2ord(y, m, d) + 6) % 7
232.167 - dnum = _days_before_month(y, m) + d
232.168 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
232.169 -
232.170 -def _format_time(hh, mm, ss, us):
232.171 - # Skip trailing microseconds when us==0.
232.172 - result = "%02d:%02d:%02d" % (hh, mm, ss)
232.173 - if us:
232.174 - result += ".%06d" % us
232.175 - return result
232.176 -
232.177 -# Correctly substitute for %z and %Z escapes in strftime formats.
232.178 -def _wrap_strftime(object, format, timetuple):
232.179 - year = timetuple[0]
232.180 - if year < 1900:
232.181 - raise ValueError("year=%d is before 1900; the datetime strftime() "
232.182 - "methods require year >= 1900" % year)
232.183 - # Don't call _utcoffset() or tzname() unless actually needed.
232.184 - zreplace = None # the string to use for %z
232.185 - Zreplace = None # the string to use for %Z
232.186 -
232.187 - # Scan format for %z and %Z escapes, replacing as needed.
232.188 - newformat = []
232.189 - push = newformat.append
232.190 - i, n = 0, len(format)
232.191 - while i < n:
232.192 - ch = format[i]
232.193 - i += 1
232.194 - if ch == '%':
232.195 - if i < n:
232.196 - ch = format[i]
232.197 - i += 1
232.198 - if ch == 'z':
232.199 - if zreplace is None:
232.200 - zreplace = ""
232.201 - if hasattr(object, "_utcoffset"):
232.202 - offset = object._utcoffset()
232.203 - if offset is not None:
232.204 - sign = '+'
232.205 - if offset < 0:
232.206 - offset = -offset
232.207 - sign = '-'
232.208 - h, m = divmod(offset, 60)
232.209 - zreplace = '%c%02d%02d' % (sign, h, m)
232.210 - assert '%' not in zreplace
232.211 - newformat.append(zreplace)
232.212 - elif ch == 'Z':
232.213 - if Zreplace is None:
232.214 - Zreplace = ""
232.215 - if hasattr(object, "tzname"):
232.216 - s = object.tzname()
232.217 - if s is not None:
232.218 - # strftime is going to have at this: escape %
232.219 - Zreplace = s.replace('%', '%%')
232.220 - newformat.append(Zreplace)
232.221 - else:
232.222 - push('%')
232.223 - push(ch)
232.224 - else:
232.225 - push('%')
232.226 - else:
232.227 - push(ch)
232.228 - newformat = "".join(newformat)
232.229 - return _time.strftime(newformat, timetuple)
232.230 -
232.231 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
232.232 - if tzinfo is None:
232.233 - return None
232.234 - return getattr(tzinfo, methname)(tzinfoarg)
232.235 -
232.236 -# Just raise TypeError if the arg isn't None or a string.
232.237 -def _check_tzname(name):
232.238 - if name is not None and not isinstance(name, str):
232.239 - raise TypeError("tzinfo.tzname() must return None or string, "
232.240 - "not '%s'" % type(name))
232.241 -
232.242 -# name is the offset-producing method, "utcoffset" or "dst".
232.243 -# offset is what it returned.
232.244 -# If offset isn't None or timedelta, raises TypeError.
232.245 -# If offset is None, returns None.
232.246 -# Else offset is checked for being in range, and a whole # of minutes.
232.247 -# If it is, its integer value is returned. Else ValueError is raised.
232.248 -def _check_utc_offset(name, offset):
232.249 - assert name in ("utcoffset", "dst")
232.250 - if offset is None:
232.251 - return None
232.252 - if not isinstance(offset, timedelta):
232.253 - raise TypeError("tzinfo.%s() must return None "
232.254 - "or timedelta, not '%s'" % (name, type(offset)))
232.255 - days = offset.days
232.256 - if days < -1 or days > 0:
232.257 - offset = 1440 # trigger out-of-range
232.258 - else:
232.259 - seconds = days * 86400 + offset.seconds
232.260 - minutes, seconds = divmod(seconds, 60)
232.261 - if seconds or offset.microseconds:
232.262 - raise ValueError("tzinfo.%s() must return a whole number "
232.263 - "of minutes" % name)
232.264 - offset = minutes
232.265 - if -1440 < offset < 1440:
232.266 - return offset
232.267 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
232.268 -
232.269 -def _check_date_fields(year, month, day):
232.270 - if not MINYEAR <= year <= MAXYEAR:
232.271 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
232.272 - if not 1 <= month <= 12:
232.273 - raise ValueError('month must be in 1..12', month)
232.274 - dim = _days_in_month(year, month)
232.275 - if not 1 <= day <= dim:
232.276 - raise ValueError('day must be in 1..%d' % dim, day)
232.277 -
232.278 -def _check_time_fields(hour, minute, second, microsecond):
232.279 - if not 0 <= hour <= 23:
232.280 - raise ValueError('hour must be in 0..23', hour)
232.281 - if not 0 <= minute <= 59:
232.282 - raise ValueError('minute must be in 0..59', minute)
232.283 - if not 0 <= second <= 59:
232.284 - raise ValueError('second must be in 0..59', second)
232.285 - if not 0 <= microsecond <= 999999:
232.286 - raise ValueError('microsecond must be in 0..999999', microsecond)
232.287 -
232.288 -def _check_tzinfo_arg(tz):
232.289 - if tz is not None and not isinstance(tz, tzinfo):
232.290 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
232.291 -
232.292 -
232.293 -# Notes on comparison: In general, datetime module comparison operators raise
232.294 -# TypeError when they don't know how to do a comparison themself. If they
232.295 -# returned NotImplemented instead, comparison could (silently) fall back to
232.296 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
232.297 -# and that's not helpful. There are two exceptions:
232.298 -#
232.299 -# 1. For date and datetime, if the other object has a "timetuple" attr,
232.300 -# NotImplemented is returned. This is a hook to allow other kinds of
232.301 -# datetime-like objects a chance to intercept the comparison.
232.302 -#
232.303 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
232.304 -# so opertaions like
232.305 -#
232.306 -# x == y
232.307 -# x != y
232.308 -# x in sequence
232.309 -# x not in sequence
232.310 -# dict[x] = y
232.311 -#
232.312 -# don't raise annoying TypeErrors just because a datetime object
232.313 -# is part of a heterogeneous collection. If there's no known way to
232.314 -# compare X to a datetime, saying they're not equal is reasonable.
232.315 -
232.316 -def _cmperror(x, y):
232.317 - raise TypeError("can't compare '%s' to '%s'" % (
232.318 - type(x).__name__, type(y).__name__))
232.319 -
232.320 -# This is a start at a struct tm workalike. Goals:
232.321 -#
232.322 -# + Works the same way across platforms.
232.323 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
232.324 -#
232.325 -# Note: I suspect it's best if this flavor of tm does *not* try to
232.326 -# second-guess timezones or DST. Instead fold whatever adjustments you want
232.327 -# into the minutes argument (and the constructor will normalize).
232.328 -
232.329 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
232.330 -
232.331 -class tmxxx:
232.332 -
232.333 - ordinal = None
232.334 -
232.335 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
232.336 - microsecond=0):
232.337 - # Normalize all the inputs, and store the normalized values.
232.338 - if not 0 <= microsecond <= 999999:
232.339 - carry, microsecond = divmod(microsecond, 1000000)
232.340 - second += carry
232.341 - if not 0 <= second <= 59:
232.342 - carry, second = divmod(second, 60)
232.343 - minute += carry
232.344 - if not 0 <= minute <= 59:
232.345 - carry, minute = divmod(minute, 60)
232.346 - hour += carry
232.347 - if not 0 <= hour <= 23:
232.348 - carry, hour = divmod(hour, 24)
232.349 - day += carry
232.350 -
232.351 - # That was easy. Now it gets muddy: the proper range for day
232.352 - # can't be determined without knowing the correct month and year,
232.353 - # but if day is, e.g., plus or minus a million, the current month
232.354 - # and year values make no sense (and may also be out of bounds
232.355 - # themselves).
232.356 - # Saying 12 months == 1 year should be non-controversial.
232.357 - if not 1 <= month <= 12:
232.358 - carry, month = divmod(month-1, 12)
232.359 - year += carry
232.360 - month += 1
232.361 - assert 1 <= month <= 12
232.362 -
232.363 - # Now only day can be out of bounds (year may also be out of bounds
232.364 - # for a datetime object, but we don't care about that here).
232.365 - # If day is out of bounds, what to do is arguable, but at least the
232.366 - # method here is principled and explainable.
232.367 - dim = _days_in_month(year, month)
232.368 - if not 1 <= day <= dim:
232.369 - # Move day-1 days from the first of the month. First try to
232.370 - # get off cheap if we're only one day out of range (adjustments
232.371 - # for timezone alone can't be worse than that).
232.372 - if day == 0: # move back a day
232.373 - month -= 1
232.374 - if month > 0:
232.375 - day = _days_in_month(year, month)
232.376 - else:
232.377 - year, month, day = year-1, 12, 31
232.378 - elif day == dim + 1: # move forward a day
232.379 - month += 1
232.380 - day = 1
232.381 - if month > 12:
232.382 - month = 1
232.383 - year += 1
232.384 - else:
232.385 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
232.386 - year, month, day = _ord2ymd(self.ordinal)
232.387 -
232.388 - self.year, self.month, self.day = year, month, day
232.389 - self.hour, self.minute, self.second = hour, minute, second
232.390 - self.microsecond = microsecond
232.391 -
232.392 - def toordinal(self):
232.393 - """Return proleptic Gregorian ordinal for the year, month and day.
232.394 -
232.395 - January 1 of year 1 is day 1. Only the year, month and day values
232.396 - contribute to the result.
232.397 - """
232.398 - if self.ordinal is None:
232.399 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
232.400 - return self.ordinal
232.401 -
232.402 - def time(self):
232.403 - "Return Unixish timestamp, as a float (assuming UTC)."
232.404 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
232.405 - seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
232.406 - return seconds + self.second + self.microsecond / 1e6
232.407 -
232.408 - def ctime(self):
232.409 - "Return ctime() style string."
232.410 - weekday = self.toordinal() % 7 or 7
232.411 - return "%s %s %2d %02d:%02d:%02d %04d" % (
232.412 - _DAYNAMES[weekday],
232.413 - _MONTHNAMES[self.month],
232.414 - self.day,
232.415 - self.hour, self.minute, self.second,
232.416 - self.year)
232.417 -
232.418 -class timedelta(object):
232.419 - """Represent the difference between two datetime objects.
232.420 -
232.421 - Supported operators:
232.422 -
232.423 - - add, subtract timedelta
232.424 - - unary plus, minus, abs
232.425 - - compare to timedelta
232.426 - - multiply, divide by int/long
232.427 -
232.428 - In addition, datetime supports subtraction of two datetime objects
232.429 - returning a timedelta, and addition or subtraction of a datetime
232.430 - and a timedelta giving a datetime.
232.431 -
232.432 - Representation: (days, seconds, microseconds). Why? Because I
232.433 - felt like it.
232.434 - """
232.435 -
232.436 - def __new__(cls, days=0, seconds=0, microseconds=0,
232.437 - # XXX The following should only be used as keyword args:
232.438 - milliseconds=0, minutes=0, hours=0, weeks=0):
232.439 - # Doing this efficiently and accurately in C is going to be difficult
232.440 - # and error-prone, due to ubiquitous overflow possibilities, and that
232.441 - # C double doesn't have enough bits of precision to represent
232.442 - # microseconds over 10K years faithfully. The code here tries to make
232.443 - # explicit where go-fast assumptions can be relied on, in order to
232.444 - # guide the C implementation; it's way more convoluted than speed-
232.445 - # ignoring auto-overflow-to-long idiomatic Python could be.
232.446 -
232.447 - # XXX Check that all inputs are ints, longs or floats.
232.448 -
232.449 - # Final values, all integer.
232.450 - # s and us fit in 32-bit signed ints; d isn't bounded.
232.451 - d = s = us = 0
232.452 -
232.453 - # Normalize everything to days, seconds, microseconds.
232.454 - days += weeks*7
232.455 - seconds += minutes*60 + hours*3600
232.456 - microseconds += milliseconds*1000
232.457 -
232.458 - # Get rid of all fractions, and normalize s and us.
232.459 - # Take a deep breath <wink>.
232.460 - if isinstance(days, float):
232.461 - dayfrac, days = _math.modf(days)
232.462 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
232.463 - assert daysecondswhole == int(daysecondswhole) # can't overflow
232.464 - s = int(daysecondswhole)
232.465 - assert days == long(days)
232.466 - d = long(days)
232.467 - else:
232.468 - daysecondsfrac = 0.0
232.469 - d = days
232.470 - assert isinstance(daysecondsfrac, float)
232.471 - assert abs(daysecondsfrac) <= 1.0
232.472 - assert isinstance(d, (int, long))
232.473 - assert abs(s) <= 24 * 3600
232.474 - # days isn't referenced again before redefinition
232.475 -
232.476 - if isinstance(seconds, float):
232.477 - secondsfrac, seconds = _math.modf(seconds)
232.478 - assert seconds == long(seconds)
232.479 - seconds = long(seconds)
232.480 - secondsfrac += daysecondsfrac
232.481 - assert abs(secondsfrac) <= 2.0
232.482 - else:
232.483 - secondsfrac = daysecondsfrac
232.484 - # daysecondsfrac isn't referenced again
232.485 - assert isinstance(secondsfrac, float)
232.486 - assert abs(secondsfrac) <= 2.0
232.487 -
232.488 - assert isinstance(seconds, (int, long))
232.489 - days, seconds = divmod(seconds, 24*3600)
232.490 - d += days
232.491 - s += int(seconds) # can't overflow
232.492 - assert isinstance(s, int)
232.493 - assert abs(s) <= 2 * 24 * 3600
232.494 - # seconds isn't referenced again before redefinition
232.495 -
232.496 - usdouble = secondsfrac * 1e6
232.497 - assert abs(usdouble) < 2.1e6 # exact value not critical
232.498 - # secondsfrac isn't referenced again
232.499 -
232.500 - if isinstance(microseconds, float):
232.501 - microseconds += usdouble
232.502 - microseconds = round(microseconds)
232.503 - seconds, microseconds = divmod(microseconds, 1e6)
232.504 - assert microseconds == int(microseconds)
232.505 - assert seconds == long(seconds)
232.506 - days, seconds = divmod(seconds, 24.*3600.)
232.507 - assert days == long(days)
232.508 - assert seconds == int(seconds)
232.509 - d += long(days)
232.510 - s += int(seconds) # can't overflow
232.511 - assert isinstance(s, int)
232.512 - assert abs(s) <= 3 * 24 * 3600
232.513 - else:
232.514 - seconds, microseconds = divmod(microseconds, 1000000)
232.515 - days, seconds = divmod(seconds, 24*3600)
232.516 - d += days
232.517 - s += int(seconds) # can't overflow
232.518 - assert isinstance(s, int)
232.519 - assert abs(s) <= 3 * 24 * 3600
232.520 - microseconds = float(microseconds)
232.521 - microseconds += usdouble
232.522 - microseconds = round(microseconds)
232.523 - assert abs(s) <= 3 * 24 * 3600
232.524 - assert abs(microseconds) < 3.1e6
232.525 -
232.526 - # Just a little bit of carrying possible for microseconds and seconds.
232.527 - assert isinstance(microseconds, float)
232.528 - assert int(microseconds) == microseconds
232.529 - us = int(microseconds)
232.530 - seconds, us = divmod(us, 1000000)
232.531 - s += seconds # cant't overflow
232.532 - assert isinstance(s, int)
232.533 - days, s = divmod(s, 24*3600)
232.534 - d += days
232.535 -
232.536 - assert isinstance(d, (int, long))
232.537 - assert isinstance(s, int) and 0 <= s < 24*3600
232.538 - assert isinstance(us, int) and 0 <= us < 1000000
232.539 -
232.540 - self = object.__new__(cls)
232.541 -
232.542 - self.__days = d
232.543 - self.__seconds = s
232.544 - self.__microseconds = us
232.545 - if abs(d) > 999999999:
232.546 - raise OverflowError("timedelta # of days is too large: %d" % d)
232.547 -
232.548 - return self
232.549 -
232.550 - def __repr__(self):
232.551 - if self.__microseconds:
232.552 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
232.553 - self.__days,
232.554 - self.__seconds,
232.555 - self.__microseconds)
232.556 - if self.__seconds:
232.557 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
232.558 - self.__days,
232.559 - self.__seconds)
232.560 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
232.561 -
232.562 - def __str__(self):
232.563 - mm, ss = divmod(self.__seconds, 60)
232.564 - hh, mm = divmod(mm, 60)
232.565 - s = "%d:%02d:%02d" % (hh, mm, ss)
232.566 - if self.__days:
232.567 - def plural(n):
232.568 - return n, abs(n) != 1 and "s" or ""
232.569 - s = ("%d day%s, " % plural(self.__days)) + s
232.570 - if self.__microseconds:
232.571 - s = s + ".%06d" % self.__microseconds
232.572 - return s
232.573 -
232.574 - days = property(lambda self: self.__days, doc="days")
232.575 - seconds = property(lambda self: self.__seconds, doc="seconds")
232.576 - microseconds = property(lambda self: self.__microseconds,
232.577 - doc="microseconds")
232.578 -
232.579 - def __add__(self, other):
232.580 - if isinstance(other, timedelta):
232.581 - return timedelta(self.__days + other.__days,
232.582 - self.__seconds + other.__seconds,
232.583 - self.__microseconds + other.__microseconds)
232.584 - return NotImplemented
232.585 -
232.586 - __radd__ = __add__
232.587 -
232.588 - def __sub__(self, other):
232.589 - if isinstance(other, timedelta):
232.590 - return self + -other
232.591 - return NotImplemented
232.592 -
232.593 - def __rsub__(self, other):
232.594 - if isinstance(other, timedelta):
232.595 - return -self + other
232.596 - return NotImplemented
232.597 -
232.598 - def __neg__(self):
232.599 - return self.__class__(-self.__days,
232.600 - -self.__seconds,
232.601 - -self.__microseconds)
232.602 -
232.603 - def __pos__(self):
232.604 - return self
232.605 -
232.606 - def __abs__(self):
232.607 - if self.__days < 0:
232.608 - return -self
232.609 - else:
232.610 - return self
232.611 -
232.612 - def __mul__(self, other):
232.613 - if isinstance(other, (int, long)):
232.614 - return self.__class__(self.__days * other,
232.615 - self.__seconds * other,
232.616 - self.__microseconds * other)
232.617 - return NotImplemented
232.618 -
232.619 - __rmul__ = __mul__
232.620 -
232.621 - def __div__(self, other):
232.622 - if isinstance(other, (int, long)):
232.623 - usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
232.624 - self.__microseconds)
232.625 - return self.__class__(0, 0, usec // other)
232.626 - return NotImplemented
232.627 -
232.628 - __floordiv__ = __div__
232.629 -
232.630 - # Comparisons.
232.631 -
232.632 - def __eq__(self, other):
232.633 - if isinstance(other, timedelta):
232.634 - return self.__cmp(other) == 0
232.635 - else:
232.636 - return False
232.637 -
232.638 - def __ne__(self, other):
232.639 - if isinstance(other, timedelta):
232.640 - return self.__cmp(other) != 0
232.641 - else:
232.642 - return True
232.643 -
232.644 - def __le__(self, other):
232.645 - if isinstance(other, timedelta):
232.646 - return self.__cmp(other) <= 0
232.647 - else:
232.648 - _cmperror(self, other)
232.649 -
232.650 - def __lt__(self, other):
232.651 - if isinstance(other, timedelta):
232.652 - return self.__cmp(other) < 0
232.653 - else:
232.654 - _cmperror(self, other)
232.655 -
232.656 - def __ge__(self, other):
232.657 - if isinstance(other, timedelta):
232.658 - return self.__cmp(other) >= 0
232.659 - else:
232.660 - _cmperror(self, other)
232.661 -
232.662 - def __gt__(self, other):
232.663 - if isinstance(other, timedelta):
232.664 - return self.__cmp(other) > 0
232.665 - else:
232.666 - _cmperror(self, other)
232.667 -
232.668 - def __cmp(self, other):
232.669 - assert isinstance(other, timedelta)
232.670 - return cmp(self.__getstate(), other.__getstate())
232.671 -
232.672 - def __hash__(self):
232.673 - return hash(self.__getstate())
232.674 -
232.675 - def __nonzero__(self):
232.676 - return (self.__days != 0 or
232.677 - self.__seconds != 0 or
232.678 - self.__microseconds != 0)
232.679 -
232.680 - # Pickle support.
232.681 -
232.682 - __safe_for_unpickling__ = True # For Python 2.2
232.683 -
232.684 - def __getstate(self):
232.685 - return (self.__days, self.__seconds, self.__microseconds)
232.686 -
232.687 - def __reduce__(self):
232.688 - return (self.__class__, self.__getstate())
232.689 -
232.690 -timedelta.min = timedelta(-999999999)
232.691 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
232.692 - microseconds=999999)
232.693 -timedelta.resolution = timedelta(microseconds=1)
232.694 -
232.695 -class date(object):
232.696 - """Concrete date type.
232.697 -
232.698 - Constructors:
232.699 -
232.700 - __new__()
232.701 - fromtimestamp()
232.702 - today()
232.703 - fromordinal()
232.704 -
232.705 - Operators:
232.706 -
232.707 - __repr__, __str__
232.708 - __cmp__, __hash__
232.709 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
232.710 -
232.711 - Methods:
232.712 -
232.713 - timetuple()
232.714 - toordinal()
232.715 - weekday()
232.716 - isoweekday(), isocalendar(), isoformat()
232.717 - ctime()
232.718 - strftime()
232.719 -
232.720 - Properties (readonly):
232.721 - year, month, day
232.722 - """
232.723 -
232.724 - def __new__(cls, year, month=None, day=None):
232.725 - """Constructor.
232.726 -
232.727 - Arguments:
232.728 -
232.729 - year, month, day (required, base 1)
232.730 - """
232.731 - if isinstance(year, str):
232.732 - # Pickle support
232.733 - self = object.__new__(cls)
232.734 - self.__setstate((year,))
232.735 - return self
232.736 - _check_date_fields(year, month, day)
232.737 - self = object.__new__(cls)
232.738 - self.__year = year
232.739 - self.__month = month
232.740 - self.__day = day
232.741 - return self
232.742 -
232.743 - # Additional constructors
232.744 -
232.745 - def fromtimestamp(cls, t):
232.746 - "Construct a date from a POSIX timestamp (like time.time())."
232.747 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
232.748 - return cls(y, m, d)
232.749 - fromtimestamp = classmethod(fromtimestamp)
232.750 -
232.751 - def today(cls):
232.752 - "Construct a date from time.time()."
232.753 - t = _time.time()
232.754 - return cls.fromtimestamp(t)
232.755 - today = classmethod(today)
232.756 -
232.757 - def fromordinal(cls, n):
232.758 - """Contruct a date from a proleptic Gregorian ordinal.
232.759 -
232.760 - January 1 of year 1 is day 1. Only the year, month and day are
232.761 - non-zero in the result.
232.762 - """
232.763 - y, m, d = _ord2ymd(n)
232.764 - return cls(y, m, d)
232.765 - fromordinal = classmethod(fromordinal)
232.766 -
232.767 - # Conversions to string
232.768 -
232.769 - def __repr__(self):
232.770 - "Convert to formal string, for repr()."
232.771 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
232.772 - self.__year,
232.773 - self.__month,
232.774 - self.__day)
232.775 - # XXX These shouldn't depend on time.localtime(), because that
232.776 - # clips the usable dates to [1970 .. 2038). At least ctime() is
232.777 - # easily done without using strftime() -- that's better too because
232.778 - # strftime("%c", ...) is locale specific.
232.779 -
232.780 - def ctime(self):
232.781 - "Format a la ctime()."
232.782 - return tmxxx(self.__year, self.__month, self.__day).ctime()
232.783 -
232.784 - def strftime(self, fmt):
232.785 - "Format using strftime()."
232.786 - return _wrap_strftime(self, fmt, self.timetuple())
232.787 -
232.788 - def isoformat(self):
232.789 - """Return the date formatted according to ISO.
232.790 -
232.791 - This is 'YYYY-MM-DD'.
232.792 -
232.793 - References:
232.794 - - http://www.w3.org/TR/NOTE-datetime
232.795 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
232.796 - """
232.797 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
232.798 -
232.799 - __str__ = isoformat
232.800 -
232.801 - # Read-only field accessors
232.802 - year = property(lambda self: self.__year,
232.803 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
232.804 - month = property(lambda self: self.__month, doc="month (1-12)")
232.805 - day = property(lambda self: self.__day, doc="day (1-31)")
232.806 -
232.807 - # Standard conversions, __cmp__, __hash__ (and helpers)
232.808 -
232.809 - def timetuple(self):
232.810 - "Return local time tuple compatible with time.localtime()."
232.811 - return _build_struct_time(self.__year, self.__month, self.__day,
232.812 - 0, 0, 0, -1)
232.813 -
232.814 - def toordinal(self):
232.815 - """Return proleptic Gregorian ordinal for the year, month and day.
232.816 -
232.817 - January 1 of year 1 is day 1. Only the year, month and day values
232.818 - contribute to the result.
232.819 - """
232.820 - return _ymd2ord(self.__year, self.__month, self.__day)
232.821 -
232.822 - def replace(self, year=None, month=None, day=None):
232.823 - """Return a new date with new values for the specified fields."""
232.824 - if year is None:
232.825 - year = self.__year
232.826 - if month is None:
232.827 - month = self.__month
232.828 - if day is None:
232.829 - day = self.__day
232.830 - _check_date_fields(year, month, day)
232.831 - return date(year, month, day)
232.832 -
232.833 - # Comparisons.
232.834 -
232.835 - def __eq__(self, other):
232.836 - if isinstance(other, date):
232.837 - return self.__cmp(other) == 0
232.838 - elif hasattr(other, "timetuple"):
232.839 - return NotImplemented
232.840 - else:
232.841 - return False
232.842 -
232.843 - def __ne__(self, other):
232.844 - if isinstance(other, date):
232.845 - return self.__cmp(other) != 0
232.846 - elif hasattr(other, "timetuple"):
232.847 - return NotImplemented
232.848 - else:
232.849 - return True
232.850 -
232.851 - def __le__(self, other):
232.852 - if isinstance(other, date):
232.853 - return self.__cmp(other) <= 0
232.854 - elif hasattr(other, "timetuple"):
232.855 - return NotImplemented
232.856 - else:
232.857 - _cmperror(self, other)
232.858 -
232.859 - def __lt__(self, other):
232.860 - if isinstance(other, date):
232.861 - return self.__cmp(other) < 0
232.862 - elif hasattr(other, "timetuple"):
232.863 - return NotImplemented
232.864 - else:
232.865 - _cmperror(self, other)
232.866 -
232.867 - def __ge__(self, other):
232.868 - if isinstance(other, date):
232.869 - return self.__cmp(other) >= 0
232.870 - elif hasattr(other, "timetuple"):
232.871 - return NotImplemented
232.872 - else:
232.873 - _cmperror(self, other)
232.874 -
232.875 - def __gt__(self, other):
232.876 - if isinstance(other, date):
232.877 - return self.__cmp(other) > 0
232.878 - elif hasattr(other, "timetuple"):
232.879 - return NotImplemented
232.880 - else:
232.881 - _cmperror(self, other)
232.882 -
232.883 - def __cmp(self, other):
232.884 - assert isinstance(other, date)
232.885 - y, m, d = self.__year, self.__month, self.__day
232.886 - y2, m2, d2 = other.__year, other.__month, other.__day
232.887 - return cmp((y, m, d), (y2, m2, d2))
232.888 -
232.889 - def __hash__(self):
232.890 - "Hash."
232.891 - return hash(self.__getstate())
232.892 -
232.893 - # Computations
232.894 -
232.895 - def _checkOverflow(self, year):
232.896 - if not MINYEAR <= year <= MAXYEAR:
232.897 - raise OverflowError("date +/-: result year %d not in %d..%d" %
232.898 - (year, MINYEAR, MAXYEAR))
232.899 -
232.900 - def __add__(self, other):
232.901 - "Add a date to a timedelta."
232.902 - if isinstance(other, timedelta):
232.903 - t = tmxxx(self.__year,
232.904 - self.__month,
232.905 - self.__day + other.days)
232.906 - self._checkOverflow(t.year)
232.907 - result = self.__class__(t.year, t.month, t.day)
232.908 - return result
232.909 - return NotImplemented
232.910 -
232.911 - __radd__ = __add__
232.912 -
232.913 - def __sub__(self, other):
232.914 - """Subtract two dates, or a date and a timedelta."""
232.915 - if isinstance(other, timedelta):
232.916 - return self + timedelta(-other.days)
232.917 - if isinstance(other, date):
232.918 - days1 = self.toordinal()
232.919 - days2 = other.toordinal()
232.920 - return timedelta(days1 - days2)
232.921 - return NotImplemented
232.922 -
232.923 - def weekday(self):
232.924 - "Return day of the week, where Monday == 0 ... Sunday == 6."
232.925 - return (self.toordinal() + 6) % 7
232.926 -
232.927 - # Day-of-the-week and week-of-the-year, according to ISO
232.928 -
232.929 - def isoweekday(self):
232.930 - "Return day of the week, where Monday == 1 ... Sunday == 7."
232.931 - # 1-Jan-0001 is a Monday
232.932 - return self.toordinal() % 7 or 7
232.933 -
232.934 - def isocalendar(self):
232.935 - """Return a 3-tuple containing ISO year, week number, and weekday.
232.936 -
232.937 - The first ISO week of the year is the (Mon-Sun) week
232.938 - containing the year's first Thursday; everything else derives
232.939 - from that.
232.940 -
232.941 - The first week is 1; Monday is 1 ... Sunday is 7.
232.942 -
232.943 - ISO calendar algorithm taken from
232.944 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
232.945 - """
232.946 - year = self.__year
232.947 - week1monday = _isoweek1monday(year)
232.948 - today = _ymd2ord(self.__year, self.__month, self.__day)
232.949 - # Internally, week and day have origin 0
232.950 - week, day = divmod(today - week1monday, 7)
232.951 - if week < 0:
232.952 - year -= 1
232.953 - week1monday = _isoweek1monday(year)
232.954 - week, day = divmod(today - week1monday, 7)
232.955 - elif week >= 52:
232.956 - if today >= _isoweek1monday(year+1):
232.957 - year += 1
232.958 - week = 0
232.959 - return year, week+1, day+1
232.960 -
232.961 - # Pickle support.
232.962 -
232.963 - __safe_for_unpickling__ = True # For Python 2.2
232.964 -
232.965 - def __getstate(self):
232.966 - yhi, ylo = divmod(self.__year, 256)
232.967 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
232.968 -
232.969 - def __setstate(self, t):
232.970 - assert isinstance(t, tuple) and len(t) == 1, `t`
232.971 - string = t[0]
232.972 - assert len(string) == 4
232.973 - yhi, ylo, self.__month, self.__day = map(ord, string)
232.974 - self.__year = yhi * 256 + ylo
232.975 -
232.976 - def __reduce__(self):
232.977 - return (self.__class__, self.__getstate())
232.978 -
232.979 -_date_class = date # so functions w/ args named "date" can get at the class
232.980 -
232.981 -date.min = date(1, 1, 1)
232.982 -date.max = date(9999, 12, 31)
232.983 -date.resolution = timedelta(days=1)
232.984 -
232.985 -class tzinfo(object):
232.986 - """Abstract base class for time zone info classes.
232.987 -
232.988 - Subclasses must override the name(), utcoffset() and dst() methods.
232.989 - """
232.990 -
232.991 - def tzname(self, dt):
232.992 - "datetime -> string name of time zone."
232.993 - raise NotImplementedError("tzinfo subclass must override tzname()")
232.994 -
232.995 - def utcoffset(self, dt):
232.996 - "datetime -> minutes east of UTC (negative for west of UTC)"
232.997 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
232.998 -
232.999 - def dst(self, dt):
232.1000 - """datetime -> DST offset in minutes east of UTC.
232.1001 -
232.1002 - Return 0 if DST not in effect. utcoffset() must include the DST
232.1003 - offset.
232.1004 - """
232.1005 - raise NotImplementedError("tzinfo subclass must override dst()")
232.1006 -
232.1007 - def fromutc(self, dt):
232.1008 - "datetime in UTC -> datetime in local time."
232.1009 -
232.1010 - if not isinstance(dt, datetime):
232.1011 - raise TypeError("fromutc() requires a datetime argument")
232.1012 - if dt.tzinfo is not self:
232.1013 - raise ValueError("dt.tzinfo is not self")
232.1014 -
232.1015 - dtoff = dt.utcoffset()
232.1016 - if dtoff is None:
232.1017 - raise ValueError("fromutc() requires a non-None utcoffset() "
232.1018 - "result")
232.1019 -
232.1020 - # See the long comment block at the end of this file for an
232.1021 - # explanation of this algorithm.
232.1022 - dtdst = dt.dst()
232.1023 - if dtdst is None:
232.1024 - raise ValueError("fromutc() requires a non-None dst() result")
232.1025 - delta = dtoff - dtdst
232.1026 - if delta:
232.1027 - dt += delta
232.1028 - dtdst = dt.dst()
232.1029 - if dtdst is None:
232.1030 - raise ValueError("fromutc(): dt.dst gave inconsistent "
232.1031 - "results; cannot convert")
232.1032 - if dtdst:
232.1033 - return dt + dtdst
232.1034 - else:
232.1035 - return dt
232.1036 -
232.1037 - # Pickle support.
232.1038 -
232.1039 - __safe_for_unpickling__ = True # For Python 2.2
232.1040 -
232.1041 - def __reduce__(self):
232.1042 - getinitargs = getattr(self, "__getinitargs__", None)
232.1043 - if getinitargs:
232.1044 - args = getinitargs()
232.1045 - else:
232.1046 - args = ()
232.1047 - getstate = getattr(self, "__getstate__", None)
232.1048 - if getstate:
232.1049 - state = getstate()
232.1050 - else:
232.1051 - state = getattr(self, "__dict__", None) or None
232.1052 - if state is None:
232.1053 - return (self.__class__, args)
232.1054 - else:
232.1055 - return (self.__class__, args, state)
232.1056 -
232.1057 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
232.1058 -
232.1059 -class time(object):
232.1060 - """Time with time zone.
232.1061 -
232.1062 - Constructors:
232.1063 -
232.1064 - __new__()
232.1065 -
232.1066 - Operators:
232.1067 -
232.1068 - __repr__, __str__
232.1069 - __cmp__, __hash__
232.1070 -
232.1071 - Methods:
232.1072 -
232.1073 - strftime()
232.1074 - isoformat()
232.1075 - utcoffset()
232.1076 - tzname()
232.1077 - dst()
232.1078 -
232.1079 - Properties (readonly):
232.1080 - hour, minute, second, microsecond, tzinfo
232.1081 - """
232.1082 -
232.1083 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
232.1084 - """Constructor.
232.1085 -
232.1086 - Arguments:
232.1087 -
232.1088 - hour, minute (required)
232.1089 - second, microsecond (default to zero)
232.1090 - tzinfo (default to None)
232.1091 - """
232.1092 - self = object.__new__(cls)
232.1093 - if isinstance(hour, str):
232.1094 - # Pickle support
232.1095 - self.__setstate((hour, minute or None))
232.1096 - return self
232.1097 - _check_tzinfo_arg(tzinfo)
232.1098 - _check_time_fields(hour, minute, second, microsecond)
232.1099 - self.__hour = hour
232.1100 - self.__minute = minute
232.1101 - self.__second = second
232.1102 - self.__microsecond = microsecond
232.1103 - self._tzinfo = tzinfo
232.1104 - return self
232.1105 -
232.1106 - # Read-only field accessors
232.1107 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
232.1108 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
232.1109 - second = property(lambda self: self.__second, doc="second (0-59)")
232.1110 - microsecond = property(lambda self: self.__microsecond,
232.1111 - doc="microsecond (0-999999)")
232.1112 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
232.1113 -
232.1114 - # Standard conversions, __hash__ (and helpers)
232.1115 -
232.1116 - # Comparisons.
232.1117 -
232.1118 - def __eq__(self, other):
232.1119 - if isinstance(other, time):
232.1120 - return self.__cmp(other) == 0
232.1121 - else:
232.1122 - return False
232.1123 -
232.1124 - def __ne__(self, other):
232.1125 - if isinstance(other, time):
232.1126 - return self.__cmp(other) != 0
232.1127 - else:
232.1128 - return True
232.1129 -
232.1130 - def __le__(self, other):
232.1131 - if isinstance(other, time):
232.1132 - return self.__cmp(other) <= 0
232.1133 - else:
232.1134 - _cmperror(self, other)
232.1135 -
232.1136 - def __lt__(self, other):
232.1137 - if isinstance(other, time):
232.1138 - return self.__cmp(other) < 0
232.1139 - else:
232.1140 - _cmperror(self, other)
232.1141 -
232.1142 - def __ge__(self, other):
232.1143 - if isinstance(other, time):
232.1144 - return self.__cmp(other) >= 0
232.1145 - else:
232.1146 - _cmperror(self, other)
232.1147 -
232.1148 - def __gt__(self, other):
232.1149 - if isinstance(other, time):
232.1150 - return self.__cmp(other) > 0
232.1151 - else:
232.1152 - _cmperror(self, other)
232.1153 -
232.1154 - def __cmp(self, other):
232.1155 - assert isinstance(other, time)
232.1156 - mytz = self._tzinfo
232.1157 - ottz = other._tzinfo
232.1158 - myoff = otoff = None
232.1159 -
232.1160 - if mytz is ottz:
232.1161 - base_compare = True
232.1162 - else:
232.1163 - myoff = self._utcoffset()
232.1164 - otoff = other._utcoffset()
232.1165 - base_compare = myoff == otoff
232.1166 -
232.1167 - if base_compare:
232.1168 - return cmp((self.__hour, self.__minute, self.__second,
232.1169 - self.__microsecond),
232.1170 - (other.__hour, other.__minute, other.__second,
232.1171 - other.__microsecond))
232.1172 - if myoff is None or otoff is None:
232.1173 - # XXX Buggy in 2.2.2.
232.1174 - raise TypeError("cannot compare naive and aware times")
232.1175 - myhhmm = self.__hour * 60 + self.__minute - myoff
232.1176 - othhmm = other.__hour * 60 + other.__minute - otoff
232.1177 - return cmp((myhhmm, self.__second, self.__microsecond),
232.1178 - (othhmm, other.__second, other.__microsecond))
232.1179 -
232.1180 - def __hash__(self):
232.1181 - """Hash."""
232.1182 - tzoff = self._utcoffset()
232.1183 - if not tzoff: # zero or None
232.1184 - return hash(self.__getstate()[0])
232.1185 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
232.1186 - if 0 <= h < 24:
232.1187 - return hash(time(h, m, self.second, self.microsecond))
232.1188 - return hash((h, m, self.second, self.microsecond))
232.1189 -
232.1190 - # Conversion to string
232.1191 -
232.1192 - def _tzstr(self, sep=":"):
232.1193 - """Return formatted timezone offset (+xx:xx) or None."""
232.1194 - off = self._utcoffset()
232.1195 - if off is not None:
232.1196 - if off < 0:
232.1197 - sign = "-"
232.1198 - off = -off
232.1199 - else:
232.1200 - sign = "+"
232.1201 - hh, mm = divmod(off, 60)
232.1202 - assert 0 <= hh < 24
232.1203 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
232.1204 - return off
232.1205 -
232.1206 - def __repr__(self):
232.1207 - """Convert to formal string, for repr()."""
232.1208 - if self.__microsecond != 0:
232.1209 - s = ", %d, %d" % (self.__second, self.__microsecond)
232.1210 - elif self.__second != 0:
232.1211 - s = ", %d" % self.__second
232.1212 - else:
232.1213 - s = ""
232.1214 - s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
232.1215 - self.__hour, self.__minute, s)
232.1216 - if self._tzinfo is not None:
232.1217 - assert s[-1:] == ")"
232.1218 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
232.1219 - return s
232.1220 -
232.1221 - def isoformat(self):
232.1222 - """Return the time formatted according to ISO.
232.1223 -
232.1224 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
232.1225 - self.microsecond == 0.
232.1226 - """
232.1227 - s = _format_time(self.__hour, self.__minute, self.__second,
232.1228 - self.__microsecond)
232.1229 - tz = self._tzstr()
232.1230 - if tz:
232.1231 - s += tz
232.1232 - return s
232.1233 -
232.1234 - __str__ = isoformat
232.1235 -
232.1236 - def strftime(self, fmt):
232.1237 - """Format using strftime(). The date part of the timestamp passed
232.1238 - to underlying strftime should not be used.
232.1239 - """
232.1240 - # The year must be >= 1900 else Python's strftime implementation
232.1241 - # can raise a bogus exception.
232.1242 - timetuple = (1900, 1, 1,
232.1243 - self.__hour, self.__minute, self.__second,
232.1244 - 0, 1, -1)
232.1245 - return _wrap_strftime(self, fmt, timetuple)
232.1246 -
232.1247 - # Timezone functions
232.1248 -
232.1249 - def utcoffset(self):
232.1250 - """Return the timezone offset in minutes east of UTC (negative west of
232.1251 - UTC)."""
232.1252 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
232.1253 - offset = _check_utc_offset("utcoffset", offset)
232.1254 - if offset is not None:
232.1255 - offset = timedelta(minutes=offset)
232.1256 - return offset
232.1257 -
232.1258 - # Return an integer (or None) instead of a timedelta (or None).
232.1259 - def _utcoffset(self):
232.1260 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
232.1261 - offset = _check_utc_offset("utcoffset", offset)
232.1262 - return offset
232.1263 -
232.1264 - def tzname(self):
232.1265 - """Return the timezone name.
232.1266 -
232.1267 - Note that the name is 100% informational -- there's no requirement that
232.1268 - it mean anything in particular. For example, "GMT", "UTC", "-500",
232.1269 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
232.1270 - """
232.1271 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
232.1272 - _check_tzname(name)
232.1273 - return name
232.1274 -
232.1275 - def dst(self):
232.1276 - """Return 0 if DST is not in effect, or the DST offset (in minutes
232.1277 - eastward) if DST is in effect.
232.1278 -
232.1279 - This is purely informational; the DST offset has already been added to
232.1280 - the UTC offset returned by utcoffset() if applicable, so there's no
232.1281 - need to consult dst() unless you're interested in displaying the DST
232.1282 - info.
232.1283 - """
232.1284 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
232.1285 - offset = _check_utc_offset("dst", offset)
232.1286 - if offset is not None:
232.1287 - offset = timedelta(minutes=offset)
232.1288 - return offset
232.1289 -
232.1290 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
232.1291 - tzinfo=True):
232.1292 - """Return a new time with new values for the specified fields."""
232.1293 - if hour is None:
232.1294 - hour = self.hour
232.1295 - if minute is None:
232.1296 - minute = self.minute
232.1297 - if second is None:
232.1298 - second = self.second
232.1299 - if microsecond is None:
232.1300 - microsecond = self.microsecond
232.1301 - if tzinfo is True:
232.1302 - tzinfo = self.tzinfo
232.1303 - _check_time_fields(hour, minute, second, microsecond)
232.1304 - _check_tzinfo_arg(tzinfo)
232.1305 - return time(hour, minute, second, microsecond, tzinfo)
232.1306 -
232.1307 - # Return an integer (or None) instead of a timedelta (or None).
232.1308 - def _dst(self):
232.1309 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
232.1310 - offset = _check_utc_offset("dst", offset)
232.1311 - return offset
232.1312 -
232.1313 - def __nonzero__(self):
232.1314 - if self.second or self.microsecond:
232.1315 - return 1
232.1316 - offset = self._utcoffset() or 0
232.1317 - return self.hour * 60 + self.minute - offset != 0
232.1318 -
232.1319 - # Pickle support.
232.1320 -
232.1321 - __safe_for_unpickling__ = True # For Python 2.2
232.1322 -
232.1323 - def __getstate(self):
232.1324 - us2, us3 = divmod(self.__microsecond, 256)
232.1325 - us1, us2 = divmod(us2, 256)
232.1326 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
232.1327 - us1, us2, us3)
232.1328 - if self._tzinfo is None:
232.1329 - return (basestate,)
232.1330 - else:
232.1331 - return (basestate, self._tzinfo)
232.1332 -
232.1333 - def __setstate(self, state):
232.1334 - assert isinstance(state, tuple)
232.1335 - assert 1 <= len(state) <= 2
232.1336 - string = state[0]
232.1337 - assert len(string) == 6
232.1338 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
232.1339 - map(ord, string)
232.1340 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
232.1341 - if len(state) == 1:
232.1342 - self._tzinfo = None
232.1343 - else:
232.1344 - self._tzinfo = state[1]
232.1345 -
232.1346 - def __reduce__(self):
232.1347 - return (self.__class__, self.__getstate())
232.1348 -
232.1349 -_time_class = time # so functions w/ args named "time" can get at the class
232.1350 -
232.1351 -time.min = time(0, 0, 0)
232.1352 -time.max = time(23, 59, 59, 999999)
232.1353 -time.resolution = timedelta(microseconds=1)
232.1354 -
232.1355 -class datetime(date):
232.1356 -
232.1357 - # XXX needs docstrings
232.1358 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
232.1359 -
232.1360 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
232.1361 - microsecond=0, tzinfo=None):
232.1362 - if isinstance(year, str):
232.1363 - # Pickle support
232.1364 - self = date.__new__(cls, year[:4])
232.1365 - self.__setstate((year, month))
232.1366 - return self
232.1367 - _check_tzinfo_arg(tzinfo)
232.1368 - _check_time_fields(hour, minute, second, microsecond)
232.1369 - self = date.__new__(cls, year, month, day)
232.1370 - # XXX This duplicates __year, __month, __day for convenience :-(
232.1371 - self.__year = year
232.1372 - self.__month = month
232.1373 - self.__day = day
232.1374 - self.__hour = hour
232.1375 - self.__minute = minute
232.1376 - self.__second = second
232.1377 - self.__microsecond = microsecond
232.1378 - self._tzinfo = tzinfo
232.1379 - return self
232.1380 -
232.1381 - # Read-only field accessors
232.1382 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
232.1383 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
232.1384 - second = property(lambda self: self.__second, doc="second (0-59)")
232.1385 - microsecond = property(lambda self: self.__microsecond,
232.1386 - doc="microsecond (0-999999)")
232.1387 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
232.1388 -
232.1389 - def fromtimestamp(cls, t, tz=None):
232.1390 - """Construct a datetime from a POSIX timestamp (like time.time()).
232.1391 -
232.1392 - A timezone info object may be passed in as well.
232.1393 - """
232.1394 -
232.1395 - _check_tzinfo_arg(tz)
232.1396 - if tz is None:
232.1397 - converter = _time.localtime
232.1398 - else:
232.1399 - converter = _time.gmtime
232.1400 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
232.1401 - us = int((t % 1.0) * 1000000)
232.1402 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
232.1403 - result = cls(y, m, d, hh, mm, ss, us, tz)
232.1404 - if tz is not None:
232.1405 - result = tz.fromutc(result)
232.1406 - return result
232.1407 - fromtimestamp = classmethod(fromtimestamp)
232.1408 -
232.1409 - def utcfromtimestamp(cls, t):
232.1410 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
232.1411 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
232.1412 - us = int((t % 1.0) * 1000000)
232.1413 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
232.1414 - return cls(y, m, d, hh, mm, ss, us)
232.1415 - utcfromtimestamp = classmethod(utcfromtimestamp)
232.1416 -
232.1417 - # XXX This is supposed to do better than we *can* do by using time.time(),
232.1418 - # XXX if the platform supports a more accurate way. The C implementation
232.1419 - # XXX uses gettimeofday on platforms that have it, but that isn't
232.1420 - # XXX available from Python. So now() may return different results
232.1421 - # XXX across the implementations.
232.1422 - def now(cls, tz=None):
232.1423 - "Construct a datetime from time.time() and optional time zone info."
232.1424 - t = _time.time()
232.1425 - return cls.fromtimestamp(t, tz)
232.1426 - now = classmethod(now)
232.1427 -
232.1428 - def utcnow(cls):
232.1429 - "Construct a UTC datetime from time.time()."
232.1430 - t = _time.time()
232.1431 - return cls.utcfromtimestamp(t)
232.1432 - utcnow = classmethod(utcnow)
232.1433 -
232.1434 - def combine(cls, date, time):
232.1435 - "Construct a datetime from a given date and a given time."
232.1436 - if not isinstance(date, _date_class):
232.1437 - raise TypeError("date argument must be a date instance")
232.1438 - if not isinstance(time, _time_class):
232.1439 - raise TypeError("time argument must be a time instance")
232.1440 - return cls(date.year, date.month, date.day,
232.1441 - time.hour, time.minute, time.second, time.microsecond,
232.1442 - time.tzinfo)
232.1443 - combine = classmethod(combine)
232.1444 -
232.1445 - def timetuple(self):
232.1446 - "Return local time tuple compatible with time.localtime()."
232.1447 - dst = self._dst()
232.1448 - if dst is None:
232.1449 - dst = -1
232.1450 - elif dst:
232.1451 - dst = 1
232.1452 - return _build_struct_time(self.year, self.month, self.day,
232.1453 - self.hour, self.minute, self.second,
232.1454 - dst)
232.1455 -
232.1456 - def utctimetuple(self):
232.1457 - "Return UTC time tuple compatible with time.gmtime()."
232.1458 - y, m, d = self.year, self.month, self.day
232.1459 - hh, mm, ss = self.hour, self.minute, self.second
232.1460 - offset = self._utcoffset()
232.1461 - if offset: # neither None nor 0
232.1462 - tm = tmxxx(y, m, d, hh, mm - offset)
232.1463 - y, m, d = tm.year, tm.month, tm.day
232.1464 - hh, mm = tm.hour, tm.minute
232.1465 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
232.1466 -
232.1467 - def date(self):
232.1468 - "Return the date part."
232.1469 - return date(self.__year, self.__month, self.__day)
232.1470 -
232.1471 - def time(self):
232.1472 - "Return the time part, with tzinfo None."
232.1473 - return time(self.hour, self.minute, self.second, self.microsecond)
232.1474 -
232.1475 - def timetz(self):
232.1476 - "Return the time part, with same tzinfo."
232.1477 - return time(self.hour, self.minute, self.second, self.microsecond,
232.1478 - self._tzinfo)
232.1479 -
232.1480 - def replace(self, year=None, month=None, day=None, hour=None,
232.1481 - minute=None, second=None, microsecond=None, tzinfo=True):
232.1482 - """Return a new datetime with new values for the specified fields."""
232.1483 - if year is None:
232.1484 - year = self.year
232.1485 - if month is None:
232.1486 - month = self.month
232.1487 - if day is None:
232.1488 - day = self.day
232.1489 - if hour is None:
232.1490 - hour = self.hour
232.1491 - if minute is None:
232.1492 - minute = self.minute
232.1493 - if second is None:
232.1494 - second = self.second
232.1495 - if microsecond is None:
232.1496 - microsecond = self.microsecond
232.1497 - if tzinfo is True:
232.1498 - tzinfo = self.tzinfo
232.1499 - _check_date_fields(year, month, day)
232.1500 - _check_time_fields(hour, minute, second, microsecond)
232.1501 - _check_tzinfo_arg(tzinfo)
232.1502 - return datetime(year, month, day, hour, minute, second,
232.1503 - microsecond, tzinfo)
232.1504 -
232.1505 - def astimezone(self, tz):
232.1506 - if not isinstance(tz, tzinfo):
232.1507 - raise TypeError("tz argument must be an instance of tzinfo")
232.1508 -
232.1509 - mytz = self.tzinfo
232.1510 - if mytz is None:
232.1511 - raise ValueError("astimezone() requires an aware datetime")
232.1512 -
232.1513 - if tz is mytz:
232.1514 - return self
232.1515 -
232.1516 - # Convert self to UTC, and attach the new time zone object.
232.1517 - myoffset = self.utcoffset()
232.1518 - if myoffset is None:
232.1519 - raise ValuError("astimezone() requires an aware datetime")
232.1520 - utc = (self - myoffset).replace(tzinfo=tz)
232.1521 -
232.1522 - # Convert from UTC to tz's local time.
232.1523 - return tz.fromutc(utc)
232.1524 -
232.1525 - # Ways to produce a string.
232.1526 -
232.1527 - def ctime(self):
232.1528 - "Format a la ctime()."
232.1529 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
232.1530 - self.__minute, self.__second)
232.1531 - return t.ctime()
232.1532 -
232.1533 - def isoformat(self, sep='T'):
232.1534 - """Return the time formatted according to ISO.
232.1535 -
232.1536 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
232.1537 - self.microsecond == 0.
232.1538 -
232.1539 - If self.tzinfo is not None, the UTC offset is also attached, giving
232.1540 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
232.1541 -
232.1542 - Optional argument sep specifies the separator between date and
232.1543 - time, default 'T'.
232.1544 - """
232.1545 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
232.1546 - sep) +
232.1547 - _format_time(self.__hour, self.__minute, self.__second,
232.1548 - self.__microsecond))
232.1549 - off = self._utcoffset()
232.1550 - if off is not None:
232.1551 - if off < 0:
232.1552 - sign = "-"
232.1553 - off = -off
232.1554 - else:
232.1555 - sign = "+"
232.1556 - hh, mm = divmod(off, 60)
232.1557 - s += "%s%02d:%02d" % (sign, hh, mm)
232.1558 - return s
232.1559 -
232.1560 - def __repr__(self):
232.1561 - "Convert to formal string, for repr()."
232.1562 - L = [self.__year, self.__month, self.__day, # These are never zero
232.1563 - self.__hour, self.__minute, self.__second, self.__microsecond]
232.1564 - if L[-1] == 0:
232.1565 - del L[-1]
232.1566 - if L[-1] == 0:
232.1567 - del L[-1]
232.1568 - s = ", ".join(map(str, L))
232.1569 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
232.1570 - if self._tzinfo is not None:
232.1571 - assert s[-1:] == ")"
232.1572 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
232.1573 - return s
232.1574 -
232.1575 - def __str__(self):
232.1576 - "Convert to string, for str()."
232.1577 - return self.isoformat(sep=' ')
232.1578 -
232.1579 - def utcoffset(self):
232.1580 - """Return the timezone offset in minutes east of UTC (negative west of
232.1581 - UTC)."""
232.1582 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
232.1583 - offset = _check_utc_offset("utcoffset", offset)
232.1584 - if offset is not None:
232.1585 - offset = timedelta(minutes=offset)
232.1586 - return offset
232.1587 -
232.1588 - # Return an integer (or None) instead of a timedelta (or None).
232.1589 - def _utcoffset(self):
232.1590 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
232.1591 - offset = _check_utc_offset("utcoffset", offset)
232.1592 - return offset
232.1593 -
232.1594 - def tzname(self):
232.1595 - """Return the timezone name.
232.1596 -
232.1597 - Note that the name is 100% informational -- there's no requirement that
232.1598 - it mean anything in particular. For example, "GMT", "UTC", "-500",
232.1599 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
232.1600 - """
232.1601 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
232.1602 - _check_tzname(name)
232.1603 - return name
232.1604 -
232.1605 - def dst(self):
232.1606 - """Return 0 if DST is not in effect, or the DST offset (in minutes
232.1607 - eastward) if DST is in effect.
232.1608 -
232.1609 - This is purely informational; the DST offset has already been added to
232.1610 - the UTC offset returned by utcoffset() if applicable, so there's no
232.1611 - need to consult dst() unless you're interested in displaying the DST
232.1612 - info.
232.1613 - """
232.1614 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
232.1615 - offset = _check_utc_offset("dst", offset)
232.1616 - if offset is not None:
232.1617 - offset = timedelta(minutes=offset)
232.1618 - return offset
232.1619 -
232.1620 - # Return an integer (or None) instead of a timedelta (or None).1573
232.1621 - def _dst(self):
232.1622 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
232.1623 - offset = _check_utc_offset("dst", offset)
232.1624 - return offset
232.1625 -
232.1626 - # Comparisons.
232.1627 -
232.1628 - def __eq__(self, other):
232.1629 - if isinstance(other, datetime):
232.1630 - return self.__cmp(other) == 0
232.1631 - elif hasattr(other, "timetuple"):
232.1632 - return NotImplemented
232.1633 - else:
232.1634 - return False
232.1635 -
232.1636 - def __ne__(self, other):
232.1637 - if isinstance(other, datetime):
232.1638 - return self.__cmp(other) != 0
232.1639 - elif hasattr(other, "timetuple"):
232.1640 - return NotImplemented
232.1641 - else:
232.1642 - return True
232.1643 -
232.1644 - def __le__(self, other):
232.1645 - if isinstance(other, datetime):
232.1646 - return self.__cmp(other) <= 0
232.1647 - elif hasattr(other, "timetuple"):
232.1648 - return NotImplemented
232.1649 - else:
232.1650 - _cmperror(self, other)
232.1651 -
232.1652 - def __lt__(self, other):
232.1653 - if isinstance(other, datetime):
232.1654 - return self.__cmp(other) < 0
232.1655 - elif hasattr(other, "timetuple"):
232.1656 - return NotImplemented
232.1657 - else:
232.1658 - _cmperror(self, other)
232.1659 -
232.1660 - def __ge__(self, other):
232.1661 - if isinstance(other, datetime):
232.1662 - return self.__cmp(other) >= 0
232.1663 - elif hasattr(other, "timetuple"):
232.1664 - return NotImplemented
232.1665 - else:
232.1666 - _cmperror(self, other)
232.1667 -
232.1668 - def __gt__(self, other):
232.1669 - if isinstance(other, datetime):
232.1670 - return self.__cmp(other) > 0
232.1671 - elif hasattr(other, "timetuple"):
232.1672 - return NotImplemented
232.1673 - else:
232.1674 - _cmperror(self, other)
232.1675 -
232.1676 - def __cmp(self, other):
232.1677 - assert isinstance(other, datetime)
232.1678 - mytz = self._tzinfo
232.1679 - ottz = other._tzinfo
232.1680 - myoff = otoff = None
232.1681 -
232.1682 - if mytz is ottz:
232.1683 - base_compare = True
232.1684 - else:
232.1685 - if mytz is not None:
232.1686 - myoff = self._utcoffset()
232.1687 - if ottz is not None:
232.1688 - otoff = other._utcoffset()
232.1689 - base_compare = myoff == otoff
232.1690 -
232.1691 - if base_compare:
232.1692 - return cmp((self.__year, self.__month, self.__day,
232.1693 - self.__hour, self.__minute, self.__second,
232.1694 - self.__microsecond),
232.1695 - (other.__year, other.__month, other.__day,
232.1696 - other.__hour, other.__minute, other.__second,
232.1697 - other.__microsecond))
232.1698 - if myoff is None or otoff is None:
232.1699 - # XXX Buggy in 2.2.2.
232.1700 - raise TypeError("cannot compare naive and aware datetimes")
232.1701 - # XXX What follows could be done more efficiently...
232.1702 - diff = self - other # this will take offsets into account
232.1703 - if diff.days < 0:
232.1704 - return -1
232.1705 - return diff and 1 or 0
232.1706 -
232.1707 - def __add__(self, other):
232.1708 - "Add a datetime and a timedelta."
232.1709 - if not isinstance(other, timedelta):
232.1710 - return NotImplemented
232.1711 - t = tmxxx(self.__year,
232.1712 - self.__month,
232.1713 - self.__day + other.days,
232.1714 - self.__hour,
232.1715 - self.__minute,
232.1716 - self.__second + other.seconds,
232.1717 - self.__microsecond + other.microseconds)
232.1718 - self._checkOverflow(t.year)
232.1719 - result = self.__class__(t.year, t.month, t.day,
232.1720 - t.hour, t.minute, t.second,
232.1721 - t.microsecond, tzinfo=self._tzinfo)
232.1722 - return result
232.1723 -
232.1724 - __radd__ = __add__
232.1725 -
232.1726 - def __sub__(self, other):
232.1727 - "Subtract two datetimes, or a datetime and a timedelta."
232.1728 - if not isinstance(other, datetime):
232.1729 - if isinstance(other, timedelta):
232.1730 - return self + -other
232.1731 - return NotImplemented
232.1732 -
232.1733 - days1 = self.toordinal()
232.1734 - days2 = other.toordinal()
232.1735 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
232.1736 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
232.1737 - base = timedelta(days1 - days2,
232.1738 - secs1 - secs2,
232.1739 - self.__microsecond - other.__microsecond)
232.1740 - if self._tzinfo is other._tzinfo:
232.1741 - return base
232.1742 - myoff = self._utcoffset()
232.1743 - otoff = other._utcoffset()
232.1744 - if myoff == otoff:
232.1745 - return base
232.1746 - if myoff is None or otoff is None:
232.1747 - raise TypeError, "cannot mix naive and timezone-aware time"
232.1748 - return base + timedelta(minutes = otoff-myoff)
232.1749 -
232.1750 - def __hash__(self):
232.1751 - tzoff = self._utcoffset()
232.1752 - if tzoff is None:
232.1753 - return hash(self.__getstate()[0])
232.1754 - days = _ymd2ord(self.year, self.month, self.day)
232.1755 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
232.1756 - return hash(timedelta(days, seconds, self.microsecond))
232.1757 -
232.1758 - # Pickle support.
232.1759 -
232.1760 - __safe_for_unpickling__ = True # For Python 2.2
232.1761 -
232.1762 - def __getstate(self):
232.1763 - yhi, ylo = divmod(self.__year, 256)
232.1764 - us2, us3 = divmod(self.__microsecond, 256)
232.1765 - us1, us2 = divmod(us2, 256)
232.1766 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
232.1767 - self.__hour, self.__minute, self.__second,
232.1768 - us1, us2, us3)
232.1769 - if self._tzinfo is None:
232.1770 - return (basestate,)
232.1771 - else:
232.1772 - return (basestate, self._tzinfo)
232.1773 -
232.1774 - def __setstate(self, state):
232.1775 - assert isinstance(state, tuple)
232.1776 - assert 1 <= len(state) <= 2
232.1777 - string = state[0]
232.1778 - assert len(string) == 10
232.1779 - (yhi, ylo, self.__month, self.__day, self.__hour,
232.1780 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
232.1781 - self.__year = yhi * 256 + ylo
232.1782 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
232.1783 - if len(state) == 1:
232.1784 - self._tzinfo = None
232.1785 - else:
232.1786 - self._tzinfo = state[1]
232.1787 -
232.1788 - def __reduce__(self):
232.1789 - return (self.__class__, self.__getstate())
232.1790 -
232.1791 -
232.1792 -datetime.min = datetime(1, 1, 1)
232.1793 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
232.1794 -datetime.resolution = timedelta(microseconds=1)
232.1795 -
232.1796 -
232.1797 -def _isoweek1monday(year):
232.1798 - # Helper to calculate the day number of the Monday starting week 1
232.1799 - # XXX This could be done more efficiently
232.1800 - THURSDAY = 3
232.1801 - firstday = _ymd2ord(year, 1, 1)
232.1802 - firstweekday = (firstday + 6) % 7 # See weekday() above
232.1803 - week1monday = firstday - firstweekday
232.1804 - if firstweekday > THURSDAY:
232.1805 - week1monday += 7
232.1806 - return week1monday
232.1807 -
232.1808 -"""
232.1809 -Some time zone algebra. For a datetime x, let
232.1810 - x.n = x stripped of its timezone -- its naive time.
232.1811 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
232.1812 - return None
232.1813 - x.d = x.dst(), and assuming that doesn't raise an exception or
232.1814 - return None
232.1815 - x.s = x's standard offset, x.o - x.d
232.1816 -
232.1817 -Now some derived rules, where k is a duration (timedelta).
232.1818 -
232.1819 -1. x.o = x.s + x.d
232.1820 - This follows from the definition of x.s.
232.1821 -
232.1822 -2. If x and y have the same tzinfo member, x.s = y.s.
232.1823 - This is actually a requirement, an assumption we need to make about
232.1824 - sane tzinfo classes.
232.1825 -
232.1826 -3. The naive UTC time corresponding to x is x.n - x.o.
232.1827 - This is again a requirement for a sane tzinfo class.
232.1828 -
232.1829 -4. (x+k).s = x.s
232.1830 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
232.1831 -
232.1832 -5. (x+k).n = x.n + k
232.1833 - Again follows from how arithmetic is defined.
232.1834 -
232.1835 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
232.1836 -(meaning that the various tzinfo methods exist, and don't blow up or return
232.1837 -None when called).
232.1838 -
232.1839 -The function wants to return a datetime y with timezone tz, equivalent to x.
232.1840 -x is already in UTC.
232.1841 -
232.1842 -By #3, we want
232.1843 -
232.1844 - y.n - y.o = x.n [1]
232.1845 -
232.1846 -The algorithm starts by attaching tz to x.n, and calling that y. So
232.1847 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
232.1848 -becomes true; in effect, we want to solve [2] for k:
232.1849 -
232.1850 - (y+k).n - (y+k).o = x.n [2]
232.1851 -
232.1852 -By #1, this is the same as
232.1853 -
232.1854 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
232.1855 -
232.1856 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
232.1857 -Substituting that into [3],
232.1858 -
232.1859 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
232.1860 - k - (y+k).s - (y+k).d = 0; rearranging,
232.1861 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
232.1862 - k = y.s - (y+k).d
232.1863 -
232.1864 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
232.1865 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
232.1866 -very large, since all offset-returning methods return a duration of magnitude
232.1867 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
232.1868 -be 0, so ignoring it has no consequence then.
232.1869 -
232.1870 -In any case, the new value is
232.1871 -
232.1872 - z = y + y.s [4]
232.1873 -
232.1874 -It's helpful to step back at look at [4] from a higher level: it's simply
232.1875 -mapping from UTC to tz's standard time.
232.1876 -
232.1877 -At this point, if
232.1878 -
232.1879 - z.n - z.o = x.n [5]
232.1880 -
232.1881 -we have an equivalent time, and are almost done. The insecurity here is
232.1882 -at the start of daylight time. Picture US Eastern for concreteness. The wall
232.1883 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
232.1884 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
232.1885 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
232.1886 -on the day DST starts. We want to return the 1:MM EST spelling because that's
232.1887 -the only spelling that makes sense on the local wall clock.
232.1888 -
232.1889 -In fact, if [5] holds at this point, we do have the standard-time spelling,
232.1890 -but that takes a bit of proof. We first prove a stronger result. What's the
232.1891 -difference between the LHS and RHS of [5]? Let
232.1892 -
232.1893 - diff = x.n - (z.n - z.o) [6]
232.1894 -
232.1895 -Now
232.1896 - z.n = by [4]
232.1897 - (y + y.s).n = by #5
232.1898 - y.n + y.s = since y.n = x.n
232.1899 - x.n + y.s = since z and y are have the same tzinfo member,
232.1900 - y.s = z.s by #2
232.1901 - x.n + z.s
232.1902 -
232.1903 -Plugging that back into [6] gives
232.1904 -
232.1905 - diff =
232.1906 - x.n - ((x.n + z.s) - z.o) = expanding
232.1907 - x.n - x.n - z.s + z.o = cancelling
232.1908 - - z.s + z.o = by #2
232.1909 - z.d
232.1910 -
232.1911 -So diff = z.d.
232.1912 -
232.1913 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
232.1914 -spelling we wanted in the endcase described above. We're done. Contrarily,
232.1915 -if z.d = 0, then we have a UTC equivalent, and are also done.
232.1916 -
232.1917 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
232.1918 -add to z (in effect, z is in tz's standard time, and we need to shift the
232.1919 -local clock into tz's daylight time).
232.1920 -
232.1921 -Let
232.1922 -
232.1923 - z' = z + z.d = z + diff [7]
232.1924 -
232.1925 -and we can again ask whether
232.1926 -
232.1927 - z'.n - z'.o = x.n [8]
232.1928 -
232.1929 -If so, we're done. If not, the tzinfo class is insane, according to the
232.1930 -assumptions we've made. This also requires a bit of proof. As before, let's
232.1931 -compute the difference between the LHS and RHS of [8] (and skipping some of
232.1932 -the justifications for the kinds of substitutions we've done several times
232.1933 -already):
232.1934 -
232.1935 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
232.1936 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
232.1937 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
232.1938 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
232.1939 - - z.n + z.n - z.o + z'.o = cancel z.n
232.1940 - - z.o + z'.o = #1 twice
232.1941 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
232.1942 - z'.d - z.d
232.1943 -
232.1944 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
232.1945 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
232.1946 -return z', not bothering to compute z'.d.
232.1947 -
232.1948 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
232.1949 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
232.1950 -would have to change the result dst() returns: we start in DST, and moving
232.1951 -a little further into it takes us out of DST.
232.1952 -
232.1953 -There isn't a sane case where this can happen. The closest it gets is at
232.1954 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
232.1955 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
232.1956 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
232.1957 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
232.1958 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
232.1959 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
232.1960 -standard time. Since that's what the local clock *does*, we want to map both
232.1961 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
232.1962 -in local time, but so it goes -- it's the way the local clock works.
232.1963 -
232.1964 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
232.1965 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
232.1966 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
232.1967 -(correctly) concludes that z' is not UTC-equivalent to x.
232.1968 -
232.1969 -Because we know z.d said z was in daylight time (else [5] would have held and
232.1970 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
232.1971 -and we we have stopped then), and there are only 2 possible values dst() can
232.1972 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
232.1973 -but the reasoning doesn't depend on the example -- it depends on there being
232.1974 -two possible dst() outcomes, one zero and the other non-zero). Therefore
232.1975 -z' must be in standard time, and is the spelling we want in this case.
232.1976 -
232.1977 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
232.1978 -concerned (because it takes z' as being in standard time rather than the
232.1979 -daylight time we intend here), but returning it gives the real-life "local
232.1980 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
232.1981 -tz.
232.1982 -
232.1983 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
232.1984 -the 1:MM standard time spelling we want.
232.1985 -
232.1986 -So how can this break? One of the assumptions must be violated. Two
232.1987 -possibilities:
232.1988 -
232.1989 -1) [2] effectively says that y.s is invariant across all y belong to a given
232.1990 - time zone. This isn't true if, for political reasons or continental drift,
232.1991 - a region decides to change its base offset from UTC.
232.1992 -
232.1993 -2) There may be versions of "double daylight" time where the tail end of
232.1994 - the analysis gives up a step too early. I haven't thought about that
232.1995 - enough to say.
232.1996 -
232.1997 -In any case, it's clear that the default fromutc() is strong enough to handle
232.1998 -"almost all" time zones: so long as the standard offset is invariant, it
232.1999 -doesn't matter if daylight time transition points change from year to year, or
232.2000 -if daylight time is skipped in some years; it doesn't matter how large or
232.2001 -small dst() may get within its bounds; and it doesn't even matter if some
232.2002 -perverse time zone returns a negative dst()). So a breaking case must be
232.2003 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
232.2004 -"""
232.2005 -
232.2006 -def _test():
232.2007 - import test_datetime
232.2008 - test_datetime.test_main()
232.2009 -
232.2010 -if __name__ == "__main__":
232.2011 - _test()
233.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.folds Sun Jan 04 13:11:53 2015 -0600
233.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
233.3 @@ -1,2009 +0,0 @@
233.4 -+ """Concrete date/time and related types -- prototype implemented in Python.
233.5 -|
233.6 -| See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
233.7 -|
233.8 -| See also http://dir.yahoo.com/Reference/calendars/
233.9 -|
233.10 -| For a primer on DST, including many current DST rules, see
233.11 -| http://webexhibits.org/daylightsaving/
233.12 -|
233.13 -| For more about DST than you ever wanted to know, see
233.14 -| ftp://elsie.nci.nih.gov/pub/
233.15 -|
233.16 -| Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
233.17 -|
233.18 -- """
233.19 -
233.20 - import time as _time
233.21 - import math as _math
233.22 -
233.23 - MINYEAR = 1
233.24 - MAXYEAR = 9999
233.25 -
233.26 - # Utility functions, adapted from Python's Demo/classes/Dates.py, which
233.27 - # also assumes the current Gregorian calendar indefinitely extended in
233.28 - # both directions. Difference: Dates.py calls January 1 of year 0 day
233.29 - # number 1. The code here calls January 1 of year 1 day number 1. This is
233.30 - # to match the definition of the "proleptic Gregorian" calendar in Dershowitz
233.31 - # and Reingold's "Calendrical Calculations", where it's the base calendar
233.32 - # for all computations. See the book for algorithms for converting between
233.33 - # proleptic Gregorian ordinals and many other calendar systems.
233.34 -
233.35 - _DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
233.36 -
233.37 - _DAYS_BEFORE_MONTH = [None]
233.38 - dbm = 0
233.39 - for dim in _DAYS_IN_MONTH[1:]:
233.40 - _DAYS_BEFORE_MONTH.append(dbm)
233.41 - dbm += dim
233.42 - del dbm, dim
233.43 -
233.44 -+ def _is_leap(year):
233.45 -| "year -> 1 if leap year, else 0."
233.46 -| return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
233.47 --
233.48 -+ def _days_in_year(year):
233.49 -| "year -> number of days in year (366 if a leap year, else 365)."
233.50 -| return 365 + _is_leap(year)
233.51 --
233.52 -+ def _days_before_year(year):
233.53 -| "year -> number of days before January 1st of year."
233.54 -| y = year - 1
233.55 -| return y*365 + y//4 - y//100 + y//400
233.56 --
233.57 -+ def _days_in_month(year, month):
233.58 -| "year, month -> number of days in that month in that year."
233.59 -| assert 1 <= month <= 12, month
233.60 -| if month == 2 and _is_leap(year):
233.61 -| return 29
233.62 -| return _DAYS_IN_MONTH[month]
233.63 --
233.64 -+ def _days_before_month(year, month):
233.65 -| "year, month -> number of days in year preceeding first day of month."
233.66 -| if not 1 <= month <= 12:
233.67 -| raise ValueError('month must be in 1..12', month)
233.68 -| return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
233.69 --
233.70 -+ def _ymd2ord(year, month, day):
233.71 -| "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
233.72 -| if not 1 <= month <= 12:
233.73 -| raise ValueError('month must be in 1..12', month)
233.74 -| dim = _days_in_month(year, month)
233.75 -| if not 1 <= day <= dim:
233.76 -| raise ValueError('day must be in 1..%d' % dim, day)
233.77 -| return (_days_before_year(year) +
233.78 -| _days_before_month(year, month) +
233.79 -| day)
233.80 --
233.81 - _DI400Y = _days_before_year(401) # number of days in 400 years
233.82 - _DI100Y = _days_before_year(101) # " " " " 100 "
233.83 - _DI4Y = _days_before_year(5) # " " " " 4 "
233.84 -
233.85 - # A 4-year cycle has an extra leap day over what we'd get from pasting
233.86 - # together 4 single years.
233.87 - assert _DI4Y == 4 * 365 + 1
233.88 -
233.89 - # Similarly, a 400-year cycle has an extra leap day over what we'd get from
233.90 - # pasting together 4 100-year cycles.
233.91 - assert _DI400Y == 4 * _DI100Y + 1
233.92 -
233.93 - # OTOH, a 100-year cycle has one fewer leap day than we'd get from
233.94 - # pasting together 25 4-year cycles.
233.95 - assert _DI100Y == 25 * _DI4Y - 1
233.96 -
233.97 -+ def _ord2ymd(n):
233.98 -| "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
233.99 -|
233.100 -| # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
233.101 -| # repeats exactly every 400 years. The basic strategy is to find the
233.102 -| # closest 400-year boundary at or before n, then work with the offset
233.103 -| # from that boundary to n. Life is much clearer if we subtract 1 from
233.104 -| # n first -- then the values of n at 400-year boundaries are exactly
233.105 -| # those divisible by _DI400Y:
233.106 -| #
233.107 -| # D M Y n n-1
233.108 -| # -- --- ---- ---------- ----------------
233.109 -| # 31 Dec -400 -_DI400Y -_DI400Y -1
233.110 -| # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
233.111 -| # ...
233.112 -| # 30 Dec 000 -1 -2
233.113 -| # 31 Dec 000 0 -1
233.114 -| # 1 Jan 001 1 0 400-year boundary
233.115 -| # 2 Jan 001 2 1
233.116 -| # 3 Jan 001 3 2
233.117 -| # ...
233.118 -| # 31 Dec 400 _DI400Y _DI400Y -1
233.119 -| # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
233.120 -| n -= 1
233.121 -| n400, n = divmod(n, _DI400Y)
233.122 -| year = n400 * 400 + 1 # ..., -399, 1, 401, ...
233.123 -|
233.124 -| # Now n is the (non-negative) offset, in days, from January 1 of year, to
233.125 -| # the desired date. Now compute how many 100-year cycles precede n.
233.126 -| # Note that it's possible for n100 to equal 4! In that case 4 full
233.127 -| # 100-year cycles precede the desired day, which implies the desired
233.128 -| # day is December 31 at the end of a 400-year cycle.
233.129 -| n100, n = divmod(n, _DI100Y)
233.130 -|
233.131 -| # Now compute how many 4-year cycles precede it.
233.132 -| n4, n = divmod(n, _DI4Y)
233.133 -|
233.134 -| # And now how many single years. Again n1 can be 4, and again meaning
233.135 -| # that the desired day is December 31 at the end of the 4-year cycle.
233.136 -| n1, n = divmod(n, 365)
233.137 -|
233.138 -| year += n100 * 100 + n4 * 4 + n1
233.139 -| if n1 == 4 or n100 == 4:
233.140 -| assert n == 0
233.141 -| return year-1, 12, 31
233.142 -|
233.143 -| # Now the year is correct, and n is the offset from January 1. We find
233.144 -| # the month via an estimate that's either exact or one too large.
233.145 -| leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
233.146 -| assert leapyear == _is_leap(year)
233.147 -| month = (n + 50) >> 5
233.148 -| preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
233.149 -| if preceding > n: # estimate is too large
233.150 -| month -= 1
233.151 -| preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
233.152 -| n -= preceding
233.153 -| assert 0 <= n < _days_in_month(year, month)
233.154 -|
233.155 -| # Now the year and month are correct, and n is the offset from the
233.156 -| # start of that month: we're done!
233.157 -| return year, month, n+1
233.158 -|
233.159 -- # Month and day names. For localized versions, see the calendar module.
233.160 - _MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
233.161 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
233.162 - _DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
233.163 -
233.164 -
233.165 -+ def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
233.166 -| wday = (_ymd2ord(y, m, d) + 6) % 7
233.167 -| dnum = _days_before_month(y, m) + d
233.168 -| return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
233.169 --
233.170 -+ def _format_time(hh, mm, ss, us):
233.171 -| # Skip trailing microseconds when us==0.
233.172 -| result = "%02d:%02d:%02d" % (hh, mm, ss)
233.173 -| if us:
233.174 -| result += ".%06d" % us
233.175 -| return result
233.176 -|
233.177 -- # Correctly substitute for %z and %Z escapes in strftime formats.
233.178 -+ def _wrap_strftime(object, format, timetuple):
233.179 -| year = timetuple[0]
233.180 -| if year < 1900:
233.181 -+ raise ValueError("year=%d is before 1900; the datetime strftime() "
233.182 -| "methods require year >= 1900" % year)
233.183 -| # Don't call _utcoffset() or tzname() unless actually needed.
233.184 -| zreplace = None # the string to use for %z
233.185 -| Zreplace = None # the string to use for %Z
233.186 -|
233.187 -| # Scan format for %z and %Z escapes, replacing as needed.
233.188 -| newformat = []
233.189 -| push = newformat.append
233.190 -| i, n = 0, len(format)
233.191 -| while i < n:
233.192 -| ch = format[i]
233.193 -| i += 1
233.194 -| if ch == '%':
233.195 -| if i < n:
233.196 -| ch = format[i]
233.197 -| i += 1
233.198 -| if ch == 'z':
233.199 -| if zreplace is None:
233.200 -| zreplace = ""
233.201 -| if hasattr(object, "_utcoffset"):
233.202 -| offset = object._utcoffset()
233.203 -| if offset is not None:
233.204 -| sign = '+'
233.205 -| if offset < 0:
233.206 -| offset = -offset
233.207 -| sign = '-'
233.208 -| h, m = divmod(offset, 60)
233.209 -| zreplace = '%c%02d%02d' % (sign, h, m)
233.210 -| assert '%' not in zreplace
233.211 -| newformat.append(zreplace)
233.212 -| elif ch == 'Z':
233.213 -| if Zreplace is None:
233.214 -| Zreplace = ""
233.215 -| if hasattr(object, "tzname"):
233.216 -| s = object.tzname()
233.217 -| if s is not None:
233.218 -| # strftime is going to have at this: escape %
233.219 -| Zreplace = s.replace('%', '%%')
233.220 -| newformat.append(Zreplace)
233.221 -| else:
233.222 -| push('%')
233.223 -| push(ch)
233.224 -| else:
233.225 -| push('%')
233.226 -| else:
233.227 -| push(ch)
233.228 -| newformat = "".join(newformat)
233.229 -| return _time.strftime(newformat, timetuple)
233.230 --
233.231 -+ def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
233.232 -| if tzinfo is None:
233.233 -| return None
233.234 -| return getattr(tzinfo, methname)(tzinfoarg)
233.235 -|
233.236 -- # Just raise TypeError if the arg isn't None or a string.
233.237 -+ def _check_tzname(name):
233.238 -| if name is not None and not isinstance(name, str):
233.239 -+ raise TypeError("tzinfo.tzname() must return None or string, "
233.240 -| "not '%s'" % type(name))
233.241 -|
233.242 -| # name is the offset-producing method, "utcoffset" or "dst".
233.243 -| # offset is what it returned.
233.244 -| # If offset isn't None or timedelta, raises TypeError.
233.245 -| # If offset is None, returns None.
233.246 -| # Else offset is checked for being in range, and a whole # of minutes.
233.247 -- # If it is, its integer value is returned. Else ValueError is raised.
233.248 -+ def _check_utc_offset(name, offset):
233.249 -| assert name in ("utcoffset", "dst")
233.250 -| if offset is None:
233.251 -| return None
233.252 -| if not isinstance(offset, timedelta):
233.253 -+ raise TypeError("tzinfo.%s() must return None "
233.254 -| "or timedelta, not '%s'" % (name, type(offset)))
233.255 -| days = offset.days
233.256 -| if days < -1 or days > 0:
233.257 -| offset = 1440 # trigger out-of-range
233.258 -| else:
233.259 -| seconds = days * 86400 + offset.seconds
233.260 -| minutes, seconds = divmod(seconds, 60)
233.261 -| if seconds or offset.microseconds:
233.262 -+ raise ValueError("tzinfo.%s() must return a whole number "
233.263 -| "of minutes" % name)
233.264 -| offset = minutes
233.265 -| if -1440 < offset < 1440:
233.266 -| return offset
233.267 -| raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
233.268 --
233.269 -+ def _check_date_fields(year, month, day):
233.270 -| if not MINYEAR <= year <= MAXYEAR:
233.271 -| raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
233.272 -| if not 1 <= month <= 12:
233.273 -| raise ValueError('month must be in 1..12', month)
233.274 -| dim = _days_in_month(year, month)
233.275 -| if not 1 <= day <= dim:
233.276 -| raise ValueError('day must be in 1..%d' % dim, day)
233.277 --
233.278 -+ def _check_time_fields(hour, minute, second, microsecond):
233.279 -| if not 0 <= hour <= 23:
233.280 -| raise ValueError('hour must be in 0..23', hour)
233.281 -| if not 0 <= minute <= 59:
233.282 -| raise ValueError('minute must be in 0..59', minute)
233.283 -| if not 0 <= second <= 59:
233.284 -| raise ValueError('second must be in 0..59', second)
233.285 -| if not 0 <= microsecond <= 999999:
233.286 -| raise ValueError('microsecond must be in 0..999999', microsecond)
233.287 --
233.288 -+ def _check_tzinfo_arg(tz):
233.289 -| if tz is not None and not isinstance(tz, tzinfo):
233.290 -| raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
233.291 -|
233.292 -|
233.293 -| # Notes on comparison: In general, datetime module comparison operators raise
233.294 -| # TypeError when they don't know how to do a comparison themself. If they
233.295 -| # returned NotImplemented instead, comparison could (silently) fall back to
233.296 -| # the default compare-objects-by-comparing-their-memory-addresses strategy,
233.297 -| # and that's not helpful. There are two exceptions:
233.298 -| #
233.299 -| # 1. For date and datetime, if the other object has a "timetuple" attr,
233.300 -| # NotImplemented is returned. This is a hook to allow other kinds of
233.301 -| # datetime-like objects a chance to intercept the comparison.
233.302 -| #
233.303 -| # 2. Else __eq__ and __ne__ return False and True, respectively. This is
233.304 -| # so opertaions like
233.305 -| #
233.306 -| # x == y
233.307 -| # x != y
233.308 -| # x in sequence
233.309 -| # x not in sequence
233.310 -| # dict[x] = y
233.311 -| #
233.312 -| # don't raise annoying TypeErrors just because a datetime object
233.313 -| # is part of a heterogeneous collection. If there's no known way to
233.314 -| # compare X to a datetime, saying they're not equal is reasonable.
233.315 --
233.316 -+ def _cmperror(x, y):
233.317 -| raise TypeError("can't compare '%s' to '%s'" % (
233.318 -| type(x).__name__, type(y).__name__))
233.319 -|
233.320 -| # This is a start at a struct tm workalike. Goals:
233.321 -| #
233.322 -| # + Works the same way across platforms.
233.323 -| # + Handles all the fields datetime needs handled, without 1970-2038 glitches.
233.324 -| #
233.325 -| # Note: I suspect it's best if this flavor of tm does *not* try to
233.326 -| # second-guess timezones or DST. Instead fold whatever adjustments you want
233.327 -| # into the minutes argument (and the constructor will normalize).
233.328 --
233.329 - _ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
233.330 -
233.331 -+ class tmxxx:
233.332 -|
233.333 -| ordinal = None
233.334 -|
233.335 -+ def __init__(self, year, month, day, hour=0, minute=0, second=0,
233.336 -| microsecond=0):
233.337 -| # Normalize all the inputs, and store the normalized values.
233.338 -| if not 0 <= microsecond <= 999999:
233.339 -| carry, microsecond = divmod(microsecond, 1000000)
233.340 -| second += carry
233.341 -| if not 0 <= second <= 59:
233.342 -| carry, second = divmod(second, 60)
233.343 -| minute += carry
233.344 -| if not 0 <= minute <= 59:
233.345 -| carry, minute = divmod(minute, 60)
233.346 -| hour += carry
233.347 -| if not 0 <= hour <= 23:
233.348 -| carry, hour = divmod(hour, 24)
233.349 -| day += carry
233.350 -|
233.351 -| # That was easy. Now it gets muddy: the proper range for day
233.352 -| # can't be determined without knowing the correct month and year,
233.353 -| # but if day is, e.g., plus or minus a million, the current month
233.354 -| # and year values make no sense (and may also be out of bounds
233.355 -| # themselves).
233.356 -| # Saying 12 months == 1 year should be non-controversial.
233.357 -| if not 1 <= month <= 12:
233.358 -| carry, month = divmod(month-1, 12)
233.359 -| year += carry
233.360 -| month += 1
233.361 -| assert 1 <= month <= 12
233.362 -|
233.363 -| # Now only day can be out of bounds (year may also be out of bounds
233.364 -| # for a datetime object, but we don't care about that here).
233.365 -| # If day is out of bounds, what to do is arguable, but at least the
233.366 -| # method here is principled and explainable.
233.367 -| dim = _days_in_month(year, month)
233.368 -| if not 1 <= day <= dim:
233.369 -| # Move day-1 days from the first of the month. First try to
233.370 -| # get off cheap if we're only one day out of range (adjustments
233.371 -| # for timezone alone can't be worse than that).
233.372 -| if day == 0: # move back a day
233.373 -| month -= 1
233.374 -| if month > 0:
233.375 -| day = _days_in_month(year, month)
233.376 -| else:
233.377 -| year, month, day = year-1, 12, 31
233.378 -| elif day == dim + 1: # move forward a day
233.379 -| month += 1
233.380 -| day = 1
233.381 -| if month > 12:
233.382 -| month = 1
233.383 -| year += 1
233.384 -| else:
233.385 -| self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
233.386 -| year, month, day = _ord2ymd(self.ordinal)
233.387 -|
233.388 -| self.year, self.month, self.day = year, month, day
233.389 -| self.hour, self.minute, self.second = hour, minute, second
233.390 -| self.microsecond = microsecond
233.391 --
233.392 -+ def toordinal(self):
233.393 -+ """Return proleptic Gregorian ordinal for the year, month and day.
233.394 -|
233.395 -| January 1 of year 1 is day 1. Only the year, month and day values
233.396 -| contribute to the result.
233.397 -- """
233.398 -| if self.ordinal is None:
233.399 -| self.ordinal = _ymd2ord(self.year, self.month, self.day)
233.400 -| return self.ordinal
233.401 --
233.402 -+ def time(self):
233.403 -| "Return Unixish timestamp, as a float (assuming UTC)."
233.404 -| days = self.toordinal() - _ORD1970 # convert to UNIX epoch
233.405 -| seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
233.406 -| return seconds + self.second + self.microsecond / 1e6
233.407 --
233.408 -+ def ctime(self):
233.409 -| "Return ctime() style string."
233.410 -| weekday = self.toordinal() % 7 or 7
233.411 -| return "%s %s %2d %02d:%02d:%02d %04d" % (
233.412 -| _DAYNAMES[weekday],
233.413 -| _MONTHNAMES[self.month],
233.414 -| self.day,
233.415 -| self.hour, self.minute, self.second,
233.416 -| self.year)
233.417 --
233.418 -+ class timedelta(object):
233.419 -+ """Represent the difference between two datetime objects.
233.420 -|
233.421 -| Supported operators:
233.422 -|
233.423 -| - add, subtract timedelta
233.424 -| - unary plus, minus, abs
233.425 -| - compare to timedelta
233.426 -| - multiply, divide by int/long
233.427 -|
233.428 -| In addition, datetime supports subtraction of two datetime objects
233.429 -| returning a timedelta, and addition or subtraction of a datetime
233.430 -| and a timedelta giving a datetime.
233.431 -|
233.432 -| Representation: (days, seconds, microseconds). Why? Because I
233.433 -| felt like it.
233.434 -- """
233.435 -|
233.436 -+ def __new__(cls, days=0, seconds=0, microseconds=0,
233.437 -| # XXX The following should only be used as keyword args:
233.438 -| milliseconds=0, minutes=0, hours=0, weeks=0):
233.439 -| # Doing this efficiently and accurately in C is going to be difficult
233.440 -| # and error-prone, due to ubiquitous overflow possibilities, and that
233.441 -| # C double doesn't have enough bits of precision to represent
233.442 -| # microseconds over 10K years faithfully. The code here tries to make
233.443 -| # explicit where go-fast assumptions can be relied on, in order to
233.444 -| # guide the C implementation; it's way more convoluted than speed-
233.445 -| # ignoring auto-overflow-to-long idiomatic Python could be.
233.446 -|
233.447 -| # XXX Check that all inputs are ints, longs or floats.
233.448 -|
233.449 -| # Final values, all integer.
233.450 -| # s and us fit in 32-bit signed ints; d isn't bounded.
233.451 -| d = s = us = 0
233.452 -|
233.453 -| # Normalize everything to days, seconds, microseconds.
233.454 -| days += weeks*7
233.455 -| seconds += minutes*60 + hours*3600
233.456 -| microseconds += milliseconds*1000
233.457 -|
233.458 -| # Get rid of all fractions, and normalize s and us.
233.459 -| # Take a deep breath <wink>.
233.460 -| if isinstance(days, float):
233.461 -| dayfrac, days = _math.modf(days)
233.462 -| daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
233.463 -| assert daysecondswhole == int(daysecondswhole) # can't overflow
233.464 -| s = int(daysecondswhole)
233.465 -| assert days == long(days)
233.466 -| d = long(days)
233.467 -| else:
233.468 -| daysecondsfrac = 0.0
233.469 -| d = days
233.470 -| assert isinstance(daysecondsfrac, float)
233.471 -| assert abs(daysecondsfrac) <= 1.0
233.472 -| assert isinstance(d, (int, long))
233.473 -| assert abs(s) <= 24 * 3600
233.474 -| # days isn't referenced again before redefinition
233.475 -|
233.476 -| if isinstance(seconds, float):
233.477 -| secondsfrac, seconds = _math.modf(seconds)
233.478 -| assert seconds == long(seconds)
233.479 -| seconds = long(seconds)
233.480 -| secondsfrac += daysecondsfrac
233.481 -| assert abs(secondsfrac) <= 2.0
233.482 -| else:
233.483 -| secondsfrac = daysecondsfrac
233.484 -| # daysecondsfrac isn't referenced again
233.485 -| assert isinstance(secondsfrac, float)
233.486 -| assert abs(secondsfrac) <= 2.0
233.487 -|
233.488 -| assert isinstance(seconds, (int, long))
233.489 -| days, seconds = divmod(seconds, 24*3600)
233.490 -| d += days
233.491 -| s += int(seconds) # can't overflow
233.492 -| assert isinstance(s, int)
233.493 -| assert abs(s) <= 2 * 24 * 3600
233.494 -| # seconds isn't referenced again before redefinition
233.495 -|
233.496 -| usdouble = secondsfrac * 1e6
233.497 -| assert abs(usdouble) < 2.1e6 # exact value not critical
233.498 -| # secondsfrac isn't referenced again
233.499 -|
233.500 -| if isinstance(microseconds, float):
233.501 -| microseconds += usdouble
233.502 -| microseconds = round(microseconds)
233.503 -| seconds, microseconds = divmod(microseconds, 1e6)
233.504 -| assert microseconds == int(microseconds)
233.505 -| assert seconds == long(seconds)
233.506 -| days, seconds = divmod(seconds, 24.*3600.)
233.507 -| assert days == long(days)
233.508 -| assert seconds == int(seconds)
233.509 -| d += long(days)
233.510 -| s += int(seconds) # can't overflow
233.511 -| assert isinstance(s, int)
233.512 -| assert abs(s) <= 3 * 24 * 3600
233.513 -| else:
233.514 -| seconds, microseconds = divmod(microseconds, 1000000)
233.515 -| days, seconds = divmod(seconds, 24*3600)
233.516 -| d += days
233.517 -| s += int(seconds) # can't overflow
233.518 -| assert isinstance(s, int)
233.519 -| assert abs(s) <= 3 * 24 * 3600
233.520 -| microseconds = float(microseconds)
233.521 -| microseconds += usdouble
233.522 -| microseconds = round(microseconds)
233.523 -| assert abs(s) <= 3 * 24 * 3600
233.524 -| assert abs(microseconds) < 3.1e6
233.525 -|
233.526 -| # Just a little bit of carrying possible for microseconds and seconds.
233.527 -| assert isinstance(microseconds, float)
233.528 -| assert int(microseconds) == microseconds
233.529 -| us = int(microseconds)
233.530 -| seconds, us = divmod(us, 1000000)
233.531 -| s += seconds # cant't overflow
233.532 -| assert isinstance(s, int)
233.533 -| days, s = divmod(s, 24*3600)
233.534 -| d += days
233.535 -|
233.536 -| assert isinstance(d, (int, long))
233.537 -| assert isinstance(s, int) and 0 <= s < 24*3600
233.538 -| assert isinstance(us, int) and 0 <= us < 1000000
233.539 -|
233.540 -| self = object.__new__(cls)
233.541 -|
233.542 -| self.__days = d
233.543 -| self.__seconds = s
233.544 -| self.__microseconds = us
233.545 -| if abs(d) > 999999999:
233.546 -| raise OverflowError("timedelta # of days is too large: %d" % d)
233.547 -|
233.548 -| return self
233.549 --
233.550 -+ def __repr__(self):
233.551 -| if self.__microseconds:
233.552 -| return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
233.553 -| self.__days,
233.554 -| self.__seconds,
233.555 -| self.__microseconds)
233.556 -| if self.__seconds:
233.557 -| return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
233.558 -| self.__days,
233.559 -| self.__seconds)
233.560 -| return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
233.561 --
233.562 -+ def __str__(self):
233.563 -| mm, ss = divmod(self.__seconds, 60)
233.564 -| hh, mm = divmod(mm, 60)
233.565 -| s = "%d:%02d:%02d" % (hh, mm, ss)
233.566 -| if self.__days:
233.567 -+ def plural(n):
233.568 -- return n, abs(n) != 1 and "s" or ""
233.569 -| s = ("%d day%s, " % plural(self.__days)) + s
233.570 -| if self.__microseconds:
233.571 -| s = s + ".%06d" % self.__microseconds
233.572 -| return s
233.573 --
233.574 -| days = property(lambda self: self.__days, doc="days")
233.575 -| seconds = property(lambda self: self.__seconds, doc="seconds")
233.576 -| microseconds = property(lambda self: self.__microseconds,
233.577 -| doc="microseconds")
233.578 -|
233.579 -+ def __add__(self, other):
233.580 -| if isinstance(other, timedelta):
233.581 -| return timedelta(self.__days + other.__days,
233.582 -| self.__seconds + other.__seconds,
233.583 -| self.__microseconds + other.__microseconds)
233.584 -| return NotImplemented
233.585 --
233.586 -| __radd__ = __add__
233.587 -|
233.588 -+ def __sub__(self, other):
233.589 -| if isinstance(other, timedelta):
233.590 -| return self + -other
233.591 -| return NotImplemented
233.592 --
233.593 -+ def __rsub__(self, other):
233.594 -| if isinstance(other, timedelta):
233.595 -| return -self + other
233.596 -| return NotImplemented
233.597 --
233.598 -+ def __neg__(self):
233.599 -| return self.__class__(-self.__days,
233.600 -| -self.__seconds,
233.601 -| -self.__microseconds)
233.602 --
233.603 -+ def __pos__(self):
233.604 -| return self
233.605 --
233.606 -+ def __abs__(self):
233.607 -| if self.__days < 0:
233.608 -| return -self
233.609 -| else:
233.610 -| return self
233.611 --
233.612 -+ def __mul__(self, other):
233.613 -| if isinstance(other, (int, long)):
233.614 -| return self.__class__(self.__days * other,
233.615 -| self.__seconds * other,
233.616 -| self.__microseconds * other)
233.617 -| return NotImplemented
233.618 --
233.619 -| __rmul__ = __mul__
233.620 -|
233.621 -+ def __div__(self, other):
233.622 -| if isinstance(other, (int, long)):
233.623 -| usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
233.624 -| self.__microseconds)
233.625 -| return self.__class__(0, 0, usec // other)
233.626 -| return NotImplemented
233.627 --
233.628 -| __floordiv__ = __div__
233.629 -|
233.630 -| # Comparisons.
233.631 -|
233.632 -+ def __eq__(self, other):
233.633 -| if isinstance(other, timedelta):
233.634 -| return self.__cmp(other) == 0
233.635 -| else:
233.636 -| return False
233.637 --
233.638 -+ def __ne__(self, other):
233.639 -| if isinstance(other, timedelta):
233.640 -| return self.__cmp(other) != 0
233.641 -| else:
233.642 -| return True
233.643 --
233.644 -+ def __le__(self, other):
233.645 -| if isinstance(other, timedelta):
233.646 -| return self.__cmp(other) <= 0
233.647 -| else:
233.648 -| _cmperror(self, other)
233.649 --
233.650 -+ def __lt__(self, other):
233.651 -| if isinstance(other, timedelta):
233.652 -| return self.__cmp(other) < 0
233.653 -| else:
233.654 -| _cmperror(self, other)
233.655 --
233.656 -+ def __ge__(self, other):
233.657 -| if isinstance(other, timedelta):
233.658 -| return self.__cmp(other) >= 0
233.659 -| else:
233.660 -| _cmperror(self, other)
233.661 --
233.662 -+ def __gt__(self, other):
233.663 -| if isinstance(other, timedelta):
233.664 -| return self.__cmp(other) > 0
233.665 -| else:
233.666 -| _cmperror(self, other)
233.667 --
233.668 -+ def __cmp(self, other):
233.669 -| assert isinstance(other, timedelta)
233.670 -| return cmp(self.__getstate(), other.__getstate())
233.671 --
233.672 -+ def __hash__(self):
233.673 -| return hash(self.__getstate())
233.674 --
233.675 -+ def __nonzero__(self):
233.676 -| return (self.__days != 0 or
233.677 -| self.__seconds != 0 or
233.678 -| self.__microseconds != 0)
233.679 -|
233.680 -| # Pickle support.
233.681 --
233.682 -| __safe_for_unpickling__ = True # For Python 2.2
233.683 -|
233.684 -+ def __getstate(self):
233.685 -| return (self.__days, self.__seconds, self.__microseconds)
233.686 --
233.687 -+ def __reduce__(self):
233.688 -| return (self.__class__, self.__getstate())
233.689 --
233.690 - timedelta.min = timedelta(-999999999)
233.691 - timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
233.692 - microseconds=999999)
233.693 - timedelta.resolution = timedelta(microseconds=1)
233.694 -
233.695 -+ class date(object):
233.696 -+ """Concrete date type.
233.697 -|
233.698 -| Constructors:
233.699 -|
233.700 -| __new__()
233.701 -| fromtimestamp()
233.702 -| today()
233.703 -| fromordinal()
233.704 -|
233.705 -| Operators:
233.706 -|
233.707 -| __repr__, __str__
233.708 -| __cmp__, __hash__
233.709 -| __add__, __radd__, __sub__ (add/radd only with timedelta arg)
233.710 -|
233.711 -| Methods:
233.712 -|
233.713 -| timetuple()
233.714 -| toordinal()
233.715 -| weekday()
233.716 -| isoweekday(), isocalendar(), isoformat()
233.717 -| ctime()
233.718 -| strftime()
233.719 -|
233.720 -| Properties (readonly):
233.721 -| year, month, day
233.722 -- """
233.723 -|
233.724 -+ def __new__(cls, year, month=None, day=None):
233.725 -+ """Constructor.
233.726 -|
233.727 -| Arguments:
233.728 -|
233.729 -| year, month, day (required, base 1)
233.730 -- """
233.731 -| if isinstance(year, str):
233.732 -| # Pickle support
233.733 -| self = object.__new__(cls)
233.734 -| self.__setstate((year,))
233.735 -| return self
233.736 -| _check_date_fields(year, month, day)
233.737 -| self = object.__new__(cls)
233.738 -| self.__year = year
233.739 -| self.__month = month
233.740 -| self.__day = day
233.741 -| return self
233.742 -|
233.743 -| # Additional constructors
233.744 --
233.745 -+ def fromtimestamp(cls, t):
233.746 -| "Construct a date from a POSIX timestamp (like time.time())."
233.747 -| y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
233.748 -- return cls(y, m, d)
233.749 -| fromtimestamp = classmethod(fromtimestamp)
233.750 -|
233.751 -+ def today(cls):
233.752 -| "Construct a date from time.time()."
233.753 -| t = _time.time()
233.754 -- return cls.fromtimestamp(t)
233.755 -| today = classmethod(today)
233.756 -|
233.757 -+ def fromordinal(cls, n):
233.758 -+ """Contruct a date from a proleptic Gregorian ordinal.
233.759 -|
233.760 -| January 1 of year 1 is day 1. Only the year, month and day are
233.761 -| non-zero in the result.
233.762 -- """
233.763 -| y, m, d = _ord2ymd(n)
233.764 -- return cls(y, m, d)
233.765 -| fromordinal = classmethod(fromordinal)
233.766 -|
233.767 -| # Conversions to string
233.768 -|
233.769 -+ def __repr__(self):
233.770 -| "Convert to formal string, for repr()."
233.771 -| return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
233.772 -| self.__year,
233.773 -| self.__month,
233.774 -| self.__day)
233.775 -| # XXX These shouldn't depend on time.localtime(), because that
233.776 -| # clips the usable dates to [1970 .. 2038). At least ctime() is
233.777 -| # easily done without using strftime() -- that's better too because
233.778 -| # strftime("%c", ...) is locale specific.
233.779 --
233.780 -+ def ctime(self):
233.781 -| "Format a la ctime()."
233.782 -| return tmxxx(self.__year, self.__month, self.__day).ctime()
233.783 --
233.784 -+ def strftime(self, fmt):
233.785 -| "Format using strftime()."
233.786 -| return _wrap_strftime(self, fmt, self.timetuple())
233.787 --
233.788 -+ def isoformat(self):
233.789 -+ """Return the date formatted according to ISO.
233.790 -|
233.791 -| This is 'YYYY-MM-DD'.
233.792 -|
233.793 -| References:
233.794 -| - http://www.w3.org/TR/NOTE-datetime
233.795 -| - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
233.796 -- """
233.797 -| return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
233.798 --
233.799 -| __str__ = isoformat
233.800 -|
233.801 -| # Read-only field accessors
233.802 -| year = property(lambda self: self.__year,
233.803 -| doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
233.804 -| month = property(lambda self: self.__month, doc="month (1-12)")
233.805 -| day = property(lambda self: self.__day, doc="day (1-31)")
233.806 -|
233.807 -| # Standard conversions, __cmp__, __hash__ (and helpers)
233.808 -|
233.809 -+ def timetuple(self):
233.810 -| "Return local time tuple compatible with time.localtime()."
233.811 -| return _build_struct_time(self.__year, self.__month, self.__day,
233.812 -| 0, 0, 0, -1)
233.813 --
233.814 -+ def toordinal(self):
233.815 -+ """Return proleptic Gregorian ordinal for the year, month and day.
233.816 -|
233.817 -| January 1 of year 1 is day 1. Only the year, month and day values
233.818 -| contribute to the result.
233.819 -- """
233.820 -| return _ymd2ord(self.__year, self.__month, self.__day)
233.821 --
233.822 -+ def replace(self, year=None, month=None, day=None):
233.823 -| """Return a new date with new values for the specified fields."""
233.824 -| if year is None:
233.825 -| year = self.__year
233.826 -| if month is None:
233.827 -| month = self.__month
233.828 -| if day is None:
233.829 -| day = self.__day
233.830 -| _check_date_fields(year, month, day)
233.831 -| return date(year, month, day)
233.832 -|
233.833 -| # Comparisons.
233.834 --
233.835 -+ def __eq__(self, other):
233.836 -| if isinstance(other, date):
233.837 -| return self.__cmp(other) == 0
233.838 -| elif hasattr(other, "timetuple"):
233.839 -| return NotImplemented
233.840 -| else:
233.841 -| return False
233.842 --
233.843 -+ def __ne__(self, other):
233.844 -| if isinstance(other, date):
233.845 -| return self.__cmp(other) != 0
233.846 -| elif hasattr(other, "timetuple"):
233.847 -| return NotImplemented
233.848 -| else:
233.849 -| return True
233.850 --
233.851 -+ def __le__(self, other):
233.852 -| if isinstance(other, date):
233.853 -| return self.__cmp(other) <= 0
233.854 -| elif hasattr(other, "timetuple"):
233.855 -| return NotImplemented
233.856 -| else:
233.857 -| _cmperror(self, other)
233.858 --
233.859 -+ def __lt__(self, other):
233.860 -| if isinstance(other, date):
233.861 -| return self.__cmp(other) < 0
233.862 -| elif hasattr(other, "timetuple"):
233.863 -| return NotImplemented
233.864 -| else:
233.865 -| _cmperror(self, other)
233.866 --
233.867 -+ def __ge__(self, other):
233.868 -| if isinstance(other, date):
233.869 -| return self.__cmp(other) >= 0
233.870 -| elif hasattr(other, "timetuple"):
233.871 -| return NotImplemented
233.872 -| else:
233.873 -| _cmperror(self, other)
233.874 --
233.875 -+ def __gt__(self, other):
233.876 -| if isinstance(other, date):
233.877 -| return self.__cmp(other) > 0
233.878 -| elif hasattr(other, "timetuple"):
233.879 -| return NotImplemented
233.880 -| else:
233.881 -| _cmperror(self, other)
233.882 --
233.883 -+ def __cmp(self, other):
233.884 -| assert isinstance(other, date)
233.885 -| y, m, d = self.__year, self.__month, self.__day
233.886 -| y2, m2, d2 = other.__year, other.__month, other.__day
233.887 -| return cmp((y, m, d), (y2, m2, d2))
233.888 --
233.889 -+ def __hash__(self):
233.890 -| "Hash."
233.891 -| return hash(self.__getstate())
233.892 -|
233.893 -| # Computations
233.894 --
233.895 -+ def _checkOverflow(self, year):
233.896 -| if not MINYEAR <= year <= MAXYEAR:
233.897 -| raise OverflowError("date +/-: result year %d not in %d..%d" %
233.898 -| (year, MINYEAR, MAXYEAR))
233.899 --
233.900 -+ def __add__(self, other):
233.901 -| "Add a date to a timedelta."
233.902 -| if isinstance(other, timedelta):
233.903 -| t = tmxxx(self.__year,
233.904 -| self.__month,
233.905 -| self.__day + other.days)
233.906 -| self._checkOverflow(t.year)
233.907 -| result = self.__class__(t.year, t.month, t.day)
233.908 -| return result
233.909 -| return NotImplemented
233.910 --
233.911 -| __radd__ = __add__
233.912 -|
233.913 -+ def __sub__(self, other):
233.914 -| """Subtract two dates, or a date and a timedelta."""
233.915 -| if isinstance(other, timedelta):
233.916 -| return self + timedelta(-other.days)
233.917 -| if isinstance(other, date):
233.918 -| days1 = self.toordinal()
233.919 -| days2 = other.toordinal()
233.920 -| return timedelta(days1 - days2)
233.921 -| return NotImplemented
233.922 --
233.923 -+ def weekday(self):
233.924 -| "Return day of the week, where Monday == 0 ... Sunday == 6."
233.925 -| return (self.toordinal() + 6) % 7
233.926 -|
233.927 -| # Day-of-the-week and week-of-the-year, according to ISO
233.928 --
233.929 -+ def isoweekday(self):
233.930 -| "Return day of the week, where Monday == 1 ... Sunday == 7."
233.931 -| # 1-Jan-0001 is a Monday
233.932 -| return self.toordinal() % 7 or 7
233.933 --
233.934 -+ def isocalendar(self):
233.935 -+ """Return a 3-tuple containing ISO year, week number, and weekday.
233.936 -|
233.937 -| The first ISO week of the year is the (Mon-Sun) week
233.938 -| containing the year's first Thursday; everything else derives
233.939 -| from that.
233.940 -|
233.941 -| The first week is 1; Monday is 1 ... Sunday is 7.
233.942 -|
233.943 -| ISO calendar algorithm taken from
233.944 -| http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
233.945 -- """
233.946 -| year = self.__year
233.947 -| week1monday = _isoweek1monday(year)
233.948 -| today = _ymd2ord(self.__year, self.__month, self.__day)
233.949 -| # Internally, week and day have origin 0
233.950 -| week, day = divmod(today - week1monday, 7)
233.951 -| if week < 0:
233.952 -| year -= 1
233.953 -| week1monday = _isoweek1monday(year)
233.954 -| week, day = divmod(today - week1monday, 7)
233.955 -| elif week >= 52:
233.956 -| if today >= _isoweek1monday(year+1):
233.957 -| year += 1
233.958 -| week = 0
233.959 -| return year, week+1, day+1
233.960 -|
233.961 -| # Pickle support.
233.962 --
233.963 -| __safe_for_unpickling__ = True # For Python 2.2
233.964 -|
233.965 -+ def __getstate(self):
233.966 -| yhi, ylo = divmod(self.__year, 256)
233.967 -| return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
233.968 --
233.969 -+ def __setstate(self, t):
233.970 -| assert isinstance(t, tuple) and len(t) == 1, `t`
233.971 -| string = t[0]
233.972 -| assert len(string) == 4
233.973 -| yhi, ylo, self.__month, self.__day = map(ord, string)
233.974 -| self.__year = yhi * 256 + ylo
233.975 --
233.976 -+ def __reduce__(self):
233.977 -| return (self.__class__, self.__getstate())
233.978 --
233.979 - _date_class = date # so functions w/ args named "date" can get at the class
233.980 -
233.981 - date.min = date(1, 1, 1)
233.982 - date.max = date(9999, 12, 31)
233.983 - date.resolution = timedelta(days=1)
233.984 -
233.985 -+ class tzinfo(object):
233.986 -+ """Abstract base class for time zone info classes.
233.987 -|
233.988 -| Subclasses must override the name(), utcoffset() and dst() methods.
233.989 -- """
233.990 -|
233.991 -+ def tzname(self, dt):
233.992 -| "datetime -> string name of time zone."
233.993 -| raise NotImplementedError("tzinfo subclass must override tzname()")
233.994 --
233.995 -+ def utcoffset(self, dt):
233.996 -| "datetime -> minutes east of UTC (negative for west of UTC)"
233.997 -| raise NotImplementedError("tzinfo subclass must override utcoffset()")
233.998 --
233.999 -+ def dst(self, dt):
233.1000 -+ """datetime -> DST offset in minutes east of UTC.
233.1001 -|
233.1002 -| Return 0 if DST not in effect. utcoffset() must include the DST
233.1003 -| offset.
233.1004 -- """
233.1005 -| raise NotImplementedError("tzinfo subclass must override dst()")
233.1006 --
233.1007 -+ def fromutc(self, dt):
233.1008 -| "datetime in UTC -> datetime in local time."
233.1009 -|
233.1010 -| if not isinstance(dt, datetime):
233.1011 -| raise TypeError("fromutc() requires a datetime argument")
233.1012 -| if dt.tzinfo is not self:
233.1013 -| raise ValueError("dt.tzinfo is not self")
233.1014 -|
233.1015 -| dtoff = dt.utcoffset()
233.1016 -| if dtoff is None:
233.1017 -+ raise ValueError("fromutc() requires a non-None utcoffset() "
233.1018 -| "result")
233.1019 -|
233.1020 -| # See the long comment block at the end of this file for an
233.1021 -| # explanation of this algorithm.
233.1022 -| dtdst = dt.dst()
233.1023 -| if dtdst is None:
233.1024 -| raise ValueError("fromutc() requires a non-None dst() result")
233.1025 -| delta = dtoff - dtdst
233.1026 -| if delta:
233.1027 -| dt += delta
233.1028 -| dtdst = dt.dst()
233.1029 -| if dtdst is None:
233.1030 -+ raise ValueError("fromutc(): dt.dst gave inconsistent "
233.1031 -| "results; cannot convert")
233.1032 -| if dtdst:
233.1033 -| return dt + dtdst
233.1034 -| else:
233.1035 -| return dt
233.1036 -|
233.1037 -| # Pickle support.
233.1038 --
233.1039 -| __safe_for_unpickling__ = True # For Python 2.2
233.1040 -|
233.1041 -+ def __reduce__(self):
233.1042 -| getinitargs = getattr(self, "__getinitargs__", None)
233.1043 -| if getinitargs:
233.1044 -| args = getinitargs()
233.1045 -| else:
233.1046 -| args = ()
233.1047 -| getstate = getattr(self, "__getstate__", None)
233.1048 -| if getstate:
233.1049 -| state = getstate()
233.1050 -| else:
233.1051 -| state = getattr(self, "__dict__", None) or None
233.1052 -| if state is None:
233.1053 -| return (self.__class__, args)
233.1054 -| else:
233.1055 -| return (self.__class__, args, state)
233.1056 --
233.1057 - _tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
233.1058 -
233.1059 -+ class time(object):
233.1060 -+ """Time with time zone.
233.1061 -|
233.1062 -| Constructors:
233.1063 -|
233.1064 -| __new__()
233.1065 -|
233.1066 -| Operators:
233.1067 -|
233.1068 -| __repr__, __str__
233.1069 -| __cmp__, __hash__
233.1070 -|
233.1071 -| Methods:
233.1072 -|
233.1073 -| strftime()
233.1074 -| isoformat()
233.1075 -| utcoffset()
233.1076 -| tzname()
233.1077 -| dst()
233.1078 -|
233.1079 -| Properties (readonly):
233.1080 -| hour, minute, second, microsecond, tzinfo
233.1081 -- """
233.1082 -|
233.1083 -+ def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
233.1084 -+ """Constructor.
233.1085 -|
233.1086 -| Arguments:
233.1087 -|
233.1088 -| hour, minute (required)
233.1089 -| second, microsecond (default to zero)
233.1090 -| tzinfo (default to None)
233.1091 -- """
233.1092 -| self = object.__new__(cls)
233.1093 -| if isinstance(hour, str):
233.1094 -| # Pickle support
233.1095 -| self.__setstate((hour, minute or None))
233.1096 -| return self
233.1097 -| _check_tzinfo_arg(tzinfo)
233.1098 -| _check_time_fields(hour, minute, second, microsecond)
233.1099 -| self.__hour = hour
233.1100 -| self.__minute = minute
233.1101 -| self.__second = second
233.1102 -| self.__microsecond = microsecond
233.1103 -| self._tzinfo = tzinfo
233.1104 -| return self
233.1105 -|
233.1106 -- # Read-only field accessors
233.1107 -| hour = property(lambda self: self.__hour, doc="hour (0-23)")
233.1108 -| minute = property(lambda self: self.__minute, doc="minute (0-59)")
233.1109 -| second = property(lambda self: self.__second, doc="second (0-59)")
233.1110 -| microsecond = property(lambda self: self.__microsecond,
233.1111 -| doc="microsecond (0-999999)")
233.1112 -| tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
233.1113 -|
233.1114 -| # Standard conversions, __hash__ (and helpers)
233.1115 -|
233.1116 -| # Comparisons.
233.1117 -|
233.1118 -+ def __eq__(self, other):
233.1119 -| if isinstance(other, time):
233.1120 -| return self.__cmp(other) == 0
233.1121 -| else:
233.1122 -| return False
233.1123 --
233.1124 -+ def __ne__(self, other):
233.1125 -| if isinstance(other, time):
233.1126 -| return self.__cmp(other) != 0
233.1127 -| else:
233.1128 -| return True
233.1129 --
233.1130 -+ def __le__(self, other):
233.1131 -| if isinstance(other, time):
233.1132 -| return self.__cmp(other) <= 0
233.1133 -| else:
233.1134 -| _cmperror(self, other)
233.1135 --
233.1136 -+ def __lt__(self, other):
233.1137 -| if isinstance(other, time):
233.1138 -| return self.__cmp(other) < 0
233.1139 -| else:
233.1140 -| _cmperror(self, other)
233.1141 --
233.1142 -+ def __ge__(self, other):
233.1143 -| if isinstance(other, time):
233.1144 -| return self.__cmp(other) >= 0
233.1145 -| else:
233.1146 -| _cmperror(self, other)
233.1147 --
233.1148 -+ def __gt__(self, other):
233.1149 -| if isinstance(other, time):
233.1150 -| return self.__cmp(other) > 0
233.1151 -| else:
233.1152 -| _cmperror(self, other)
233.1153 --
233.1154 -+ def __cmp(self, other):
233.1155 -| assert isinstance(other, time)
233.1156 -| mytz = self._tzinfo
233.1157 -| ottz = other._tzinfo
233.1158 -| myoff = otoff = None
233.1159 -|
233.1160 -| if mytz is ottz:
233.1161 -| base_compare = True
233.1162 -| else:
233.1163 -| myoff = self._utcoffset()
233.1164 -| otoff = other._utcoffset()
233.1165 -| base_compare = myoff == otoff
233.1166 -|
233.1167 -| if base_compare:
233.1168 -| return cmp((self.__hour, self.__minute, self.__second,
233.1169 -| self.__microsecond),
233.1170 -| (other.__hour, other.__minute, other.__second,
233.1171 -| other.__microsecond))
233.1172 -| if myoff is None or otoff is None:
233.1173 -| # XXX Buggy in 2.2.2.
233.1174 -| raise TypeError("cannot compare naive and aware times")
233.1175 -| myhhmm = self.__hour * 60 + self.__minute - myoff
233.1176 -| othhmm = other.__hour * 60 + other.__minute - otoff
233.1177 -| return cmp((myhhmm, self.__second, self.__microsecond),
233.1178 -| (othhmm, other.__second, other.__microsecond))
233.1179 --
233.1180 -+ def __hash__(self):
233.1181 -| """Hash."""
233.1182 -| tzoff = self._utcoffset()
233.1183 -| if not tzoff: # zero or None
233.1184 -| return hash(self.__getstate()[0])
233.1185 -| h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
233.1186 -| if 0 <= h < 24:
233.1187 -| return hash(time(h, m, self.second, self.microsecond))
233.1188 -| return hash((h, m, self.second, self.microsecond))
233.1189 -|
233.1190 -| # Conversion to string
233.1191 --
233.1192 -+ def _tzstr(self, sep=":"):
233.1193 -| """Return formatted timezone offset (+xx:xx) or None."""
233.1194 -| off = self._utcoffset()
233.1195 -| if off is not None:
233.1196 -| if off < 0:
233.1197 -| sign = "-"
233.1198 -| off = -off
233.1199 -| else:
233.1200 -| sign = "+"
233.1201 -| hh, mm = divmod(off, 60)
233.1202 -| assert 0 <= hh < 24
233.1203 -| off = "%s%02d%s%02d" % (sign, hh, sep, mm)
233.1204 -| return off
233.1205 --
233.1206 -+ def __repr__(self):
233.1207 -| """Convert to formal string, for repr()."""
233.1208 -| if self.__microsecond != 0:
233.1209 -| s = ", %d, %d" % (self.__second, self.__microsecond)
233.1210 -| elif self.__second != 0:
233.1211 -| s = ", %d" % self.__second
233.1212 -| else:
233.1213 -| s = ""
233.1214 -| s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
233.1215 -| self.__hour, self.__minute, s)
233.1216 -| if self._tzinfo is not None:
233.1217 -| assert s[-1:] == ")"
233.1218 -| s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
233.1219 -| return s
233.1220 --
233.1221 -+ def isoformat(self):
233.1222 -+ """Return the time formatted according to ISO.
233.1223 -|
233.1224 -| This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
233.1225 -| self.microsecond == 0.
233.1226 -- """
233.1227 -| s = _format_time(self.__hour, self.__minute, self.__second,
233.1228 -| self.__microsecond)
233.1229 -| tz = self._tzstr()
233.1230 -| if tz:
233.1231 -| s += tz
233.1232 -| return s
233.1233 --
233.1234 -| __str__ = isoformat
233.1235 -|
233.1236 -+ def strftime(self, fmt):
233.1237 -+ """Format using strftime(). The date part of the timestamp passed
233.1238 -| to underlying strftime should not be used.
233.1239 -- """
233.1240 -| # The year must be >= 1900 else Python's strftime implementation
233.1241 -| # can raise a bogus exception.
233.1242 -| timetuple = (1900, 1, 1,
233.1243 -| self.__hour, self.__minute, self.__second,
233.1244 -| 0, 1, -1)
233.1245 -| return _wrap_strftime(self, fmt, timetuple)
233.1246 -|
233.1247 -| # Timezone functions
233.1248 --
233.1249 -+ def utcoffset(self):
233.1250 -+ """Return the timezone offset in minutes east of UTC (negative west of
233.1251 -- UTC)."""
233.1252 -| offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
233.1253 -| offset = _check_utc_offset("utcoffset", offset)
233.1254 -| if offset is not None:
233.1255 -| offset = timedelta(minutes=offset)
233.1256 -| return offset
233.1257 -|
233.1258 -- # Return an integer (or None) instead of a timedelta (or None).
233.1259 -+ def _utcoffset(self):
233.1260 -| offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
233.1261 -| offset = _check_utc_offset("utcoffset", offset)
233.1262 -| return offset
233.1263 --
233.1264 -+ def tzname(self):
233.1265 -+ """Return the timezone name.
233.1266 -|
233.1267 -| Note that the name is 100% informational -- there's no requirement that
233.1268 -| it mean anything in particular. For example, "GMT", "UTC", "-500",
233.1269 -| "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
233.1270 -- """
233.1271 -| name = _call_tzinfo_method(self._tzinfo, "tzname", None)
233.1272 -| _check_tzname(name)
233.1273 -| return name
233.1274 --
233.1275 -+ def dst(self):
233.1276 -+ """Return 0 if DST is not in effect, or the DST offset (in minutes
233.1277 -| eastward) if DST is in effect.
233.1278 -|
233.1279 -| This is purely informational; the DST offset has already been added to
233.1280 -| the UTC offset returned by utcoffset() if applicable, so there's no
233.1281 -| need to consult dst() unless you're interested in displaying the DST
233.1282 -| info.
233.1283 -- """
233.1284 -| offset = _call_tzinfo_method(self._tzinfo, "dst", None)
233.1285 -| offset = _check_utc_offset("dst", offset)
233.1286 -| if offset is not None:
233.1287 -| offset = timedelta(minutes=offset)
233.1288 -| return offset
233.1289 --
233.1290 -+ def replace(self, hour=None, minute=None, second=None, microsecond=None,
233.1291 -| tzinfo=True):
233.1292 -| """Return a new time with new values for the specified fields."""
233.1293 -| if hour is None:
233.1294 -| hour = self.hour
233.1295 -| if minute is None:
233.1296 -| minute = self.minute
233.1297 -| if second is None:
233.1298 -| second = self.second
233.1299 -| if microsecond is None:
233.1300 -| microsecond = self.microsecond
233.1301 -| if tzinfo is True:
233.1302 -| tzinfo = self.tzinfo
233.1303 -| _check_time_fields(hour, minute, second, microsecond)
233.1304 -| _check_tzinfo_arg(tzinfo)
233.1305 -| return time(hour, minute, second, microsecond, tzinfo)
233.1306 -|
233.1307 -- # Return an integer (or None) instead of a timedelta (or None).
233.1308 -+ def _dst(self):
233.1309 -| offset = _call_tzinfo_method(self._tzinfo, "dst", None)
233.1310 -| offset = _check_utc_offset("dst", offset)
233.1311 -| return offset
233.1312 --
233.1313 -+ def __nonzero__(self):
233.1314 -| if self.second or self.microsecond:
233.1315 -| return 1
233.1316 -| offset = self._utcoffset() or 0
233.1317 -| return self.hour * 60 + self.minute - offset != 0
233.1318 -|
233.1319 -| # Pickle support.
233.1320 --
233.1321 -| __safe_for_unpickling__ = True # For Python 2.2
233.1322 -|
233.1323 -+ def __getstate(self):
233.1324 -| us2, us3 = divmod(self.__microsecond, 256)
233.1325 -| us1, us2 = divmod(us2, 256)
233.1326 -| basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
233.1327 -| us1, us2, us3)
233.1328 -| if self._tzinfo is None:
233.1329 -| return (basestate,)
233.1330 -| else:
233.1331 -| return (basestate, self._tzinfo)
233.1332 --
233.1333 -+ def __setstate(self, state):
233.1334 -| assert isinstance(state, tuple)
233.1335 -| assert 1 <= len(state) <= 2
233.1336 -| string = state[0]
233.1337 -| assert len(string) == 6
233.1338 -| self.__hour, self.__minute, self.__second, us1, us2, us3 = \
233.1339 -| map(ord, string)
233.1340 -| self.__microsecond = (((us1 << 8) | us2) << 8) | us3
233.1341 -| if len(state) == 1:
233.1342 -| self._tzinfo = None
233.1343 -| else:
233.1344 -| self._tzinfo = state[1]
233.1345 --
233.1346 -+ def __reduce__(self):
233.1347 -| return (self.__class__, self.__getstate())
233.1348 --
233.1349 - _time_class = time # so functions w/ args named "time" can get at the class
233.1350 -
233.1351 - time.min = time(0, 0, 0)
233.1352 - time.max = time(23, 59, 59, 999999)
233.1353 - time.resolution = timedelta(microseconds=1)
233.1354 -
233.1355 -+ class datetime(date):
233.1356 -|
233.1357 -| # XXX needs docstrings
233.1358 -| # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
233.1359 -|
233.1360 -+ def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
233.1361 -| microsecond=0, tzinfo=None):
233.1362 -| if isinstance(year, str):
233.1363 -| # Pickle support
233.1364 -| self = date.__new__(cls, year[:4])
233.1365 -| self.__setstate((year, month))
233.1366 -| return self
233.1367 -| _check_tzinfo_arg(tzinfo)
233.1368 -| _check_time_fields(hour, minute, second, microsecond)
233.1369 -| self = date.__new__(cls, year, month, day)
233.1370 -| # XXX This duplicates __year, __month, __day for convenience :-(
233.1371 -| self.__year = year
233.1372 -| self.__month = month
233.1373 -| self.__day = day
233.1374 -| self.__hour = hour
233.1375 -| self.__minute = minute
233.1376 -| self.__second = second
233.1377 -| self.__microsecond = microsecond
233.1378 -| self._tzinfo = tzinfo
233.1379 -| return self
233.1380 -|
233.1381 -- # Read-only field accessors
233.1382 -| hour = property(lambda self: self.__hour, doc="hour (0-23)")
233.1383 -| minute = property(lambda self: self.__minute, doc="minute (0-59)")
233.1384 -| second = property(lambda self: self.__second, doc="second (0-59)")
233.1385 -| microsecond = property(lambda self: self.__microsecond,
233.1386 -| doc="microsecond (0-999999)")
233.1387 -| tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
233.1388 -|
233.1389 -+ def fromtimestamp(cls, t, tz=None):
233.1390 -+ """Construct a datetime from a POSIX timestamp (like time.time()).
233.1391 -|
233.1392 -| A timezone info object may be passed in as well.
233.1393 -- """
233.1394 -|
233.1395 -| _check_tzinfo_arg(tz)
233.1396 -| if tz is None:
233.1397 -| converter = _time.localtime
233.1398 -| else:
233.1399 -| converter = _time.gmtime
233.1400 -| y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
233.1401 -| us = int((t % 1.0) * 1000000)
233.1402 -| ss = min(ss, 59) # clamp out leap seconds if the platform has them
233.1403 -| result = cls(y, m, d, hh, mm, ss, us, tz)
233.1404 -| if tz is not None:
233.1405 -| result = tz.fromutc(result)
233.1406 -- return result
233.1407 -| fromtimestamp = classmethod(fromtimestamp)
233.1408 -|
233.1409 -+ def utcfromtimestamp(cls, t):
233.1410 -| "Construct a UTC datetime from a POSIX timestamp (like time.time())."
233.1411 -| y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
233.1412 -| us = int((t % 1.0) * 1000000)
233.1413 -| ss = min(ss, 59) # clamp out leap seconds if the platform has them
233.1414 -- return cls(y, m, d, hh, mm, ss, us)
233.1415 -| utcfromtimestamp = classmethod(utcfromtimestamp)
233.1416 -|
233.1417 -| # XXX This is supposed to do better than we *can* do by using time.time(),
233.1418 -| # XXX if the platform supports a more accurate way. The C implementation
233.1419 -| # XXX uses gettimeofday on platforms that have it, but that isn't
233.1420 -| # XXX available from Python. So now() may return different results
233.1421 -| # XXX across the implementations.
233.1422 -+ def now(cls, tz=None):
233.1423 -| "Construct a datetime from time.time() and optional time zone info."
233.1424 -| t = _time.time()
233.1425 -- return cls.fromtimestamp(t, tz)
233.1426 -| now = classmethod(now)
233.1427 -|
233.1428 -+ def utcnow(cls):
233.1429 -| "Construct a UTC datetime from time.time()."
233.1430 -| t = _time.time()
233.1431 -- return cls.utcfromtimestamp(t)
233.1432 -| utcnow = classmethod(utcnow)
233.1433 -|
233.1434 -+ def combine(cls, date, time):
233.1435 -| "Construct a datetime from a given date and a given time."
233.1436 -| if not isinstance(date, _date_class):
233.1437 -| raise TypeError("date argument must be a date instance")
233.1438 -| if not isinstance(time, _time_class):
233.1439 -| raise TypeError("time argument must be a time instance")
233.1440 -| return cls(date.year, date.month, date.day,
233.1441 -| time.hour, time.minute, time.second, time.microsecond,
233.1442 -- time.tzinfo)
233.1443 -| combine = classmethod(combine)
233.1444 -|
233.1445 -+ def timetuple(self):
233.1446 -| "Return local time tuple compatible with time.localtime()."
233.1447 -| dst = self._dst()
233.1448 -| if dst is None:
233.1449 -| dst = -1
233.1450 -| elif dst:
233.1451 -| dst = 1
233.1452 -| return _build_struct_time(self.year, self.month, self.day,
233.1453 -| self.hour, self.minute, self.second,
233.1454 -| dst)
233.1455 --
233.1456 -+ def utctimetuple(self):
233.1457 -| "Return UTC time tuple compatible with time.gmtime()."
233.1458 -| y, m, d = self.year, self.month, self.day
233.1459 -| hh, mm, ss = self.hour, self.minute, self.second
233.1460 -| offset = self._utcoffset()
233.1461 -| if offset: # neither None nor 0
233.1462 -| tm = tmxxx(y, m, d, hh, mm - offset)
233.1463 -| y, m, d = tm.year, tm.month, tm.day
233.1464 -| hh, mm = tm.hour, tm.minute
233.1465 -| return _build_struct_time(y, m, d, hh, mm, ss, 0)
233.1466 --
233.1467 -+ def date(self):
233.1468 -| "Return the date part."
233.1469 -| return date(self.__year, self.__month, self.__day)
233.1470 --
233.1471 -+ def time(self):
233.1472 -| "Return the time part, with tzinfo None."
233.1473 -| return time(self.hour, self.minute, self.second, self.microsecond)
233.1474 --
233.1475 -+ def timetz(self):
233.1476 -| "Return the time part, with same tzinfo."
233.1477 -| return time(self.hour, self.minute, self.second, self.microsecond,
233.1478 -| self._tzinfo)
233.1479 --
233.1480 -+ def replace(self, year=None, month=None, day=None, hour=None,
233.1481 -| minute=None, second=None, microsecond=None, tzinfo=True):
233.1482 -| """Return a new datetime with new values for the specified fields."""
233.1483 -| if year is None:
233.1484 -| year = self.year
233.1485 -| if month is None:
233.1486 -| month = self.month
233.1487 -| if day is None:
233.1488 -| day = self.day
233.1489 -| if hour is None:
233.1490 -| hour = self.hour
233.1491 -| if minute is None:
233.1492 -| minute = self.minute
233.1493 -| if second is None:
233.1494 -| second = self.second
233.1495 -| if microsecond is None:
233.1496 -| microsecond = self.microsecond
233.1497 -| if tzinfo is True:
233.1498 -| tzinfo = self.tzinfo
233.1499 -| _check_date_fields(year, month, day)
233.1500 -| _check_time_fields(hour, minute, second, microsecond)
233.1501 -| _check_tzinfo_arg(tzinfo)
233.1502 -| return datetime(year, month, day, hour, minute, second,
233.1503 -| microsecond, tzinfo)
233.1504 --
233.1505 -+ def astimezone(self, tz):
233.1506 -| if not isinstance(tz, tzinfo):
233.1507 -| raise TypeError("tz argument must be an instance of tzinfo")
233.1508 -|
233.1509 -| mytz = self.tzinfo
233.1510 -| if mytz is None:
233.1511 -| raise ValueError("astimezone() requires an aware datetime")
233.1512 -|
233.1513 -| if tz is mytz:
233.1514 -| return self
233.1515 -|
233.1516 -| # Convert self to UTC, and attach the new time zone object.
233.1517 -| myoffset = self.utcoffset()
233.1518 -| if myoffset is None:
233.1519 -| raise ValuError("astimezone() requires an aware datetime")
233.1520 -| utc = (self - myoffset).replace(tzinfo=tz)
233.1521 -|
233.1522 -| # Convert from UTC to tz's local time.
233.1523 -| return tz.fromutc(utc)
233.1524 -|
233.1525 -| # Ways to produce a string.
233.1526 --
233.1527 -+ def ctime(self):
233.1528 -| "Format a la ctime()."
233.1529 -| t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
233.1530 -| self.__minute, self.__second)
233.1531 -| return t.ctime()
233.1532 --
233.1533 -+ def isoformat(self, sep='T'):
233.1534 -+ """Return the time formatted according to ISO.
233.1535 -|
233.1536 -| This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
233.1537 -| self.microsecond == 0.
233.1538 -|
233.1539 -| If self.tzinfo is not None, the UTC offset is also attached, giving
233.1540 -| 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
233.1541 -|
233.1542 -| Optional argument sep specifies the separator between date and
233.1543 -| time, default 'T'.
233.1544 -- """
233.1545 -| s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
233.1546 -| sep) +
233.1547 -| _format_time(self.__hour, self.__minute, self.__second,
233.1548 -| self.__microsecond))
233.1549 -| off = self._utcoffset()
233.1550 -| if off is not None:
233.1551 -| if off < 0:
233.1552 -| sign = "-"
233.1553 -| off = -off
233.1554 -| else:
233.1555 -| sign = "+"
233.1556 -| hh, mm = divmod(off, 60)
233.1557 -| s += "%s%02d:%02d" % (sign, hh, mm)
233.1558 -| return s
233.1559 --
233.1560 -+ def __repr__(self):
233.1561 -| "Convert to formal string, for repr()."
233.1562 -| L = [self.__year, self.__month, self.__day, # These are never zero
233.1563 -| self.__hour, self.__minute, self.__second, self.__microsecond]
233.1564 -| if L[-1] == 0:
233.1565 -| del L[-1]
233.1566 -| if L[-1] == 0:
233.1567 -| del L[-1]
233.1568 -| s = ", ".join(map(str, L))
233.1569 -| s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
233.1570 -| if self._tzinfo is not None:
233.1571 -| assert s[-1:] == ")"
233.1572 -| s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
233.1573 -| return s
233.1574 --
233.1575 -+ def __str__(self):
233.1576 -| "Convert to string, for str()."
233.1577 -| return self.isoformat(sep=' ')
233.1578 --
233.1579 -+ def utcoffset(self):
233.1580 -+ """Return the timezone offset in minutes east of UTC (negative west of
233.1581 -- UTC)."""
233.1582 -| offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
233.1583 -| offset = _check_utc_offset("utcoffset", offset)
233.1584 -| if offset is not None:
233.1585 -| offset = timedelta(minutes=offset)
233.1586 -| return offset
233.1587 -|
233.1588 -- # Return an integer (or None) instead of a timedelta (or None).
233.1589 -+ def _utcoffset(self):
233.1590 -| offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
233.1591 -| offset = _check_utc_offset("utcoffset", offset)
233.1592 -| return offset
233.1593 --
233.1594 -+ def tzname(self):
233.1595 -+ """Return the timezone name.
233.1596 -|
233.1597 -| Note that the name is 100% informational -- there's no requirement that
233.1598 -| it mean anything in particular. For example, "GMT", "UTC", "-500",
233.1599 -| "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
233.1600 -- """
233.1601 -| name = _call_tzinfo_method(self._tzinfo, "tzname", self)
233.1602 -| _check_tzname(name)
233.1603 -| return name
233.1604 --
233.1605 -+ def dst(self):
233.1606 -+ """Return 0 if DST is not in effect, or the DST offset (in minutes
233.1607 -| eastward) if DST is in effect.
233.1608 -|
233.1609 -| This is purely informational; the DST offset has already been added to
233.1610 -| the UTC offset returned by utcoffset() if applicable, so there's no
233.1611 -| need to consult dst() unless you're interested in displaying the DST
233.1612 -| info.
233.1613 -- """
233.1614 -| offset = _call_tzinfo_method(self._tzinfo, "dst", self)
233.1615 -| offset = _check_utc_offset("dst", offset)
233.1616 -| if offset is not None:
233.1617 -| offset = timedelta(minutes=offset)
233.1618 -| return offset
233.1619 -|
233.1620 -- # Return an integer (or None) instead of a timedelta (or None).1573
233.1621 -+ def _dst(self):
233.1622 -| offset = _call_tzinfo_method(self._tzinfo, "dst", self)
233.1623 -| offset = _check_utc_offset("dst", offset)
233.1624 -| return offset
233.1625 -|
233.1626 -| # Comparisons.
233.1627 --
233.1628 -+ def __eq__(self, other):
233.1629 -| if isinstance(other, datetime):
233.1630 -| return self.__cmp(other) == 0
233.1631 -| elif hasattr(other, "timetuple"):
233.1632 -| return NotImplemented
233.1633 -| else:
233.1634 -| return False
233.1635 --
233.1636 -+ def __ne__(self, other):
233.1637 -| if isinstance(other, datetime):
233.1638 -| return self.__cmp(other) != 0
233.1639 -| elif hasattr(other, "timetuple"):
233.1640 -| return NotImplemented
233.1641 -| else:
233.1642 -| return True
233.1643 --
233.1644 -+ def __le__(self, other):
233.1645 -| if isinstance(other, datetime):
233.1646 -| return self.__cmp(other) <= 0
233.1647 -| elif hasattr(other, "timetuple"):
233.1648 -| return NotImplemented
233.1649 -| else:
233.1650 -| _cmperror(self, other)
233.1651 --
233.1652 -+ def __lt__(self, other):
233.1653 -| if isinstance(other, datetime):
233.1654 -| return self.__cmp(other) < 0
233.1655 -| elif hasattr(other, "timetuple"):
233.1656 -| return NotImplemented
233.1657 -| else:
233.1658 -| _cmperror(self, other)
233.1659 --
233.1660 -+ def __ge__(self, other):
233.1661 -| if isinstance(other, datetime):
233.1662 -| return self.__cmp(other) >= 0
233.1663 -| elif hasattr(other, "timetuple"):
233.1664 -| return NotImplemented
233.1665 -| else:
233.1666 -| _cmperror(self, other)
233.1667 --
233.1668 -+ def __gt__(self, other):
233.1669 -| if isinstance(other, datetime):
233.1670 -| return self.__cmp(other) > 0
233.1671 -| elif hasattr(other, "timetuple"):
233.1672 -| return NotImplemented
233.1673 -| else:
233.1674 -| _cmperror(self, other)
233.1675 --
233.1676 -+ def __cmp(self, other):
233.1677 -| assert isinstance(other, datetime)
233.1678 -| mytz = self._tzinfo
233.1679 -| ottz = other._tzinfo
233.1680 -| myoff = otoff = None
233.1681 -|
233.1682 -| if mytz is ottz:
233.1683 -| base_compare = True
233.1684 -| else:
233.1685 -| if mytz is not None:
233.1686 -| myoff = self._utcoffset()
233.1687 -| if ottz is not None:
233.1688 -| otoff = other._utcoffset()
233.1689 -| base_compare = myoff == otoff
233.1690 -|
233.1691 -| if base_compare:
233.1692 -| return cmp((self.__year, self.__month, self.__day,
233.1693 -| self.__hour, self.__minute, self.__second,
233.1694 -| self.__microsecond),
233.1695 -| (other.__year, other.__month, other.__day,
233.1696 -| other.__hour, other.__minute, other.__second,
233.1697 -| other.__microsecond))
233.1698 -| if myoff is None or otoff is None:
233.1699 -| # XXX Buggy in 2.2.2.
233.1700 -| raise TypeError("cannot compare naive and aware datetimes")
233.1701 -| # XXX What follows could be done more efficiently...
233.1702 -| diff = self - other # this will take offsets into account
233.1703 -| if diff.days < 0:
233.1704 -| return -1
233.1705 -| return diff and 1 or 0
233.1706 --
233.1707 -+ def __add__(self, other):
233.1708 -| "Add a datetime and a timedelta."
233.1709 -| if not isinstance(other, timedelta):
233.1710 -| return NotImplemented
233.1711 -| t = tmxxx(self.__year,
233.1712 -| self.__month,
233.1713 -| self.__day + other.days,
233.1714 -| self.__hour,
233.1715 -| self.__minute,
233.1716 -| self.__second + other.seconds,
233.1717 -| self.__microsecond + other.microseconds)
233.1718 -| self._checkOverflow(t.year)
233.1719 -| result = self.__class__(t.year, t.month, t.day,
233.1720 -| t.hour, t.minute, t.second,
233.1721 -| t.microsecond, tzinfo=self._tzinfo)
233.1722 -| return result
233.1723 --
233.1724 -| __radd__ = __add__
233.1725 -|
233.1726 -+ def __sub__(self, other):
233.1727 -| "Subtract two datetimes, or a datetime and a timedelta."
233.1728 -| if not isinstance(other, datetime):
233.1729 -| if isinstance(other, timedelta):
233.1730 -| return self + -other
233.1731 -| return NotImplemented
233.1732 -|
233.1733 -| days1 = self.toordinal()
233.1734 -| days2 = other.toordinal()
233.1735 -| secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
233.1736 -| secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
233.1737 -| base = timedelta(days1 - days2,
233.1738 -| secs1 - secs2,
233.1739 -| self.__microsecond - other.__microsecond)
233.1740 -| if self._tzinfo is other._tzinfo:
233.1741 -| return base
233.1742 -| myoff = self._utcoffset()
233.1743 -| otoff = other._utcoffset()
233.1744 -| if myoff == otoff:
233.1745 -| return base
233.1746 -| if myoff is None or otoff is None:
233.1747 -| raise TypeError, "cannot mix naive and timezone-aware time"
233.1748 -| return base + timedelta(minutes = otoff-myoff)
233.1749 --
233.1750 -+ def __hash__(self):
233.1751 -| tzoff = self._utcoffset()
233.1752 -| if tzoff is None:
233.1753 -| return hash(self.__getstate()[0])
233.1754 -| days = _ymd2ord(self.year, self.month, self.day)
233.1755 -| seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
233.1756 -| return hash(timedelta(days, seconds, self.microsecond))
233.1757 -|
233.1758 -| # Pickle support.
233.1759 --
233.1760 -| __safe_for_unpickling__ = True # For Python 2.2
233.1761 -|
233.1762 -+ def __getstate(self):
233.1763 -| yhi, ylo = divmod(self.__year, 256)
233.1764 -| us2, us3 = divmod(self.__microsecond, 256)
233.1765 -| us1, us2 = divmod(us2, 256)
233.1766 -| basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
233.1767 -| self.__hour, self.__minute, self.__second,
233.1768 -| us1, us2, us3)
233.1769 -| if self._tzinfo is None:
233.1770 -| return (basestate,)
233.1771 -| else:
233.1772 -| return (basestate, self._tzinfo)
233.1773 --
233.1774 -+ def __setstate(self, state):
233.1775 -| assert isinstance(state, tuple)
233.1776 -| assert 1 <= len(state) <= 2
233.1777 -| string = state[0]
233.1778 -| assert len(string) == 10
233.1779 -| (yhi, ylo, self.__month, self.__day, self.__hour,
233.1780 -| self.__minute, self.__second, us1, us2, us3) = map(ord, string)
233.1781 -| self.__year = yhi * 256 + ylo
233.1782 -| self.__microsecond = (((us1 << 8) | us2) << 8) | us3
233.1783 -| if len(state) == 1:
233.1784 -| self._tzinfo = None
233.1785 -| else:
233.1786 -| self._tzinfo = state[1]
233.1787 --
233.1788 -+ def __reduce__(self):
233.1789 -| return (self.__class__, self.__getstate())
233.1790 -|
233.1791 --
233.1792 - datetime.min = datetime(1, 1, 1)
233.1793 - datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
233.1794 - datetime.resolution = timedelta(microseconds=1)
233.1795 -
233.1796 -
233.1797 -+ def _isoweek1monday(year):
233.1798 -| # Helper to calculate the day number of the Monday starting week 1
233.1799 -| # XXX This could be done more efficiently
233.1800 -| THURSDAY = 3
233.1801 -| firstday = _ymd2ord(year, 1, 1)
233.1802 -| firstweekday = (firstday + 6) % 7 # See weekday() above
233.1803 -| week1monday = firstday - firstweekday
233.1804 -| if firstweekday > THURSDAY:
233.1805 -| week1monday += 7
233.1806 -| return week1monday
233.1807 --
233.1808 -+ """
233.1809 -| Some time zone algebra. For a datetime x, let
233.1810 -| x.n = x stripped of its timezone -- its naive time.
233.1811 -| x.o = x.utcoffset(), and assuming that doesn't raise an exception or
233.1812 -| return None
233.1813 -| x.d = x.dst(), and assuming that doesn't raise an exception or
233.1814 -| return None
233.1815 -| x.s = x's standard offset, x.o - x.d
233.1816 -|
233.1817 -| Now some derived rules, where k is a duration (timedelta).
233.1818 -|
233.1819 -| 1. x.o = x.s + x.d
233.1820 -| This follows from the definition of x.s.
233.1821 -|
233.1822 -| 2. If x and y have the same tzinfo member, x.s = y.s.
233.1823 -| This is actually a requirement, an assumption we need to make about
233.1824 -| sane tzinfo classes.
233.1825 -|
233.1826 -| 3. The naive UTC time corresponding to x is x.n - x.o.
233.1827 -| This is again a requirement for a sane tzinfo class.
233.1828 -|
233.1829 -| 4. (x+k).s = x.s
233.1830 -| This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
233.1831 -|
233.1832 -| 5. (x+k).n = x.n + k
233.1833 -| Again follows from how arithmetic is defined.
233.1834 -|
233.1835 -| Now we can explain tz.fromutc(x). Let's assume it's an interesting case
233.1836 -| (meaning that the various tzinfo methods exist, and don't blow up or return
233.1837 -| None when called).
233.1838 -|
233.1839 -| The function wants to return a datetime y with timezone tz, equivalent to x.
233.1840 -| x is already in UTC.
233.1841 -|
233.1842 -| By #3, we want
233.1843 -|
233.1844 -| y.n - y.o = x.n [1]
233.1845 -|
233.1846 -| The algorithm starts by attaching tz to x.n, and calling that y. So
233.1847 -| x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
233.1848 -| becomes true; in effect, we want to solve [2] for k:
233.1849 -|
233.1850 -| (y+k).n - (y+k).o = x.n [2]
233.1851 -|
233.1852 -| By #1, this is the same as
233.1853 -|
233.1854 -| (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
233.1855 -|
233.1856 -| By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
233.1857 -| Substituting that into [3],
233.1858 -|
233.1859 -| x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
233.1860 -| k - (y+k).s - (y+k).d = 0; rearranging,
233.1861 -| k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
233.1862 -| k = y.s - (y+k).d
233.1863 -|
233.1864 -| On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
233.1865 -| approximate k by ignoring the (y+k).d term at first. Note that k can't be
233.1866 -| very large, since all offset-returning methods return a duration of magnitude
233.1867 -| less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
233.1868 -| be 0, so ignoring it has no consequence then.
233.1869 -|
233.1870 -| In any case, the new value is
233.1871 -|
233.1872 -| z = y + y.s [4]
233.1873 -|
233.1874 -| It's helpful to step back at look at [4] from a higher level: it's simply
233.1875 -| mapping from UTC to tz's standard time.
233.1876 -|
233.1877 -| At this point, if
233.1878 -|
233.1879 -| z.n - z.o = x.n [5]
233.1880 -|
233.1881 -| we have an equivalent time, and are almost done. The insecurity here is
233.1882 -| at the start of daylight time. Picture US Eastern for concreteness. The wall
233.1883 -| time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
233.1884 -| sense then. The docs ask that an Eastern tzinfo class consider such a time to
233.1885 -| be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
233.1886 -| on the day DST starts. We want to return the 1:MM EST spelling because that's
233.1887 -| the only spelling that makes sense on the local wall clock.
233.1888 -|
233.1889 -| In fact, if [5] holds at this point, we do have the standard-time spelling,
233.1890 -| but that takes a bit of proof. We first prove a stronger result. What's the
233.1891 -| difference between the LHS and RHS of [5]? Let
233.1892 -|
233.1893 -| diff = x.n - (z.n - z.o) [6]
233.1894 -|
233.1895 -| Now
233.1896 -| z.n = by [4]
233.1897 -| (y + y.s).n = by #5
233.1898 -| y.n + y.s = since y.n = x.n
233.1899 -| x.n + y.s = since z and y are have the same tzinfo member,
233.1900 -| y.s = z.s by #2
233.1901 -| x.n + z.s
233.1902 -|
233.1903 -| Plugging that back into [6] gives
233.1904 -|
233.1905 -| diff =
233.1906 -| x.n - ((x.n + z.s) - z.o) = expanding
233.1907 -| x.n - x.n - z.s + z.o = cancelling
233.1908 -| - z.s + z.o = by #2
233.1909 -| z.d
233.1910 -|
233.1911 -| So diff = z.d.
233.1912 -|
233.1913 -| If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
233.1914 -| spelling we wanted in the endcase described above. We're done. Contrarily,
233.1915 -| if z.d = 0, then we have a UTC equivalent, and are also done.
233.1916 -|
233.1917 -| If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
233.1918 -| add to z (in effect, z is in tz's standard time, and we need to shift the
233.1919 -| local clock into tz's daylight time).
233.1920 -|
233.1921 -| Let
233.1922 -|
233.1923 -| z' = z + z.d = z + diff [7]
233.1924 -|
233.1925 -| and we can again ask whether
233.1926 -|
233.1927 -| z'.n - z'.o = x.n [8]
233.1928 -|
233.1929 -| If so, we're done. If not, the tzinfo class is insane, according to the
233.1930 -| assumptions we've made. This also requires a bit of proof. As before, let's
233.1931 -| compute the difference between the LHS and RHS of [8] (and skipping some of
233.1932 -| the justifications for the kinds of substitutions we've done several times
233.1933 -| already):
233.1934 -|
233.1935 -| diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
233.1936 -| x.n - (z.n + diff - z'.o) = replacing diff via [6]
233.1937 -| x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
233.1938 -| x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
233.1939 -| - z.n + z.n - z.o + z'.o = cancel z.n
233.1940 -| - z.o + z'.o = #1 twice
233.1941 -| -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
233.1942 -| z'.d - z.d
233.1943 -|
233.1944 -| So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
233.1945 -| we've found the UTC-equivalent so are done. In fact, we stop with [7] and
233.1946 -| return z', not bothering to compute z'.d.
233.1947 -|
233.1948 -| How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
233.1949 -| a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
233.1950 -| would have to change the result dst() returns: we start in DST, and moving
233.1951 -| a little further into it takes us out of DST.
233.1952 -|
233.1953 -| There isn't a sane case where this can happen. The closest it gets is at
233.1954 -| the end of DST, where there's an hour in UTC with no spelling in a hybrid
233.1955 -| tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
233.1956 -| that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
233.1957 -| UTC) because the docs insist on that, but 0:MM is taken as being in daylight
233.1958 -| time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
233.1959 -| clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
233.1960 -| standard time. Since that's what the local clock *does*, we want to map both
233.1961 -| UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
233.1962 -| in local time, but so it goes -- it's the way the local clock works.
233.1963 -|
233.1964 -| When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
233.1965 -| so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
233.1966 -| z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
233.1967 -| (correctly) concludes that z' is not UTC-equivalent to x.
233.1968 -|
233.1969 -| Because we know z.d said z was in daylight time (else [5] would have held and
233.1970 -| we would have stopped then), and we know z.d != z'.d (else [8] would have held
233.1971 -| and we we have stopped then), and there are only 2 possible values dst() can
233.1972 -| return in Eastern, it follows that z'.d must be 0 (which it is in the example,
233.1973 -| but the reasoning doesn't depend on the example -- it depends on there being
233.1974 -| two possible dst() outcomes, one zero and the other non-zero). Therefore
233.1975 -| z' must be in standard time, and is the spelling we want in this case.
233.1976 -|
233.1977 -| Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
233.1978 -| concerned (because it takes z' as being in standard time rather than the
233.1979 -| daylight time we intend here), but returning it gives the real-life "local
233.1980 -| clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
233.1981 -| tz.
233.1982 -|
233.1983 -| When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
233.1984 -| the 1:MM standard time spelling we want.
233.1985 -|
233.1986 -| So how can this break? One of the assumptions must be violated. Two
233.1987 -| possibilities:
233.1988 -|
233.1989 -| 1) [2] effectively says that y.s is invariant across all y belong to a given
233.1990 -| time zone. This isn't true if, for political reasons or continental drift,
233.1991 -| a region decides to change its base offset from UTC.
233.1992 -|
233.1993 -| 2) There may be versions of "double daylight" time where the tail end of
233.1994 -| the analysis gives up a step too early. I haven't thought about that
233.1995 -| enough to say.
233.1996 -|
233.1997 -| In any case, it's clear that the default fromutc() is strong enough to handle
233.1998 -| "almost all" time zones: so long as the standard offset is invariant, it
233.1999 -| doesn't matter if daylight time transition points change from year to year, or
233.2000 -| if daylight time is skipped in some years; it doesn't matter how large or
233.2001 -| small dst() may get within its bounds; and it doesn't even matter if some
233.2002 -| perverse time zone returns a negative dst()). So a breaking case must be
233.2003 -| pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
233.2004 -- """
233.2005 -
233.2006 -+ def _test():
233.2007 -| import test_datetime
233.2008 -| test_datetime.test_main()
233.2009 --
233.2010 - if __name__ == "__main__":
233.2011 - _test()
233.2012 -
234.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.formatted Sun Jan 04 13:11:53 2015 -0600
234.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
234.3 @@ -1,2008 +0,0 @@
234.4 -"""Concrete date/time and related types -- prototype implemented in Python.
234.5 -
234.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
234.7 -
234.8 -See also http://dir.yahoo.com/Reference/calendars/
234.9 -
234.10 -For a primer on DST, including many current DST rules, see
234.11 -http://webexhibits.org/daylightsaving/
234.12 -
234.13 -For more about DST than you ever wanted to know, see
234.14 -ftp://elsie.nci.nih.gov/pub/
234.15 -
234.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
234.17 -
234.18 -"""
234.19 -
234.20 -import math as _math
234.21 -import time as _time
234.22 -
234.23 -MINYEAR = 1
234.24 -MAXYEAR = 9999
234.25 -
234.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
234.27 -# also assumes the current Gregorian calendar indefinitely extended in
234.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
234.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
234.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
234.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
234.32 -# for all computations. See the book for algorithms for converting between
234.33 -# proleptic Gregorian ordinals and many other calendar systems.
234.34 -
234.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
234.36 -
234.37 -_DAYS_BEFORE_MONTH = [None]
234.38 -dbm = 0
234.39 -for dim in _DAYS_IN_MONTH[1:]:
234.40 - _DAYS_BEFORE_MONTH.append(dbm)
234.41 - dbm += dim
234.42 -del dbm, dim
234.43 -
234.44 -def _is_leap(year):
234.45 - "year -> 1 if leap year, else 0."
234.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
234.47 -
234.48 -def _days_in_year(year):
234.49 - "year -> number of days in year (366 if a leap year, else 365)."
234.50 - return 365 + _is_leap(year)
234.51 -
234.52 -def _days_before_year(year):
234.53 - "year -> number of days before January 1st of year."
234.54 - y = year - 1
234.55 - return y * 365 + y // 4 - y // 100 + y // 400
234.56 -
234.57 -def _days_in_month(year, month):
234.58 - "year, month -> number of days in that month in that year."
234.59 - assert 1 <= month <= 12, month
234.60 - if month == 2 and _is_leap(year):
234.61 - return 29
234.62 - return _DAYS_IN_MONTH[month]
234.63 -
234.64 -def _days_before_month(year, month):
234.65 - "year, month -> number of days in year preceeding first day of month."
234.66 - if not 1 <= month <= 12:
234.67 - raise ValueError('month must be in 1..12', month)
234.68 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
234.69 -
234.70 -def _ymd2ord(year, month, day):
234.71 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
234.72 - if not 1 <= month <= 12:
234.73 - raise ValueError('month must be in 1..12', month)
234.74 - dim = _days_in_month(year, month)
234.75 - if not 1 <= day <= dim:
234.76 - raise ValueError('day must be in 1..%d' % dim, day)
234.77 - return (_days_before_year(year) +
234.78 - _days_before_month(year, month) +
234.79 - day)
234.80 -
234.81 -_DI400Y = _days_before_year(401) # number of days in 400 years
234.82 -_DI100Y = _days_before_year(101) # " " " " 100 "
234.83 -_DI4Y = _days_before_year(5) # " " " " 4 "
234.84 -
234.85 -# A 4-year cycle has an extra leap day over what we'd get from pasting
234.86 -# together 4 single years.
234.87 -assert _DI4Y == 4 * 365 + 1
234.88 -
234.89 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
234.90 -# pasting together 4 100-year cycles.
234.91 -assert _DI400Y == 4 * _DI100Y + 1
234.92 -
234.93 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
234.94 -# pasting together 25 4-year cycles.
234.95 -assert _DI100Y == 25 * _DI4Y - 1
234.96 -
234.97 -def _ord2ymd(n):
234.98 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
234.99 -
234.100 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
234.101 - # repeats exactly every 400 years. The basic strategy is to find the
234.102 - # closest 400-year boundary at or before n, then work with the offset
234.103 - # from that boundary to n. Life is much clearer if we subtract 1 from
234.104 - # n first -- then the values of n at 400-year boundaries are exactly
234.105 - # those divisible by _DI400Y:
234.106 - #
234.107 - # D M Y n n-1
234.108 - # -- --- ---- ---------- ----------------
234.109 - # 31 Dec -400 -_DI400Y -_DI400Y -1
234.110 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
234.111 - # ...
234.112 - # 30 Dec 000 -1 -2
234.113 - # 31 Dec 000 0 -1
234.114 - # 1 Jan 001 1 0 400-year boundary
234.115 - # 2 Jan 001 2 1
234.116 - # 3 Jan 001 3 2
234.117 - # ...
234.118 - # 31 Dec 400 _DI400Y _DI400Y -1
234.119 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
234.120 - n -= 1
234.121 - n400, n = divmod(n, _DI400Y)
234.122 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
234.123 -
234.124 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
234.125 - # the desired date. Now compute how many 100-year cycles precede n.
234.126 - # Note that it's possible for n100 to equal 4! In that case 4 full
234.127 - # 100-year cycles precede the desired day, which implies the desired
234.128 - # day is December 31 at the end of a 400-year cycle.
234.129 - n100, n = divmod(n, _DI100Y)
234.130 -
234.131 - # Now compute how many 4-year cycles precede it.
234.132 - n4, n = divmod(n, _DI4Y)
234.133 -
234.134 - # And now how many single years. Again n1 can be 4, and again meaning
234.135 - # that the desired day is December 31 at the end of the 4-year cycle.
234.136 - n1, n = divmod(n, 365)
234.137 -
234.138 - year += n100 * 100 + n4 * 4 + n1
234.139 - if n1 == 4 or n100 == 4:
234.140 - assert n == 0
234.141 - return year-1, 12, 31
234.142 -
234.143 - # Now the year is correct, and n is the offset from January 1. We find
234.144 - # the month via an estimate that's either exact or one too large.
234.145 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
234.146 - assert leapyear == _is_leap(year)
234.147 - month = (n + 50) >> 5
234.148 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
234.149 - if preceding > n: # estimate is too large
234.150 - month -= 1
234.151 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
234.152 - n -= preceding
234.153 - assert 0 <= n < _days_in_month(year, month)
234.154 -
234.155 - # Now the year and month are correct, and n is the offset from the
234.156 - # start of that month: we're done!
234.157 - return year, month, n + 1
234.158 -
234.159 -# Month and day names. For localized versions, see the calendar module.
234.160 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
234.161 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
234.162 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
234.163 -
234.164 -
234.165 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
234.166 - wday = (_ymd2ord(y, m, d) + 6) % 7
234.167 - dnum = _days_before_month(y, m) + d
234.168 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
234.169 -
234.170 -def _format_time(hh, mm, ss, us):
234.171 - # Skip trailing microseconds when us==0.
234.172 - result = "%02d:%02d:%02d" % (hh, mm, ss)
234.173 - if us:
234.174 - result += ".%06d" % us
234.175 - return result
234.176 -
234.177 -# Correctly substitute for %z and %Z escapes in strftime formats.
234.178 -def _wrap_strftime(object, format, timetuple):
234.179 - year = timetuple[0]
234.180 - if year < 1900:
234.181 - raise ValueError("year=%d is before 1900; the datetime strftime() "
234.182 - "methods require year >= 1900" % year)
234.183 - # Don't call _utcoffset() or tzname() unless actually needed.
234.184 - zreplace = None # the string to use for %z
234.185 - Zreplace = None # the string to use for %Z
234.186 -
234.187 - # Scan format for %z and %Z escapes, replacing as needed.
234.188 - newformat = []
234.189 - push = newformat.append
234.190 - i, n = 0, len(format)
234.191 - while i < n:
234.192 - ch = format[i]
234.193 - i += 1
234.194 - if ch == '%':
234.195 - if i < n:
234.196 - ch = format[i]
234.197 - i += 1
234.198 - if ch == 'z':
234.199 - if zreplace is None:
234.200 - zreplace = ""
234.201 - if hasattr(object, "_utcoffset"):
234.202 - offset = object._utcoffset()
234.203 - if offset is not None:
234.204 - sign = '+'
234.205 - if offset < 0:
234.206 - offset = -offset
234.207 - sign = '-'
234.208 - h, m = divmod(offset, 60)
234.209 - zreplace = '%c%02d%02d' % (sign, h, m)
234.210 - assert '%' not in zreplace
234.211 - newformat.append(zreplace)
234.212 - elif ch == 'Z':
234.213 - if Zreplace is None:
234.214 - Zreplace = ""
234.215 - if hasattr(object, "tzname"):
234.216 - s = object.tzname()
234.217 - if s is not None:
234.218 - # strftime is going to have at this: escape %
234.219 - Zreplace = s.replace('%', '%%')
234.220 - newformat.append(Zreplace)
234.221 - else:
234.222 - push('%')
234.223 - push(ch)
234.224 - else:
234.225 - push('%')
234.226 - else:
234.227 - push(ch)
234.228 - newformat = "".join(newformat)
234.229 - return _time.strftime(newformat, timetuple)
234.230 -
234.231 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
234.232 - if tzinfo is None:
234.233 - return None
234.234 - return getattr(tzinfo, methname)(tzinfoarg)
234.235 -
234.236 -# Just raise TypeError if the arg isn't None or a string.
234.237 -def _check_tzname(name):
234.238 - if name is not None and not isinstance(name, str):
234.239 - raise TypeError("tzinfo.tzname() must return None or string, "
234.240 - "not '%s'" % type(name))
234.241 -
234.242 -# name is the offset-producing method, "utcoffset" or "dst".
234.243 -# offset is what it returned.
234.244 -# If offset isn't None or timedelta, raises TypeError.
234.245 -# If offset is None, returns None.
234.246 -# Else offset is checked for being in range, and a whole # of minutes.
234.247 -# If it is, its integer value is returned. Else ValueError is raised.
234.248 -def _check_utc_offset(name, offset):
234.249 - assert name in ("utcoffset", "dst")
234.250 - if offset is None:
234.251 - return None
234.252 - if not isinstance(offset, timedelta):
234.253 - raise TypeError("tzinfo.%s() must return None "
234.254 - "or timedelta, not '%s'" % (name, type(offset)))
234.255 - days = offset.days
234.256 - if days < -1 or days > 0:
234.257 - offset = 1440 # trigger out-of-range
234.258 - else:
234.259 - seconds = days * 86400 + offset.seconds
234.260 - minutes, seconds = divmod(seconds, 60)
234.261 - if seconds or offset.microseconds:
234.262 - raise ValueError("tzinfo.%s() must return a whole number "
234.263 - "of minutes" % name)
234.264 - offset = minutes
234.265 - if -1440 < offset < 1440:
234.266 - return offset
234.267 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
234.268 -
234.269 -def _check_date_fields(year, month, day):
234.270 - if not MINYEAR <= year <= MAXYEAR:
234.271 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
234.272 - if not 1 <= month <= 12:
234.273 - raise ValueError('month must be in 1..12', month)
234.274 - dim = _days_in_month(year, month)
234.275 - if not 1 <= day <= dim:
234.276 - raise ValueError('day must be in 1..%d' % dim, day)
234.277 -
234.278 -def _check_time_fields(hour, minute, second, microsecond):
234.279 - if not 0 <= hour <= 23:
234.280 - raise ValueError('hour must be in 0..23', hour)
234.281 - if not 0 <= minute <= 59:
234.282 - raise ValueError('minute must be in 0..59', minute)
234.283 - if not 0 <= second <= 59:
234.284 - raise ValueError('second must be in 0..59', second)
234.285 - if not 0 <= microsecond <= 999999:
234.286 - raise ValueError('microsecond must be in 0..999999', microsecond)
234.287 -
234.288 -def _check_tzinfo_arg(tz):
234.289 - if tz is not None and not isinstance(tz, tzinfo):
234.290 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
234.291 -
234.292 -
234.293 -# Notes on comparison: In general, datetime module comparison operators raise
234.294 -# TypeError when they don't know how to do a comparison themself. If they
234.295 -# returned NotImplemented instead, comparison could (silently) fall back to
234.296 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
234.297 -# and that's not helpful. There are two exceptions:
234.298 -#
234.299 -# 1. For date and datetime, if the other object has a "timetuple" attr,
234.300 -# NotImplemented is returned. This is a hook to allow other kinds of
234.301 -# datetime-like objects a chance to intercept the comparison.
234.302 -#
234.303 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
234.304 -# so opertaions like
234.305 -#
234.306 -# x == y
234.307 -# x != y
234.308 -# x in sequence
234.309 -# x not in sequence
234.310 -# dict[x] = y
234.311 -#
234.312 -# don't raise annoying TypeErrors just because a datetime object
234.313 -# is part of a heterogeneous collection. If there's no known way to
234.314 -# compare X to a datetime, saying they're not equal is reasonable.
234.315 -
234.316 -def _cmperror(x, y):
234.317 - raise TypeError("can't compare '%s' to '%s'" % (
234.318 - type(x).__name__, type(y).__name__))
234.319 -
234.320 -# This is a start at a struct tm workalike. Goals:
234.321 -#
234.322 -# + Works the same way across platforms.
234.323 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
234.324 -#
234.325 -# Note: I suspect it's best if this flavor of tm does *not* try to
234.326 -# second-guess timezones or DST. Instead fold whatever adjustments you want
234.327 -# into the minutes argument (and the constructor will normalize).
234.328 -
234.329 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
234.330 -
234.331 -class tmxxx:
234.332 -
234.333 - ordinal = None
234.334 -
234.335 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
234.336 - microsecond=0):
234.337 - # Normalize all the inputs, and store the normalized values.
234.338 - if not 0 <= microsecond <= 999999:
234.339 - carry, microsecond = divmod(microsecond, 1000000)
234.340 - second += carry
234.341 - if not 0 <= second <= 59:
234.342 - carry, second = divmod(second, 60)
234.343 - minute += carry
234.344 - if not 0 <= minute <= 59:
234.345 - carry, minute = divmod(minute, 60)
234.346 - hour += carry
234.347 - if not 0 <= hour <= 23:
234.348 - carry, hour = divmod(hour, 24)
234.349 - day += carry
234.350 -
234.351 - # That was easy. Now it gets muddy: the proper range for day
234.352 - # can't be determined without knowing the correct month and year,
234.353 - # but if day is, e.g., plus or minus a million, the current month
234.354 - # and year values make no sense (and may also be out of bounds
234.355 - # themselves).
234.356 - # Saying 12 months == 1 year should be non-controversial.
234.357 - if not 1 <= month <= 12:
234.358 - carry, month = divmod(month-1, 12)
234.359 - year += carry
234.360 - month += 1
234.361 - assert 1 <= month <= 12
234.362 -
234.363 - # Now only day can be out of bounds (year may also be out of bounds
234.364 - # for a datetime object, but we don't care about that here).
234.365 - # If day is out of bounds, what to do is arguable, but at least the
234.366 - # method here is principled and explainable.
234.367 - dim = _days_in_month(year, month)
234.368 - if not 1 <= day <= dim:
234.369 - # Move day-1 days from the first of the month. First try to
234.370 - # get off cheap if we're only one day out of range (adjustments
234.371 - # for timezone alone can't be worse than that).
234.372 - if day == 0: # move back a day
234.373 - month -= 1
234.374 - if month > 0:
234.375 - day = _days_in_month(year, month)
234.376 - else:
234.377 - year, month, day = year-1, 12, 31
234.378 - elif day == dim + 1: # move forward a day
234.379 - month += 1
234.380 - day = 1
234.381 - if month > 12:
234.382 - month = 1
234.383 - year += 1
234.384 - else:
234.385 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
234.386 - year, month, day = _ord2ymd(self.ordinal)
234.387 -
234.388 - self.year, self.month, self.day = year, month, day
234.389 - self.hour, self.minute, self.second = hour, minute, second
234.390 - self.microsecond = microsecond
234.391 -
234.392 - def toordinal(self):
234.393 - """Return proleptic Gregorian ordinal for the year, month and day.
234.394 -
234.395 - January 1 of year 1 is day 1. Only the year, month and day values
234.396 - contribute to the result.
234.397 - """
234.398 - if self.ordinal is None:
234.399 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
234.400 - return self.ordinal
234.401 -
234.402 - def time(self):
234.403 - "Return Unixish timestamp, as a float (assuming UTC)."
234.404 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
234.405 - seconds = ((days * 24. + self.hour) * 60. + self.minute) * 60.
234.406 - return seconds + self.second + self.microsecond / 1e6
234.407 -
234.408 - def ctime(self):
234.409 - "Return ctime() style string."
234.410 - weekday = self.toordinal() % 7 or 7
234.411 - return "%s %s %2d %02d:%02d:%02d %04d" % (
234.412 - _DAYNAMES[weekday],
234.413 - _MONTHNAMES[self.month],
234.414 - self.day,
234.415 - self.hour, self.minute, self.second,
234.416 - self.year)
234.417 -
234.418 -class timedelta(object):
234.419 - """Represent the difference between two datetime objects.
234.420 -
234.421 - Supported operators:
234.422 -
234.423 - - add, subtract timedelta
234.424 - - unary plus, minus, abs
234.425 - - compare to timedelta
234.426 - - multiply, divide by int/long
234.427 -
234.428 - In addition, datetime supports subtraction of two datetime objects
234.429 - returning a timedelta, and addition or subtraction of a datetime
234.430 - and a timedelta giving a datetime.
234.431 -
234.432 - Representation: (days, seconds, microseconds). Why? Because I
234.433 - felt like it.
234.434 - """
234.435 -
234.436 - def __new__(cls, days=0, seconds=0, microseconds=0,
234.437 - # XXX The following should only be used as keyword args:
234.438 - milliseconds=0, minutes=0, hours=0, weeks=0):
234.439 - # Doing this efficiently and accurately in C is going to be difficult
234.440 - # and error-prone, due to ubiquitous overflow possibilities, and that
234.441 - # C double doesn't have enough bits of precision to represent
234.442 - # microseconds over 10K years faithfully. The code here tries to make
234.443 - # explicit where go-fast assumptions can be relied on, in order to
234.444 - # guide the C implementation; it's way more convoluted than speed-
234.445 - # ignoring auto-overflow-to-long idiomatic Python could be.
234.446 -
234.447 - # XXX Check that all inputs are ints, longs or floats.
234.448 -
234.449 - # Final values, all integer.
234.450 - # s and us fit in 32-bit signed ints; d isn't bounded.
234.451 - d = s = us = 0
234.452 -
234.453 - # Normalize everything to days, seconds, microseconds.
234.454 - days += weeks * 7
234.455 - seconds += minutes * 60 + hours * 3600
234.456 - microseconds += milliseconds * 1000
234.457 -
234.458 - # Get rid of all fractions, and normalize s and us.
234.459 - # Take a deep breath <wink>.
234.460 - if isinstance(days, float):
234.461 - dayfrac, days = _math.modf(days)
234.462 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24. * 3600.))
234.463 - assert daysecondswhole == int(daysecondswhole) # can't overflow
234.464 - s = int(daysecondswhole)
234.465 - assert days == long(days)
234.466 - d = long(days)
234.467 - else:
234.468 - daysecondsfrac = 0.0
234.469 - d = days
234.470 - assert isinstance(daysecondsfrac, float)
234.471 - assert abs(daysecondsfrac) <= 1.0
234.472 - assert isinstance(d, (int, long))
234.473 - assert abs(s) <= 24 * 3600
234.474 - # days isn't referenced again before redefinition
234.475 -
234.476 - if isinstance(seconds, float):
234.477 - secondsfrac, seconds = _math.modf(seconds)
234.478 - assert seconds == long(seconds)
234.479 - seconds = long(seconds)
234.480 - secondsfrac += daysecondsfrac
234.481 - assert abs(secondsfrac) <= 2.0
234.482 - else:
234.483 - secondsfrac = daysecondsfrac
234.484 - # daysecondsfrac isn't referenced again
234.485 - assert isinstance(secondsfrac, float)
234.486 - assert abs(secondsfrac) <= 2.0
234.487 -
234.488 - assert isinstance(seconds, (int, long))
234.489 - days, seconds = divmod(seconds, 24 * 3600)
234.490 - d += days
234.491 - s += int(seconds) # can't overflow
234.492 - assert isinstance(s, int)
234.493 - assert abs(s) <= 2 * 24 * 3600
234.494 - # seconds isn't referenced again before redefinition
234.495 -
234.496 - usdouble = secondsfrac * 1e6
234.497 - assert abs(usdouble) < 2.1e6 # exact value not critical
234.498 - # secondsfrac isn't referenced again
234.499 -
234.500 - if isinstance(microseconds, float):
234.501 - microseconds += usdouble
234.502 - microseconds = round(microseconds)
234.503 - seconds, microseconds = divmod(microseconds, 1e6)
234.504 - assert microseconds == int(microseconds)
234.505 - assert seconds == long(seconds)
234.506 - days, seconds = divmod(seconds, 24. * 3600.)
234.507 - assert days == long(days)
234.508 - assert seconds == int(seconds)
234.509 - d += long(days)
234.510 - s += int(seconds) # can't overflow
234.511 - assert isinstance(s, int)
234.512 - assert abs(s) <= 3 * 24 * 3600
234.513 - else:
234.514 - seconds, microseconds = divmod(microseconds, 1000000)
234.515 - days, seconds = divmod(seconds, 24 * 3600)
234.516 - d += days
234.517 - s += int(seconds) # can't overflow
234.518 - assert isinstance(s, int)
234.519 - assert abs(s) <= 3 * 24 * 3600
234.520 - microseconds = float(microseconds)
234.521 - microseconds += usdouble
234.522 - microseconds = round(microseconds)
234.523 - assert abs(s) <= 3 * 24 * 3600
234.524 - assert abs(microseconds) < 3.1e6
234.525 -
234.526 - # Just a little bit of carrying possible for microseconds and seconds.
234.527 - assert isinstance(microseconds, float)
234.528 - assert int(microseconds) == microseconds
234.529 - us = int(microseconds)
234.530 - seconds, us = divmod(us, 1000000)
234.531 - s += seconds # cant't overflow
234.532 - assert isinstance(s, int)
234.533 - days, s = divmod(s, 24 * 3600)
234.534 - d += days
234.535 -
234.536 - assert isinstance(d, (int, long))
234.537 - assert isinstance(s, int) and 0 <= s < 24 * 3600
234.538 - assert isinstance(us, int) and 0 <= us < 1000000
234.539 -
234.540 - self = object.__new__(cls)
234.541 -
234.542 - self.__days = d
234.543 - self.__seconds = s
234.544 - self.__microseconds = us
234.545 - if abs(d) > 999999999:
234.546 - raise OverflowError("timedelta # of days is too large: %d" % d)
234.547 -
234.548 - return self
234.549 -
234.550 - def __repr__(self):
234.551 - if self.__microseconds:
234.552 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
234.553 - self.__days,
234.554 - self.__seconds,
234.555 - self.__microseconds)
234.556 - if self.__seconds:
234.557 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
234.558 - self.__days,
234.559 - self.__seconds)
234.560 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
234.561 -
234.562 - def __str__(self):
234.563 - mm, ss = divmod(self.__seconds, 60)
234.564 - hh, mm = divmod(mm, 60)
234.565 - s = "%d:%02d:%02d" % (hh, mm, ss)
234.566 - if self.__days:
234.567 - def plural(n):
234.568 - return n, abs(n) != 1 and "s" or ""
234.569 - s = ("%d day%s, " % plural(self.__days)) + s
234.570 - if self.__microseconds:
234.571 - s = s + ".%06d" % self.__microseconds
234.572 - return s
234.573 -
234.574 - days = property(lambda self: self.__days, doc="days")
234.575 - seconds = property(lambda self: self.__seconds, doc="seconds")
234.576 - microseconds = property(lambda self: self.__microseconds,
234.577 - doc="microseconds")
234.578 -
234.579 - def __add__(self, other):
234.580 - if isinstance(other, timedelta):
234.581 - return timedelta(self.__days + other.__days,
234.582 - self.__seconds + other.__seconds,
234.583 - self.__microseconds + other.__microseconds)
234.584 - return NotImplemented
234.585 -
234.586 - __radd__ = __add__
234.587 -
234.588 - def __sub__(self, other):
234.589 - if isinstance(other, timedelta):
234.590 - return self + -other
234.591 - return NotImplemented
234.592 -
234.593 - def __rsub__(self, other):
234.594 - if isinstance(other, timedelta):
234.595 - return -self + other
234.596 - return NotImplemented
234.597 -
234.598 - def __neg__(self):
234.599 - return self.__class__(-self.__days,
234.600 - -self.__seconds,
234.601 - -self.__microseconds)
234.602 -
234.603 - def __pos__(self):
234.604 - return self
234.605 -
234.606 - def __abs__(self):
234.607 - if self.__days < 0:
234.608 - return -self
234.609 - else:
234.610 - return self
234.611 -
234.612 - def __mul__(self, other):
234.613 - if isinstance(other, (int, long)):
234.614 - return self.__class__(self.__days * other,
234.615 - self.__seconds * other,
234.616 - self.__microseconds * other)
234.617 - return NotImplemented
234.618 -
234.619 - __rmul__ = __mul__
234.620 -
234.621 - def __div__(self, other):
234.622 - if isinstance(other, (int, long)):
234.623 - usec = ((self.__days * (24 * 3600L) + self.__seconds) * 1000000 +
234.624 - self.__microseconds)
234.625 - return self.__class__(0, 0, usec // other)
234.626 - return NotImplemented
234.627 -
234.628 - __floordiv__ = __div__
234.629 -
234.630 - # Comparisons.
234.631 -
234.632 - def __eq__(self, other):
234.633 - if isinstance(other, timedelta):
234.634 - return self.__cmp(other) == 0
234.635 - else:
234.636 - return False
234.637 -
234.638 - def __ne__(self, other):
234.639 - if isinstance(other, timedelta):
234.640 - return self.__cmp(other) != 0
234.641 - else:
234.642 - return True
234.643 -
234.644 - def __le__(self, other):
234.645 - if isinstance(other, timedelta):
234.646 - return self.__cmp(other) <= 0
234.647 - else:
234.648 - _cmperror(self, other)
234.649 -
234.650 - def __lt__(self, other):
234.651 - if isinstance(other, timedelta):
234.652 - return self.__cmp(other) < 0
234.653 - else:
234.654 - _cmperror(self, other)
234.655 -
234.656 - def __ge__(self, other):
234.657 - if isinstance(other, timedelta):
234.658 - return self.__cmp(other) >= 0
234.659 - else:
234.660 - _cmperror(self, other)
234.661 -
234.662 - def __gt__(self, other):
234.663 - if isinstance(other, timedelta):
234.664 - return self.__cmp(other) > 0
234.665 - else:
234.666 - _cmperror(self, other)
234.667 -
234.668 - def __cmp(self, other):
234.669 - assert isinstance(other, timedelta)
234.670 - return cmp(self.__getstate(), other.__getstate())
234.671 -
234.672 - def __hash__(self):
234.673 - return hash(self.__getstate())
234.674 -
234.675 - def __nonzero__(self):
234.676 - return (self.__days != 0 or
234.677 - self.__seconds != 0 or
234.678 - self.__microseconds != 0)
234.679 -
234.680 - # Pickle support.
234.681 -
234.682 - __safe_for_unpickling__ = True # For Python 2.2
234.683 -
234.684 - def __getstate(self):
234.685 - return (self.__days, self.__seconds, self.__microseconds)
234.686 -
234.687 - def __reduce__(self):
234.688 - return (self.__class__, self.__getstate())
234.689 -
234.690 -timedelta.min = timedelta(-999999999)
234.691 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
234.692 - microseconds=999999)
234.693 -timedelta.resolution = timedelta(microseconds=1)
234.694 -
234.695 -class date(object):
234.696 - """Concrete date type.
234.697 -
234.698 - Constructors:
234.699 -
234.700 - __new__()
234.701 - fromtimestamp()
234.702 - today()
234.703 - fromordinal()
234.704 -
234.705 - Operators:
234.706 -
234.707 - __repr__, __str__
234.708 - __cmp__, __hash__
234.709 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
234.710 -
234.711 - Methods:
234.712 -
234.713 - timetuple()
234.714 - toordinal()
234.715 - weekday()
234.716 - isoweekday(), isocalendar(), isoformat()
234.717 - ctime()
234.718 - strftime()
234.719 -
234.720 - Properties (readonly):
234.721 - year, month, day
234.722 - """
234.723 -
234.724 - def __new__(cls, year, month=None, day=None):
234.725 - """Constructor.
234.726 -
234.727 - Arguments:
234.728 -
234.729 - year, month, day (required, base 1)
234.730 - """
234.731 - if isinstance(year, str):
234.732 - # Pickle support
234.733 - self = object.__new__(cls)
234.734 - self.__setstate((year, ))
234.735 - return self
234.736 - _check_date_fields(year, month, day)
234.737 - self = object.__new__(cls)
234.738 - self.__year = year
234.739 - self.__month = month
234.740 - self.__day = day
234.741 - return self
234.742 -
234.743 - # Additional constructors
234.744 -
234.745 - def fromtimestamp(cls, t):
234.746 - "Construct a date from a POSIX timestamp (like time.time())."
234.747 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
234.748 - return cls(y, m, d)
234.749 - fromtimestamp = classmethod(fromtimestamp)
234.750 -
234.751 - def today(cls):
234.752 - "Construct a date from time.time()."
234.753 - t = _time.time()
234.754 - return cls.fromtimestamp(t)
234.755 - today = classmethod(today)
234.756 -
234.757 - def fromordinal(cls, n):
234.758 - """Contruct a date from a proleptic Gregorian ordinal.
234.759 -
234.760 - January 1 of year 1 is day 1. Only the year, month and day are
234.761 - non-zero in the result.
234.762 - """
234.763 - y, m, d = _ord2ymd(n)
234.764 - return cls(y, m, d)
234.765 - fromordinal = classmethod(fromordinal)
234.766 -
234.767 - # Conversions to string
234.768 -
234.769 - def __repr__(self):
234.770 - "Convert to formal string, for repr()."
234.771 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
234.772 - self.__year,
234.773 - self.__month,
234.774 - self.__day)
234.775 - # XXX These shouldn't depend on time.localtime(), because that
234.776 - # clips the usable dates to [1970 .. 2038). At least ctime() is
234.777 - # easily done without using strftime() -- that's better too because
234.778 - # strftime("%c", ...) is locale specific.
234.779 -
234.780 - def ctime(self):
234.781 - "Format a la ctime()."
234.782 - return tmxxx(self.__year, self.__month, self.__day).ctime()
234.783 -
234.784 - def strftime(self, fmt):
234.785 - "Format using strftime()."
234.786 - return _wrap_strftime(self, fmt, self.timetuple())
234.787 -
234.788 - def isoformat(self):
234.789 - """Return the date formatted according to ISO.
234.790 -
234.791 - This is 'YYYY-MM-DD'.
234.792 -
234.793 - References:
234.794 - - http://www.w3.org/TR/NOTE-datetime
234.795 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
234.796 - """
234.797 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
234.798 -
234.799 - __str__ = isoformat
234.800 -
234.801 - # Read-only field accessors
234.802 - year = property(lambda self: self.__year,
234.803 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
234.804 - month = property(lambda self: self.__month, doc="month (1-12)")
234.805 - day = property(lambda self: self.__day, doc="day (1-31)")
234.806 -
234.807 - # Standard conversions, __cmp__, __hash__ (and helpers)
234.808 -
234.809 - def timetuple(self):
234.810 - "Return local time tuple compatible with time.localtime()."
234.811 - return _build_struct_time(self.__year, self.__month, self.__day,
234.812 - 0, 0, 0, -1)
234.813 -
234.814 - def toordinal(self):
234.815 - """Return proleptic Gregorian ordinal for the year, month and day.
234.816 -
234.817 - January 1 of year 1 is day 1. Only the year, month and day values
234.818 - contribute to the result.
234.819 - """
234.820 - return _ymd2ord(self.__year, self.__month, self.__day)
234.821 -
234.822 - def replace(self, year=None, month=None, day=None):
234.823 - """Return a new date with new values for the specified fields."""
234.824 - if year is None:
234.825 - year = self.__year
234.826 - if month is None:
234.827 - month = self.__month
234.828 - if day is None:
234.829 - day = self.__day
234.830 - _check_date_fields(year, month, day)
234.831 - return date(year, month, day)
234.832 -
234.833 - # Comparisons.
234.834 -
234.835 - def __eq__(self, other):
234.836 - if isinstance(other, date):
234.837 - return self.__cmp(other) == 0
234.838 - elif hasattr(other, "timetuple"):
234.839 - return NotImplemented
234.840 - else:
234.841 - return False
234.842 -
234.843 - def __ne__(self, other):
234.844 - if isinstance(other, date):
234.845 - return self.__cmp(other) != 0
234.846 - elif hasattr(other, "timetuple"):
234.847 - return NotImplemented
234.848 - else:
234.849 - return True
234.850 -
234.851 - def __le__(self, other):
234.852 - if isinstance(other, date):
234.853 - return self.__cmp(other) <= 0
234.854 - elif hasattr(other, "timetuple"):
234.855 - return NotImplemented
234.856 - else:
234.857 - _cmperror(self, other)
234.858 -
234.859 - def __lt__(self, other):
234.860 - if isinstance(other, date):
234.861 - return self.__cmp(other) < 0
234.862 - elif hasattr(other, "timetuple"):
234.863 - return NotImplemented
234.864 - else:
234.865 - _cmperror(self, other)
234.866 -
234.867 - def __ge__(self, other):
234.868 - if isinstance(other, date):
234.869 - return self.__cmp(other) >= 0
234.870 - elif hasattr(other, "timetuple"):
234.871 - return NotImplemented
234.872 - else:
234.873 - _cmperror(self, other)
234.874 -
234.875 - def __gt__(self, other):
234.876 - if isinstance(other, date):
234.877 - return self.__cmp(other) > 0
234.878 - elif hasattr(other, "timetuple"):
234.879 - return NotImplemented
234.880 - else:
234.881 - _cmperror(self, other)
234.882 -
234.883 - def __cmp(self, other):
234.884 - assert isinstance(other, date)
234.885 - y, m, d = self.__year, self.__month, self.__day
234.886 - y2, m2, d2 = other.__year, other.__month, other.__day
234.887 - return cmp((y, m, d), (y2, m2, d2))
234.888 -
234.889 - def __hash__(self):
234.890 - "Hash."
234.891 - return hash(self.__getstate())
234.892 -
234.893 - # Computations
234.894 -
234.895 - def _checkOverflow(self, year):
234.896 - if not MINYEAR <= year <= MAXYEAR:
234.897 - raise OverflowError("date +/-: result year %d not in %d..%d" %
234.898 - (year, MINYEAR, MAXYEAR))
234.899 -
234.900 - def __add__(self, other):
234.901 - "Add a date to a timedelta."
234.902 - if isinstance(other, timedelta):
234.903 - t = tmxxx(self.__year,
234.904 - self.__month,
234.905 - self.__day + other.days)
234.906 - self._checkOverflow(t.year)
234.907 - result = self.__class__(t.year, t.month, t.day)
234.908 - return result
234.909 - return NotImplemented
234.910 -
234.911 - __radd__ = __add__
234.912 -
234.913 - def __sub__(self, other):
234.914 - """Subtract two dates, or a date and a timedelta."""
234.915 - if isinstance(other, timedelta):
234.916 - return self + timedelta(-other.days)
234.917 - if isinstance(other, date):
234.918 - days1 = self.toordinal()
234.919 - days2 = other.toordinal()
234.920 - return timedelta(days1 - days2)
234.921 - return NotImplemented
234.922 -
234.923 - def weekday(self):
234.924 - "Return day of the week, where Monday == 0 ... Sunday == 6."
234.925 - return (self.toordinal() + 6) % 7
234.926 -
234.927 - # Day-of-the-week and week-of-the-year, according to ISO
234.928 -
234.929 - def isoweekday(self):
234.930 - "Return day of the week, where Monday == 1 ... Sunday == 7."
234.931 - # 1-Jan-0001 is a Monday
234.932 - return self.toordinal() % 7 or 7
234.933 -
234.934 - def isocalendar(self):
234.935 - """Return a 3-tuple containing ISO year, week number, and weekday.
234.936 -
234.937 - The first ISO week of the year is the (Mon-Sun) week
234.938 - containing the year's first Thursday; everything else derives
234.939 - from that.
234.940 -
234.941 - The first week is 1; Monday is 1 ... Sunday is 7.
234.942 -
234.943 - ISO calendar algorithm taken from
234.944 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
234.945 - """
234.946 - year = self.__year
234.947 - week1monday = _isoweek1monday(year)
234.948 - today = _ymd2ord(self.__year, self.__month, self.__day)
234.949 - # Internally, week and day have origin 0
234.950 - week, day = divmod(today - week1monday, 7)
234.951 - if week < 0:
234.952 - year -= 1
234.953 - week1monday = _isoweek1monday(year)
234.954 - week, day = divmod(today - week1monday, 7)
234.955 - elif week >= 52:
234.956 - if today >= _isoweek1monday(year + 1):
234.957 - year += 1
234.958 - week = 0
234.959 - return year, week + 1, day + 1
234.960 -
234.961 - # Pickle support.
234.962 -
234.963 - __safe_for_unpickling__ = True # For Python 2.2
234.964 -
234.965 - def __getstate(self):
234.966 - yhi, ylo = divmod(self.__year, 256)
234.967 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day),)
234.968 -
234.969 - def __setstate(self, t):
234.970 - assert isinstance(t, tuple) and len(t) == 1, `t`
234.971 - string = t[0]
234.972 - assert len(string) == 4
234.973 - yhi, ylo, self.__month, self.__day = map(ord, string)
234.974 - self.__year = yhi * 256 + ylo
234.975 -
234.976 - def __reduce__(self):
234.977 - return (self.__class__, self.__getstate())
234.978 -
234.979 -_date_class = date # so functions w/ args named "date" can get at the class
234.980 -
234.981 -date.min = date(1, 1, 1)
234.982 -date.max = date(9999, 12, 31)
234.983 -date.resolution = timedelta(days=1)
234.984 -
234.985 -class tzinfo(object):
234.986 - """Abstract base class for time zone info classes.
234.987 -
234.988 - Subclasses must override the name(), utcoffset() and dst() methods.
234.989 - """
234.990 -
234.991 - def tzname(self, dt):
234.992 - "datetime -> string name of time zone."
234.993 - raise NotImplementedError("tzinfo subclass must override tzname()")
234.994 -
234.995 - def utcoffset(self, dt):
234.996 - "datetime -> minutes east of UTC (negative for west of UTC)"
234.997 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
234.998 -
234.999 - def dst(self, dt):
234.1000 - """datetime -> DST offset in minutes east of UTC.
234.1001 -
234.1002 - Return 0 if DST not in effect. utcoffset() must include the DST
234.1003 - offset.
234.1004 - """
234.1005 - raise NotImplementedError("tzinfo subclass must override dst()")
234.1006 -
234.1007 - def fromutc(self, dt):
234.1008 - "datetime in UTC -> datetime in local time."
234.1009 -
234.1010 - if not isinstance(dt, datetime):
234.1011 - raise TypeError("fromutc() requires a datetime argument")
234.1012 - if dt.tzinfo is not self:
234.1013 - raise ValueError("dt.tzinfo is not self")
234.1014 -
234.1015 - dtoff = dt.utcoffset()
234.1016 - if dtoff is None:
234.1017 - raise ValueError("fromutc() requires a non-None utcoffset() "
234.1018 - "result")
234.1019 -
234.1020 - # See the long comment block at the end of this file for an
234.1021 - # explanation of this algorithm.
234.1022 - dtdst = dt.dst()
234.1023 - if dtdst is None:
234.1024 - raise ValueError("fromutc() requires a non-None dst() result")
234.1025 - delta = dtoff - dtdst
234.1026 - if delta:
234.1027 - dt += delta
234.1028 - dtdst = dt.dst()
234.1029 - if dtdst is None:
234.1030 - raise ValueError("fromutc(): dt.dst gave inconsistent "
234.1031 - "results; cannot convert")
234.1032 - if dtdst:
234.1033 - return dt + dtdst
234.1034 - else:
234.1035 - return dt
234.1036 -
234.1037 - # Pickle support.
234.1038 -
234.1039 - __safe_for_unpickling__ = True # For Python 2.2
234.1040 -
234.1041 - def __reduce__(self):
234.1042 - getinitargs = getattr(self, "__getinitargs__", None)
234.1043 - if getinitargs:
234.1044 - args = getinitargs()
234.1045 - else:
234.1046 - args = ()
234.1047 - getstate = getattr(self, "__getstate__", None)
234.1048 - if getstate:
234.1049 - state = getstate()
234.1050 - else:
234.1051 - state = getattr(self, "__dict__", None) or None
234.1052 - if state is None:
234.1053 - return (self.__class__, args)
234.1054 - else:
234.1055 - return (self.__class__, args, state)
234.1056 -
234.1057 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
234.1058 -
234.1059 -class time(object):
234.1060 - """Time with time zone.
234.1061 -
234.1062 - Constructors:
234.1063 -
234.1064 - __new__()
234.1065 -
234.1066 - Operators:
234.1067 -
234.1068 - __repr__, __str__
234.1069 - __cmp__, __hash__
234.1070 -
234.1071 - Methods:
234.1072 -
234.1073 - strftime()
234.1074 - isoformat()
234.1075 - utcoffset()
234.1076 - tzname()
234.1077 - dst()
234.1078 -
234.1079 - Properties (readonly):
234.1080 - hour, minute, second, microsecond, tzinfo
234.1081 - """
234.1082 -
234.1083 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
234.1084 - """Constructor.
234.1085 -
234.1086 - Arguments:
234.1087 -
234.1088 - hour, minute (required)
234.1089 - second, microsecond (default to zero)
234.1090 - tzinfo (default to None)
234.1091 - """
234.1092 - self = object.__new__(cls)
234.1093 - if isinstance(hour, str):
234.1094 - # Pickle support
234.1095 - self.__setstate((hour, minute or None))
234.1096 - return self
234.1097 - _check_tzinfo_arg(tzinfo)
234.1098 - _check_time_fields(hour, minute, second, microsecond)
234.1099 - self.__hour = hour
234.1100 - self.__minute = minute
234.1101 - self.__second = second
234.1102 - self.__microsecond = microsecond
234.1103 - self._tzinfo = tzinfo
234.1104 - return self
234.1105 -
234.1106 - # Read-only field accessors
234.1107 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
234.1108 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
234.1109 - second = property(lambda self: self.__second, doc="second (0-59)")
234.1110 - microsecond = property(lambda self: self.__microsecond,
234.1111 - doc="microsecond (0-999999)")
234.1112 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
234.1113 -
234.1114 - # Standard conversions, __hash__ (and helpers)
234.1115 -
234.1116 - # Comparisons.
234.1117 -
234.1118 - def __eq__(self, other):
234.1119 - if isinstance(other, time):
234.1120 - return self.__cmp(other) == 0
234.1121 - else:
234.1122 - return False
234.1123 -
234.1124 - def __ne__(self, other):
234.1125 - if isinstance(other, time):
234.1126 - return self.__cmp(other) != 0
234.1127 - else:
234.1128 - return True
234.1129 -
234.1130 - def __le__(self, other):
234.1131 - if isinstance(other, time):
234.1132 - return self.__cmp(other) <= 0
234.1133 - else:
234.1134 - _cmperror(self, other)
234.1135 -
234.1136 - def __lt__(self, other):
234.1137 - if isinstance(other, time):
234.1138 - return self.__cmp(other) < 0
234.1139 - else:
234.1140 - _cmperror(self, other)
234.1141 -
234.1142 - def __ge__(self, other):
234.1143 - if isinstance(other, time):
234.1144 - return self.__cmp(other) >= 0
234.1145 - else:
234.1146 - _cmperror(self, other)
234.1147 -
234.1148 - def __gt__(self, other):
234.1149 - if isinstance(other, time):
234.1150 - return self.__cmp(other) > 0
234.1151 - else:
234.1152 - _cmperror(self, other)
234.1153 -
234.1154 - def __cmp(self, other):
234.1155 - assert isinstance(other, time)
234.1156 - mytz = self._tzinfo
234.1157 - ottz = other._tzinfo
234.1158 - myoff = otoff = None
234.1159 -
234.1160 - if mytz is ottz:
234.1161 - base_compare = True
234.1162 - else:
234.1163 - myoff = self._utcoffset()
234.1164 - otoff = other._utcoffset()
234.1165 - base_compare = myoff == otoff
234.1166 -
234.1167 - if base_compare:
234.1168 - return cmp((self.__hour, self.__minute, self.__second,
234.1169 - self.__microsecond),
234.1170 - (other.__hour, other.__minute, other.__second,
234.1171 - other.__microsecond))
234.1172 - if myoff is None or otoff is None:
234.1173 - # XXX Buggy in 2.2.2.
234.1174 - raise TypeError("cannot compare naive and aware times")
234.1175 - myhhmm = self.__hour * 60 + self.__minute - myoff
234.1176 - othhmm = other.__hour * 60 + other.__minute - otoff
234.1177 - return cmp((myhhmm, self.__second, self.__microsecond),
234.1178 - (othhmm, other.__second, other.__microsecond))
234.1179 -
234.1180 - def __hash__(self):
234.1181 - """Hash."""
234.1182 - tzoff = self._utcoffset()
234.1183 - if not tzoff: # zero or None
234.1184 - return hash(self.__getstate()[0])
234.1185 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
234.1186 - if 0 <= h < 24:
234.1187 - return hash(time(h, m, self.second, self.microsecond))
234.1188 - return hash((h, m, self.second, self.microsecond))
234.1189 -
234.1190 - # Conversion to string
234.1191 -
234.1192 - def _tzstr(self, sep=":"):
234.1193 - """Return formatted timezone offset (+xx:xx) or None."""
234.1194 - off = self._utcoffset()
234.1195 - if off is not None:
234.1196 - if off < 0:
234.1197 - sign = "-"
234.1198 - off = -off
234.1199 - else:
234.1200 - sign = "+"
234.1201 - hh, mm = divmod(off, 60)
234.1202 - assert 0 <= hh < 24
234.1203 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
234.1204 - return off
234.1205 -
234.1206 - def __repr__(self):
234.1207 - """Convert to formal string, for repr()."""
234.1208 - if self.__microsecond != 0:
234.1209 - s = ", %d, %d" % (self.__second, self.__microsecond)
234.1210 - elif self.__second != 0:
234.1211 - s = ", %d" % self.__second
234.1212 - else:
234.1213 - s = ""
234.1214 - s = "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
234.1215 - self.__hour, self.__minute, s)
234.1216 - if self._tzinfo is not None:
234.1217 - assert s[-1:] == ")"
234.1218 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
234.1219 - return s
234.1220 -
234.1221 - def isoformat(self):
234.1222 - """Return the time formatted according to ISO.
234.1223 -
234.1224 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
234.1225 - self.microsecond == 0.
234.1226 - """
234.1227 - s = _format_time(self.__hour, self.__minute, self.__second,
234.1228 - self.__microsecond)
234.1229 - tz = self._tzstr()
234.1230 - if tz:
234.1231 - s += tz
234.1232 - return s
234.1233 -
234.1234 - __str__ = isoformat
234.1235 -
234.1236 - def strftime(self, fmt):
234.1237 - """Format using strftime(). The date part of the timestamp passed
234.1238 - to underlying strftime should not be used.
234.1239 - """
234.1240 - # The year must be >= 1900 else Python's strftime implementation
234.1241 - # can raise a bogus exception.
234.1242 - timetuple = (1900, 1, 1,
234.1243 - self.__hour, self.__minute, self.__second,
234.1244 - 0, 1, -1)
234.1245 - return _wrap_strftime(self, fmt, timetuple)
234.1246 -
234.1247 - # Timezone functions
234.1248 -
234.1249 - def utcoffset(self):
234.1250 - """Return the timezone offset in minutes east of UTC (negative west of
234.1251 - UTC)."""
234.1252 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
234.1253 - offset = _check_utc_offset("utcoffset", offset)
234.1254 - if offset is not None:
234.1255 - offset = timedelta(minutes=offset)
234.1256 - return offset
234.1257 -
234.1258 - # Return an integer (or None) instead of a timedelta (or None).
234.1259 - def _utcoffset(self):
234.1260 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
234.1261 - offset = _check_utc_offset("utcoffset", offset)
234.1262 - return offset
234.1263 -
234.1264 - def tzname(self):
234.1265 - """Return the timezone name.
234.1266 -
234.1267 - Note that the name is 100% informational -- there's no requirement that
234.1268 - it mean anything in particular. For example, "GMT", "UTC", "-500",
234.1269 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
234.1270 - """
234.1271 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
234.1272 - _check_tzname(name)
234.1273 - return name
234.1274 -
234.1275 - def dst(self):
234.1276 - """Return 0 if DST is not in effect, or the DST offset (in minutes
234.1277 - eastward) if DST is in effect.
234.1278 -
234.1279 - This is purely informational; the DST offset has already been added to
234.1280 - the UTC offset returned by utcoffset() if applicable, so there's no
234.1281 - need to consult dst() unless you're interested in displaying the DST
234.1282 - info.
234.1283 - """
234.1284 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
234.1285 - offset = _check_utc_offset("dst", offset)
234.1286 - if offset is not None:
234.1287 - offset = timedelta(minutes=offset)
234.1288 - return offset
234.1289 -
234.1290 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
234.1291 - tzinfo=True):
234.1292 - """Return a new time with new values for the specified fields."""
234.1293 - if hour is None:
234.1294 - hour = self.hour
234.1295 - if minute is None:
234.1296 - minute = self.minute
234.1297 - if second is None:
234.1298 - second = self.second
234.1299 - if microsecond is None:
234.1300 - microsecond = self.microsecond
234.1301 - if tzinfo is True:
234.1302 - tzinfo = self.tzinfo
234.1303 - _check_time_fields(hour, minute, second, microsecond)
234.1304 - _check_tzinfo_arg(tzinfo)
234.1305 - return time(hour, minute, second, microsecond, tzinfo)
234.1306 -
234.1307 - # Return an integer (or None) instead of a timedelta (or None).
234.1308 - def _dst(self):
234.1309 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
234.1310 - offset = _check_utc_offset("dst", offset)
234.1311 - return offset
234.1312 -
234.1313 - def __nonzero__(self):
234.1314 - if self.second or self.microsecond:
234.1315 - return 1
234.1316 - offset = self._utcoffset() or 0
234.1317 - return self.hour * 60 + self.minute - offset != 0
234.1318 -
234.1319 - # Pickle support.
234.1320 -
234.1321 - __safe_for_unpickling__ = True # For Python 2.2
234.1322 -
234.1323 - def __getstate(self):
234.1324 - us2, us3 = divmod(self.__microsecond, 256)
234.1325 - us1, us2 = divmod(us2, 256)
234.1326 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
234.1327 - us1, us2, us3)
234.1328 - if self._tzinfo is None:
234.1329 - return (basestate, )
234.1330 - else:
234.1331 - return (basestate, self._tzinfo)
234.1332 -
234.1333 - def __setstate(self, state):
234.1334 - assert isinstance(state, tuple)
234.1335 - assert 1 <= len(state) <= 2
234.1336 - string = state[0]
234.1337 - assert len(string) == 6
234.1338 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
234.1339 - map(ord, string)
234.1340 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
234.1341 - if len(state) == 1:
234.1342 - self._tzinfo = None
234.1343 - else:
234.1344 - self._tzinfo = state[1]
234.1345 -
234.1346 - def __reduce__(self):
234.1347 - return (self.__class__, self.__getstate())
234.1348 -
234.1349 -_time_class = time # so functions w/ args named "time" can get at the class
234.1350 -
234.1351 -time.min = time(0, 0, 0)
234.1352 -time.max = time(23, 59, 59, 999999)
234.1353 -time.resolution = timedelta(microseconds=1)
234.1354 -
234.1355 -class datetime(date):
234.1356 -
234.1357 - # XXX needs docstrings
234.1358 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
234.1359 -
234.1360 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
234.1361 - microsecond=0, tzinfo=None):
234.1362 - if isinstance(year, str):
234.1363 - # Pickle support
234.1364 - self = date.__new__(cls, year[:4])
234.1365 - self.__setstate((year, month))
234.1366 - return self
234.1367 - _check_tzinfo_arg(tzinfo)
234.1368 - _check_time_fields(hour, minute, second, microsecond)
234.1369 - self = date.__new__(cls, year, month, day)
234.1370 - # XXX This duplicates __year, __month, __day for convenience :-(
234.1371 - self.__year = year
234.1372 - self.__month = month
234.1373 - self.__day = day
234.1374 - self.__hour = hour
234.1375 - self.__minute = minute
234.1376 - self.__second = second
234.1377 - self.__microsecond = microsecond
234.1378 - self._tzinfo = tzinfo
234.1379 - return self
234.1380 -
234.1381 - # Read-only field accessors
234.1382 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
234.1383 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
234.1384 - second = property(lambda self: self.__second, doc="second (0-59)")
234.1385 - microsecond = property(lambda self: self.__microsecond,
234.1386 - doc="microsecond (0-999999)")
234.1387 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
234.1388 -
234.1389 - def fromtimestamp(cls, t, tz=None):
234.1390 - """Construct a datetime from a POSIX timestamp (like time.time()).
234.1391 -
234.1392 - A timezone info object may be passed in as well.
234.1393 - """
234.1394 -
234.1395 - _check_tzinfo_arg(tz)
234.1396 - if tz is None:
234.1397 - converter = _time.localtime
234.1398 - else:
234.1399 - converter = _time.gmtime
234.1400 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
234.1401 - us = int((t % 1.0) * 1000000)
234.1402 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
234.1403 - result = cls(y, m, d, hh, mm, ss, us, tz)
234.1404 - if tz is not None:
234.1405 - result = tz.fromutc(result)
234.1406 - return result
234.1407 - fromtimestamp = classmethod(fromtimestamp)
234.1408 -
234.1409 - def utcfromtimestamp(cls, t):
234.1410 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
234.1411 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
234.1412 - us = int((t % 1.0) * 1000000)
234.1413 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
234.1414 - return cls(y, m, d, hh, mm, ss, us)
234.1415 - utcfromtimestamp = classmethod(utcfromtimestamp)
234.1416 -
234.1417 - # XXX This is supposed to do better than we *can* do by using time.time(),
234.1418 - # XXX if the platform supports a more accurate way. The C implementation
234.1419 - # XXX uses gettimeofday on platforms that have it, but that isn't
234.1420 - # XXX available from Python. So now() may return different results
234.1421 - # XXX across the implementations.
234.1422 - def now(cls, tz=None):
234.1423 - "Construct a datetime from time.time() and optional time zone info."
234.1424 - t = _time.time()
234.1425 - return cls.fromtimestamp(t, tz)
234.1426 - now = classmethod(now)
234.1427 -
234.1428 - def utcnow(cls):
234.1429 - "Construct a UTC datetime from time.time()."
234.1430 - t = _time.time()
234.1431 - return cls.utcfromtimestamp(t)
234.1432 - utcnow = classmethod(utcnow)
234.1433 -
234.1434 - def combine(cls, date, time):
234.1435 - "Construct a datetime from a given date and a given time."
234.1436 - if not isinstance(date, _date_class):
234.1437 - raise TypeError("date argument must be a date instance")
234.1438 - if not isinstance(time, _time_class):
234.1439 - raise TypeError("time argument must be a time instance")
234.1440 - return cls(date.year, date.month, date.day,
234.1441 - time.hour, time.minute, time.second, time.microsecond,
234.1442 - time.tzinfo)
234.1443 - combine = classmethod(combine)
234.1444 -
234.1445 - def timetuple(self):
234.1446 - "Return local time tuple compatible with time.localtime()."
234.1447 - dst = self._dst()
234.1448 - if dst is None:
234.1449 - dst = -1
234.1450 - elif dst:
234.1451 - dst = 1
234.1452 - return _build_struct_time(self.year, self.month, self.day,
234.1453 - self.hour, self.minute, self.second,
234.1454 - dst)
234.1455 -
234.1456 - def utctimetuple(self):
234.1457 - "Return UTC time tuple compatible with time.gmtime()."
234.1458 - y, m, d = self.year, self.month, self.day
234.1459 - hh, mm, ss = self.hour, self.minute, self.second
234.1460 - offset = self._utcoffset()
234.1461 - if offset: # neither None nor 0
234.1462 - tm = tmxxx(y, m, d, hh, mm - offset)
234.1463 - y, m, d = tm.year, tm.month, tm.day
234.1464 - hh, mm = tm.hour, tm.minute
234.1465 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
234.1466 -
234.1467 - def date(self):
234.1468 - "Return the date part."
234.1469 - return date(self.__year, self.__month, self.__day)
234.1470 -
234.1471 - def time(self):
234.1472 - "Return the time part, with tzinfo None."
234.1473 - return time(self.hour, self.minute, self.second, self.microsecond)
234.1474 -
234.1475 - def timetz(self):
234.1476 - "Return the time part, with same tzinfo."
234.1477 - return time(self.hour, self.minute, self.second, self.microsecond,
234.1478 - self._tzinfo)
234.1479 -
234.1480 - def replace(self, year=None, month=None, day=None, hour=None,
234.1481 - minute=None, second=None, microsecond=None, tzinfo=True):
234.1482 - """Return a new datetime with new values for the specified fields."""
234.1483 - if year is None:
234.1484 - year = self.year
234.1485 - if month is None:
234.1486 - month = self.month
234.1487 - if day is None:
234.1488 - day = self.day
234.1489 - if hour is None:
234.1490 - hour = self.hour
234.1491 - if minute is None:
234.1492 - minute = self.minute
234.1493 - if second is None:
234.1494 - second = self.second
234.1495 - if microsecond is None:
234.1496 - microsecond = self.microsecond
234.1497 - if tzinfo is True:
234.1498 - tzinfo = self.tzinfo
234.1499 - _check_date_fields(year, month, day)
234.1500 - _check_time_fields(hour, minute, second, microsecond)
234.1501 - _check_tzinfo_arg(tzinfo)
234.1502 - return datetime(year, month, day, hour, minute, second,
234.1503 - microsecond, tzinfo)
234.1504 -
234.1505 - def astimezone(self, tz):
234.1506 - if not isinstance(tz, tzinfo):
234.1507 - raise TypeError("tz argument must be an instance of tzinfo")
234.1508 -
234.1509 - mytz = self.tzinfo
234.1510 - if mytz is None:
234.1511 - raise ValueError("astimezone() requires an aware datetime")
234.1512 -
234.1513 - if tz is mytz:
234.1514 - return self
234.1515 -
234.1516 - # Convert self to UTC, and attach the new time zone object.
234.1517 - myoffset = self.utcoffset()
234.1518 - if myoffset is None:
234.1519 - raise ValuError("astimezone() requires an aware datetime")
234.1520 - utc = (self - myoffset).replace(tzinfo=tz)
234.1521 -
234.1522 - # Convert from UTC to tz's local time.
234.1523 - return tz.fromutc(utc)
234.1524 -
234.1525 - # Ways to produce a string.
234.1526 -
234.1527 - def ctime(self):
234.1528 - "Format a la ctime()."
234.1529 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
234.1530 - self.__minute, self.__second)
234.1531 - return t.ctime()
234.1532 -
234.1533 - def isoformat(self, sep='T'):
234.1534 - """Return the time formatted according to ISO.
234.1535 -
234.1536 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
234.1537 - self.microsecond == 0.
234.1538 -
234.1539 - If self.tzinfo is not None, the UTC offset is also attached, giving
234.1540 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
234.1541 -
234.1542 - Optional argument sep specifies the separator between date and
234.1543 - time, default 'T'.
234.1544 - """
234.1545 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
234.1546 - sep) +
234.1547 - _format_time(self.__hour, self.__minute, self.__second,
234.1548 - self.__microsecond))
234.1549 - off = self._utcoffset()
234.1550 - if off is not None:
234.1551 - if off < 0:
234.1552 - sign = "-"
234.1553 - off = -off
234.1554 - else:
234.1555 - sign = "+"
234.1556 - hh, mm = divmod(off, 60)
234.1557 - s += "%s%02d:%02d" % (sign, hh, mm)
234.1558 - return s
234.1559 -
234.1560 - def __repr__(self):
234.1561 - "Convert to formal string, for repr()."
234.1562 - L = [self.__year, self.__month, self.__day, # These are never zero
234.1563 - self.__hour, self.__minute, self.__second, self.__microsecond]
234.1564 - if L[-1] == 0:
234.1565 - del L[-1]
234.1566 - if L[-1] == 0:
234.1567 - del L[-1]
234.1568 - s = ", ".join(map(str, L))
234.1569 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
234.1570 - if self._tzinfo is not None:
234.1571 - assert s[-1:] == ")"
234.1572 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
234.1573 - return s
234.1574 -
234.1575 - def __str__(self):
234.1576 - "Convert to string, for str()."
234.1577 - return self.isoformat(sep=' ')
234.1578 -
234.1579 - def utcoffset(self):
234.1580 - """Return the timezone offset in minutes east of UTC (negative west of
234.1581 - UTC)."""
234.1582 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
234.1583 - offset = _check_utc_offset("utcoffset", offset)
234.1584 - if offset is not None:
234.1585 - offset = timedelta(minutes=offset)
234.1586 - return offset
234.1587 -
234.1588 - # Return an integer (or None) instead of a timedelta (or None).
234.1589 - def _utcoffset(self):
234.1590 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
234.1591 - offset = _check_utc_offset("utcoffset", offset)
234.1592 - return offset
234.1593 -
234.1594 - def tzname(self):
234.1595 - """Return the timezone name.
234.1596 -
234.1597 - Note that the name is 100% informational -- there's no requirement that
234.1598 - it mean anything in particular. For example, "GMT", "UTC", "-500",
234.1599 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
234.1600 - """
234.1601 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
234.1602 - _check_tzname(name)
234.1603 - return name
234.1604 -
234.1605 - def dst(self):
234.1606 - """Return 0 if DST is not in effect, or the DST offset (in minutes
234.1607 - eastward) if DST is in effect.
234.1608 -
234.1609 - This is purely informational; the DST offset has already been added to
234.1610 - the UTC offset returned by utcoffset() if applicable, so there's no
234.1611 - need to consult dst() unless you're interested in displaying the DST
234.1612 - info.
234.1613 - """
234.1614 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
234.1615 - offset = _check_utc_offset("dst", offset)
234.1616 - if offset is not None:
234.1617 - offset = timedelta(minutes=offset)
234.1618 - return offset
234.1619 -
234.1620 - # Return an integer (or None) instead of a timedelta (or None).1573
234.1621 - def _dst(self):
234.1622 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
234.1623 - offset = _check_utc_offset("dst", offset)
234.1624 - return offset
234.1625 -
234.1626 - # Comparisons.
234.1627 -
234.1628 - def __eq__(self, other):
234.1629 - if isinstance(other, datetime):
234.1630 - return self.__cmp(other) == 0
234.1631 - elif hasattr(other, "timetuple"):
234.1632 - return NotImplemented
234.1633 - else:
234.1634 - return False
234.1635 -
234.1636 - def __ne__(self, other):
234.1637 - if isinstance(other, datetime):
234.1638 - return self.__cmp(other) != 0
234.1639 - elif hasattr(other, "timetuple"):
234.1640 - return NotImplemented
234.1641 - else:
234.1642 - return True
234.1643 -
234.1644 - def __le__(self, other):
234.1645 - if isinstance(other, datetime):
234.1646 - return self.__cmp(other) <= 0
234.1647 - elif hasattr(other, "timetuple"):
234.1648 - return NotImplemented
234.1649 - else:
234.1650 - _cmperror(self, other)
234.1651 -
234.1652 - def __lt__(self, other):
234.1653 - if isinstance(other, datetime):
234.1654 - return self.__cmp(other) < 0
234.1655 - elif hasattr(other, "timetuple"):
234.1656 - return NotImplemented
234.1657 - else:
234.1658 - _cmperror(self, other)
234.1659 -
234.1660 - def __ge__(self, other):
234.1661 - if isinstance(other, datetime):
234.1662 - return self.__cmp(other) >= 0
234.1663 - elif hasattr(other, "timetuple"):
234.1664 - return NotImplemented
234.1665 - else:
234.1666 - _cmperror(self, other)
234.1667 -
234.1668 - def __gt__(self, other):
234.1669 - if isinstance(other, datetime):
234.1670 - return self.__cmp(other) > 0
234.1671 - elif hasattr(other, "timetuple"):
234.1672 - return NotImplemented
234.1673 - else:
234.1674 - _cmperror(self, other)
234.1675 -
234.1676 - def __cmp(self, other):
234.1677 - assert isinstance(other, datetime)
234.1678 - mytz = self._tzinfo
234.1679 - ottz = other._tzinfo
234.1680 - myoff = otoff = None
234.1681 -
234.1682 - if mytz is ottz:
234.1683 - base_compare = True
234.1684 - else:
234.1685 - if mytz is not None:
234.1686 - myoff = self._utcoffset()
234.1687 - if ottz is not None:
234.1688 - otoff = other._utcoffset()
234.1689 - base_compare = myoff == otoff
234.1690 -
234.1691 - if base_compare:
234.1692 - return cmp((self.__year, self.__month, self.__day,
234.1693 - self.__hour, self.__minute, self.__second,
234.1694 - self.__microsecond),
234.1695 - (other.__year, other.__month, other.__day,
234.1696 - other.__hour, other.__minute, other.__second,
234.1697 - other.__microsecond))
234.1698 - if myoff is None or otoff is None:
234.1699 - # XXX Buggy in 2.2.2.
234.1700 - raise TypeError("cannot compare naive and aware datetimes")
234.1701 - # XXX What follows could be done more efficiently...
234.1702 - diff = self - other # this will take offsets into account
234.1703 - if diff.days < 0:
234.1704 - return -1
234.1705 - return diff and 1 or 0
234.1706 -
234.1707 - def __add__(self, other):
234.1708 - "Add a datetime and a timedelta."
234.1709 - if not isinstance(other, timedelta):
234.1710 - return NotImplemented
234.1711 - t = tmxxx(self.__year,
234.1712 - self.__month,
234.1713 - self.__day + other.days,
234.1714 - self.__hour,
234.1715 - self.__minute,
234.1716 - self.__second + other.seconds,
234.1717 - self.__microsecond + other.microseconds)
234.1718 - self._checkOverflow(t.year)
234.1719 - result = self.__class__(t.year, t.month, t.day,
234.1720 - t.hour, t.minute, t.second,
234.1721 - t.microsecond, tzinfo=self._tzinfo)
234.1722 - return result
234.1723 -
234.1724 - __radd__ = __add__
234.1725 -
234.1726 - def __sub__(self, other):
234.1727 - "Subtract two datetimes, or a datetime and a timedelta."
234.1728 - if not isinstance(other, datetime):
234.1729 - if isinstance(other, timedelta):
234.1730 - return self + -other
234.1731 - return NotImplemented
234.1732 -
234.1733 - days1 = self.toordinal()
234.1734 - days2 = other.toordinal()
234.1735 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
234.1736 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
234.1737 - base = timedelta(days1 - days2,
234.1738 - secs1 - secs2,
234.1739 - self.__microsecond - other.__microsecond)
234.1740 - if self._tzinfo is other._tzinfo:
234.1741 - return base
234.1742 - myoff = self._utcoffset()
234.1743 - otoff = other._utcoffset()
234.1744 - if myoff == otoff:
234.1745 - return base
234.1746 - if myoff is None or otoff is None:
234.1747 - raise TypeError, "cannot mix naive and timezone-aware time"
234.1748 - return base + timedelta(minutes=otoff-myoff)
234.1749 -
234.1750 - def __hash__(self):
234.1751 - tzoff = self._utcoffset()
234.1752 - if tzoff is None:
234.1753 - return hash(self.__getstate()[0])
234.1754 - days = _ymd2ord(self.year, self.month, self.day)
234.1755 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
234.1756 - return hash(timedelta(days, seconds, self.microsecond))
234.1757 -
234.1758 - # Pickle support.
234.1759 -
234.1760 - __safe_for_unpickling__ = True # For Python 2.2
234.1761 -
234.1762 - def __getstate(self):
234.1763 - yhi, ylo = divmod(self.__year, 256)
234.1764 - us2, us3 = divmod(self.__microsecond, 256)
234.1765 - us1, us2 = divmod(us2, 256)
234.1766 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
234.1767 - self.__hour, self.__minute, self.__second,
234.1768 - us1, us2, us3)
234.1769 - if self._tzinfo is None:
234.1770 - return (basestate, )
234.1771 - else:
234.1772 - return (basestate, self._tzinfo)
234.1773 -
234.1774 - def __setstate(self, state):
234.1775 - assert isinstance(state, tuple)
234.1776 - assert 1 <= len(state) <= 2
234.1777 - string = state[0]
234.1778 - assert len(string) == 10
234.1779 - (yhi, ylo, self.__month, self.__day, self.__hour,
234.1780 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
234.1781 - self.__year = yhi * 256 + ylo
234.1782 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
234.1783 - if len(state) == 1:
234.1784 - self._tzinfo = None
234.1785 - else:
234.1786 - self._tzinfo = state[1]
234.1787 -
234.1788 - def __reduce__(self):
234.1789 - return (self.__class__, self.__getstate())
234.1790 -
234.1791 -
234.1792 -datetime.min = datetime(1, 1, 1)
234.1793 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
234.1794 -datetime.resolution = timedelta(microseconds=1)
234.1795 -
234.1796 -
234.1797 -def _isoweek1monday(year):
234.1798 - # Helper to calculate the day number of the Monday starting week 1
234.1799 - # XXX This could be done more efficiently
234.1800 - THURSDAY = 3
234.1801 - firstday = _ymd2ord(year, 1, 1)
234.1802 - firstweekday = (firstday + 6) % 7 # See weekday() above
234.1803 - week1monday = firstday - firstweekday
234.1804 - if firstweekday > THURSDAY:
234.1805 - week1monday += 7
234.1806 - return week1monday
234.1807 -
234.1808 -"""
234.1809 -Some time zone algebra. For a datetime x, let
234.1810 - x.n = x stripped of its timezone -- its naive time.
234.1811 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
234.1812 - return None
234.1813 - x.d = x.dst(), and assuming that doesn't raise an exception or
234.1814 - return None
234.1815 - x.s = x's standard offset, x.o - x.d
234.1816 -
234.1817 -Now some derived rules, where k is a duration (timedelta).
234.1818 -
234.1819 -1. x.o = x.s + x.d
234.1820 - This follows from the definition of x.s.
234.1821 -
234.1822 -2. If x and y have the same tzinfo member, x.s = y.s.
234.1823 - This is actually a requirement, an assumption we need to make about
234.1824 - sane tzinfo classes.
234.1825 -
234.1826 -3. The naive UTC time corresponding to x is x.n - x.o.
234.1827 - This is again a requirement for a sane tzinfo class.
234.1828 -
234.1829 -4. (x+k).s = x.s
234.1830 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
234.1831 -
234.1832 -5. (x+k).n = x.n + k
234.1833 - Again follows from how arithmetic is defined.
234.1834 -
234.1835 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
234.1836 -(meaning that the various tzinfo methods exist, and don't blow up or return
234.1837 -None when called).
234.1838 -
234.1839 -The function wants to return a datetime y with timezone tz, equivalent to x.
234.1840 -x is already in UTC.
234.1841 -
234.1842 -By #3, we want
234.1843 -
234.1844 - y.n - y.o = x.n [1]
234.1845 -
234.1846 -The algorithm starts by attaching tz to x.n, and calling that y. So
234.1847 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
234.1848 -becomes true; in effect, we want to solve [2] for k:
234.1849 -
234.1850 - (y+k).n - (y+k).o = x.n [2]
234.1851 -
234.1852 -By #1, this is the same as
234.1853 -
234.1854 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
234.1855 -
234.1856 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
234.1857 -Substituting that into [3],
234.1858 -
234.1859 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
234.1860 - k - (y+k).s - (y+k).d = 0; rearranging,
234.1861 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
234.1862 - k = y.s - (y+k).d
234.1863 -
234.1864 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
234.1865 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
234.1866 -very large, since all offset-returning methods return a duration of magnitude
234.1867 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
234.1868 -be 0, so ignoring it has no consequence then.
234.1869 -
234.1870 -In any case, the new value is
234.1871 -
234.1872 - z = y + y.s [4]
234.1873 -
234.1874 -It's helpful to step back at look at [4] from a higher level: it's simply
234.1875 -mapping from UTC to tz's standard time.
234.1876 -
234.1877 -At this point, if
234.1878 -
234.1879 - z.n - z.o = x.n [5]
234.1880 -
234.1881 -we have an equivalent time, and are almost done. The insecurity here is
234.1882 -at the start of daylight time. Picture US Eastern for concreteness. The wall
234.1883 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
234.1884 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
234.1885 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
234.1886 -on the day DST starts. We want to return the 1:MM EST spelling because that's
234.1887 -the only spelling that makes sense on the local wall clock.
234.1888 -
234.1889 -In fact, if [5] holds at this point, we do have the standard-time spelling,
234.1890 -but that takes a bit of proof. We first prove a stronger result. What's the
234.1891 -difference between the LHS and RHS of [5]? Let
234.1892 -
234.1893 - diff = x.n - (z.n - z.o) [6]
234.1894 -
234.1895 -Now
234.1896 - z.n = by [4]
234.1897 - (y + y.s).n = by #5
234.1898 - y.n + y.s = since y.n = x.n
234.1899 - x.n + y.s = since z and y are have the same tzinfo member,
234.1900 - y.s = z.s by #2
234.1901 - x.n + z.s
234.1902 -
234.1903 -Plugging that back into [6] gives
234.1904 -
234.1905 - diff =
234.1906 - x.n - ((x.n + z.s) - z.o) = expanding
234.1907 - x.n - x.n - z.s + z.o = cancelling
234.1908 - - z.s + z.o = by #2
234.1909 - z.d
234.1910 -
234.1911 -So diff = z.d.
234.1912 -
234.1913 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
234.1914 -spelling we wanted in the endcase described above. We're done. Contrarily,
234.1915 -if z.d = 0, then we have a UTC equivalent, and are also done.
234.1916 -
234.1917 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
234.1918 -add to z (in effect, z is in tz's standard time, and we need to shift the
234.1919 -local clock into tz's daylight time).
234.1920 -
234.1921 -Let
234.1922 -
234.1923 - z' = z + z.d = z + diff [7]
234.1924 -
234.1925 -and we can again ask whether
234.1926 -
234.1927 - z'.n - z'.o = x.n [8]
234.1928 -
234.1929 -If so, we're done. If not, the tzinfo class is insane, according to the
234.1930 -assumptions we've made. This also requires a bit of proof. As before, let's
234.1931 -compute the difference between the LHS and RHS of [8] (and skipping some of
234.1932 -the justifications for the kinds of substitutions we've done several times
234.1933 -already):
234.1934 -
234.1935 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
234.1936 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
234.1937 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
234.1938 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
234.1939 - - z.n + z.n - z.o + z'.o = cancel z.n
234.1940 - - z.o + z'.o = #1 twice
234.1941 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
234.1942 - z'.d - z.d
234.1943 -
234.1944 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
234.1945 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
234.1946 -return z', not bothering to compute z'.d.
234.1947 -
234.1948 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
234.1949 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
234.1950 -would have to change the result dst() returns: we start in DST, and moving
234.1951 -a little further into it takes us out of DST.
234.1952 -
234.1953 -There isn't a sane case where this can happen. The closest it gets is at
234.1954 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
234.1955 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
234.1956 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
234.1957 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
234.1958 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
234.1959 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
234.1960 -standard time. Since that's what the local clock *does*, we want to map both
234.1961 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
234.1962 -in local time, but so it goes -- it's the way the local clock works.
234.1963 -
234.1964 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
234.1965 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
234.1966 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
234.1967 -(correctly) concludes that z' is not UTC-equivalent to x.
234.1968 -
234.1969 -Because we know z.d said z was in daylight time (else [5] would have held and
234.1970 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
234.1971 -and we we have stopped then), and there are only 2 possible values dst() can
234.1972 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
234.1973 -but the reasoning doesn't depend on the example -- it depends on there being
234.1974 -two possible dst() outcomes, one zero and the other non-zero). Therefore
234.1975 -z' must be in standard time, and is the spelling we want in this case.
234.1976 -
234.1977 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
234.1978 -concerned (because it takes z' as being in standard time rather than the
234.1979 -daylight time we intend here), but returning it gives the real-life "local
234.1980 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
234.1981 -tz.
234.1982 -
234.1983 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
234.1984 -the 1:MM standard time spelling we want.
234.1985 -
234.1986 -So how can this break? One of the assumptions must be violated. Two
234.1987 -possibilities:
234.1988 -
234.1989 -1) [2] effectively says that y.s is invariant across all y belong to a given
234.1990 - time zone. This isn't true if, for political reasons or continental drift,
234.1991 - a region decides to change its base offset from UTC.
234.1992 -
234.1993 -2) There may be versions of "double daylight" time where the tail end of
234.1994 - the analysis gives up a step too early. I haven't thought about that
234.1995 - enough to say.
234.1996 -
234.1997 -In any case, it's clear that the default fromutc() is strong enough to handle
234.1998 -"almost all" time zones: so long as the standard offset is invariant, it
234.1999 -doesn't matter if daylight time transition points change from year to year, or
234.2000 -if daylight time is skipped in some years; it doesn't matter how large or
234.2001 -small dst() may get within its bounds; and it doesn't even matter if some
234.2002 -perverse time zone returns a negative dst()). So a breaking case must be
234.2003 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
234.2004 -"""
234.2005 -
234.2006 -def _test():
234.2007 - import test_datetime
234.2008 - test_datetime.test_main()
234.2009 -
234.2010 -if __name__ == "__main__":
234.2011 - _test()
235.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.indexed Sun Jan 04 13:11:53 2015 -0600
235.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
235.3 @@ -1,392 +0,0 @@
235.4 -
235.5 -
235.6 -Document 0
235.7 -Searchable Keys:
235.8 - class : _date_class
235.9 - class-ig : _date_class
235.10 - extends : object
235.11 - in : datetime
235.12 - member : __add__;F;;self,other;
235.13 - member : __cmp;F;|PRIVATE|;self,other;
235.14 - member : __day;D;|PRIVATE|;
235.15 - member : __eq__;F;;self,other;
235.16 - member : __ge__;F;;self,other;
235.17 - member : __getstate;F;|PRIVATE|;self;
235.18 - member : __gt__;F;;self,other;
235.19 - member : __hash__;F;;self;
235.20 - member : __le__;F;;self,other;
235.21 - member : __lt__;F;;self,other;
235.22 - member : __month;D;|PRIVATE|;
235.23 - member : __ne__;F;;self,other;
235.24 - member : __new__;F;;cls,year,month,day;
235.25 - member : __radd__;F;;self,other;
235.26 - member : __reduce__;F;;self;
235.27 - member : __repr__;F;;self;
235.28 - member : __safe_for_unpickling__;D;;
235.29 - member : __setstate;F;|PRIVATE|;self,t;
235.30 - member : __str__;F;;self;
235.31 - member : __sub__;F;;self,other;
235.32 - member : __year;D;|PRIVATE|;
235.33 - member : _checkOverflow;F;|PRIVATE|;self,year;
235.34 - member : ctime;F;;self;
235.35 - member : day;D;;
235.36 - member : fromordinal;F;;cls,n;
235.37 - member : fromtimestamp;F;;cls,t;
235.38 - member : isocalendar;F;;self;
235.39 - member : isoformat;F;;self;
235.40 - member : isoweekday;F;;self;
235.41 - member : month;D;;
235.42 - member : replace;F;;self,year,month,day;
235.43 - member : strftime;F;;self,fmt;
235.44 - member : timetuple;F;;self;
235.45 - member : today;F;;cls;
235.46 - member : toordinal;F;;self;
235.47 - member : weekday;F;;self;
235.48 - member : year;D;;
235.49 -
235.50 -Not Searchable Keys:
235.51 - clzattrs : ;|PRIVATE|;
235.52 -
235.53 -
235.54 -Document 1
235.55 -Searchable Keys:
235.56 - class : _time_class
235.57 - class-ig : _time_class
235.58 - extends : object
235.59 - in : datetime
235.60 - member : __cmp;F;|PRIVATE|;self,other;
235.61 - member : __eq__;F;;self,other;
235.62 - member : __ge__;F;;self,other;
235.63 - member : __getstate;F;|PRIVATE|;self;
235.64 - member : __gt__;F;;self,other;
235.65 - member : __hash__;F;;self;
235.66 - member : __hour;D;|PRIVATE|;
235.67 - member : __le__;F;;self,other;
235.68 - member : __lt__;F;;self,other;
235.69 - member : __microsecond;D;|PRIVATE|;
235.70 - member : __minute;D;|PRIVATE|;
235.71 - member : __ne__;F;;self,other;
235.72 - member : __new__;F;;cls,hour,minute,second,microsecond,tzinfo;
235.73 - member : __nonzero__;F;;self;
235.74 - member : __reduce__;F;;self;
235.75 - member : __repr__;F;;self;
235.76 - member : __safe_for_unpickling__;D;;
235.77 - member : __second;D;|PRIVATE|;
235.78 - member : __setstate;F;|PRIVATE|;self,state;
235.79 - member : __str__;F;;self;
235.80 - member : _dst;F;|PRIVATE|;self;
235.81 - member : _tzinfo;D;|PRIVATE|;
235.82 - member : _tzstr;F;|PRIVATE|;self,sep;
235.83 - member : _utcoffset;F;|PRIVATE|;self;
235.84 - member : dst;F;;self;
235.85 - member : hour;D;;
235.86 - member : isoformat;F;;self;
235.87 - member : microsecond;D;;
235.88 - member : minute;D;;
235.89 - member : replace;F;;self,hour,minute,second,microsecond,tzinfo;
235.90 - member : second;D;;
235.91 - member : strftime;F;;self,fmt;
235.92 - member : tzinfo;D;;
235.93 - member : tzname;F;;self;
235.94 - member : utcoffset;F;;self;
235.95 -
235.96 -Not Searchable Keys:
235.97 - clzattrs : ;|PRIVATE|;
235.98 -
235.99 -
235.100 -Document 2
235.101 -Searchable Keys:
235.102 - class : _tzinfo_class
235.103 - class-ig : _tzinfo_class
235.104 - extends : object
235.105 - in : datetime
235.106 - member : __reduce__;F;;self;
235.107 - member : __safe_for_unpickling__;D;;
235.108 - member : dst;F;;self,dt;
235.109 - member : fromutc;F;;self,dt;
235.110 - member : tzname;F;;self,dt;
235.111 - member : utcoffset;F;;self,dt;
235.112 -
235.113 -Not Searchable Keys:
235.114 - clzattrs : ;|PRIVATE|;
235.115 -
235.116 -
235.117 -Document 3
235.118 -Searchable Keys:
235.119 - class : date
235.120 - class-ig : date
235.121 - extends : object
235.122 - in : datetime
235.123 - member : __add__;F;;self,other;
235.124 - member : __cmp;F;|PRIVATE|;self,other;
235.125 - member : __day;D;|PRIVATE|;
235.126 - member : __eq__;F;;self,other;
235.127 - member : __ge__;F;;self,other;
235.128 - member : __getstate;F;|PRIVATE|;self;
235.129 - member : __gt__;F;;self,other;
235.130 - member : __hash__;F;;self;
235.131 - member : __le__;F;;self,other;
235.132 - member : __lt__;F;;self,other;
235.133 - member : __month;D;|PRIVATE|;
235.134 - member : __ne__;F;;self,other;
235.135 - member : __new__;F;;cls,year,month,day;
235.136 - member : __radd__;F;;self,other;
235.137 - member : __reduce__;F;;self;
235.138 - member : __repr__;F;;self;
235.139 - member : __safe_for_unpickling__;D;;
235.140 - member : __setstate;F;|PRIVATE|;self,t;
235.141 - member : __str__;F;;self;
235.142 - member : __sub__;F;;self,other;
235.143 - member : __year;D;|PRIVATE|;
235.144 - member : _checkOverflow;F;|PRIVATE|;self,year;
235.145 - member : ctime;F;;self;
235.146 - member : day;D;;
235.147 - member : fromordinal;F;;cls,n;
235.148 - member : fromtimestamp;F;;cls,t;
235.149 - member : isocalendar;F;;self;
235.150 - member : isoformat;F;;self;
235.151 - member : isoweekday;F;;self;
235.152 - member : month;D;;
235.153 - member : replace;F;;self,year,month,day;
235.154 - member : strftime;F;;self,fmt;
235.155 - member : timetuple;F;;self;
235.156 - member : today;F;;cls;
235.157 - member : toordinal;F;;self;
235.158 - member : weekday;F;;self;
235.159 - member : year;D;;
235.160 -
235.161 -Not Searchable Keys:
235.162 -
235.163 -
235.164 -Document 4
235.165 -Searchable Keys:
235.166 - class : datetime
235.167 - class-ig : datetime
235.168 - extends : date
235.169 - in : datetime
235.170 - member : __add__;F;;self,other;
235.171 - member : __cmp;F;|PRIVATE|;self,other;
235.172 - member : __day;D;|PRIVATE|;
235.173 - member : __eq__;F;;self,other;
235.174 - member : __ge__;F;;self,other;
235.175 - member : __getstate;F;|PRIVATE|;self;
235.176 - member : __gt__;F;;self,other;
235.177 - member : __hash__;F;;self;
235.178 - member : __hour;D;|PRIVATE|;
235.179 - member : __le__;F;;self,other;
235.180 - member : __lt__;F;;self,other;
235.181 - member : __microsecond;D;|PRIVATE|;
235.182 - member : __minute;D;|PRIVATE|;
235.183 - member : __month;D;|PRIVATE|;
235.184 - member : __ne__;F;;self,other;
235.185 - member : __new__;F;;cls,year,month,day,hour,minute,second,microsecond,tzinfo;
235.186 - member : __radd__;F;;self,other;
235.187 - member : __reduce__;F;;self;
235.188 - member : __repr__;F;;self;
235.189 - member : __safe_for_unpickling__;D;;
235.190 - member : __second;D;|PRIVATE|;
235.191 - member : __setstate;F;|PRIVATE|;self,state;
235.192 - member : __str__;F;;self;
235.193 - member : __sub__;F;;self,other;
235.194 - member : __year;D;|PRIVATE|;
235.195 - member : _dst;F;|PRIVATE|;self;
235.196 - member : _tzinfo;D;|PRIVATE|;
235.197 - member : _utcoffset;F;|PRIVATE|;self;
235.198 - member : astimezone;F;;self,tz;
235.199 - member : combine;F;;cls,date,time;
235.200 - member : ctime;F;;self;
235.201 - member : date;F;;self;
235.202 - member : dst;F;;self;
235.203 - member : fromtimestamp;F;;cls,t,tz;
235.204 - member : hour;D;;
235.205 - member : isoformat;F;;self,sep;
235.206 - member : microsecond;D;;
235.207 - member : minute;D;;
235.208 - member : now;F;;cls,tz;
235.209 - member : replace;F;;self,year,month,day,hour,minute,second,microsecond,tzinfo;
235.210 - member : second;D;;
235.211 - member : time;F;;self;
235.212 - member : timetuple;F;;self;
235.213 - member : timetz;F;;self;
235.214 - member : tzinfo;D;;
235.215 - member : tzname;F;;self;
235.216 - member : utcfromtimestamp;F;;cls,t;
235.217 - member : utcnow;F;;cls;
235.218 - member : utcoffset;F;;self;
235.219 - member : utctimetuple;F;;self;
235.220 -
235.221 -Not Searchable Keys:
235.222 -
235.223 -
235.224 -Document 5
235.225 -Searchable Keys:
235.226 - class : time
235.227 - class-ig : time
235.228 - extends : object
235.229 - in : datetime
235.230 - member : __cmp;F;|PRIVATE|;self,other;
235.231 - member : __eq__;F;;self,other;
235.232 - member : __ge__;F;;self,other;
235.233 - member : __getstate;F;|PRIVATE|;self;
235.234 - member : __gt__;F;;self,other;
235.235 - member : __hash__;F;;self;
235.236 - member : __hour;D;|PRIVATE|;
235.237 - member : __le__;F;;self,other;
235.238 - member : __lt__;F;;self,other;
235.239 - member : __microsecond;D;|PRIVATE|;
235.240 - member : __minute;D;|PRIVATE|;
235.241 - member : __ne__;F;;self,other;
235.242 - member : __new__;F;;cls,hour,minute,second,microsecond,tzinfo;
235.243 - member : __nonzero__;F;;self;
235.244 - member : __reduce__;F;;self;
235.245 - member : __repr__;F;;self;
235.246 - member : __safe_for_unpickling__;D;;
235.247 - member : __second;D;|PRIVATE|;
235.248 - member : __setstate;F;|PRIVATE|;self,state;
235.249 - member : __str__;F;;self;
235.250 - member : _dst;F;|PRIVATE|;self;
235.251 - member : _tzinfo;D;|PRIVATE|;
235.252 - member : _tzstr;F;|PRIVATE|;self,sep;
235.253 - member : _utcoffset;F;|PRIVATE|;self;
235.254 - member : dst;F;;self;
235.255 - member : hour;D;;
235.256 - member : isoformat;F;;self;
235.257 - member : microsecond;D;;
235.258 - member : minute;D;;
235.259 - member : replace;F;;self,hour,minute,second,microsecond,tzinfo;
235.260 - member : second;D;;
235.261 - member : strftime;F;;self,fmt;
235.262 - member : tzinfo;D;;
235.263 - member : tzname;F;;self;
235.264 - member : utcoffset;F;;self;
235.265 -
235.266 -Not Searchable Keys:
235.267 -
235.268 -
235.269 -Document 6
235.270 -Searchable Keys:
235.271 - class : timedelta
235.272 - class-ig : timedelta
235.273 - extends : object
235.274 - in : datetime
235.275 - member : __abs__;F;;self;
235.276 - member : __add__;F;;self,other;
235.277 - member : __cmp;F;|PRIVATE|;self,other;
235.278 - member : __days;D;|PRIVATE|;
235.279 - member : __div__;F;;self,other;
235.280 - member : __eq__;F;;self,other;
235.281 - member : __floordiv__;F;;self,other;
235.282 - member : __ge__;F;;self,other;
235.283 - member : __getstate;F;|PRIVATE|;self;
235.284 - member : __gt__;F;;self,other;
235.285 - member : __hash__;F;;self;
235.286 - member : __le__;F;;self,other;
235.287 - member : __lt__;F;;self,other;
235.288 - member : __microseconds;D;|PRIVATE|;
235.289 - member : __mul__;F;;self,other;
235.290 - member : __ne__;F;;self,other;
235.291 - member : __neg__;F;;self;
235.292 - member : __new__;F;;cls,days,seconds,microseconds,milliseconds,minutes,hours,weeks;
235.293 - member : __nonzero__;F;;self;
235.294 - member : __pos__;F;;self;
235.295 - member : __radd__;F;;self,other;
235.296 - member : __reduce__;F;;self;
235.297 - member : __repr__;F;;self;
235.298 - member : __rmul__;F;;self,other;
235.299 - member : __rsub__;F;;self,other;
235.300 - member : __safe_for_unpickling__;D;;
235.301 - member : __seconds;D;|PRIVATE|;
235.302 - member : __str__;F;;self;
235.303 - member : __sub__;F;;self,other;
235.304 - member : days;D;;
235.305 - member : microseconds;D;;
235.306 - member : seconds;D;;
235.307 -
235.308 -Not Searchable Keys:
235.309 -
235.310 -
235.311 -Document 7
235.312 -Searchable Keys:
235.313 - class : tmxxx
235.314 - class-ig : tmxxx
235.315 - in : datetime
235.316 - member : __init__;c;|CONSTRUCTOR|;self,year,month,day,hour,minute,second,microsecond;
235.317 - member : ctime;F;;self;
235.318 - member : day;D;;
235.319 - member : hour;D;;
235.320 - member : microsecond;D;;
235.321 - member : minute;D;;
235.322 - member : month;D;;
235.323 - member : ordinal;D;;
235.324 - member : ordinal;D;;
235.325 - member : second;D;;
235.326 - member : time;F;;self;
235.327 - member : toordinal;F;;self;
235.328 - member : year;D;;
235.329 -
235.330 -Not Searchable Keys:
235.331 -
235.332 -
235.333 -Document 8
235.334 -Searchable Keys:
235.335 - class : tzinfo
235.336 - class-ig : tzinfo
235.337 - extends : object
235.338 - in : datetime
235.339 - member : __reduce__;F;;self;
235.340 - member : __safe_for_unpickling__;D;;
235.341 - member : dst;F;;self,dt;
235.342 - member : fromutc;F;;self,dt;
235.343 - member : tzname;F;;self,dt;
235.344 - member : utcoffset;F;;self,dt;
235.345 -
235.346 -Not Searchable Keys:
235.347 -
235.348 -
235.349 -Document 9
235.350 -Searchable Keys:
235.351 - item : MAXYEAR;D;;
235.352 - item : MINYEAR;D;;
235.353 - item : _DAYNAMES;D;|PRIVATE|;
235.354 - item : _DAYS_BEFORE_MONTH;D;|PRIVATE|;
235.355 - item : _DAYS_IN_MONTH;D;|PRIVATE|;
235.356 - item : _DI100Y;D;|PRIVATE|;
235.357 - item : _DI400Y;D;|PRIVATE|;
235.358 - item : _DI4Y;D;|PRIVATE|;
235.359 - item : _MONTHNAMES;D;|PRIVATE|;
235.360 - item : _ORD1970;D;|PRIVATE|;
235.361 - item : _build_struct_time;F;|PRIVATE|;y,m,d,hh,mm,ss,dstflag;
235.362 - item : _call_tzinfo_method;F;|PRIVATE|;tzinfo,methname,tzinfoarg;
235.363 - item : _check_date_fields;F;|PRIVATE|;year,month,day;
235.364 - item : _check_time_fields;F;|PRIVATE|;hour,minute,second,microsecond;
235.365 - item : _check_tzinfo_arg;F;|PRIVATE|;tz;
235.366 - item : _check_tzname;F;|PRIVATE|;name;
235.367 - item : _check_utc_offset;F;|PRIVATE|;name,offset;
235.368 - item : _cmperror;F;|PRIVATE|;x,y;
235.369 - item : _date_class;C;|PRIVATE|;
235.370 - item : _days_before_month;F;|PRIVATE|;year,month;
235.371 - item : _days_before_year;F;|PRIVATE|;year;
235.372 - item : _days_in_month;F;|PRIVATE|;year,month;
235.373 - item : _days_in_year;F;|PRIVATE|;year;
235.374 - item : _format_time;F;|PRIVATE|;hh,mm,ss,us;
235.375 - item : _is_leap;F;|PRIVATE|;year;
235.376 - item : _isoweek1monday;F;|PRIVATE|;year;
235.377 - item : _math;I;|PRIVATE|;
235.378 - item : _ord2ymd;F;|PRIVATE|;n;
235.379 - item : _test;F;|PRIVATE|;;
235.380 - item : _time;I;|PRIVATE|;
235.381 - item : _time_class;C;|PRIVATE|;
235.382 - item : _tzinfo_class;C;|PRIVATE|;
235.383 - item : _wrap_strftime;F;|PRIVATE|;object,format,timetuple;
235.384 - item : _ymd2ord;F;|PRIVATE|;year,month,day;
235.385 - item : date;C;;
235.386 - item : datetime;C;;
235.387 - item : dbm;D;;
235.388 - item : dim;D;;
235.389 - item : time;C;;
235.390 - item : timedelta;C;;
235.391 - item : tmxxx;C;;
235.392 - item : tzinfo;C;;
235.393 - module : datetime
235.394 -
235.395 -Not Searchable Keys:
236.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.nameoffsets Sun Jan 04 13:11:53 2015 -0600
236.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
236.3 @@ -1,2009 +0,0 @@
236.4 -
236.5 -"""Concrete date/time and related types -- prototype implemented in Python.
236.6 -
236.7 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
236.8 -
236.9 -See also http://dir.yahoo.com/Reference/calendars/
236.10 -
236.11 -For a primer on DST, including many current DST rules, see
236.12 -http://webexhibits.org/daylightsaving/
236.13 -
236.14 -For more about DST than you ever wanted to know, see
236.15 -ftp://elsie.nci.nih.gov/pub/
236.16 -
236.17 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
236.18 -
236.19 -"""
236.20 -
236.21 -import time as _time
236.22 -import math as _math
236.23 -
236.24 -<Name>MINYEAR</Name> = 1
236.25 -<Name>MAXYEAR</Name> = 9999
236.26 -
236.27 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
236.28 -# also assumes the current Gregorian calendar indefinitely extended in
236.29 -# both directions. Difference: Dates.py calls January 1 of year 0 day
236.30 -# number 1. The code here calls January 1 of year 1 day number 1. This is
236.31 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
236.32 -# and Reingold's "Calendrical Calculations", where it's the base calendar
236.33 -# for all computations. See the book for algorithms for converting between
236.34 -# proleptic Gregorian ordinals and many other calendar systems.
236.35 -
236.36 -<Name>_DAYS_IN_MONTH</Name> = [<Name>None</Name>, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
236.37 -
236.38 -<Name>_DAYS_BEFORE_MONTH</Name> = [<Name>None</Name>]
236.39 -<Name>dbm</Name> = 0
236.40 -for <Name>dim</Name> in <Name>_DAYS_IN_MONTH</Name>[1:]:
236.41 - <Attribute><Name>_DAYS_BEFORE_MONTH</Name></Attribute>.<Call>append</Call>(<Name>dbm</Name>)
236.42 - <Name>dbm</Name> += <Name>dim</Name>
236.43 -del <Name>dbm</Name>, <Name>dim</Name>
236.44 -
236.45 -def <FunctionDef>_is_leap</FunctionDef>(<Name>year</Name>):
236.46 - "year -> 1 if leap year, else 0."
236.47 - return <Name>year</Name> % 4 == 0 and (<Name>year</Name> % 100 != 0 or <Name>year</Name> % 400 == 0)
236.48 -
236.49 -def <FunctionDef>_days_in_year</FunctionDef>(<Name>year</Name>):
236.50 - "year -> number of days in year (366 if a leap year, else 365)."
236.51 - return 365 + <Call><Name>_is_leap</Name></Call>(<Name>year</Name>)
236.52 -
236.53 -def <FunctionDef>_days_before_year</FunctionDef>(<Name>year</Name>):
236.54 - "year -> number of days before January 1st of year."
236.55 - <Name>y</Name> = <Name>year</Name> - 1
236.56 - return <Name>y</Name>*365 + <Name>y</Name>//4 - <Name>y</Name>//100 + <Name>y</Name>//400
236.57 -
236.58 -def <FunctionDef>_days_in_month</FunctionDef>(<Name>year</Name>, <Name>month</Name>):
236.59 - "year, month -> number of days in that month in that year."
236.60 - assert 1 <= <Name>month</Name> <= 12, <Name>month</Name>
236.61 - if <Name>month</Name> == 2 and <Call><Name>_is_leap</Name></Call>(<Name>year</Name>):
236.62 - return 29
236.63 - return <Name>_DAYS_IN_MONTH</Name>[<Name>month</Name>]
236.64 -
236.65 -def <FunctionDef>_days_before_month</FunctionDef>(<Name>year</Name>, <Name>month</Name>):
236.66 - "year, month -> number of days in year preceeding first day of month."
236.67 - if not 1 <= <Name>month</Name> <= 12:
236.68 - raise <Call><Name>ValueError</Name></Call>('month must be in 1..12', <Name>month</Name>)
236.69 - return <Name>_DAYS_BEFORE_MONTH</Name>[<Name>month</Name>] + (<Name>month</Name> > 2 and <Call><Name>_is_leap</Name></Call>(<Name>year</Name>))
236.70 -
236.71 -def <FunctionDef>_ymd2ord</FunctionDef>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>):
236.72 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
236.73 - if not 1 <= <Name>month</Name> <= 12:
236.74 - raise <Call><Name>ValueError</Name></Call>('month must be in 1..12', <Name>month</Name>)
236.75 - <Name>dim</Name> = <Call><Name>_days_in_month</Name></Call>(<Name>year</Name>, <Name>month</Name>)
236.76 - if not 1 <= <Name>day</Name> <= <Name>dim</Name>:
236.77 - raise <Call><Name>ValueError</Name></Call>('day must be in 1..%d' % <Name>dim</Name>, <Name>day</Name>)
236.78 - return (<Call><Name>_days_before_year</Name></Call>(<Name>year</Name>) +
236.79 - <Call><Name>_days_before_month</Name></Call>(<Name>year</Name>, <Name>month</Name>) +
236.80 - <Name>day</Name>)
236.81 -
236.82 -<Name>_DI400Y</Name> = <Call><Name>_days_before_year</Name></Call>(401) # number of days in 400 years
236.83 -<Name>_DI100Y</Name> = <Call><Name>_days_before_year</Name></Call>(101) # " " " " 100 "
236.84 -<Name>_DI4Y</Name> = <Call><Name>_days_before_year</Name></Call>(5) # " " " " 4 "
236.85 -
236.86 -# A 4-year cycle has an extra leap day over what we'd get from pasting
236.87 -# together 4 single years.
236.88 -assert <Name>_DI4Y</Name> == 4 * 365 + 1
236.89 -
236.90 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
236.91 -# pasting together 4 100-year cycles.
236.92 -assert <Name>_DI400Y</Name> == 4 * <Name>_DI100Y</Name> + 1
236.93 -
236.94 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
236.95 -# pasting together 25 4-year cycles.
236.96 -assert <Name>_DI100Y</Name> == 25 * <Name>_DI4Y</Name> - 1
236.97 -
236.98 -def <FunctionDef>_ord2ymd</FunctionDef>(<Name>n</Name>):
236.99 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
236.100 -
236.101 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
236.102 - # repeats exactly every 400 years. The basic strategy is to find the
236.103 - # closest 400-year boundary at or before n, then work with the offset
236.104 - # from that boundary to n. Life is much clearer if we subtract 1 from
236.105 - # n first -- then the values of n at 400-year boundaries are exactly
236.106 - # those divisible by _DI400Y:
236.107 - #
236.108 - # D M Y n n-1
236.109 - # -- --- ---- ---------- ----------------
236.110 - # 31 Dec -400 -_DI400Y -_DI400Y -1
236.111 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
236.112 - # ...
236.113 - # 30 Dec 000 -1 -2
236.114 - # 31 Dec 000 0 -1
236.115 - # 1 Jan 001 1 0 400-year boundary
236.116 - # 2 Jan 001 2 1
236.117 - # 3 Jan 001 3 2
236.118 - # ...
236.119 - # 31 Dec 400 _DI400Y _DI400Y -1
236.120 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
236.121 - <Name>n</Name> -= 1
236.122 - <Name>n400</Name>, <Name>n</Name> = <Call><Name>divmod</Name></Call>(<Name>n</Name>, <Name>_DI400Y</Name>)
236.123 - <Name>year</Name> = <Name>n400</Name> * 400 + 1 # ..., -399, 1, 401, ...
236.124 -
236.125 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
236.126 - # the desired date. Now compute how many 100-year cycles precede n.
236.127 - # Note that it's possible for n100 to equal 4! In that case 4 full
236.128 - # 100-year cycles precede the desired day, which implies the desired
236.129 - # day is December 31 at the end of a 400-year cycle.
236.130 - <Name>n100</Name>, <Name>n</Name> = <Call><Name>divmod</Name></Call>(<Name>n</Name>, <Name>_DI100Y</Name>)
236.131 -
236.132 - # Now compute how many 4-year cycles precede it.
236.133 - <Name>n4</Name>, <Name>n</Name> = <Call><Name>divmod</Name></Call>(<Name>n</Name>, <Name>_DI4Y</Name>)
236.134 -
236.135 - # And now how many single years. Again n1 can be 4, and again meaning
236.136 - # that the desired day is December 31 at the end of the 4-year cycle.
236.137 - <Name>n1</Name>, <Name>n</Name> = <Call><Name>divmod</Name></Call>(<Name>n</Name>, 365)
236.138 -
236.139 - <Name>year</Name> += <Name>n100</Name> * 100 + <Name>n4</Name> * 4 + <Name>n1</Name>
236.140 - if <Name>n1</Name> == 4 or <Name>n100</Name> == 4:
236.141 - assert <Name>n</Name> == 0
236.142 - return <Name>year</Name>-1, 12, 31
236.143 -
236.144 - # Now the year is correct, and n is the offset from January 1. We find
236.145 - # the month via an estimate that's either exact or one too large.
236.146 - <Name>leapyear</Name> = <Name>n1</Name> == 3 and (<Name>n4</Name> != 24 or <Name>n100</Name> == 3)
236.147 - assert <Name>leapyear</Name> == <Call><Name>_is_leap</Name></Call>(<Name>year</Name>)
236.148 - <Name>month</Name> = (<Name>n</Name> + 50) >> 5
236.149 - <Name>preceding</Name> = <Name>_DAYS_BEFORE_MONTH</Name>[<Name>month</Name>] + (<Name>month</Name> > 2 and <Name>leapyear</Name>)
236.150 - if <Name>preceding</Name> > <Name>n</Name>: # estimate is too large
236.151 - <Name>month</Name> -= 1
236.152 - <Name>preceding</Name> -= <Name>_DAYS_IN_MONTH</Name>[<Name>month</Name>] + (<Name>month</Name> == 2 and <Name>leapyear</Name>)
236.153 - <Name>n</Name> -= <Name>preceding</Name>
236.154 - assert 0 <= <Name>n</Name> < <Call><Name>_days_in_month</Name></Call>(<Name>year</Name>, <Name>month</Name>)
236.155 -
236.156 - # Now the year and month are correct, and n is the offset from the
236.157 - # start of that month: we're done!
236.158 - return <Name>year</Name>, <Name>month</Name>, <Name>n</Name>+1
236.159 -
236.160 -# Month and day names. For localized versions, see the calendar module.
236.161 -<Name>_MONTHNAMES</Name> = [<Name>None</Name>, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
236.162 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
236.163 -<Name>_DAYNAMES</Name> = [<Name>None</Name>, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
236.164 -
236.165 -
236.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>):
236.167 - <Name>wday</Name> = (<Call><Name>_ymd2ord</Name></Call>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>) + 6) % 7
236.168 - <Name>dnum</Name> = <Call><Name>_days_before_month</Name></Call>(<Name>y</Name>, <Name>m</Name>) + <Name>d</Name>
236.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>))
236.170 -
236.171 -def <FunctionDef>_format_time</FunctionDef>(<Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>us</Name>):
236.172 - # Skip trailing microseconds when us==0.
236.173 - <Name>result</Name> = "%02d:%02d:%02d" % (<Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>)
236.174 - if <Name>us</Name>:
236.175 - <Name>result</Name> += ".%06d" % <Name>us</Name>
236.176 - return <Name>result</Name>
236.177 -
236.178 -# Correctly substitute for %z and %Z escapes in strftime formats.
236.179 -def <FunctionDef>_wrap_strftime</FunctionDef>(<Name>object</Name>, <Name>format</Name>, <Name>timetuple</Name>):
236.180 - <Name>year</Name> = <Name>timetuple</Name>[0]
236.181 - if <Name>year</Name> < 1900:
236.182 - raise <Call><Name>ValueError</Name></Call>("year=%d is before 1900; the datetime strftime() "
236.183 - "methods require year >= 1900" % <Name>year</Name>)
236.184 - # Don't call _utcoffset() or tzname() unless actually needed.
236.185 - <Name>zreplace</Name> = <Name>None</Name> # the string to use for %z
236.186 - <Name>Zreplace</Name> = <Name>None</Name> # the string to use for %Z
236.187 -
236.188 - # Scan format for %z and %Z escapes, replacing as needed.
236.189 - <Name>newformat</Name> = []
236.190 - <Name>push</Name> = <Attribute><Name>newformat</Name></Attribute>.append
236.191 - <Name>i</Name>, <Name>n</Name> = 0, <Call><Name>len</Name></Call>(<Name>format</Name>)
236.192 - while <Name>i</Name> < <Name>n</Name>:
236.193 - <Name>ch</Name> = <Name>format</Name>[<Name>i</Name>]
236.194 - <Name>i</Name> += 1
236.195 - if <Name>ch</Name> == '%':
236.196 - if <Name>i</Name> < <Name>n</Name>:
236.197 - <Name>ch</Name> = <Name>format</Name>[<Name>i</Name>]
236.198 - <Name>i</Name> += 1
236.199 - if <Name>ch</Name> == 'z':
236.200 - if <Name>zreplace</Name> is <Name>None</Name>:
236.201 - <Name>zreplace</Name> = ""
236.202 - if <Call><Name>hasattr</Name></Call>(<Name>object</Name>, "_utcoffset"):
236.203 - <Name>offset</Name> = <Attribute><Name>object</Name></Attribute>.<Call>_utcoffset</Call>()
236.204 - if <Name>offset</Name> is not <Name>None</Name>:
236.205 - <Name>sign</Name> = '+'
236.206 - if <Name>offset</Name> < 0:
236.207 - <Name>offset</Name> = -<Name>offset</Name>
236.208 - <Name>sign</Name> = '-'
236.209 - <Name>h</Name>, <Name>m</Name> = <Call><Name>divmod</Name></Call>(<Name>offset</Name>, 60)
236.210 - <Name>zreplace</Name> = '%c%02d%02d' % (<Name>sign</Name>, <Name>h</Name>, <Name>m</Name>)
236.211 - assert '%' not in <Name>zreplace</Name>
236.212 - <Attribute><Name>newformat</Name></Attribute>.<Call>append</Call>(<Name>zreplace</Name>)
236.213 - elif <Name>ch</Name> == 'Z':
236.214 - if <Name>Zreplace</Name> is <Name>None</Name>:
236.215 - <Name>Zreplace</Name> = ""
236.216 - if <Call><Name>hasattr</Name></Call>(<Name>object</Name>, "tzname"):
236.217 - <Name>s</Name> = <Attribute><Name>object</Name></Attribute>.<Call>tzname</Call>()
236.218 - if <Name>s</Name> is not <Name>None</Name>:
236.219 - # strftime is going to have at this: escape %
236.220 - <Name>Zreplace</Name> = <Attribute><Name>s</Name></Attribute>.<Call>replace</Call>('%', '%%')
236.221 - <Attribute><Name>newformat</Name></Attribute>.<Call>append</Call>(<Name>Zreplace</Name>)
236.222 - else:
236.223 - <Call><Name>push</Name></Call>('%')
236.224 - <Call><Name>push</Name></Call>(<Name>ch</Name>)
236.225 - else:
236.226 - <Call><Name>push</Name></Call>('%')
236.227 - else:
236.228 - <Call><Name>push</Name></Call>(<Name>ch</Name>)
236.229 - <Name>newformat</Name> = <Attribute>""</Attribute>.<Call>join</Call>(<Name>newformat</Name>)
236.230 - return <Attribute><Name>_time</Name></Attribute>.<Call>strftime</Call>(<Name>newformat</Name>, <Name>timetuple</Name>)
236.231 -
236.232 -def <FunctionDef>_call_tzinfo_method</FunctionDef>(<Name>tzinfo</Name>, <Name>methname</Name>, <Name>tzinfoarg</Name>):
236.233 - if <Name>tzinfo</Name> is <Name>None</Name>:
236.234 - return <Name>None</Name>
236.235 - return <Call><Call><Name>getattr</Name></Call></Call>(<Name>tzinfo</Name>, <Name>methname</Name>)(<Name>tzinfoarg</Name>)
236.236 -
236.237 -# Just raise TypeError if the arg isn't None or a string.
236.238 -def <FunctionDef>_check_tzname</FunctionDef>(<Name>name</Name>):
236.239 - if <Name>name</Name> is not <Name>None</Name> and not <Call><Name>isinstance</Name></Call>(<Name>name</Name>, <Name>str</Name>):
236.240 - raise <Call><Name>TypeError</Name></Call>("tzinfo.tzname() must return None or string, "
236.241 - "not '%s'" % <Call><Name>type</Name></Call>(<Name>name</Name>))
236.242 -
236.243 -# name is the offset-producing method, "utcoffset" or "dst".
236.244 -# offset is what it returned.
236.245 -# If offset isn't None or timedelta, raises TypeError.
236.246 -# If offset is None, returns None.
236.247 -# Else offset is checked for being in range, and a whole # of minutes.
236.248 -# If it is, its integer value is returned. Else ValueError is raised.
236.249 -def <FunctionDef>_check_utc_offset</FunctionDef>(<Name>name</Name>, <Name>offset</Name>):
236.250 - assert <Name>name</Name> in ("utcoffset", "dst")
236.251 - if <Name>offset</Name> is <Name>None</Name>:
236.252 - return <Name>None</Name>
236.253 - if not <Call><Name>isinstance</Name></Call>(<Name>offset</Name>, <Name>timedelta</Name>):
236.254 - raise <Call><Name>TypeError</Name></Call>("tzinfo.%s() must return None "
236.255 - "or timedelta, not '%s'" % (<Name>name</Name>, <Call><Name>type</Name></Call>(<Name>offset</Name>)))
236.256 - <Name>days</Name> = <Attribute><Name>offset</Name></Attribute>.days
236.257 - if <Name>days</Name> < -1 or <Name>days</Name> > 0:
236.258 - <Name>offset</Name> = 1440 # trigger out-of-range
236.259 - else:
236.260 - <Name>seconds</Name> = <Name>days</Name> * 86400 + <Attribute><Name>offset</Name></Attribute>.seconds
236.261 - <Name>minutes</Name>, <Name>seconds</Name> = <Call><Name>divmod</Name></Call>(<Name>seconds</Name>, 60)
236.262 - if <Name>seconds</Name> or <Attribute><Name>offset</Name></Attribute>.microseconds:
236.263 - raise <Call><Name>ValueError</Name></Call>("tzinfo.%s() must return a whole number "
236.264 - "of minutes" % <Name>name</Name>)
236.265 - <Name>offset</Name> = <Name>minutes</Name>
236.266 - if -1440 < <Name>offset</Name> < 1440:
236.267 - return <Name>offset</Name>
236.268 - raise <Call><Name>ValueError</Name></Call>("%s()=%d, must be in -1439..1439" % (<Name>name</Name>, <Name>offset</Name>))
236.269 -
236.270 -def <FunctionDef>_check_date_fields</FunctionDef>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>):
236.271 - if not <Name>MINYEAR</Name> <= <Name>year</Name> <= <Name>MAXYEAR</Name>:
236.272 - raise <Call><Name>ValueError</Name></Call>('year must be in %d..%d' % (<Name>MINYEAR</Name>, <Name>MAXYEAR</Name>), <Name>year</Name>)
236.273 - if not 1 <= <Name>month</Name> <= 12:
236.274 - raise <Call><Name>ValueError</Name></Call>('month must be in 1..12', <Name>month</Name>)
236.275 - <Name>dim</Name> = <Call><Name>_days_in_month</Name></Call>(<Name>year</Name>, <Name>month</Name>)
236.276 - if not 1 <= <Name>day</Name> <= <Name>dim</Name>:
236.277 - raise <Call><Name>ValueError</Name></Call>('day must be in 1..%d' % <Name>dim</Name>, <Name>day</Name>)
236.278 -
236.279 -def <FunctionDef>_check_time_fields</FunctionDef>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>):
236.280 - if not 0 <= <Name>hour</Name> <= 23:
236.281 - raise <Call><Name>ValueError</Name></Call>('hour must be in 0..23', <Name>hour</Name>)
236.282 - if not 0 <= <Name>minute</Name> <= 59:
236.283 - raise <Call><Name>ValueError</Name></Call>('minute must be in 0..59', <Name>minute</Name>)
236.284 - if not 0 <= <Name>second</Name> <= 59:
236.285 - raise <Call><Name>ValueError</Name></Call>('second must be in 0..59', <Name>second</Name>)
236.286 - if not 0 <= <Name>microsecond</Name> <= 999999:
236.287 - raise <Call><Name>ValueError</Name></Call>('microsecond must be in 0..999999', <Name>microsecond</Name>)
236.288 -
236.289 -def <FunctionDef>_check_tzinfo_arg</FunctionDef>(<Name>tz</Name>):
236.290 - if <Name>tz</Name> is not <Name>None</Name> and not <Call><Name>isinstance</Name></Call>(<Name>tz</Name>, <Name>tzinfo</Name>):
236.291 - raise <Call><Name>TypeError</Name></Call>("tzinfo argument must be None or of a tzinfo subclass")
236.292 -
236.293 -
236.294 -# Notes on comparison: In general, datetime module comparison operators raise
236.295 -# TypeError when they don't know how to do a comparison themself. If they
236.296 -# returned NotImplemented instead, comparison could (silently) fall back to
236.297 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
236.298 -# and that's not helpful. There are two exceptions:
236.299 -#
236.300 -# 1. For date and datetime, if the other object has a "timetuple" attr,
236.301 -# NotImplemented is returned. This is a hook to allow other kinds of
236.302 -# datetime-like objects a chance to intercept the comparison.
236.303 -#
236.304 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
236.305 -# so opertaions like
236.306 -#
236.307 -# x == y
236.308 -# x != y
236.309 -# x in sequence
236.310 -# x not in sequence
236.311 -# dict[x] = y
236.312 -#
236.313 -# don't raise annoying TypeErrors just because a datetime object
236.314 -# is part of a heterogeneous collection. If there's no known way to
236.315 -# compare X to a datetime, saying they're not equal is reasonable.
236.316 -
236.317 -def <FunctionDef>_cmperror</FunctionDef>(<Name>x</Name>, <Name>y</Name>):
236.318 - raise <Call><Name>TypeError</Name></Call>("can't compare '%s' to '%s'" % (
236.319 - <Attribute><Call><Name>type</Name></Call></Attribute>(<Name>x</Name>).__name__, <Attribute><Call><Name>type</Name></Call></Attribute>(<Name>y</Name>).__name__))
236.320 -
236.321 -# This is a start at a struct tm workalike. Goals:
236.322 -#
236.323 -# + Works the same way across platforms.
236.324 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
236.325 -#
236.326 -# Note: I suspect it's best if this flavor of tm does *not* try to
236.327 -# second-guess timezones or DST. Instead fold whatever adjustments you want
236.328 -# into the minutes argument (and the constructor will normalize).
236.329 -
236.330 -<Name>_ORD1970</Name> = <Call><Name>_ymd2ord</Name></Call>(1970, 1, 1) # base ordinal for UNIX epoch
236.331 -
236.332 -class <ClassDef>tmxxx</ClassDef>:
236.333 -
236.334 - <Name>ordinal</Name> = <Name>None</Name>
236.335 -
236.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,
236.337 - <Name>microsecond</Name>=0):
236.338 - # Normalize all the inputs, and store the normalized values.
236.339 - if not 0 <= <Name>microsecond</Name> <= 999999:
236.340 - <Name>carry</Name>, <Name>microsecond</Name> = <Call><Name>divmod</Name></Call>(<Name>microsecond</Name>, 1000000)
236.341 - <Name>second</Name> += <Name>carry</Name>
236.342 - if not 0 <= <Name>second</Name> <= 59:
236.343 - <Name>carry</Name>, <Name>second</Name> = <Call><Name>divmod</Name></Call>(<Name>second</Name>, 60)
236.344 - <Name>minute</Name> += <Name>carry</Name>
236.345 - if not 0 <= <Name>minute</Name> <= 59:
236.346 - <Name>carry</Name>, <Name>minute</Name> = <Call><Name>divmod</Name></Call>(<Name>minute</Name>, 60)
236.347 - <Name>hour</Name> += <Name>carry</Name>
236.348 - if not 0 <= <Name>hour</Name> <= 23:
236.349 - <Name>carry</Name>, <Name>hour</Name> = <Call><Name>divmod</Name></Call>(<Name>hour</Name>, 24)
236.350 - <Name>day</Name> += <Name>carry</Name>
236.351 -
236.352 - # That was easy. Now it gets muddy: the proper range for day
236.353 - # can't be determined without knowing the correct month and year,
236.354 - # but if day is, e.g., plus or minus a million, the current month
236.355 - # and year values make no sense (and may also be out of bounds
236.356 - # themselves).
236.357 - # Saying 12 months == 1 year should be non-controversial.
236.358 - if not 1 <= <Name>month</Name> <= 12:
236.359 - <Name>carry</Name>, <Name>month</Name> = <Call><Name>divmod</Name></Call>(<Name>month</Name>-1, 12)
236.360 - <Name>year</Name> += <Name>carry</Name>
236.361 - <Name>month</Name> += 1
236.362 - assert 1 <= <Name>month</Name> <= 12
236.363 -
236.364 - # Now only day can be out of bounds (year may also be out of bounds
236.365 - # for a datetime object, but we don't care about that here).
236.366 - # If day is out of bounds, what to do is arguable, but at least the
236.367 - # method here is principled and explainable.
236.368 - <Name>dim</Name> = <Call><Name>_days_in_month</Name></Call>(<Name>year</Name>, <Name>month</Name>)
236.369 - if not 1 <= <Name>day</Name> <= <Name>dim</Name>:
236.370 - # Move day-1 days from the first of the month. First try to
236.371 - # get off cheap if we're only one day out of range (adjustments
236.372 - # for timezone alone can't be worse than that).
236.373 - if <Name>day</Name> == 0: # move back a day
236.374 - <Name>month</Name> -= 1
236.375 - if <Name>month</Name> > 0:
236.376 - <Name>day</Name> = <Call><Name>_days_in_month</Name></Call>(<Name>year</Name>, <Name>month</Name>)
236.377 - else:
236.378 - <Name>year</Name>, <Name>month</Name>, <Name>day</Name> = <Name>year</Name>-1, 12, 31
236.379 - elif <Name>day</Name> == <Name>dim</Name> + 1: # move forward a day
236.380 - <Name>month</Name> += 1
236.381 - <Name>day</Name> = 1
236.382 - if <Name>month</Name> > 12:
236.383 - <Name>month</Name> = 1
236.384 - <Name>year</Name> += 1
236.385 - else:
236.386 - <Attribute><Name>self</Name></Attribute>.ordinal = <Call><Name>_ymd2ord</Name></Call>(<Name>year</Name>, <Name>month</Name>, 1) + (<Name>day</Name> - 1)
236.387 - <Name>year</Name>, <Name>month</Name>, <Name>day</Name> = <Call><Name>_ord2ymd</Name></Call>(<Attribute><Name>self</Name></Attribute>.ordinal)
236.388 -
236.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>
236.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>
236.391 - <Attribute><Name>self</Name></Attribute>.microsecond = <Name>microsecond</Name>
236.392 -
236.393 - def <FunctionDef>toordinal</FunctionDef>(<Name>self</Name>):
236.394 - """Return proleptic Gregorian ordinal for the year, month and day.
236.395 -
236.396 - January 1 of year 1 is day 1. Only the year, month and day values
236.397 - contribute to the result.
236.398 - """
236.399 - if <Attribute><Name>self</Name></Attribute>.ordinal is <Name>None</Name>:
236.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)
236.401 - return <Attribute><Name>self</Name></Attribute>.ordinal
236.402 -
236.403 - def <FunctionDef>time</FunctionDef>(<Name>self</Name>):
236.404 - "Return Unixish timestamp, as a float (assuming UTC)."
236.405 - <Name>days</Name> = <Attribute><Name>self</Name></Attribute>.<Call>toordinal</Call>() - <Name>_ORD1970</Name> # convert to UNIX epoch
236.406 - <Name>seconds</Name> = ((<Name>days</Name> * 24. + <Attribute><Name>self</Name></Attribute>.hour)*60. + <Attribute><Name>self</Name></Attribute>.minute)*60.
236.407 - return <Name>seconds</Name> + <Attribute><Name>self</Name></Attribute>.second + <Attribute><Name>self</Name></Attribute>.microsecond / 1e6
236.408 -
236.409 - def <FunctionDef>ctime</FunctionDef>(<Name>self</Name>):
236.410 - "Return ctime() style string."
236.411 - <Name>weekday</Name> = <Attribute><Name>self</Name></Attribute>.<Call>toordinal</Call>() % 7 or 7
236.412 - return "%s %s %2d %02d:%02d:%02d %04d" % (
236.413 - <Name>_DAYNAMES</Name>[<Name>weekday</Name>],
236.414 - <Name>_MONTHNAMES</Name>[<Attribute><Name>self</Name></Attribute>.month],
236.415 - <Attribute><Name>self</Name></Attribute>.day,
236.416 - <Attribute><Name>self</Name></Attribute>.hour, <Attribute><Name>self</Name></Attribute>.minute, <Attribute><Name>self</Name></Attribute>.second,
236.417 - <Attribute><Name>self</Name></Attribute>.year)
236.418 -
236.419 -class <ClassDef>timedelta</ClassDef>(<Name>object</Name>):
236.420 - """Represent the difference between two datetime objects.
236.421 -
236.422 - Supported operators:
236.423 -
236.424 - - add, subtract timedelta
236.425 - - unary plus, minus, abs
236.426 - - compare to timedelta
236.427 - - multiply, divide by int/long
236.428 -
236.429 - In addition, datetime supports subtraction of two datetime objects
236.430 - returning a timedelta, and addition or subtraction of a datetime
236.431 - and a timedelta giving a datetime.
236.432 -
236.433 - Representation: (days, seconds, microseconds). Why? Because I
236.434 - felt like it.
236.435 - """
236.436 -
236.437 - def <FunctionDef>__new__</FunctionDef>(<Name>cls</Name>, <Name>days</Name>=0, <Name>seconds</Name>=0, <Name>microseconds</Name>=0,
236.438 - # XXX The following should only be used as keyword args:
236.439 - <Name>milliseconds</Name>=0, <Name>minutes</Name>=0, <Name>hours</Name>=0, <Name>weeks</Name>=0):
236.440 - # Doing this efficiently and accurately in C is going to be difficult
236.441 - # and error-prone, due to ubiquitous overflow possibilities, and that
236.442 - # C double doesn't have enough bits of precision to represent
236.443 - # microseconds over 10K years faithfully. The code here tries to make
236.444 - # explicit where go-fast assumptions can be relied on, in order to
236.445 - # guide the C implementation; it's way more convoluted than speed-
236.446 - # ignoring auto-overflow-to-long idiomatic Python could be.
236.447 -
236.448 - # XXX Check that all inputs are ints, longs or floats.
236.449 -
236.450 - # Final values, all integer.
236.451 - # s and us fit in 32-bit signed ints; d isn't bounded.
236.452 - <Name>d</Name> = <Name>s</Name> = <Name>us</Name> = 0
236.453 -
236.454 - # Normalize everything to days, seconds, microseconds.
236.455 - <Name>days</Name> += <Name>weeks</Name>*7
236.456 - <Name>seconds</Name> += <Name>minutes</Name>*60 + <Name>hours</Name>*3600
236.457 - <Name>microseconds</Name> += <Name>milliseconds</Name>*1000
236.458 -
236.459 - # Get rid of all fractions, and normalize s and us.
236.460 - # Take a deep breath <wink>.
236.461 - if <Call><Name>isinstance</Name></Call>(<Name>days</Name>, <Name>float</Name>):
236.462 - <Name>dayfrac</Name>, <Name>days</Name> = <Attribute><Name>_math</Name></Attribute>.<Call>modf</Call>(<Name>days</Name>)
236.463 - <Name>daysecondsfrac</Name>, <Name>daysecondswhole</Name> = <Attribute><Name>_math</Name></Attribute>.<Call>modf</Call>(<Name>dayfrac</Name> * (24.*3600.))
236.464 - assert <Name>daysecondswhole</Name> == <Call><Name>int</Name></Call>(<Name>daysecondswhole</Name>) # can't overflow
236.465 - <Name>s</Name> = <Call><Name>int</Name></Call>(<Name>daysecondswhole</Name>)
236.466 - assert <Name>days</Name> == <Call><Name>long</Name></Call>(<Name>days</Name>)
236.467 - <Name>d</Name> = <Call><Name>long</Name></Call>(<Name>days</Name>)
236.468 - else:
236.469 - <Name>daysecondsfrac</Name> = 0.0
236.470 - <Name>d</Name> = <Name>days</Name>
236.471 - assert <Call><Name>isinstance</Name></Call>(<Name>daysecondsfrac</Name>, <Name>float</Name>)
236.472 - assert <Call><Name>abs</Name></Call>(<Name>daysecondsfrac</Name>) <= 1.0
236.473 - assert <Call><Name>isinstance</Name></Call>(<Name>d</Name>, (<Name>int</Name>, <Name>long</Name>))
236.474 - assert <Call><Name>abs</Name></Call>(<Name>s</Name>) <= 24 * 3600
236.475 - # days isn't referenced again before redefinition
236.476 -
236.477 - if <Call><Name>isinstance</Name></Call>(<Name>seconds</Name>, <Name>float</Name>):
236.478 - <Name>secondsfrac</Name>, <Name>seconds</Name> = <Attribute><Name>_math</Name></Attribute>.<Call>modf</Call>(<Name>seconds</Name>)
236.479 - assert <Name>seconds</Name> == <Call><Name>long</Name></Call>(<Name>seconds</Name>)
236.480 - <Name>seconds</Name> = <Call><Name>long</Name></Call>(<Name>seconds</Name>)
236.481 - <Name>secondsfrac</Name> += <Name>daysecondsfrac</Name>
236.482 - assert <Call><Name>abs</Name></Call>(<Name>secondsfrac</Name>) <= 2.0
236.483 - else:
236.484 - <Name>secondsfrac</Name> = <Name>daysecondsfrac</Name>
236.485 - # daysecondsfrac isn't referenced again
236.486 - assert <Call><Name>isinstance</Name></Call>(<Name>secondsfrac</Name>, <Name>float</Name>)
236.487 - assert <Call><Name>abs</Name></Call>(<Name>secondsfrac</Name>) <= 2.0
236.488 -
236.489 - assert <Call><Name>isinstance</Name></Call>(<Name>seconds</Name>, (<Name>int</Name>, <Name>long</Name>))
236.490 - <Name>days</Name>, <Name>seconds</Name> = <Call><Name>divmod</Name></Call>(<Name>seconds</Name>, 24*3600)
236.491 - <Name>d</Name> += <Name>days</Name>
236.492 - <Name>s</Name> += <Call><Name>int</Name></Call>(<Name>seconds</Name>) # can't overflow
236.493 - assert <Call><Name>isinstance</Name></Call>(<Name>s</Name>, <Name>int</Name>)
236.494 - assert <Call><Name>abs</Name></Call>(<Name>s</Name>) <= 2 * 24 * 3600
236.495 - # seconds isn't referenced again before redefinition
236.496 -
236.497 - <Name>usdouble</Name> = <Name>secondsfrac</Name> * 1e6
236.498 - assert <Call><Name>abs</Name></Call>(<Name>usdouble</Name>) < 2.1e6 # exact value not critical
236.499 - # secondsfrac isn't referenced again
236.500 -
236.501 - if <Call><Name>isinstance</Name></Call>(<Name>microseconds</Name>, <Name>float</Name>):
236.502 - <Name>microseconds</Name> += <Name>usdouble</Name>
236.503 - <Name>microseconds</Name> = <Call><Name>round</Name></Call>(<Name>microseconds</Name>)
236.504 - <Name>seconds</Name>, <Name>microseconds</Name> = <Call><Name>divmod</Name></Call>(<Name>microseconds</Name>, 1e6)
236.505 - assert <Name>microseconds</Name> == <Call><Name>int</Name></Call>(<Name>microseconds</Name>)
236.506 - assert <Name>seconds</Name> == <Call><Name>long</Name></Call>(<Name>seconds</Name>)
236.507 - <Name>days</Name>, <Name>seconds</Name> = <Call><Name>divmod</Name></Call>(<Name>seconds</Name>, 24.*3600.)
236.508 - assert <Name>days</Name> == <Call><Name>long</Name></Call>(<Name>days</Name>)
236.509 - assert <Name>seconds</Name> == <Call><Name>int</Name></Call>(<Name>seconds</Name>)
236.510 - <Name>d</Name> += <Call><Name>long</Name></Call>(<Name>days</Name>)
236.511 - <Name>s</Name> += <Call><Name>int</Name></Call>(<Name>seconds</Name>) # can't overflow
236.512 - assert <Call><Name>isinstance</Name></Call>(<Name>s</Name>, <Name>int</Name>)
236.513 - assert <Call><Name>abs</Name></Call>(<Name>s</Name>) <= 3 * 24 * 3600
236.514 - else:
236.515 - <Name>seconds</Name>, <Name>microseconds</Name> = <Call><Name>divmod</Name></Call>(<Name>microseconds</Name>, 1000000)
236.516 - <Name>days</Name>, <Name>seconds</Name> = <Call><Name>divmod</Name></Call>(<Name>seconds</Name>, 24*3600)
236.517 - <Name>d</Name> += <Name>days</Name>
236.518 - <Name>s</Name> += <Call><Name>int</Name></Call>(<Name>seconds</Name>) # can't overflow
236.519 - assert <Call><Name>isinstance</Name></Call>(<Name>s</Name>, <Name>int</Name>)
236.520 - assert <Call><Name>abs</Name></Call>(<Name>s</Name>) <= 3 * 24 * 3600
236.521 - <Name>microseconds</Name> = <Call><Name>float</Name></Call>(<Name>microseconds</Name>)
236.522 - <Name>microseconds</Name> += <Name>usdouble</Name>
236.523 - <Name>microseconds</Name> = <Call><Name>round</Name></Call>(<Name>microseconds</Name>)
236.524 - assert <Call><Name>abs</Name></Call>(<Name>s</Name>) <= 3 * 24 * 3600
236.525 - assert <Call><Name>abs</Name></Call>(<Name>microseconds</Name>) < 3.1e6
236.526 -
236.527 - # Just a little bit of carrying possible for microseconds and seconds.
236.528 - assert <Call><Name>isinstance</Name></Call>(<Name>microseconds</Name>, <Name>float</Name>)
236.529 - assert <Call><Name>int</Name></Call>(<Name>microseconds</Name>) == <Name>microseconds</Name>
236.530 - <Name>us</Name> = <Call><Name>int</Name></Call>(<Name>microseconds</Name>)
236.531 - <Name>seconds</Name>, <Name>us</Name> = <Call><Name>divmod</Name></Call>(<Name>us</Name>, 1000000)
236.532 - <Name>s</Name> += <Name>seconds</Name> # cant't overflow
236.533 - assert <Call><Name>isinstance</Name></Call>(<Name>s</Name>, <Name>int</Name>)
236.534 - <Name>days</Name>, <Name>s</Name> = <Call><Name>divmod</Name></Call>(<Name>s</Name>, 24*3600)
236.535 - <Name>d</Name> += <Name>days</Name>
236.536 -
236.537 - assert <Call><Name>isinstance</Name></Call>(<Name>d</Name>, (<Name>int</Name>, <Name>long</Name>))
236.538 - assert <Call><Name>isinstance</Name></Call>(<Name>s</Name>, <Name>int</Name>) and 0 <= <Name>s</Name> < 24*3600
236.539 - assert <Call><Name>isinstance</Name></Call>(<Name>us</Name>, <Name>int</Name>) and 0 <= <Name>us</Name> < 1000000
236.540 -
236.541 - <Name>self</Name> = <Attribute><Name>object</Name></Attribute>.<Call>__new__</Call>(<Name>cls</Name>)
236.542 -
236.543 - <Attribute><Name>self</Name></Attribute>.__days = <Name>d</Name>
236.544 - <Attribute><Name>self</Name></Attribute>.__seconds = <Name>s</Name>
236.545 - <Attribute><Name>self</Name></Attribute>.__microseconds = <Name>us</Name>
236.546 - if <Call><Name>abs</Name></Call>(<Name>d</Name>) > 999999999:
236.547 - raise <Call><Name>OverflowError</Name></Call>("timedelta # of days is too large: %d" % <Name>d</Name>)
236.548 -
236.549 - return <Name>self</Name>
236.550 -
236.551 - def <FunctionDef>__repr__</FunctionDef>(<Name>self</Name>):
236.552 - if <Attribute><Name>self</Name></Attribute>.__microseconds:
236.553 - return "%s(%d, %d, %d)" % ('datetime.' + <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.__class__.__name__,
236.554 - <Attribute><Name>self</Name></Attribute>.__days,
236.555 - <Attribute><Name>self</Name></Attribute>.__seconds,
236.556 - <Attribute><Name>self</Name></Attribute>.__microseconds)
236.557 - if <Attribute><Name>self</Name></Attribute>.__seconds:
236.558 - return "%s(%d, %d)" % ('datetime.' + <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.__class__.__name__,
236.559 - <Attribute><Name>self</Name></Attribute>.__days,
236.560 - <Attribute><Name>self</Name></Attribute>.__seconds)
236.561 - return "%s(%d)" % ('datetime.' + <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.__class__.__name__, <Attribute><Name>self</Name></Attribute>.__days)
236.562 -
236.563 - def <FunctionDef>__str__</FunctionDef>(<Name>self</Name>):
236.564 - <Name>mm</Name>, <Name>ss</Name> = <Call><Name>divmod</Name></Call>(<Attribute><Name>self</Name></Attribute>.__seconds, 60)
236.565 - <Name>hh</Name>, <Name>mm</Name> = <Call><Name>divmod</Name></Call>(<Name>mm</Name>, 60)
236.566 - <Name>s</Name> = "%d:%02d:%02d" % (<Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>)
236.567 - if <Attribute><Name>self</Name></Attribute>.__days:
236.568 - def <FunctionDef>plural</FunctionDef>(<Name>n</Name>):
236.569 - return <Name>n</Name>, <Call><Name>abs</Name></Call>(<Name>n</Name>) != 1 and "s" or ""
236.570 - <Name>s</Name> = ("%d day%s, " % <Call><Name>plural</Name></Call>(<Attribute><Name>self</Name></Attribute>.__days)) + <Name>s</Name>
236.571 - if <Attribute><Name>self</Name></Attribute>.__microseconds:
236.572 - <Name>s</Name> = <Name>s</Name> + ".%06d" % <Attribute><Name>self</Name></Attribute>.__microseconds
236.573 - return <Name>s</Name>
236.574 -
236.575 - <Name>days</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__days, doc="days")
236.576 - <Name>seconds</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__seconds, doc="seconds")
236.577 - <Name>microseconds</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__microseconds,
236.578 - doc="microseconds")
236.579 -
236.580 - def <FunctionDef>__add__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.581 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
236.582 - return <Call><Name>timedelta</Name></Call>(<Attribute><Name>self</Name></Attribute>.__days + <Attribute><Name>other</Name></Attribute>.__days,
236.583 - <Attribute><Name>self</Name></Attribute>.__seconds + <Attribute><Name>other</Name></Attribute>.__seconds,
236.584 - <Attribute><Name>self</Name></Attribute>.__microseconds + <Attribute><Name>other</Name></Attribute>.__microseconds)
236.585 - return <Name>NotImplemented</Name>
236.586 -
236.587 - <Name>__radd__</Name> = <Name>__add__</Name>
236.588 -
236.589 - def <FunctionDef>__sub__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.590 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
236.591 - return <Name>self</Name> + -<Name>other</Name>
236.592 - return <Name>NotImplemented</Name>
236.593 -
236.594 - def <FunctionDef>__rsub__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.595 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
236.596 - return -<Name>self</Name> + <Name>other</Name>
236.597 - return <Name>NotImplemented</Name>
236.598 -
236.599 - def <FunctionDef>__neg__</FunctionDef>(<Name>self</Name>):
236.600 - return <Attribute><Name>self</Name></Attribute>.<Call>__class__</Call>(-<Attribute><Name>self</Name></Attribute>.__days,
236.601 - -<Attribute><Name>self</Name></Attribute>.__seconds,
236.602 - -<Attribute><Name>self</Name></Attribute>.__microseconds)
236.603 -
236.604 - def <FunctionDef>__pos__</FunctionDef>(<Name>self</Name>):
236.605 - return <Name>self</Name>
236.606 -
236.607 - def <FunctionDef>__abs__</FunctionDef>(<Name>self</Name>):
236.608 - if <Attribute><Name>self</Name></Attribute>.__days < 0:
236.609 - return -<Name>self</Name>
236.610 - else:
236.611 - return <Name>self</Name>
236.612 -
236.613 - def <FunctionDef>__mul__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.614 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, (<Name>int</Name>, <Name>long</Name>)):
236.615 - return <Attribute><Name>self</Name></Attribute>.<Call>__class__</Call>(<Attribute><Name>self</Name></Attribute>.__days * <Name>other</Name>,
236.616 - <Attribute><Name>self</Name></Attribute>.__seconds * <Name>other</Name>,
236.617 - <Attribute><Name>self</Name></Attribute>.__microseconds * <Name>other</Name>)
236.618 - return <Name>NotImplemented</Name>
236.619 -
236.620 - <Name>__rmul__</Name> = <Name>__mul__</Name>
236.621 -
236.622 - def <FunctionDef>__div__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.623 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, (<Name>int</Name>, <Name>long</Name>)):
236.624 - <Name>usec</Name> = ((<Attribute><Name>self</Name></Attribute>.__days * (24*3600L) + <Attribute><Name>self</Name></Attribute>.__seconds) * 1000000 +
236.625 - <Attribute><Name>self</Name></Attribute>.__microseconds)
236.626 - return <Attribute><Name>self</Name></Attribute>.<Call>__class__</Call>(0, 0, <Name>usec</Name> // <Name>other</Name>)
236.627 - return <Name>NotImplemented</Name>
236.628 -
236.629 - <Name>__floordiv__</Name> = <Name>__div__</Name>
236.630 -
236.631 - # Comparisons.
236.632 -
236.633 - def <FunctionDef>__eq__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.634 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
236.635 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) == 0
236.636 - else:
236.637 - return <Name>False</Name>
236.638 -
236.639 - def <FunctionDef>__ne__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.640 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
236.641 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) != 0
236.642 - else:
236.643 - return <Name>True</Name>
236.644 -
236.645 - def <FunctionDef>__le__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.646 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
236.647 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) <= 0
236.648 - else:
236.649 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.650 -
236.651 - def <FunctionDef>__lt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.652 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
236.653 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) < 0
236.654 - else:
236.655 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.656 -
236.657 - def <FunctionDef>__ge__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.658 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
236.659 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) >= 0
236.660 - else:
236.661 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.662 -
236.663 - def <FunctionDef>__gt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.664 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
236.665 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) > 0
236.666 - else:
236.667 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.668 -
236.669 - def <FunctionDef>__cmp</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.670 - assert <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>)
236.671 - return <Call><Name>cmp</Name></Call>(<Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>(), <Attribute><Name>other</Name></Attribute>.<Call>__getstate</Call>())
236.672 -
236.673 - def <FunctionDef>__hash__</FunctionDef>(<Name>self</Name>):
236.674 - return <Call><Name>hash</Name></Call>(<Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>())
236.675 -
236.676 - def <FunctionDef>__nonzero__</FunctionDef>(<Name>self</Name>):
236.677 - return (<Attribute><Name>self</Name></Attribute>.__days != 0 or
236.678 - <Attribute><Name>self</Name></Attribute>.__seconds != 0 or
236.679 - <Attribute><Name>self</Name></Attribute>.__microseconds != 0)
236.680 -
236.681 - # Pickle support.
236.682 -
236.683 - <Name>__safe_for_unpickling__</Name> = <Name>True</Name> # For Python 2.2
236.684 -
236.685 - def <FunctionDef>__getstate</FunctionDef>(<Name>self</Name>):
236.686 - return (<Attribute><Name>self</Name></Attribute>.__days, <Attribute><Name>self</Name></Attribute>.__seconds, <Attribute><Name>self</Name></Attribute>.__microseconds)
236.687 -
236.688 - def <FunctionDef>__reduce__</FunctionDef>(<Name>self</Name>):
236.689 - return (<Attribute><Name>self</Name></Attribute>.__class__, <Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>())
236.690 -
236.691 -<Attribute><Name>timedelta</Name></Attribute>.min = <Call><Name>timedelta</Name></Call>(-999999999)
236.692 -<Attribute><Name>timedelta</Name></Attribute>.max = <Call><Name>timedelta</Name></Call>(days=999999999, hours=23, minutes=59, seconds=59,
236.693 - microseconds=999999)
236.694 -<Attribute><Name>timedelta</Name></Attribute>.resolution = <Call><Name>timedelta</Name></Call>(microseconds=1)
236.695 -
236.696 -class <ClassDef>date</ClassDef>(<Name>object</Name>):
236.697 - """Concrete date type.
236.698 -
236.699 - Constructors:
236.700 -
236.701 - __new__()
236.702 - fromtimestamp()
236.703 - today()
236.704 - fromordinal()
236.705 -
236.706 - Operators:
236.707 -
236.708 - __repr__, __str__
236.709 - __cmp__, __hash__
236.710 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
236.711 -
236.712 - Methods:
236.713 -
236.714 - timetuple()
236.715 - toordinal()
236.716 - weekday()
236.717 - isoweekday(), isocalendar(), isoformat()
236.718 - ctime()
236.719 - strftime()
236.720 -
236.721 - Properties (readonly):
236.722 - year, month, day
236.723 - """
236.724 -
236.725 - def <FunctionDef>__new__</FunctionDef>(<Name>cls</Name>, <Name>year</Name>, <Name>month</Name>=<Name>None</Name>, <Name>day</Name>=<Name>None</Name>):
236.726 - """Constructor.
236.727 -
236.728 - Arguments:
236.729 -
236.730 - year, month, day (required, base 1)
236.731 - """
236.732 - if <Call><Name>isinstance</Name></Call>(<Name>year</Name>, <Name>str</Name>):
236.733 - # Pickle support
236.734 - <Name>self</Name> = <Attribute><Name>object</Name></Attribute>.<Call>__new__</Call>(<Name>cls</Name>)
236.735 - <Attribute><Name>self</Name></Attribute>.<Call>__setstate</Call>((<Name>year</Name>,))
236.736 - return <Name>self</Name>
236.737 - <Call><Name>_check_date_fields</Name></Call>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)
236.738 - <Name>self</Name> = <Attribute><Name>object</Name></Attribute>.<Call>__new__</Call>(<Name>cls</Name>)
236.739 - <Attribute><Name>self</Name></Attribute>.__year = <Name>year</Name>
236.740 - <Attribute><Name>self</Name></Attribute>.__month = <Name>month</Name>
236.741 - <Attribute><Name>self</Name></Attribute>.__day = <Name>day</Name>
236.742 - return <Name>self</Name>
236.743 -
236.744 - # Additional constructors
236.745 -
236.746 - def <FunctionDef>fromtimestamp</FunctionDef>(<Name>cls</Name>, <Name>t</Name>):
236.747 - "Construct a date from a POSIX timestamp (like time.time())."
236.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>)
236.749 - return <Call><Name>cls</Name></Call>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>)
236.750 - <Name>fromtimestamp</Name> = <Call><Name>classmethod</Name></Call>(<Name>fromtimestamp</Name>)
236.751 -
236.752 - def <FunctionDef>today</FunctionDef>(<Name>cls</Name>):
236.753 - "Construct a date from time.time()."
236.754 - <Name>t</Name> = <Attribute><Name>_time</Name></Attribute>.<Call>time</Call>()
236.755 - return <Attribute><Name>cls</Name></Attribute>.<Call>fromtimestamp</Call>(<Name>t</Name>)
236.756 - <Name>today</Name> = <Call><Name>classmethod</Name></Call>(<Name>today</Name>)
236.757 -
236.758 - def <FunctionDef>fromordinal</FunctionDef>(<Name>cls</Name>, <Name>n</Name>):
236.759 - """Contruct a date from a proleptic Gregorian ordinal.
236.760 -
236.761 - January 1 of year 1 is day 1. Only the year, month and day are
236.762 - non-zero in the result.
236.763 - """
236.764 - <Name>y</Name>, <Name>m</Name>, <Name>d</Name> = <Call><Name>_ord2ymd</Name></Call>(<Name>n</Name>)
236.765 - return <Call><Name>cls</Name></Call>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>)
236.766 - <Name>fromordinal</Name> = <Call><Name>classmethod</Name></Call>(<Name>fromordinal</Name>)
236.767 -
236.768 - # Conversions to string
236.769 -
236.770 - def <FunctionDef>__repr__</FunctionDef>(<Name>self</Name>):
236.771 - "Convert to formal string, for repr()."
236.772 - return "%s(%d, %d, %d)" % ('datetime.' + <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.__class__.__name__,
236.773 - <Attribute><Name>self</Name></Attribute>.__year,
236.774 - <Attribute><Name>self</Name></Attribute>.__month,
236.775 - <Attribute><Name>self</Name></Attribute>.__day)
236.776 - # XXX These shouldn't depend on time.localtime(), because that
236.777 - # clips the usable dates to [1970 .. 2038). At least ctime() is
236.778 - # easily done without using strftime() -- that's better too because
236.779 - # strftime("%c", ...) is locale specific.
236.780 -
236.781 - def <FunctionDef>ctime</FunctionDef>(<Name>self</Name>):
236.782 - "Format a la ctime()."
236.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>()
236.784 -
236.785 - def <FunctionDef>strftime</FunctionDef>(<Name>self</Name>, <Name>fmt</Name>):
236.786 - "Format using strftime()."
236.787 - return <Call><Name>_wrap_strftime</Name></Call>(<Name>self</Name>, <Name>fmt</Name>, <Attribute><Name>self</Name></Attribute>.<Call>timetuple</Call>())
236.788 -
236.789 - def <FunctionDef>isoformat</FunctionDef>(<Name>self</Name>):
236.790 - """Return the date formatted according to ISO.
236.791 -
236.792 - This is 'YYYY-MM-DD'.
236.793 -
236.794 - References:
236.795 - - http://www.w3.org/TR/NOTE-datetime
236.796 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
236.797 - """
236.798 - return "%04d-%02d-%02d" % (<Attribute><Name>self</Name></Attribute>.__year, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day)
236.799 -
236.800 - <Name>__str__</Name> = <Name>isoformat</Name>
236.801 -
236.802 - # Read-only field accessors
236.803 - <Name>year</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__year,
236.804 - doc="year (%d-%d)" % (<Name>MINYEAR</Name>, <Name>MAXYEAR</Name>))
236.805 - <Name>month</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__month, doc="month (1-12)")
236.806 - <Name>day</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__day, doc="day (1-31)")
236.807 -
236.808 - # Standard conversions, __cmp__, __hash__ (and helpers)
236.809 -
236.810 - def <FunctionDef>timetuple</FunctionDef>(<Name>self</Name>):
236.811 - "Return local time tuple compatible with time.localtime()."
236.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,
236.813 - 0, 0, 0, -1)
236.814 -
236.815 - def <FunctionDef>toordinal</FunctionDef>(<Name>self</Name>):
236.816 - """Return proleptic Gregorian ordinal for the year, month and day.
236.817 -
236.818 - January 1 of year 1 is day 1. Only the year, month and day values
236.819 - contribute to the result.
236.820 - """
236.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)
236.822 -
236.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>):
236.824 - """Return a new date with new values for the specified fields."""
236.825 - if <Name>year</Name> is <Name>None</Name>:
236.826 - <Name>year</Name> = <Attribute><Name>self</Name></Attribute>.__year
236.827 - if <Name>month</Name> is <Name>None</Name>:
236.828 - <Name>month</Name> = <Attribute><Name>self</Name></Attribute>.__month
236.829 - if <Name>day</Name> is <Name>None</Name>:
236.830 - <Name>day</Name> = <Attribute><Name>self</Name></Attribute>.__day
236.831 - <Call><Name>_check_date_fields</Name></Call>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)
236.832 - return <Call><Name>date</Name></Call>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)
236.833 -
236.834 - # Comparisons.
236.835 -
236.836 - def <FunctionDef>__eq__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.837 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
236.838 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) == 0
236.839 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
236.840 - return <Name>NotImplemented</Name>
236.841 - else:
236.842 - return <Name>False</Name>
236.843 -
236.844 - def <FunctionDef>__ne__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.845 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
236.846 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) != 0
236.847 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
236.848 - return <Name>NotImplemented</Name>
236.849 - else:
236.850 - return <Name>True</Name>
236.851 -
236.852 - def <FunctionDef>__le__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.853 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
236.854 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) <= 0
236.855 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
236.856 - return <Name>NotImplemented</Name>
236.857 - else:
236.858 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.859 -
236.860 - def <FunctionDef>__lt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.861 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
236.862 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) < 0
236.863 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
236.864 - return <Name>NotImplemented</Name>
236.865 - else:
236.866 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.867 -
236.868 - def <FunctionDef>__ge__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.869 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
236.870 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) >= 0
236.871 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
236.872 - return <Name>NotImplemented</Name>
236.873 - else:
236.874 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.875 -
236.876 - def <FunctionDef>__gt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.877 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
236.878 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) > 0
236.879 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
236.880 - return <Name>NotImplemented</Name>
236.881 - else:
236.882 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.883 -
236.884 - def <FunctionDef>__cmp</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.885 - assert <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>)
236.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
236.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
236.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>))
236.889 -
236.890 - def <FunctionDef>__hash__</FunctionDef>(<Name>self</Name>):
236.891 - "Hash."
236.892 - return <Call><Name>hash</Name></Call>(<Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>())
236.893 -
236.894 - # Computations
236.895 -
236.896 - def <FunctionDef>_checkOverflow</FunctionDef>(<Name>self</Name>, <Name>year</Name>):
236.897 - if not <Name>MINYEAR</Name> <= <Name>year</Name> <= <Name>MAXYEAR</Name>:
236.898 - raise <Call><Name>OverflowError</Name></Call>("date +/-: result year %d not in %d..%d" %
236.899 - (<Name>year</Name>, <Name>MINYEAR</Name>, <Name>MAXYEAR</Name>))
236.900 -
236.901 - def <FunctionDef>__add__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.902 - "Add a date to a timedelta."
236.903 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
236.904 - <Name>t</Name> = <Call><Name>tmxxx</Name></Call>(<Attribute><Name>self</Name></Attribute>.__year,
236.905 - <Attribute><Name>self</Name></Attribute>.__month,
236.906 - <Attribute><Name>self</Name></Attribute>.__day + <Attribute><Name>other</Name></Attribute>.days)
236.907 - <Attribute><Name>self</Name></Attribute>.<Call>_checkOverflow</Call>(<Attribute><Name>t</Name></Attribute>.year)
236.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)
236.909 - return <Name>result</Name>
236.910 - return <Name>NotImplemented</Name>
236.911 -
236.912 - <Name>__radd__</Name> = <Name>__add__</Name>
236.913 -
236.914 - def <FunctionDef>__sub__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.915 - """Subtract two dates, or a date and a timedelta."""
236.916 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
236.917 - return <Name>self</Name> + <Call><Name>timedelta</Name></Call>(-<Attribute><Name>other</Name></Attribute>.days)
236.918 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
236.919 - <Name>days1</Name> = <Attribute><Name>self</Name></Attribute>.<Call>toordinal</Call>()
236.920 - <Name>days2</Name> = <Attribute><Name>other</Name></Attribute>.<Call>toordinal</Call>()
236.921 - return <Call><Name>timedelta</Name></Call>(<Name>days1</Name> - <Name>days2</Name>)
236.922 - return <Name>NotImplemented</Name>
236.923 -
236.924 - def <FunctionDef>weekday</FunctionDef>(<Name>self</Name>):
236.925 - "Return day of the week, where Monday == 0 ... Sunday == 6."
236.926 - return (<Attribute><Name>self</Name></Attribute>.<Call>toordinal</Call>() + 6) % 7
236.927 -
236.928 - # Day-of-the-week and week-of-the-year, according to ISO
236.929 -
236.930 - def <FunctionDef>isoweekday</FunctionDef>(<Name>self</Name>):
236.931 - "Return day of the week, where Monday == 1 ... Sunday == 7."
236.932 - # 1-Jan-0001 is a Monday
236.933 - return <Attribute><Name>self</Name></Attribute>.<Call>toordinal</Call>() % 7 or 7
236.934 -
236.935 - def <FunctionDef>isocalendar</FunctionDef>(<Name>self</Name>):
236.936 - """Return a 3-tuple containing ISO year, week number, and weekday.
236.937 -
236.938 - The first ISO week of the year is the (Mon-Sun) week
236.939 - containing the year's first Thursday; everything else derives
236.940 - from that.
236.941 -
236.942 - The first week is 1; Monday is 1 ... Sunday is 7.
236.943 -
236.944 - ISO calendar algorithm taken from
236.945 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
236.946 - """
236.947 - <Name>year</Name> = <Attribute><Name>self</Name></Attribute>.__year
236.948 - <Name>week1monday</Name> = <Call><Name>_isoweek1monday</Name></Call>(<Name>year</Name>)
236.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)
236.950 - # Internally, week and day have origin 0
236.951 - <Name>week</Name>, <Name>day</Name> = <Call><Name>divmod</Name></Call>(<Name>today</Name> - <Name>week1monday</Name>, 7)
236.952 - if <Name>week</Name> < 0:
236.953 - <Name>year</Name> -= 1
236.954 - <Name>week1monday</Name> = <Call><Name>_isoweek1monday</Name></Call>(<Name>year</Name>)
236.955 - <Name>week</Name>, <Name>day</Name> = <Call><Name>divmod</Name></Call>(<Name>today</Name> - <Name>week1monday</Name>, 7)
236.956 - elif <Name>week</Name> >= 52:
236.957 - if <Name>today</Name> >= <Call><Name>_isoweek1monday</Name></Call>(<Name>year</Name>+1):
236.958 - <Name>year</Name> += 1
236.959 - <Name>week</Name> = 0
236.960 - return <Name>year</Name>, <Name>week</Name>+1, <Name>day</Name>+1
236.961 -
236.962 - # Pickle support.
236.963 -
236.964 - <Name>__safe_for_unpickling__</Name> = <Name>True</Name> # For Python 2.2
236.965 -
236.966 - def <FunctionDef>__getstate</FunctionDef>(<Name>self</Name>):
236.967 - <Name>yhi</Name>, <Name>ylo</Name> = <Call><Name>divmod</Name></Call>(<Attribute><Name>self</Name></Attribute>.__year, 256)
236.968 - return ("%c%c%c%c" % (<Name>yhi</Name>, <Name>ylo</Name>, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day), )
236.969 -
236.970 - def <FunctionDef>__setstate</FunctionDef>(<Name>self</Name>, <Name>t</Name>):
236.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>`
236.972 - <Name>string</Name> = <Name>t</Name>[0]
236.973 - assert <Call><Name>len</Name></Call>(<Name>string</Name>) == 4
236.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>)
236.975 - <Attribute><Name>self</Name></Attribute>.__year = <Name>yhi</Name> * 256 + <Name>ylo</Name>
236.976 -
236.977 - def <FunctionDef>__reduce__</FunctionDef>(<Name>self</Name>):
236.978 - return (<Attribute><Name>self</Name></Attribute>.__class__, <Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>())
236.979 -
236.980 -<Name>_date_class</Name> = <Name>date</Name> # so functions w/ args named "date" can get at the class
236.981 -
236.982 -<Attribute><Name>date</Name></Attribute>.min = <Call><Name>date</Name></Call>(1, 1, 1)
236.983 -<Attribute><Name>date</Name></Attribute>.max = <Call><Name>date</Name></Call>(9999, 12, 31)
236.984 -<Attribute><Name>date</Name></Attribute>.resolution = <Call><Name>timedelta</Name></Call>(days=1)
236.985 -
236.986 -class <ClassDef>tzinfo</ClassDef>(<Name>object</Name>):
236.987 - """Abstract base class for time zone info classes.
236.988 -
236.989 - Subclasses must override the name(), utcoffset() and dst() methods.
236.990 - """
236.991 -
236.992 - def <FunctionDef>tzname</FunctionDef>(<Name>self</Name>, <Name>dt</Name>):
236.993 - "datetime -> string name of time zone."
236.994 - raise <Call><Name>NotImplementedError</Name></Call>("tzinfo subclass must override tzname()")
236.995 -
236.996 - def <FunctionDef>utcoffset</FunctionDef>(<Name>self</Name>, <Name>dt</Name>):
236.997 - "datetime -> minutes east of UTC (negative for west of UTC)"
236.998 - raise <Call><Name>NotImplementedError</Name></Call>("tzinfo subclass must override utcoffset()")
236.999 -
236.1000 - def <FunctionDef>dst</FunctionDef>(<Name>self</Name>, <Name>dt</Name>):
236.1001 - """datetime -> DST offset in minutes east of UTC.
236.1002 -
236.1003 - Return 0 if DST not in effect. utcoffset() must include the DST
236.1004 - offset.
236.1005 - """
236.1006 - raise <Call><Name>NotImplementedError</Name></Call>("tzinfo subclass must override dst()")
236.1007 -
236.1008 - def <FunctionDef>fromutc</FunctionDef>(<Name>self</Name>, <Name>dt</Name>):
236.1009 - "datetime in UTC -> datetime in local time."
236.1010 -
236.1011 - if not <Call><Name>isinstance</Name></Call>(<Name>dt</Name>, <Name>datetime</Name>):
236.1012 - raise <Call><Name>TypeError</Name></Call>("fromutc() requires a datetime argument")
236.1013 - if <Attribute><Name>dt</Name></Attribute>.tzinfo is not <Name>self</Name>:
236.1014 - raise <Call><Name>ValueError</Name></Call>("dt.tzinfo is not self")
236.1015 -
236.1016 - <Name>dtoff</Name> = <Attribute><Name>dt</Name></Attribute>.<Call>utcoffset</Call>()
236.1017 - if <Name>dtoff</Name> is <Name>None</Name>:
236.1018 - raise <Call><Name>ValueError</Name></Call>("fromutc() requires a non-None utcoffset() "
236.1019 - "result")
236.1020 -
236.1021 - # See the long comment block at the end of this file for an
236.1022 - # explanation of this algorithm.
236.1023 - <Name>dtdst</Name> = <Attribute><Name>dt</Name></Attribute>.<Call>dst</Call>()
236.1024 - if <Name>dtdst</Name> is <Name>None</Name>:
236.1025 - raise <Call><Name>ValueError</Name></Call>("fromutc() requires a non-None dst() result")
236.1026 - <Name>delta</Name> = <Name>dtoff</Name> - <Name>dtdst</Name>
236.1027 - if <Name>delta</Name>:
236.1028 - <Name>dt</Name> += <Name>delta</Name>
236.1029 - <Name>dtdst</Name> = <Attribute><Name>dt</Name></Attribute>.<Call>dst</Call>()
236.1030 - if <Name>dtdst</Name> is <Name>None</Name>:
236.1031 - raise <Call><Name>ValueError</Name></Call>("fromutc(): dt.dst gave inconsistent "
236.1032 - "results; cannot convert")
236.1033 - if <Name>dtdst</Name>:
236.1034 - return <Name>dt</Name> + <Name>dtdst</Name>
236.1035 - else:
236.1036 - return <Name>dt</Name>
236.1037 -
236.1038 - # Pickle support.
236.1039 -
236.1040 - <Name>__safe_for_unpickling__</Name> = <Name>True</Name> # For Python 2.2
236.1041 -
236.1042 - def <FunctionDef>__reduce__</FunctionDef>(<Name>self</Name>):
236.1043 - <Name>getinitargs</Name> = <Call><Name>getattr</Name></Call>(<Name>self</Name>, "__getinitargs__", <Name>None</Name>)
236.1044 - if <Name>getinitargs</Name>:
236.1045 - <Name>args</Name> = <Call><Name>getinitargs</Name></Call>()
236.1046 - else:
236.1047 - <Name>args</Name> = ()
236.1048 - <Name>getstate</Name> = <Call><Name>getattr</Name></Call>(<Name>self</Name>, "__getstate__", <Name>None</Name>)
236.1049 - if <Name>getstate</Name>:
236.1050 - <Name>state</Name> = <Call><Name>getstate</Name></Call>()
236.1051 - else:
236.1052 - <Name>state</Name> = <Call><Name>getattr</Name></Call>(<Name>self</Name>, "__dict__", <Name>None</Name>) or <Name>None</Name>
236.1053 - if <Name>state</Name> is <Name>None</Name>:
236.1054 - return (<Attribute><Name>self</Name></Attribute>.__class__, <Name>args</Name>)
236.1055 - else:
236.1056 - return (<Attribute><Name>self</Name></Attribute>.__class__, <Name>args</Name>, <Name>state</Name>)
236.1057 -
236.1058 -<Name>_tzinfo_class</Name> = <Name>tzinfo</Name> # so functions w/ args named "tinfo" can get at it
236.1059 -
236.1060 -class <ClassDef>time</ClassDef>(<Name>object</Name>):
236.1061 - """Time with time zone.
236.1062 -
236.1063 - Constructors:
236.1064 -
236.1065 - __new__()
236.1066 -
236.1067 - Operators:
236.1068 -
236.1069 - __repr__, __str__
236.1070 - __cmp__, __hash__
236.1071 -
236.1072 - Methods:
236.1073 -
236.1074 - strftime()
236.1075 - isoformat()
236.1076 - utcoffset()
236.1077 - tzname()
236.1078 - dst()
236.1079 -
236.1080 - Properties (readonly):
236.1081 - hour, minute, second, microsecond, tzinfo
236.1082 - """
236.1083 -
236.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>):
236.1085 - """Constructor.
236.1086 -
236.1087 - Arguments:
236.1088 -
236.1089 - hour, minute (required)
236.1090 - second, microsecond (default to zero)
236.1091 - tzinfo (default to None)
236.1092 - """
236.1093 - <Name>self</Name> = <Attribute><Name>object</Name></Attribute>.<Call>__new__</Call>(<Name>cls</Name>)
236.1094 - if <Call><Name>isinstance</Name></Call>(<Name>hour</Name>, <Name>str</Name>):
236.1095 - # Pickle support
236.1096 - <Attribute><Name>self</Name></Attribute>.<Call>__setstate</Call>((<Name>hour</Name>, <Name>minute</Name> or <Name>None</Name>))
236.1097 - return <Name>self</Name>
236.1098 - <Call><Name>_check_tzinfo_arg</Name></Call>(<Name>tzinfo</Name>)
236.1099 - <Call><Name>_check_time_fields</Name></Call>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)
236.1100 - <Attribute><Name>self</Name></Attribute>.__hour = <Name>hour</Name>
236.1101 - <Attribute><Name>self</Name></Attribute>.__minute = <Name>minute</Name>
236.1102 - <Attribute><Name>self</Name></Attribute>.__second = <Name>second</Name>
236.1103 - <Attribute><Name>self</Name></Attribute>.__microsecond = <Name>microsecond</Name>
236.1104 - <Attribute><Name>self</Name></Attribute>._tzinfo = <Name>tzinfo</Name>
236.1105 - return <Name>self</Name>
236.1106 -
236.1107 - # Read-only field accessors
236.1108 - <Name>hour</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__hour, doc="hour (0-23)")
236.1109 - <Name>minute</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__minute, doc="minute (0-59)")
236.1110 - <Name>second</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__second, doc="second (0-59)")
236.1111 - <Name>microsecond</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__microsecond,
236.1112 - doc="microsecond (0-999999)")
236.1113 - <Name>tzinfo</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>._tzinfo, doc="timezone info object")
236.1114 -
236.1115 - # Standard conversions, __hash__ (and helpers)
236.1116 -
236.1117 - # Comparisons.
236.1118 -
236.1119 - def <FunctionDef>__eq__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1120 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>):
236.1121 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) == 0
236.1122 - else:
236.1123 - return <Name>False</Name>
236.1124 -
236.1125 - def <FunctionDef>__ne__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1126 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>):
236.1127 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) != 0
236.1128 - else:
236.1129 - return <Name>True</Name>
236.1130 -
236.1131 - def <FunctionDef>__le__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1132 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>):
236.1133 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) <= 0
236.1134 - else:
236.1135 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.1136 -
236.1137 - def <FunctionDef>__lt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1138 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>):
236.1139 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) < 0
236.1140 - else:
236.1141 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.1142 -
236.1143 - def <FunctionDef>__ge__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1144 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>):
236.1145 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) >= 0
236.1146 - else:
236.1147 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.1148 -
236.1149 - def <FunctionDef>__gt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1150 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>):
236.1151 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) > 0
236.1152 - else:
236.1153 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.1154 -
236.1155 - def <FunctionDef>__cmp</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1156 - assert <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>)
236.1157 - <Name>mytz</Name> = <Attribute><Name>self</Name></Attribute>._tzinfo
236.1158 - <Name>ottz</Name> = <Attribute><Name>other</Name></Attribute>._tzinfo
236.1159 - <Name>myoff</Name> = <Name>otoff</Name> = <Name>None</Name>
236.1160 -
236.1161 - if <Name>mytz</Name> is <Name>ottz</Name>:
236.1162 - <Name>base_compare</Name> = <Name>True</Name>
236.1163 - else:
236.1164 - <Name>myoff</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
236.1165 - <Name>otoff</Name> = <Attribute><Name>other</Name></Attribute>.<Call>_utcoffset</Call>()
236.1166 - <Name>base_compare</Name> = <Name>myoff</Name> == <Name>otoff</Name>
236.1167 -
236.1168 - if <Name>base_compare</Name>:
236.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,
236.1170 - <Attribute><Name>self</Name></Attribute>.__microsecond),
236.1171 - (<Attribute><Name>other</Name></Attribute>.__hour, <Attribute><Name>other</Name></Attribute>.__minute, <Attribute><Name>other</Name></Attribute>.__second,
236.1172 - <Attribute><Name>other</Name></Attribute>.__microsecond))
236.1173 - if <Name>myoff</Name> is <Name>None</Name> or <Name>otoff</Name> is <Name>None</Name>:
236.1174 - # XXX Buggy in 2.2.2.
236.1175 - raise <Call><Name>TypeError</Name></Call>("cannot compare naive and aware times")
236.1176 - <Name>myhhmm</Name> = <Attribute><Name>self</Name></Attribute>.__hour * 60 + <Attribute><Name>self</Name></Attribute>.__minute - <Name>myoff</Name>
236.1177 - <Name>othhmm</Name> = <Attribute><Name>other</Name></Attribute>.__hour * 60 + <Attribute><Name>other</Name></Attribute>.__minute - <Name>otoff</Name>
236.1178 - return <Call><Name>cmp</Name></Call>((<Name>myhhmm</Name>, <Attribute><Name>self</Name></Attribute>.__second, <Attribute><Name>self</Name></Attribute>.__microsecond),
236.1179 - (<Name>othhmm</Name>, <Attribute><Name>other</Name></Attribute>.__second, <Attribute><Name>other</Name></Attribute>.__microsecond))
236.1180 -
236.1181 - def <FunctionDef>__hash__</FunctionDef>(<Name>self</Name>):
236.1182 - """Hash."""
236.1183 - <Name>tzoff</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
236.1184 - if not <Name>tzoff</Name>: # zero or None
236.1185 - return <Call><Name>hash</Name></Call>(<Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>()[0])
236.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)
236.1187 - if 0 <= <Name>h</Name> < 24:
236.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))
236.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))
236.1190 -
236.1191 - # Conversion to string
236.1192 -
236.1193 - def <FunctionDef>_tzstr</FunctionDef>(<Name>self</Name>, <Name>sep</Name>=":"):
236.1194 - """Return formatted timezone offset (+xx:xx) or None."""
236.1195 - <Name>off</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
236.1196 - if <Name>off</Name> is not <Name>None</Name>:
236.1197 - if <Name>off</Name> < 0:
236.1198 - <Name>sign</Name> = "-"
236.1199 - <Name>off</Name> = -<Name>off</Name>
236.1200 - else:
236.1201 - <Name>sign</Name> = "+"
236.1202 - <Name>hh</Name>, <Name>mm</Name> = <Call><Name>divmod</Name></Call>(<Name>off</Name>, 60)
236.1203 - assert 0 <= <Name>hh</Name> < 24
236.1204 - <Name>off</Name> = "%s%02d%s%02d" % (<Name>sign</Name>, <Name>hh</Name>, <Name>sep</Name>, <Name>mm</Name>)
236.1205 - return <Name>off</Name>
236.1206 -
236.1207 - def <FunctionDef>__repr__</FunctionDef>(<Name>self</Name>):
236.1208 - """Convert to formal string, for repr()."""
236.1209 - if <Attribute><Name>self</Name></Attribute>.__microsecond != 0:
236.1210 - <Name>s</Name> = ", %d, %d" % (<Attribute><Name>self</Name></Attribute>.__second, <Attribute><Name>self</Name></Attribute>.__microsecond)
236.1211 - elif <Attribute><Name>self</Name></Attribute>.__second != 0:
236.1212 - <Name>s</Name> = ", %d" % <Attribute><Name>self</Name></Attribute>.__second
236.1213 - else:
236.1214 - <Name>s</Name> = ""
236.1215 - <Name>s</Name>= "%s(%d, %d%s)" % ('datetime.' + <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.__class__.__name__,
236.1216 - <Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Name>s</Name>)
236.1217 - if <Attribute><Name>self</Name></Attribute>._tzinfo is not <Name>None</Name>:
236.1218 - assert <Name>s</Name>[-1:] == ")"
236.1219 - <Name>s</Name> = <Name>s</Name>[:-1] + ", tzinfo=%r" % <Attribute><Name>self</Name></Attribute>._tzinfo + ")"
236.1220 - return <Name>s</Name>
236.1221 -
236.1222 - def <FunctionDef>isoformat</FunctionDef>(<Name>self</Name>):
236.1223 - """Return the time formatted according to ISO.
236.1224 -
236.1225 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
236.1226 - self.microsecond == 0.
236.1227 - """
236.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,
236.1229 - <Attribute><Name>self</Name></Attribute>.__microsecond)
236.1230 - <Name>tz</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_tzstr</Call>()
236.1231 - if <Name>tz</Name>:
236.1232 - <Name>s</Name> += <Name>tz</Name>
236.1233 - return <Name>s</Name>
236.1234 -
236.1235 - <Name>__str__</Name> = <Name>isoformat</Name>
236.1236 -
236.1237 - def <FunctionDef>strftime</FunctionDef>(<Name>self</Name>, <Name>fmt</Name>):
236.1238 - """Format using strftime(). The date part of the timestamp passed
236.1239 - to underlying strftime should not be used.
236.1240 - """
236.1241 - # The year must be >= 1900 else Python's strftime implementation
236.1242 - # can raise a bogus exception.
236.1243 - <Name>timetuple</Name> = (1900, 1, 1,
236.1244 - <Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second,
236.1245 - 0, 1, -1)
236.1246 - return <Call><Name>_wrap_strftime</Name></Call>(<Name>self</Name>, <Name>fmt</Name>, <Name>timetuple</Name>)
236.1247 -
236.1248 - # Timezone functions
236.1249 -
236.1250 - def <FunctionDef>utcoffset</FunctionDef>(<Name>self</Name>):
236.1251 - """Return the timezone offset in minutes east of UTC (negative west of
236.1252 - UTC)."""
236.1253 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "utcoffset", <Name>None</Name>)
236.1254 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("utcoffset", <Name>offset</Name>)
236.1255 - if <Name>offset</Name> is not <Name>None</Name>:
236.1256 - <Name>offset</Name> = <Call><Name>timedelta</Name></Call>(minutes=<Name>offset</Name>)
236.1257 - return <Name>offset</Name>
236.1258 -
236.1259 - # Return an integer (or None) instead of a timedelta (or None).
236.1260 - def <FunctionDef>_utcoffset</FunctionDef>(<Name>self</Name>):
236.1261 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "utcoffset", <Name>None</Name>)
236.1262 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("utcoffset", <Name>offset</Name>)
236.1263 - return <Name>offset</Name>
236.1264 -
236.1265 - def <FunctionDef>tzname</FunctionDef>(<Name>self</Name>):
236.1266 - """Return the timezone name.
236.1267 -
236.1268 - Note that the name is 100% informational -- there's no requirement that
236.1269 - it mean anything in particular. For example, "GMT", "UTC", "-500",
236.1270 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
236.1271 - """
236.1272 - <Name>name</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "tzname", <Name>None</Name>)
236.1273 - <Call><Name>_check_tzname</Name></Call>(<Name>name</Name>)
236.1274 - return <Name>name</Name>
236.1275 -
236.1276 - def <FunctionDef>dst</FunctionDef>(<Name>self</Name>):
236.1277 - """Return 0 if DST is not in effect, or the DST offset (in minutes
236.1278 - eastward) if DST is in effect.
236.1279 -
236.1280 - This is purely informational; the DST offset has already been added to
236.1281 - the UTC offset returned by utcoffset() if applicable, so there's no
236.1282 - need to consult dst() unless you're interested in displaying the DST
236.1283 - info.
236.1284 - """
236.1285 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "dst", <Name>None</Name>)
236.1286 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("dst", <Name>offset</Name>)
236.1287 - if <Name>offset</Name> is not <Name>None</Name>:
236.1288 - <Name>offset</Name> = <Call><Name>timedelta</Name></Call>(minutes=<Name>offset</Name>)
236.1289 - return <Name>offset</Name>
236.1290 -
236.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>,
236.1292 - <Name>tzinfo</Name>=<Name>True</Name>):
236.1293 - """Return a new time with new values for the specified fields."""
236.1294 - if <Name>hour</Name> is <Name>None</Name>:
236.1295 - <Name>hour</Name> = <Attribute><Name>self</Name></Attribute>.hour
236.1296 - if <Name>minute</Name> is <Name>None</Name>:
236.1297 - <Name>minute</Name> = <Attribute><Name>self</Name></Attribute>.minute
236.1298 - if <Name>second</Name> is <Name>None</Name>:
236.1299 - <Name>second</Name> = <Attribute><Name>self</Name></Attribute>.second
236.1300 - if <Name>microsecond</Name> is <Name>None</Name>:
236.1301 - <Name>microsecond</Name> = <Attribute><Name>self</Name></Attribute>.microsecond
236.1302 - if <Name>tzinfo</Name> is <Name>True</Name>:
236.1303 - <Name>tzinfo</Name> = <Attribute><Name>self</Name></Attribute>.tzinfo
236.1304 - <Call><Name>_check_time_fields</Name></Call>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)
236.1305 - <Call><Name>_check_tzinfo_arg</Name></Call>(<Name>tzinfo</Name>)
236.1306 - return <Call><Name>time</Name></Call>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>, <Name>tzinfo</Name>)
236.1307 -
236.1308 - # Return an integer (or None) instead of a timedelta (or None).
236.1309 - def <FunctionDef>_dst</FunctionDef>(<Name>self</Name>):
236.1310 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "dst", <Name>None</Name>)
236.1311 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("dst", <Name>offset</Name>)
236.1312 - return <Name>offset</Name>
236.1313 -
236.1314 - def <FunctionDef>__nonzero__</FunctionDef>(<Name>self</Name>):
236.1315 - if <Attribute><Name>self</Name></Attribute>.second or <Attribute><Name>self</Name></Attribute>.microsecond:
236.1316 - return 1
236.1317 - <Name>offset</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>() or 0
236.1318 - return <Attribute><Name>self</Name></Attribute>.hour * 60 + <Attribute><Name>self</Name></Attribute>.minute - <Name>offset</Name> != 0
236.1319 -
236.1320 - # Pickle support.
236.1321 -
236.1322 - <Name>__safe_for_unpickling__</Name> = <Name>True</Name> # For Python 2.2
236.1323 -
236.1324 - def <FunctionDef>__getstate</FunctionDef>(<Name>self</Name>):
236.1325 - <Name>us2</Name>, <Name>us3</Name> = <Call><Name>divmod</Name></Call>(<Attribute><Name>self</Name></Attribute>.__microsecond, 256)
236.1326 - <Name>us1</Name>, <Name>us2</Name> = <Call><Name>divmod</Name></Call>(<Name>us2</Name>, 256)
236.1327 - <Name>basestate</Name> = ("%c" * 6) % (<Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second,
236.1328 - <Name>us1</Name>, <Name>us2</Name>, <Name>us3</Name>)
236.1329 - if <Attribute><Name>self</Name></Attribute>._tzinfo is <Name>None</Name>:
236.1330 - return (<Name>basestate</Name>,)
236.1331 - else:
236.1332 - return (<Name>basestate</Name>, <Attribute><Name>self</Name></Attribute>._tzinfo)
236.1333 -
236.1334 - def <FunctionDef>__setstate</FunctionDef>(<Name>self</Name>, <Name>state</Name>):
236.1335 - assert <Call><Name>isinstance</Name></Call>(<Name>state</Name>, <Name>tuple</Name>)
236.1336 - assert 1 <= <Call><Name>len</Name></Call>(<Name>state</Name>) <= 2
236.1337 - <Name>string</Name> = <Name>state</Name>[0]
236.1338 - assert <Call><Name>len</Name></Call>(<Name>string</Name>) == 6
236.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> = \
236.1340 - <Call><Name>map</Name></Call>(<Name>ord</Name>, <Name>string</Name>)
236.1341 - <Attribute><Name>self</Name></Attribute>.__microsecond = (((<Name>us1</Name> << 8) | <Name>us2</Name>) << 8) | <Name>us3</Name>
236.1342 - if <Call><Name>len</Name></Call>(<Name>state</Name>) == 1:
236.1343 - <Attribute><Name>self</Name></Attribute>._tzinfo = <Name>None</Name>
236.1344 - else:
236.1345 - <Attribute><Name>self</Name></Attribute>._tzinfo = <Name>state</Name>[1]
236.1346 -
236.1347 - def <FunctionDef>__reduce__</FunctionDef>(<Name>self</Name>):
236.1348 - return (<Attribute><Name>self</Name></Attribute>.__class__, <Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>())
236.1349 -
236.1350 -<Name>_time_class</Name> = <Name>time</Name> # so functions w/ args named "time" can get at the class
236.1351 -
236.1352 -<Attribute><Name>time</Name></Attribute>.min = <Call><Name>time</Name></Call>(0, 0, 0)
236.1353 -<Attribute><Name>time</Name></Attribute>.max = <Call><Name>time</Name></Call>(23, 59, 59, 999999)
236.1354 -<Attribute><Name>time</Name></Attribute>.resolution = <Call><Name>timedelta</Name></Call>(microseconds=1)
236.1355 -
236.1356 -class <ClassDef>datetime</ClassDef>(<Name>date</Name>):
236.1357 -
236.1358 - # XXX needs docstrings
236.1359 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
236.1360 -
236.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,
236.1362 - <Name>microsecond</Name>=0, <Name>tzinfo</Name>=<Name>None</Name>):
236.1363 - if <Call><Name>isinstance</Name></Call>(<Name>year</Name>, <Name>str</Name>):
236.1364 - # Pickle support
236.1365 - <Name>self</Name> = <Attribute><Name>date</Name></Attribute>.<Call>__new__</Call>(<Name>cls</Name>, <Name>year</Name>[:4])
236.1366 - <Attribute><Name>self</Name></Attribute>.<Call>__setstate</Call>((<Name>year</Name>, <Name>month</Name>))
236.1367 - return <Name>self</Name>
236.1368 - <Call><Name>_check_tzinfo_arg</Name></Call>(<Name>tzinfo</Name>)
236.1369 - <Call><Name>_check_time_fields</Name></Call>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)
236.1370 - <Name>self</Name> = <Attribute><Name>date</Name></Attribute>.<Call>__new__</Call>(<Name>cls</Name>, <Name>year</Name>, <Name>month</Name>, <Name>day</Name>)
236.1371 - # XXX This duplicates __year, __month, __day for convenience :-(
236.1372 - <Attribute><Name>self</Name></Attribute>.__year = <Name>year</Name>
236.1373 - <Attribute><Name>self</Name></Attribute>.__month = <Name>month</Name>
236.1374 - <Attribute><Name>self</Name></Attribute>.__day = <Name>day</Name>
236.1375 - <Attribute><Name>self</Name></Attribute>.__hour = <Name>hour</Name>
236.1376 - <Attribute><Name>self</Name></Attribute>.__minute = <Name>minute</Name>
236.1377 - <Attribute><Name>self</Name></Attribute>.__second = <Name>second</Name>
236.1378 - <Attribute><Name>self</Name></Attribute>.__microsecond = <Name>microsecond</Name>
236.1379 - <Attribute><Name>self</Name></Attribute>._tzinfo = <Name>tzinfo</Name>
236.1380 - return <Name>self</Name>
236.1381 -
236.1382 - # Read-only field accessors
236.1383 - <Name>hour</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__hour, doc="hour (0-23)")
236.1384 - <Name>minute</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__minute, doc="minute (0-59)")
236.1385 - <Name>second</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__second, doc="second (0-59)")
236.1386 - <Name>microsecond</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__microsecond,
236.1387 - doc="microsecond (0-999999)")
236.1388 - <Name>tzinfo</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>._tzinfo, doc="timezone info object")
236.1389 -
236.1390 - def <FunctionDef>fromtimestamp</FunctionDef>(<Name>cls</Name>, <Name>t</Name>, <Name>tz</Name>=<Name>None</Name>):
236.1391 - """Construct a datetime from a POSIX timestamp (like time.time()).
236.1392 -
236.1393 - A timezone info object may be passed in as well.
236.1394 - """
236.1395 -
236.1396 - <Call><Name>_check_tzinfo_arg</Name></Call>(<Name>tz</Name>)
236.1397 - if <Name>tz</Name> is <Name>None</Name>:
236.1398 - <Name>converter</Name> = <Attribute><Name>_time</Name></Attribute>.localtime
236.1399 - else:
236.1400 - <Name>converter</Name> = <Attribute><Name>_time</Name></Attribute>.gmtime
236.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>)
236.1402 - <Name>us</Name> = <Call><Name>int</Name></Call>((<Name>t</Name> % 1.0) * 1000000)
236.1403 - <Name>ss</Name> = <Call><Name>min</Name></Call>(<Name>ss</Name>, 59) # clamp out leap seconds if the platform has them
236.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>)
236.1405 - if <Name>tz</Name> is not <Name>None</Name>:
236.1406 - <Name>result</Name> = <Attribute><Name>tz</Name></Attribute>.<Call>fromutc</Call>(<Name>result</Name>)
236.1407 - return <Name>result</Name>
236.1408 - <Name>fromtimestamp</Name> = <Call><Name>classmethod</Name></Call>(<Name>fromtimestamp</Name>)
236.1409 -
236.1410 - def <FunctionDef>utcfromtimestamp</FunctionDef>(<Name>cls</Name>, <Name>t</Name>):
236.1411 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
236.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>)
236.1413 - <Name>us</Name> = <Call><Name>int</Name></Call>((<Name>t</Name> % 1.0) * 1000000)
236.1414 - <Name>ss</Name> = <Call><Name>min</Name></Call>(<Name>ss</Name>, 59) # clamp out leap seconds if the platform has them
236.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>)
236.1416 - <Name>utcfromtimestamp</Name> = <Call><Name>classmethod</Name></Call>(<Name>utcfromtimestamp</Name>)
236.1417 -
236.1418 - # XXX This is supposed to do better than we *can* do by using time.time(),
236.1419 - # XXX if the platform supports a more accurate way. The C implementation
236.1420 - # XXX uses gettimeofday on platforms that have it, but that isn't
236.1421 - # XXX available from Python. So now() may return different results
236.1422 - # XXX across the implementations.
236.1423 - def <FunctionDef>now</FunctionDef>(<Name>cls</Name>, <Name>tz</Name>=<Name>None</Name>):
236.1424 - "Construct a datetime from time.time() and optional time zone info."
236.1425 - <Name>t</Name> = <Attribute><Name>_time</Name></Attribute>.<Call>time</Call>()
236.1426 - return <Attribute><Name>cls</Name></Attribute>.<Call>fromtimestamp</Call>(<Name>t</Name>, <Name>tz</Name>)
236.1427 - <Name>now</Name> = <Call><Name>classmethod</Name></Call>(<Name>now</Name>)
236.1428 -
236.1429 - def <FunctionDef>utcnow</FunctionDef>(<Name>cls</Name>):
236.1430 - "Construct a UTC datetime from time.time()."
236.1431 - <Name>t</Name> = <Attribute><Name>_time</Name></Attribute>.<Call>time</Call>()
236.1432 - return <Attribute><Name>cls</Name></Attribute>.<Call>utcfromtimestamp</Call>(<Name>t</Name>)
236.1433 - <Name>utcnow</Name> = <Call><Name>classmethod</Name></Call>(<Name>utcnow</Name>)
236.1434 -
236.1435 - def <FunctionDef>combine</FunctionDef>(<Name>cls</Name>, <Name>date</Name>, <Name>time</Name>):
236.1436 - "Construct a datetime from a given date and a given time."
236.1437 - if not <Call><Name>isinstance</Name></Call>(<Name>date</Name>, <Name>_date_class</Name>):
236.1438 - raise <Call><Name>TypeError</Name></Call>("date argument must be a date instance")
236.1439 - if not <Call><Name>isinstance</Name></Call>(<Name>time</Name>, <Name>_time_class</Name>):
236.1440 - raise <Call><Name>TypeError</Name></Call>("time argument must be a time instance")
236.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,
236.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,
236.1443 - <Attribute><Name>time</Name></Attribute>.tzinfo)
236.1444 - <Name>combine</Name> = <Call><Name>classmethod</Name></Call>(<Name>combine</Name>)
236.1445 -
236.1446 - def <FunctionDef>timetuple</FunctionDef>(<Name>self</Name>):
236.1447 - "Return local time tuple compatible with time.localtime()."
236.1448 - <Name>dst</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_dst</Call>()
236.1449 - if <Name>dst</Name> is <Name>None</Name>:
236.1450 - <Name>dst</Name> = -1
236.1451 - elif <Name>dst</Name>:
236.1452 - <Name>dst</Name> = 1
236.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,
236.1454 - <Attribute><Name>self</Name></Attribute>.hour, <Attribute><Name>self</Name></Attribute>.minute, <Attribute><Name>self</Name></Attribute>.second,
236.1455 - <Name>dst</Name>)
236.1456 -
236.1457 - def <FunctionDef>utctimetuple</FunctionDef>(<Name>self</Name>):
236.1458 - "Return UTC time tuple compatible with time.gmtime()."
236.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
236.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
236.1461 - <Name>offset</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
236.1462 - if <Name>offset</Name>: # neither None nor 0
236.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>)
236.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
236.1465 - <Name>hh</Name>, <Name>mm</Name> = <Attribute><Name>tm</Name></Attribute>.hour, <Attribute><Name>tm</Name></Attribute>.minute
236.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)
236.1467 -
236.1468 - def <FunctionDef>date</FunctionDef>(<Name>self</Name>):
236.1469 - "Return the date part."
236.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)
236.1471 -
236.1472 - def <FunctionDef>time</FunctionDef>(<Name>self</Name>):
236.1473 - "Return the time part, with tzinfo None."
236.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)
236.1475 -
236.1476 - def <FunctionDef>timetz</FunctionDef>(<Name>self</Name>):
236.1477 - "Return the time part, with same tzinfo."
236.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,
236.1479 - <Attribute><Name>self</Name></Attribute>._tzinfo)
236.1480 -
236.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>,
236.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>):
236.1483 - """Return a new datetime with new values for the specified fields."""
236.1484 - if <Name>year</Name> is <Name>None</Name>:
236.1485 - <Name>year</Name> = <Attribute><Name>self</Name></Attribute>.year
236.1486 - if <Name>month</Name> is <Name>None</Name>:
236.1487 - <Name>month</Name> = <Attribute><Name>self</Name></Attribute>.month
236.1488 - if <Name>day</Name> is <Name>None</Name>:
236.1489 - <Name>day</Name> = <Attribute><Name>self</Name></Attribute>.day
236.1490 - if <Name>hour</Name> is <Name>None</Name>:
236.1491 - <Name>hour</Name> = <Attribute><Name>self</Name></Attribute>.hour
236.1492 - if <Name>minute</Name> is <Name>None</Name>:
236.1493 - <Name>minute</Name> = <Attribute><Name>self</Name></Attribute>.minute
236.1494 - if <Name>second</Name> is <Name>None</Name>:
236.1495 - <Name>second</Name> = <Attribute><Name>self</Name></Attribute>.second
236.1496 - if <Name>microsecond</Name> is <Name>None</Name>:
236.1497 - <Name>microsecond</Name> = <Attribute><Name>self</Name></Attribute>.microsecond
236.1498 - if <Name>tzinfo</Name> is <Name>True</Name>:
236.1499 - <Name>tzinfo</Name> = <Attribute><Name>self</Name></Attribute>.tzinfo
236.1500 - <Call><Name>_check_date_fields</Name></Call>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)
236.1501 - <Call><Name>_check_time_fields</Name></Call>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)
236.1502 - <Call><Name>_check_tzinfo_arg</Name></Call>(<Name>tzinfo</Name>)
236.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>,
236.1504 - <Name>microsecond</Name>, <Name>tzinfo</Name>)
236.1505 -
236.1506 - def <FunctionDef>astimezone</FunctionDef>(<Name>self</Name>, <Name>tz</Name>):
236.1507 - if not <Call><Name>isinstance</Name></Call>(<Name>tz</Name>, <Name>tzinfo</Name>):
236.1508 - raise <Call><Name>TypeError</Name></Call>("tz argument must be an instance of tzinfo")
236.1509 -
236.1510 - <Name>mytz</Name> = <Attribute><Name>self</Name></Attribute>.tzinfo
236.1511 - if <Name>mytz</Name> is <Name>None</Name>:
236.1512 - raise <Call><Name>ValueError</Name></Call>("astimezone() requires an aware datetime")
236.1513 -
236.1514 - if <Name>tz</Name> is <Name>mytz</Name>:
236.1515 - return <Name>self</Name>
236.1516 -
236.1517 - # Convert self to UTC, and attach the new time zone object.
236.1518 - <Name>myoffset</Name> = <Attribute><Name>self</Name></Attribute>.<Call>utcoffset</Call>()
236.1519 - if <Name>myoffset</Name> is <Name>None</Name>:
236.1520 - raise <Call><Name>ValuError</Name></Call>("astimezone() requires an aware datetime")
236.1521 - <Name>utc</Name> = <Attribute>(<Name>self</Name> - <Name>myoffset</Name>)</Attribute>.<Call>replace</Call>(tzinfo=<Name>tz</Name>)
236.1522 -
236.1523 - # Convert from UTC to tz's local time.
236.1524 - return <Attribute><Name>tz</Name></Attribute>.<Call>fromutc</Call>(<Name>utc</Name>)
236.1525 -
236.1526 - # Ways to produce a string.
236.1527 -
236.1528 - def <FunctionDef>ctime</FunctionDef>(<Name>self</Name>):
236.1529 - "Format a la ctime()."
236.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,
236.1531 - <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second)
236.1532 - return <Attribute><Name>t</Name></Attribute>.<Call>ctime</Call>()
236.1533 -
236.1534 - def <FunctionDef>isoformat</FunctionDef>(<Name>self</Name>, <Name>sep</Name>='T'):
236.1535 - """Return the time formatted according to ISO.
236.1536 -
236.1537 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
236.1538 - self.microsecond == 0.
236.1539 -
236.1540 - If self.tzinfo is not None, the UTC offset is also attached, giving
236.1541 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
236.1542 -
236.1543 - Optional argument sep specifies the separator between date and
236.1544 - time, default 'T'.
236.1545 - """
236.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,
236.1547 - <Name>sep</Name>) +
236.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,
236.1549 - <Attribute><Name>self</Name></Attribute>.__microsecond))
236.1550 - <Name>off</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
236.1551 - if <Name>off</Name> is not <Name>None</Name>:
236.1552 - if <Name>off</Name> < 0:
236.1553 - <Name>sign</Name> = "-"
236.1554 - <Name>off</Name> = -<Name>off</Name>
236.1555 - else:
236.1556 - <Name>sign</Name> = "+"
236.1557 - <Name>hh</Name>, <Name>mm</Name> = <Call><Name>divmod</Name></Call>(<Name>off</Name>, 60)
236.1558 - <Name>s</Name> += "%s%02d:%02d" % (<Name>sign</Name>, <Name>hh</Name>, <Name>mm</Name>)
236.1559 - return <Name>s</Name>
236.1560 -
236.1561 - def <FunctionDef>__repr__</FunctionDef>(<Name>self</Name>):
236.1562 - "Convert to formal string, for repr()."
236.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
236.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]
236.1565 - if <Name>L</Name>[-1] == 0:
236.1566 - del <Name>L</Name>[-1]
236.1567 - if <Name>L</Name>[-1] == 0:
236.1568 - del <Name>L</Name>[-1]
236.1569 - <Name>s</Name> = <Attribute>", "</Attribute>.<Call>join</Call>(<Call><Name>map</Name></Call>(<Name>str</Name>, <Name>L</Name>))
236.1570 - <Name>s</Name> = "%s(%s)" % ('datetime.' + <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.__class__.__name__, <Name>s</Name>)
236.1571 - if <Attribute><Name>self</Name></Attribute>._tzinfo is not <Name>None</Name>:
236.1572 - assert <Name>s</Name>[-1:] == ")"
236.1573 - <Name>s</Name> = <Name>s</Name>[:-1] + ", tzinfo=%r" % <Attribute><Name>self</Name></Attribute>._tzinfo + ")"
236.1574 - return <Name>s</Name>
236.1575 -
236.1576 - def <FunctionDef>__str__</FunctionDef>(<Name>self</Name>):
236.1577 - "Convert to string, for str()."
236.1578 - return <Attribute><Name>self</Name></Attribute>.<Call>isoformat</Call>(sep=' ')
236.1579 -
236.1580 - def <FunctionDef>utcoffset</FunctionDef>(<Name>self</Name>):
236.1581 - """Return the timezone offset in minutes east of UTC (negative west of
236.1582 - UTC)."""
236.1583 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "utcoffset", <Name>self</Name>)
236.1584 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("utcoffset", <Name>offset</Name>)
236.1585 - if <Name>offset</Name> is not <Name>None</Name>:
236.1586 - <Name>offset</Name> = <Call><Name>timedelta</Name></Call>(minutes=<Name>offset</Name>)
236.1587 - return <Name>offset</Name>
236.1588 -
236.1589 - # Return an integer (or None) instead of a timedelta (or None).
236.1590 - def <FunctionDef>_utcoffset</FunctionDef>(<Name>self</Name>):
236.1591 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "utcoffset", <Name>self</Name>)
236.1592 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("utcoffset", <Name>offset</Name>)
236.1593 - return <Name>offset</Name>
236.1594 -
236.1595 - def <FunctionDef>tzname</FunctionDef>(<Name>self</Name>):
236.1596 - """Return the timezone name.
236.1597 -
236.1598 - Note that the name is 100% informational -- there's no requirement that
236.1599 - it mean anything in particular. For example, "GMT", "UTC", "-500",
236.1600 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
236.1601 - """
236.1602 - <Name>name</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "tzname", <Name>self</Name>)
236.1603 - <Call><Name>_check_tzname</Name></Call>(<Name>name</Name>)
236.1604 - return <Name>name</Name>
236.1605 -
236.1606 - def <FunctionDef>dst</FunctionDef>(<Name>self</Name>):
236.1607 - """Return 0 if DST is not in effect, or the DST offset (in minutes
236.1608 - eastward) if DST is in effect.
236.1609 -
236.1610 - This is purely informational; the DST offset has already been added to
236.1611 - the UTC offset returned by utcoffset() if applicable, so there's no
236.1612 - need to consult dst() unless you're interested in displaying the DST
236.1613 - info.
236.1614 - """
236.1615 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "dst", <Name>self</Name>)
236.1616 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("dst", <Name>offset</Name>)
236.1617 - if <Name>offset</Name> is not <Name>None</Name>:
236.1618 - <Name>offset</Name> = <Call><Name>timedelta</Name></Call>(minutes=<Name>offset</Name>)
236.1619 - return <Name>offset</Name>
236.1620 -
236.1621 - # Return an integer (or None) instead of a timedelta (or None).1573
236.1622 - def <FunctionDef>_dst</FunctionDef>(<Name>self</Name>):
236.1623 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "dst", <Name>self</Name>)
236.1624 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("dst", <Name>offset</Name>)
236.1625 - return <Name>offset</Name>
236.1626 -
236.1627 - # Comparisons.
236.1628 -
236.1629 - def <FunctionDef>__eq__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1630 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
236.1631 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) == 0
236.1632 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
236.1633 - return <Name>NotImplemented</Name>
236.1634 - else:
236.1635 - return <Name>False</Name>
236.1636 -
236.1637 - def <FunctionDef>__ne__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1638 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
236.1639 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) != 0
236.1640 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
236.1641 - return <Name>NotImplemented</Name>
236.1642 - else:
236.1643 - return <Name>True</Name>
236.1644 -
236.1645 - def <FunctionDef>__le__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1646 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
236.1647 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) <= 0
236.1648 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
236.1649 - return <Name>NotImplemented</Name>
236.1650 - else:
236.1651 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.1652 -
236.1653 - def <FunctionDef>__lt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1654 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
236.1655 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) < 0
236.1656 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
236.1657 - return <Name>NotImplemented</Name>
236.1658 - else:
236.1659 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.1660 -
236.1661 - def <FunctionDef>__ge__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1662 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
236.1663 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) >= 0
236.1664 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
236.1665 - return <Name>NotImplemented</Name>
236.1666 - else:
236.1667 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.1668 -
236.1669 - def <FunctionDef>__gt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1670 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
236.1671 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) > 0
236.1672 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
236.1673 - return <Name>NotImplemented</Name>
236.1674 - else:
236.1675 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
236.1676 -
236.1677 - def <FunctionDef>__cmp</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1678 - assert <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>)
236.1679 - <Name>mytz</Name> = <Attribute><Name>self</Name></Attribute>._tzinfo
236.1680 - <Name>ottz</Name> = <Attribute><Name>other</Name></Attribute>._tzinfo
236.1681 - <Name>myoff</Name> = <Name>otoff</Name> = <Name>None</Name>
236.1682 -
236.1683 - if <Name>mytz</Name> is <Name>ottz</Name>:
236.1684 - <Name>base_compare</Name> = <Name>True</Name>
236.1685 - else:
236.1686 - if <Name>mytz</Name> is not <Name>None</Name>:
236.1687 - <Name>myoff</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
236.1688 - if <Name>ottz</Name> is not <Name>None</Name>:
236.1689 - <Name>otoff</Name> = <Attribute><Name>other</Name></Attribute>.<Call>_utcoffset</Call>()
236.1690 - <Name>base_compare</Name> = <Name>myoff</Name> == <Name>otoff</Name>
236.1691 -
236.1692 - if <Name>base_compare</Name>:
236.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,
236.1694 - <Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second,
236.1695 - <Attribute><Name>self</Name></Attribute>.__microsecond),
236.1696 - (<Attribute><Name>other</Name></Attribute>.__year, <Attribute><Name>other</Name></Attribute>.__month, <Attribute><Name>other</Name></Attribute>.__day,
236.1697 - <Attribute><Name>other</Name></Attribute>.__hour, <Attribute><Name>other</Name></Attribute>.__minute, <Attribute><Name>other</Name></Attribute>.__second,
236.1698 - <Attribute><Name>other</Name></Attribute>.__microsecond))
236.1699 - if <Name>myoff</Name> is <Name>None</Name> or <Name>otoff</Name> is <Name>None</Name>:
236.1700 - # XXX Buggy in 2.2.2.
236.1701 - raise <Call><Name>TypeError</Name></Call>("cannot compare naive and aware datetimes")
236.1702 - # XXX What follows could be done more efficiently...
236.1703 - <Name>diff</Name> = <Name>self</Name> - <Name>other</Name> # this will take offsets into account
236.1704 - if <Attribute><Name>diff</Name></Attribute>.days < 0:
236.1705 - return -1
236.1706 - return <Name>diff</Name> and 1 or 0
236.1707 -
236.1708 - def <FunctionDef>__add__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1709 - "Add a datetime and a timedelta."
236.1710 - if not <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
236.1711 - return <Name>NotImplemented</Name>
236.1712 - <Name>t</Name> = <Call><Name>tmxxx</Name></Call>(<Attribute><Name>self</Name></Attribute>.__year,
236.1713 - <Attribute><Name>self</Name></Attribute>.__month,
236.1714 - <Attribute><Name>self</Name></Attribute>.__day + <Attribute><Name>other</Name></Attribute>.days,
236.1715 - <Attribute><Name>self</Name></Attribute>.__hour,
236.1716 - <Attribute><Name>self</Name></Attribute>.__minute,
236.1717 - <Attribute><Name>self</Name></Attribute>.__second + <Attribute><Name>other</Name></Attribute>.seconds,
236.1718 - <Attribute><Name>self</Name></Attribute>.__microsecond + <Attribute><Name>other</Name></Attribute>.microseconds)
236.1719 - <Attribute><Name>self</Name></Attribute>.<Call>_checkOverflow</Call>(<Attribute><Name>t</Name></Attribute>.year)
236.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,
236.1721 - <Attribute><Name>t</Name></Attribute>.hour, <Attribute><Name>t</Name></Attribute>.minute, <Attribute><Name>t</Name></Attribute>.second,
236.1722 - <Attribute><Name>t</Name></Attribute>.microsecond, tzinfo=<Attribute><Name>self</Name></Attribute>._tzinfo)
236.1723 - return <Name>result</Name>
236.1724 -
236.1725 - <Name>__radd__</Name> = <Name>__add__</Name>
236.1726 -
236.1727 - def <FunctionDef>__sub__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
236.1728 - "Subtract two datetimes, or a datetime and a timedelta."
236.1729 - if not <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
236.1730 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
236.1731 - return <Name>self</Name> + -<Name>other</Name>
236.1732 - return <Name>NotImplemented</Name>
236.1733 -
236.1734 - <Name>days1</Name> = <Attribute><Name>self</Name></Attribute>.<Call>toordinal</Call>()
236.1735 - <Name>days2</Name> = <Attribute><Name>other</Name></Attribute>.<Call>toordinal</Call>()
236.1736 - <Name>secs1</Name> = <Attribute><Name>self</Name></Attribute>.__second + <Attribute><Name>self</Name></Attribute>.__minute * 60 + <Attribute><Name>self</Name></Attribute>.__hour * 3600
236.1737 - <Name>secs2</Name> = <Attribute><Name>other</Name></Attribute>.__second + <Attribute><Name>other</Name></Attribute>.__minute * 60 + <Attribute><Name>other</Name></Attribute>.__hour * 3600
236.1738 - <Name>base</Name> = <Call><Name>timedelta</Name></Call>(<Name>days1</Name> - <Name>days2</Name>,
236.1739 - <Name>secs1</Name> - <Name>secs2</Name>,
236.1740 - <Attribute><Name>self</Name></Attribute>.__microsecond - <Attribute><Name>other</Name></Attribute>.__microsecond)
236.1741 - if <Attribute><Name>self</Name></Attribute>._tzinfo is <Attribute><Name>other</Name></Attribute>._tzinfo:
236.1742 - return <Name>base</Name>
236.1743 - <Name>myoff</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
236.1744 - <Name>otoff</Name> = <Attribute><Name>other</Name></Attribute>.<Call>_utcoffset</Call>()
236.1745 - if <Name>myoff</Name> == <Name>otoff</Name>:
236.1746 - return <Name>base</Name>
236.1747 - if <Name>myoff</Name> is <Name>None</Name> or <Name>otoff</Name> is <Name>None</Name>:
236.1748 - raise <Name>TypeError</Name>, "cannot mix naive and timezone-aware time"
236.1749 - return <Name>base</Name> + <Call><Name>timedelta</Name></Call>(minutes = <Name>otoff</Name>-<Name>myoff</Name>)
236.1750 -
236.1751 - def <FunctionDef>__hash__</FunctionDef>(<Name>self</Name>):
236.1752 - <Name>tzoff</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
236.1753 - if <Name>tzoff</Name> is <Name>None</Name>:
236.1754 - return <Call><Name>hash</Name></Call>(<Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>()[0])
236.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)
236.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
236.1757 - return <Call><Name>hash</Name></Call>(<Call><Name>timedelta</Name></Call>(<Name>days</Name>, <Name>seconds</Name>, <Attribute><Name>self</Name></Attribute>.microsecond))
236.1758 -
236.1759 - # Pickle support.
236.1760 -
236.1761 - <Name>__safe_for_unpickling__</Name> = <Name>True</Name> # For Python 2.2
236.1762 -
236.1763 - def <FunctionDef>__getstate</FunctionDef>(<Name>self</Name>):
236.1764 - <Name>yhi</Name>, <Name>ylo</Name> = <Call><Name>divmod</Name></Call>(<Attribute><Name>self</Name></Attribute>.__year, 256)
236.1765 - <Name>us2</Name>, <Name>us3</Name> = <Call><Name>divmod</Name></Call>(<Attribute><Name>self</Name></Attribute>.__microsecond, 256)
236.1766 - <Name>us1</Name>, <Name>us2</Name> = <Call><Name>divmod</Name></Call>(<Name>us2</Name>, 256)
236.1767 - <Name>basestate</Name> = ("%c" * 10) % (<Name>yhi</Name>, <Name>ylo</Name>, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day,
236.1768 - <Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second,
236.1769 - <Name>us1</Name>, <Name>us2</Name>, <Name>us3</Name>)
236.1770 - if <Attribute><Name>self</Name></Attribute>._tzinfo is <Name>None</Name>:
236.1771 - return (<Name>basestate</Name>,)
236.1772 - else:
236.1773 - return (<Name>basestate</Name>, <Attribute><Name>self</Name></Attribute>._tzinfo)
236.1774 -
236.1775 - def <FunctionDef>__setstate</FunctionDef>(<Name>self</Name>, <Name>state</Name>):
236.1776 - assert <Call><Name>isinstance</Name></Call>(<Name>state</Name>, <Name>tuple</Name>)
236.1777 - assert 1 <= <Call><Name>len</Name></Call>(<Name>state</Name>) <= 2
236.1778 - <Name>string</Name> = <Name>state</Name>[0]
236.1779 - assert <Call><Name>len</Name></Call>(<Name>string</Name>) == 10
236.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,
236.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>)
236.1782 - <Attribute><Name>self</Name></Attribute>.__year = <Name>yhi</Name> * 256 + <Name>ylo</Name>
236.1783 - <Attribute><Name>self</Name></Attribute>.__microsecond = (((<Name>us1</Name> << 8) | <Name>us2</Name>) << 8) | <Name>us3</Name>
236.1784 - if <Call><Name>len</Name></Call>(<Name>state</Name>) == 1:
236.1785 - <Attribute><Name>self</Name></Attribute>._tzinfo = <Name>None</Name>
236.1786 - else:
236.1787 - <Attribute><Name>self</Name></Attribute>._tzinfo = <Name>state</Name>[1]
236.1788 -
236.1789 - def <FunctionDef>__reduce__</FunctionDef>(<Name>self</Name>):
236.1790 - return (<Attribute><Name>self</Name></Attribute>.__class__, <Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>())
236.1791 -
236.1792 -
236.1793 -<Attribute><Name>datetime</Name></Attribute>.min = <Call><Name>datetime</Name></Call>(1, 1, 1)
236.1794 -<Attribute><Name>datetime</Name></Attribute>.max = <Call><Name>datetime</Name></Call>(9999, 12, 31, 23, 59, 59, 999999)
236.1795 -<Attribute><Name>datetime</Name></Attribute>.resolution = <Call><Name>timedelta</Name></Call>(microseconds=1)
236.1796 -
236.1797 -
236.1798 -def <FunctionDef>_isoweek1monday</FunctionDef>(<Name>year</Name>):
236.1799 - # Helper to calculate the day number of the Monday starting week 1
236.1800 - # XXX This could be done more efficiently
236.1801 - <Name>THURSDAY</Name> = 3
236.1802 - <Name>firstday</Name> = <Call><Name>_ymd2ord</Name></Call>(<Name>year</Name>, 1, 1)
236.1803 - <Name>firstweekday</Name> = (<Name>firstday</Name> + 6) % 7 # See weekday() above
236.1804 - <Name>week1monday</Name> = <Name>firstday</Name> - <Name>firstweekday</Name>
236.1805 - if <Name>firstweekday</Name> > <Name>THURSDAY</Name>:
236.1806 - <Name>week1monday</Name> += 7
236.1807 - return <Name>week1monday</Name>
236.1808 -
236.1809 -"""
236.1810 -Some time zone algebra. For a datetime x, let
236.1811 - x.n = x stripped of its timezone -- its naive time.
236.1812 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
236.1813 - return None
236.1814 - x.d = x.dst(), and assuming that doesn't raise an exception or
236.1815 - return None
236.1816 - x.s = x's standard offset, x.o - x.d
236.1817 -
236.1818 -Now some derived rules, where k is a duration (timedelta).
236.1819 -
236.1820 -1. x.o = x.s + x.d
236.1821 - This follows from the definition of x.s.
236.1822 -
236.1823 -2. If x and y have the same tzinfo member, x.s = y.s.
236.1824 - This is actually a requirement, an assumption we need to make about
236.1825 - sane tzinfo classes.
236.1826 -
236.1827 -3. The naive UTC time corresponding to x is x.n - x.o.
236.1828 - This is again a requirement for a sane tzinfo class.
236.1829 -
236.1830 -4. (x+k).s = x.s
236.1831 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
236.1832 -
236.1833 -5. (x+k).n = x.n + k
236.1834 - Again follows from how arithmetic is defined.
236.1835 -
236.1836 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
236.1837 -(meaning that the various tzinfo methods exist, and don't blow up or return
236.1838 -None when called).
236.1839 -
236.1840 -The function wants to return a datetime y with timezone tz, equivalent to x.
236.1841 -x is already in UTC.
236.1842 -
236.1843 -By #3, we want
236.1844 -
236.1845 - y.n - y.o = x.n [1]
236.1846 -
236.1847 -The algorithm starts by attaching tz to x.n, and calling that y. So
236.1848 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
236.1849 -becomes true; in effect, we want to solve [2] for k:
236.1850 -
236.1851 - (y+k).n - (y+k).o = x.n [2]
236.1852 -
236.1853 -By #1, this is the same as
236.1854 -
236.1855 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
236.1856 -
236.1857 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
236.1858 -Substituting that into [3],
236.1859 -
236.1860 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
236.1861 - k - (y+k).s - (y+k).d = 0; rearranging,
236.1862 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
236.1863 - k = y.s - (y+k).d
236.1864 -
236.1865 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
236.1866 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
236.1867 -very large, since all offset-returning methods return a duration of magnitude
236.1868 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
236.1869 -be 0, so ignoring it has no consequence then.
236.1870 -
236.1871 -In any case, the new value is
236.1872 -
236.1873 - z = y + y.s [4]
236.1874 -
236.1875 -It's helpful to step back at look at [4] from a higher level: it's simply
236.1876 -mapping from UTC to tz's standard time.
236.1877 -
236.1878 -At this point, if
236.1879 -
236.1880 - z.n - z.o = x.n [5]
236.1881 -
236.1882 -we have an equivalent time, and are almost done. The insecurity here is
236.1883 -at the start of daylight time. Picture US Eastern for concreteness. The wall
236.1884 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
236.1885 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
236.1886 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
236.1887 -on the day DST starts. We want to return the 1:MM EST spelling because that's
236.1888 -the only spelling that makes sense on the local wall clock.
236.1889 -
236.1890 -In fact, if [5] holds at this point, we do have the standard-time spelling,
236.1891 -but that takes a bit of proof. We first prove a stronger result. What's the
236.1892 -difference between the LHS and RHS of [5]? Let
236.1893 -
236.1894 - diff = x.n - (z.n - z.o) [6]
236.1895 -
236.1896 -Now
236.1897 - z.n = by [4]
236.1898 - (y + y.s).n = by #5
236.1899 - y.n + y.s = since y.n = x.n
236.1900 - x.n + y.s = since z and y are have the same tzinfo member,
236.1901 - y.s = z.s by #2
236.1902 - x.n + z.s
236.1903 -
236.1904 -Plugging that back into [6] gives
236.1905 -
236.1906 - diff =
236.1907 - x.n - ((x.n + z.s) - z.o) = expanding
236.1908 - x.n - x.n - z.s + z.o = cancelling
236.1909 - - z.s + z.o = by #2
236.1910 - z.d
236.1911 -
236.1912 -So diff = z.d.
236.1913 -
236.1914 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
236.1915 -spelling we wanted in the endcase described above. We're done. Contrarily,
236.1916 -if z.d = 0, then we have a UTC equivalent, and are also done.
236.1917 -
236.1918 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
236.1919 -add to z (in effect, z is in tz's standard time, and we need to shift the
236.1920 -local clock into tz's daylight time).
236.1921 -
236.1922 -Let
236.1923 -
236.1924 - z' = z + z.d = z + diff [7]
236.1925 -
236.1926 -and we can again ask whether
236.1927 -
236.1928 - z'.n - z'.o = x.n [8]
236.1929 -
236.1930 -If so, we're done. If not, the tzinfo class is insane, according to the
236.1931 -assumptions we've made. This also requires a bit of proof. As before, let's
236.1932 -compute the difference between the LHS and RHS of [8] (and skipping some of
236.1933 -the justifications for the kinds of substitutions we've done several times
236.1934 -already):
236.1935 -
236.1936 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
236.1937 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
236.1938 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
236.1939 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
236.1940 - - z.n + z.n - z.o + z'.o = cancel z.n
236.1941 - - z.o + z'.o = #1 twice
236.1942 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
236.1943 - z'.d - z.d
236.1944 -
236.1945 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
236.1946 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
236.1947 -return z', not bothering to compute z'.d.
236.1948 -
236.1949 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
236.1950 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
236.1951 -would have to change the result dst() returns: we start in DST, and moving
236.1952 -a little further into it takes us out of DST.
236.1953 -
236.1954 -There isn't a sane case where this can happen. The closest it gets is at
236.1955 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
236.1956 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
236.1957 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
236.1958 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
236.1959 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
236.1960 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
236.1961 -standard time. Since that's what the local clock *does*, we want to map both
236.1962 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
236.1963 -in local time, but so it goes -- it's the way the local clock works.
236.1964 -
236.1965 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
236.1966 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
236.1967 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
236.1968 -(correctly) concludes that z' is not UTC-equivalent to x.
236.1969 -
236.1970 -Because we know z.d said z was in daylight time (else [5] would have held and
236.1971 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
236.1972 -and we we have stopped then), and there are only 2 possible values dst() can
236.1973 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
236.1974 -but the reasoning doesn't depend on the example -- it depends on there being
236.1975 -two possible dst() outcomes, one zero and the other non-zero). Therefore
236.1976 -z' must be in standard time, and is the spelling we want in this case.
236.1977 -
236.1978 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
236.1979 -concerned (because it takes z' as being in standard time rather than the
236.1980 -daylight time we intend here), but returning it gives the real-life "local
236.1981 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
236.1982 -tz.
236.1983 -
236.1984 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
236.1985 -the 1:MM standard time spelling we want.
236.1986 -
236.1987 -So how can this break? One of the assumptions must be violated. Two
236.1988 -possibilities:
236.1989 -
236.1990 -1) [2] effectively says that y.s is invariant across all y belong to a given
236.1991 - time zone. This isn't true if, for political reasons or continental drift,
236.1992 - a region decides to change its base offset from UTC.
236.1993 -
236.1994 -2) There may be versions of "double daylight" time where the tail end of
236.1995 - the analysis gives up a step too early. I haven't thought about that
236.1996 - enough to say.
236.1997 -
236.1998 -In any case, it's clear that the default fromutc() is strong enough to handle
236.1999 -"almost all" time zones: so long as the standard offset is invariant, it
236.2000 -doesn't matter if daylight time transition points change from year to year, or
236.2001 -if daylight time is skipped in some years; it doesn't matter how large or
236.2002 -small dst() may get within its bounds; and it doesn't even matter if some
236.2003 -perverse time zone returns a negative dst()). So a breaking case must be
236.2004 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
236.2005 -"""
236.2006 -
236.2007 -def <FunctionDef>_test</FunctionDef>():
236.2008 - import test_datetime
236.2009 - <Attribute><Name>test_datetime</Name></Attribute>.<Call>test_main</Call>()
236.2010 -
236.2011 -if <Name>__name__</Name> == "__main__":
236.2012 - <Call><Name>_test</Name></Call>()
237.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.offsets Sun Jan 04 13:11:53 2015 -0600
237.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
237.3 @@ -1,2009 +0,0 @@
237.4 -
237.5 -<Module><Expr><Str>"""Concrete date/time and related types -- prototype implemented in Python.
237.6 -
237.7 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
237.8 -
237.9 -See also http://dir.yahoo.com/Reference/calendars/
237.10 -
237.11 -For a primer on DST, including many current DST rules, see
237.12 -http://webexhibits.org/daylightsaving/
237.13 -
237.14 -For more about DST than you ever wanted to know, see
237.15 -ftp://elsie.nci.nih.gov/pub/
237.16 -
237.17 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
237.18 -
237.19 -"""</Str></Expr>
237.20 -
237.21 -<Import>import time as _time</Import>
237.22 -<Import>import math as _math</Import>
237.23 -
237.24 -<Assign><Name>MINYEAR</Name> = <Num>1</Num></Assign>
237.25 -<Assign><Name>MAXYEAR</Name> = <Num>9999</Num></Assign>
237.26 -
237.27 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
237.28 -# also assumes the current Gregorian calendar indefinitely extended in
237.29 -# both directions. Difference: Dates.py calls January 1 of year 0 day
237.30 -# number 1. The code here calls January 1 of year 1 day number 1. This is
237.31 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
237.32 -# and Reingold's "Calendrical Calculations", where it's the base calendar
237.33 -# for all computations. See the book for algorithms for converting between
237.34 -# proleptic Gregorian ordinals and many other calendar systems.
237.35 -
237.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>
237.37 -
237.38 -<Assign><Name>_DAYS_BEFORE_MONTH</Name> = <List>[<Name>None</Name>]</List></Assign>
237.39 -<Assign><Name>dbm</Name> = <Num>0</Num></Assign>
237.40 -<For>for <Name>dim</Name> in <Subscript><Name>_DAYS_IN_MONTH</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript>:
237.41 - <Expr><Call><Attribute><Name>_DAYS_BEFORE_MONTH</Name>.append</Attribute>(<Name>dbm</Name>)</Call></Expr>
237.42 - <AugAssign><Name>dbm</Name> += <Name>dim</Name></AugAssign>
237.43 -</For><Delete>del <Name>dbm</Name>, <Name>dim</Name></Delete>
237.44 -
237.45 -<FunctionDef>def _is_leap(<Name>year</Name>):
237.46 - <Expr><Str>"year -> 1 if leap year, else 0."</Str></Expr>
237.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>
237.48 -
237.49 -</FunctionDef><FunctionDef>def _days_in_year(<Name>year</Name>):
237.50 - <Expr><Str>"year -> number of days in year (366 if a leap year, else 365)."</Str></Expr>
237.51 - <Return>return <BinOp><Num>365</Num> + <Call><Name>_is_leap</Name>(<Name>year</Name>)</Call></BinOp></Return>
237.52 -
237.53 -</FunctionDef><FunctionDef>def _days_before_year(<Name>year</Name>):
237.54 - <Expr><Str>"year -> number of days before January 1st of year."</Str></Expr>
237.55 - <Assign><Name>y</Name> = <BinOp><Name>year</Name> - <Num>1</Num></BinOp></Assign>
237.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>
237.57 -
237.58 -</FunctionDef><FunctionDef>def _days_in_month(<Name>year</Name>, <Name>month</Name>):
237.59 - <Expr><Str>"year, month -> number of days in that month in that year."</Str></Expr>
237.60 - <Assert>assert <Compare><Num>1</Num> <= <Name>month</Name> <= <Num>12</Num></Compare>, <Name>month</Name></Assert>
237.61 - <If>if <BoolOp><Compare><Name>month</Name> == <Num>2</Num></Compare> and <Call><Name>_is_leap</Name>(<Name>year</Name>)</Call></BoolOp>:
237.62 - <Return>return <Num>29</Num></Return>
237.63 - </If> <Return>return <Subscript><Name>_DAYS_IN_MONTH</Name>[<Index><Name>month</Name></Index>]</Subscript></Return>
237.64 -
237.65 -</FunctionDef><FunctionDef>def _days_before_month(<Name>year</Name>, <Name>month</Name>):
237.66 - <Expr><Str>"year, month -> number of days in year preceeding first day of month."</Str></Expr>
237.67 - <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>month</Name> <= <Num>12</Num></Compare></UnaryOp>:
237.68 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'month must be in 1..12'</Str>, <Name>month</Name>)</Call></Raise>
237.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>
237.70 -
237.71 -</FunctionDef><FunctionDef>def _ymd2ord(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>):
237.72 - <Expr><Str>"year, month, day -> ordinal, considering 01-Jan-0001 as day 1."</Str></Expr>
237.73 - <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>month</Name> <= <Num>12</Num></Compare></UnaryOp>:
237.74 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'month must be in 1..12'</Str>, <Name>month</Name>)</Call></Raise>
237.75 - </If> <Assign><Name>dim</Name> = <Call><Name>_days_in_month</Name>(<Name>year</Name>, <Name>month</Name>)</Call></Assign>
237.76 - <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>day</Name> <= <Name>dim</Name></Compare></UnaryOp>:
237.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>
237.78 - </If> <Return>return <BinOp>(<BinOp><Call><Name>_days_before_year</Name>(<Name>year</Name>)</Call></BinOp> +
237.79 - <Call><Name>_days_before_month</Name>(<Name>year</Name>, <Name>month</Name>)</Call> +
237.80 - <Name>day</Name>)</BinOp></Return>
237.81 -
237.82 -</FunctionDef><Assign><Name>_DI400Y</Name> = <Call><Name>_days_before_year</Name>(<Num>401</Num>)</Call></Assign> # number of days in 400 years
237.83 -<Assign><Name>_DI100Y</Name> = <Call><Name>_days_before_year</Name>(<Num>101</Num>)</Call></Assign> # " " " " 100 "
237.84 -<Assign><Name>_DI4Y</Name> = <Call><Name>_days_before_year</Name>(<Num>5</Num>)</Call></Assign> # " " " " 4 "
237.85 -
237.86 -# A 4-year cycle has an extra leap day over what we'd get from pasting
237.87 -# together 4 single years.
237.88 -<Assert>assert <Compare><Name>_DI4Y</Name> == <BinOp><BinOp><Num>4</Num></BinOp> * <Num>365</Num> + <Num>1</Num></BinOp></Compare></Assert>
237.89 -
237.90 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
237.91 -# pasting together 4 100-year cycles.
237.92 -<Assert>assert <Compare><Name>_DI400Y</Name> == <BinOp><BinOp><Num>4</Num></BinOp> * <Name>_DI100Y</Name> + <Num>1</Num></BinOp></Compare></Assert>
237.93 -
237.94 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
237.95 -# pasting together 25 4-year cycles.
237.96 -<Assert>assert <Compare><Name>_DI100Y</Name> == <BinOp><BinOp><Num>25</Num></BinOp> * <Name>_DI4Y</Name> - <Num>1</Num></BinOp></Compare></Assert>
237.97 -
237.98 -<FunctionDef>def _ord2ymd(<Name>n</Name>):
237.99 - <Expr><Str>"ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."</Str></Expr>
237.100 -
237.101 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
237.102 - # repeats exactly every 400 years. The basic strategy is to find the
237.103 - # closest 400-year boundary at or before n, then work with the offset
237.104 - # from that boundary to n. Life is much clearer if we subtract 1 from
237.105 - # n first -- then the values of n at 400-year boundaries are exactly
237.106 - # those divisible by _DI400Y:
237.107 - #
237.108 - # D M Y n n-1
237.109 - # -- --- ---- ---------- ----------------
237.110 - # 31 Dec -400 -_DI400Y -_DI400Y -1
237.111 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
237.112 - # ...
237.113 - # 30 Dec 000 -1 -2
237.114 - # 31 Dec 000 0 -1
237.115 - # 1 Jan 001 1 0 400-year boundary
237.116 - # 2 Jan 001 2 1
237.117 - # 3 Jan 001 3 2
237.118 - # ...
237.119 - # 31 Dec 400 _DI400Y _DI400Y -1
237.120 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
237.121 - <AugAssign><Name>n</Name> -= <Num>1</Num></AugAssign>
237.122 - <Assign><Tuple><Name>n400</Name>, <Name>n</Name></Tuple> = <Call><Name>divmod</Name>(<Name>n</Name>, <Name>_DI400Y</Name>)</Call></Assign>
237.123 - <Assign><Name>year</Name> = <BinOp><BinOp><Name>n400</Name></BinOp> * <Num>400</Num> + <Num>1</Num></BinOp></Assign> # ..., -399, 1, 401, ...
237.124 -
237.125 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
237.126 - # the desired date. Now compute how many 100-year cycles precede n.
237.127 - # Note that it's possible for n100 to equal 4! In that case 4 full
237.128 - # 100-year cycles precede the desired day, which implies the desired
237.129 - # day is December 31 at the end of a 400-year cycle.
237.130 - <Assign><Tuple><Name>n100</Name>, <Name>n</Name></Tuple> = <Call><Name>divmod</Name>(<Name>n</Name>, <Name>_DI100Y</Name>)</Call></Assign>
237.131 -
237.132 - # Now compute how many 4-year cycles precede it.
237.133 - <Assign><Tuple><Name>n4</Name>, <Name>n</Name></Tuple> = <Call><Name>divmod</Name>(<Name>n</Name>, <Name>_DI4Y</Name>)</Call></Assign>
237.134 -
237.135 - # And now how many single years. Again n1 can be 4, and again meaning
237.136 - # that the desired day is December 31 at the end of the 4-year cycle.
237.137 - <Assign><Tuple><Name>n1</Name>, <Name>n</Name></Tuple> = <Call><Name>divmod</Name>(<Name>n</Name>, <Num>365</Num>)</Call></Assign>
237.138 -
237.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>
237.140 - <If>if <BoolOp><Compare><Name>n1</Name> == <Num>4</Num></Compare> or <Compare><Name>n100</Name> == <Num>4</Num></Compare></BoolOp>:
237.141 - <Assert>assert <Compare><Name>n</Name> == <Num>0</Num></Compare></Assert>
237.142 - <Return>return <Tuple><BinOp><Name>year</Name>-<Num>1</Num></BinOp>, <Num>12</Num>, <Num>31</Num></Tuple></Return>
237.143 -
237.144 - # Now the year is correct, and n is the offset from January 1. We find
237.145 - # the month via an estimate that's either exact or one too large.
237.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>
237.147 - <Assert>assert <Compare><Name>leapyear</Name> == <Call><Name>_is_leap</Name>(<Name>year</Name>)</Call></Compare></Assert>
237.148 - <Assign><Name>month</Name> = <BinOp><BinOp>(<Name>n</Name> + <Num>50</Num>)</BinOp> >> <Num>5</Num></BinOp></Assign>
237.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>
237.150 - <If>if <Compare><Name>preceding</Name> > <Name>n</Name></Compare>: # estimate is too large
237.151 - <AugAssign><Name>month</Name> -= <Num>1</Num></AugAssign>
237.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>
237.153 - </If> <AugAssign><Name>n</Name> -= <Name>preceding</Name></AugAssign>
237.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>
237.155 -
237.156 - # Now the year and month are correct, and n is the offset from the
237.157 - # start of that month: we're done!
237.158 - <Return>return <Tuple><Name>year</Name>, <Name>month</Name>, <BinOp><Name>n</Name>+<Num>1</Num></BinOp></Tuple></Return>
237.159 -
237.160 -# Month and day names. For localized versions, see the calendar module.
237.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>,
237.162 - <Str>"Jul"</Str>, <Str>"Aug"</Str>, <Str>"Sep"</Str>, <Str>"Oct"</Str>, <Str>"Nov"</Str>, <Str>"Dec"</Str>]</List></Assign>
237.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>
237.164 -
237.165 -
237.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>):
237.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>
237.168 - <Assign><Name>dnum</Name> = <BinOp><Call><Name>_days_before_month</Name>(<Name>y</Name>, <Name>m</Name>)</Call> + <Name>d</Name></BinOp></Assign>
237.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>
237.170 -
237.171 -</FunctionDef><FunctionDef>def _format_time(<Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>us</Name>):
237.172 - # Skip trailing microseconds when us==0.
237.173 - <Assign><Name>result</Name> = <BinOp><Str>"%02d:%02d:%02d"</Str> % <Tuple>(<Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>)</Tuple></BinOp></Assign>
237.174 - <If>if <Name>us</Name>:
237.175 - <AugAssign><Name>result</Name> += <BinOp><Str>".%06d"</Str> % <Name>us</Name></BinOp></AugAssign>
237.176 - </If> <Return>return <Name>result</Name></Return>
237.177 -
237.178 -# Correctly substitute for %z and %Z escapes in strftime formats.
237.179 -</FunctionDef><FunctionDef>def _wrap_strftime(<Name>object</Name>, <Name>format</Name>, <Name>timetuple</Name>):
237.180 - <Assign><Name>year</Name> = <Subscript><Name>timetuple</Name>[<Index><Num>0</Num></Index>]</Subscript></Assign>
237.181 - <If>if <Compare><Name>year</Name> < <Num>1900</Num></Compare>:
237.182 - <Raise>raise <Call><Name>ValueError</Name>(<BinOp><Str>"year=%d is before 1900; the datetime strftime() "
237.183 - "methods require year >= 1900"</Str> % <Name>year</Name></BinOp>)</Call></Raise>
237.184 - # Don't call _utcoffset() or tzname() unless actually needed.
237.185 - </If> <Assign><Name>zreplace</Name> = <Name>None</Name></Assign> # the string to use for %z
237.186 - <Assign><Name>Zreplace</Name> = <Name>None</Name></Assign> # the string to use for %Z
237.187 -
237.188 - # Scan format for %z and %Z escapes, replacing as needed.
237.189 - <Assign><Name>newformat</Name> = <List>[]</List></Assign>
237.190 - <Assign><Name>push</Name> = <Attribute><Name>newformat</Name>.append</Attribute></Assign>
237.191 - <Assign><Tuple><Name>i</Name>, <Name>n</Name></Tuple> = <Tuple><Num>0</Num>, <Call><Name>len</Name>(<Name>format</Name>)</Call></Tuple></Assign>
237.192 - <While>while <Compare><Name>i</Name> < <Name>n</Name></Compare>:
237.193 - <Assign><Name>ch</Name> = <Subscript><Name>format</Name>[<Index><Name>i</Name></Index>]</Subscript></Assign>
237.194 - <AugAssign><Name>i</Name> += <Num>1</Num></AugAssign>
237.195 - <If>if <Compare><Name>ch</Name> == <Str>'%'</Str></Compare>:
237.196 - <If>if <Compare><Name>i</Name> < <Name>n</Name></Compare>:
237.197 - <Assign><Name>ch</Name> = <Subscript><Name>format</Name>[<Index><Name>i</Name></Index>]</Subscript></Assign>
237.198 - <AugAssign><Name>i</Name> += <Num>1</Num></AugAssign>
237.199 - <If>if <Compare><Name>ch</Name> == <Str>'z'</Str></Compare>:
237.200 - <If>if <Compare><Name>zreplace</Name> is <Name>None</Name></Compare>:
237.201 - <Assign><Name>zreplace</Name> = <Str>""</Str></Assign>
237.202 - <If>if <Call><Name>hasattr</Name>(<Name>object</Name>, <Str>"_utcoffset"</Str>)</Call>:
237.203 - <Assign><Name>offset</Name> = <Call><Attribute><Name>object</Name>._utcoffset</Attribute>()</Call></Assign>
237.204 - <If>if <Compare><Name>offset</Name> is not <Name>None</Name></Compare>:
237.205 - <Assign><Name>sign</Name> = <Str>'+'</Str></Assign>
237.206 - <If>if <Compare><Name>offset</Name> < <Num>0</Num></Compare>:
237.207 - <Assign><Name>offset</Name> = <UnaryOp>-<Name>offset</Name></UnaryOp></Assign>
237.208 - <Assign><Name>sign</Name> = <Str>'-'</Str></Assign>
237.209 - </If> <Assign><Tuple><Name>h</Name>, <Name>m</Name></Tuple> = <Call><Name>divmod</Name>(<Name>offset</Name>, <Num>60</Num>)</Call></Assign>
237.210 - <Assign><Name>zreplace</Name> = <BinOp><Str>'%c%02d%02d'</Str> % <Tuple>(<Name>sign</Name>, <Name>h</Name>, <Name>m</Name>)</Tuple></BinOp></Assign>
237.211 - </If></If></If> <Assert>assert <Compare><Str>'%'</Str> not in <Name>zreplace</Name></Compare></Assert>
237.212 - <Expr><Call><Attribute><Name>newformat</Name>.append</Attribute>(<Name>zreplace</Name>)</Call></Expr>
237.213 - <If>elif <Compare><Name>ch</Name> == <Str>'Z'</Str></Compare>:
237.214 - <If>if <Compare><Name>Zreplace</Name> is <Name>None</Name></Compare>:
237.215 - <Assign><Name>Zreplace</Name> = <Str>""</Str></Assign>
237.216 - <If>if <Call><Name>hasattr</Name>(<Name>object</Name>, <Str>"tzname"</Str>)</Call>:
237.217 - <Assign><Name>s</Name> = <Call><Attribute><Name>object</Name>.tzname</Attribute>()</Call></Assign>
237.218 - <If>if <Compare><Name>s</Name> is not <Name>None</Name></Compare>:
237.219 - # strftime is going to have at this: escape %
237.220 - <Assign><Name>Zreplace</Name> = <Call><Attribute><Name>s</Name>.replace</Attribute>(<Str>'%'</Str>, <Str>'%%'</Str>)</Call></Assign>
237.221 - </If></If></If> <Expr><Call><Attribute><Name>newformat</Name>.append</Attribute>(<Name>Zreplace</Name>)</Call></Expr>
237.222 - else:
237.223 - <Expr><Call><Name>push</Name>(<Str>'%'</Str>)</Call></Expr>
237.224 - <Expr><Call><Name>push</Name>(<Name>ch</Name>)</Call></Expr>
237.225 - </If></If> else:
237.226 - <Expr><Call><Name>push</Name>(<Str>'%'</Str>)</Call></Expr>
237.227 - </If> else:
237.228 - <Expr><Call><Name>push</Name>(<Name>ch</Name>)</Call></Expr>
237.229 - </If></While> <Assign><Name>newformat</Name> = <Call><Attribute><Str>""</Str>.join</Attribute>(<Name>newformat</Name>)</Call></Assign>
237.230 - <Return>return <Call><Attribute><Name>_time</Name>.strftime</Attribute>(<Name>newformat</Name>, <Name>timetuple</Name>)</Call></Return>
237.231 -
237.232 -</FunctionDef><FunctionDef>def _call_tzinfo_method(<Name>tzinfo</Name>, <Name>methname</Name>, <Name>tzinfoarg</Name>):
237.233 - <If>if <Compare><Name>tzinfo</Name> is <Name>None</Name></Compare>:
237.234 - <Return>return <Name>None</Name></Return>
237.235 - </If> <Return>return <Call><Name>getattr</Name><Call>(<Name>tzinfo</Name>, <Name>methname</Name>)</Call>(<Name>tzinfoarg</Name>)</Call></Return>
237.236 -
237.237 -# Just raise TypeError if the arg isn't None or a string.
237.238 -</FunctionDef><FunctionDef>def _check_tzname(<Name>name</Name>):
237.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>:
237.240 - <Raise>raise <Call><Name>TypeError</Name>(<BinOp><Str>"tzinfo.tzname() must return None or string, "
237.241 - "not '%s'"</Str> % <Call><Name>type</Name>(<Name>name</Name>)</Call></BinOp>)</Call></Raise>
237.242 -
237.243 -# name is the offset-producing method, "utcoffset" or "dst".
237.244 -# offset is what it returned.
237.245 -# If offset isn't None or timedelta, raises TypeError.
237.246 -# If offset is None, returns None.
237.247 -# Else offset is checked for being in range, and a whole # of minutes.
237.248 -# If it is, its integer value is returned. Else ValueError is raised.
237.249 -</If></FunctionDef><FunctionDef>def _check_utc_offset(<Name>name</Name>, <Name>offset</Name>):
237.250 - <Assert>assert <Compare><Name>name</Name> in <Tuple>(<Str>"utcoffset"</Str>, <Str>"dst"</Str>)</Tuple></Compare></Assert>
237.251 - <If>if <Compare><Name>offset</Name> is <Name>None</Name></Compare>:
237.252 - <Return>return <Name>None</Name></Return>
237.253 - </If> <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>offset</Name>, <Name>timedelta</Name>)</Call></UnaryOp>:
237.254 - <Raise>raise <Call><Name>TypeError</Name>(<BinOp><Str>"tzinfo.%s() must return None "
237.255 - "or timedelta, not '%s'"</Str> % <Tuple>(<Name>name</Name>, <Call><Name>type</Name>(<Name>offset</Name>)</Call>)</Tuple></BinOp>)</Call></Raise>
237.256 - </If> <Assign><Name>days</Name> = <Attribute><Name>offset</Name>.days</Attribute></Assign>
237.257 - <If>if <BoolOp><Compare><Name>days</Name> < <Num>-1</Num></Compare> or <Compare><Name>days</Name> > <Num>0</Num></Compare></BoolOp>:
237.258 - <Assign><Name>offset</Name> = <Num>1440</Num></Assign> # trigger out-of-range
237.259 - else:
237.260 - <Assign><Name>seconds</Name> = <BinOp><BinOp><Name>days</Name></BinOp> * <Num>86400</Num> + <Attribute><Name>offset</Name>.seconds</Attribute></BinOp></Assign>
237.261 - <Assign><Tuple><Name>minutes</Name>, <Name>seconds</Name></Tuple> = <Call><Name>divmod</Name>(<Name>seconds</Name>, <Num>60</Num>)</Call></Assign>
237.262 - <If>if <BoolOp><Name>seconds</Name> or <Attribute><Name>offset</Name>.microseconds</Attribute></BoolOp>:
237.263 - <Raise>raise <Call><Name>ValueError</Name>(<BinOp><Str>"tzinfo.%s() must return a whole number "
237.264 - "of minutes"</Str> % <Name>name</Name></BinOp>)</Call></Raise>
237.265 - </If> <Assign><Name>offset</Name> = <Name>minutes</Name></Assign>
237.266 - </If> <If>if <Compare><Num>-1440</Num> < <Name>offset</Name> < <Num>1440</Num></Compare>:
237.267 - <Return>return <Name>offset</Name></Return>
237.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>
237.269 -
237.270 -</FunctionDef><FunctionDef>def _check_date_fields(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>):
237.271 - <If>if <UnaryOp>not <Compare><Name>MINYEAR</Name> <= <Name>year</Name> <= <Name>MAXYEAR</Name></Compare></UnaryOp>:
237.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>
237.273 - </If> <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>month</Name> <= <Num>12</Num></Compare></UnaryOp>:
237.274 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'month must be in 1..12'</Str>, <Name>month</Name>)</Call></Raise>
237.275 - </If> <Assign><Name>dim</Name> = <Call><Name>_days_in_month</Name>(<Name>year</Name>, <Name>month</Name>)</Call></Assign>
237.276 - <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>day</Name> <= <Name>dim</Name></Compare></UnaryOp>:
237.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>
237.278 -
237.279 -</If></FunctionDef><FunctionDef>def _check_time_fields(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>):
237.280 - <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>hour</Name> <= <Num>23</Num></Compare></UnaryOp>:
237.281 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'hour must be in 0..23'</Str>, <Name>hour</Name>)</Call></Raise>
237.282 - </If> <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>minute</Name> <= <Num>59</Num></Compare></UnaryOp>:
237.283 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'minute must be in 0..59'</Str>, <Name>minute</Name>)</Call></Raise>
237.284 - </If> <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>second</Name> <= <Num>59</Num></Compare></UnaryOp>:
237.285 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'second must be in 0..59'</Str>, <Name>second</Name>)</Call></Raise>
237.286 - </If> <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>microsecond</Name> <= <Num>999999</Num></Compare></UnaryOp>:
237.287 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'microsecond must be in 0..999999'</Str>, <Name>microsecond</Name>)</Call></Raise>
237.288 -
237.289 -</If></FunctionDef><FunctionDef>def _check_tzinfo_arg(<Name>tz</Name>):
237.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>:
237.291 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"tzinfo argument must be None or of a tzinfo subclass"</Str>)</Call></Raise>
237.292 -
237.293 -
237.294 -# Notes on comparison: In general, datetime module comparison operators raise
237.295 -# TypeError when they don't know how to do a comparison themself. If they
237.296 -# returned NotImplemented instead, comparison could (silently) fall back to
237.297 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
237.298 -# and that's not helpful. There are two exceptions:
237.299 -#
237.300 -# 1. For date and datetime, if the other object has a "timetuple" attr,
237.301 -# NotImplemented is returned. This is a hook to allow other kinds of
237.302 -# datetime-like objects a chance to intercept the comparison.
237.303 -#
237.304 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
237.305 -# so opertaions like
237.306 -#
237.307 -# x == y
237.308 -# x != y
237.309 -# x in sequence
237.310 -# x not in sequence
237.311 -# dict[x] = y
237.312 -#
237.313 -# don't raise annoying TypeErrors just because a datetime object
237.314 -# is part of a heterogeneous collection. If there's no known way to
237.315 -# compare X to a datetime, saying they're not equal is reasonable.
237.316 -
237.317 -</If></FunctionDef><FunctionDef>def _cmperror(<Name>x</Name>, <Name>y</Name>):
237.318 - <Raise>raise <Call><Name>TypeError</Name>(<BinOp><Str>"can't compare '%s' to '%s'"</Str> % <Tuple>(
237.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>
237.320 -
237.321 -# This is a start at a struct tm workalike. Goals:
237.322 -#
237.323 -# + Works the same way across platforms.
237.324 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
237.325 -#
237.326 -# Note: I suspect it's best if this flavor of tm does *not* try to
237.327 -# second-guess timezones or DST. Instead fold whatever adjustments you want
237.328 -# into the minutes argument (and the constructor will normalize).
237.329 -
237.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
237.331 -
237.332 -<ClassDef>class tmxxx:
237.333 -
237.334 - <Assign><Name>ordinal</Name> = <Name>None</Name></Assign>
237.335 -
237.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>,
237.337 - <Name>microsecond</Name>=<Num>0</Num>):
237.338 - # Normalize all the inputs, and store the normalized values.
237.339 - <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>microsecond</Name> <= <Num>999999</Num></Compare></UnaryOp>:
237.340 - <Assign><Tuple><Name>carry</Name>, <Name>microsecond</Name></Tuple> = <Call><Name>divmod</Name>(<Name>microsecond</Name>, <Num>1000000</Num>)</Call></Assign>
237.341 - <AugAssign><Name>second</Name> += <Name>carry</Name></AugAssign>
237.342 - </If> <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>second</Name> <= <Num>59</Num></Compare></UnaryOp>:
237.343 - <Assign><Tuple><Name>carry</Name>, <Name>second</Name></Tuple> = <Call><Name>divmod</Name>(<Name>second</Name>, <Num>60</Num>)</Call></Assign>
237.344 - <AugAssign><Name>minute</Name> += <Name>carry</Name></AugAssign>
237.345 - </If> <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>minute</Name> <= <Num>59</Num></Compare></UnaryOp>:
237.346 - <Assign><Tuple><Name>carry</Name>, <Name>minute</Name></Tuple> = <Call><Name>divmod</Name>(<Name>minute</Name>, <Num>60</Num>)</Call></Assign>
237.347 - <AugAssign><Name>hour</Name> += <Name>carry</Name></AugAssign>
237.348 - </If> <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>hour</Name> <= <Num>23</Num></Compare></UnaryOp>:
237.349 - <Assign><Tuple><Name>carry</Name>, <Name>hour</Name></Tuple> = <Call><Name>divmod</Name>(<Name>hour</Name>, <Num>24</Num>)</Call></Assign>
237.350 - <AugAssign><Name>day</Name> += <Name>carry</Name></AugAssign>
237.351 -
237.352 - # That was easy. Now it gets muddy: the proper range for day
237.353 - # can't be determined without knowing the correct month and year,
237.354 - # but if day is, e.g., plus or minus a million, the current month
237.355 - # and year values make no sense (and may also be out of bounds
237.356 - # themselves).
237.357 - # Saying 12 months == 1 year should be non-controversial.
237.358 - </If> <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>month</Name> <= <Num>12</Num></Compare></UnaryOp>:
237.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>
237.360 - <AugAssign><Name>year</Name> += <Name>carry</Name></AugAssign>
237.361 - <AugAssign><Name>month</Name> += <Num>1</Num></AugAssign>
237.362 - <Assert>assert <Compare><Num>1</Num> <= <Name>month</Name> <= <Num>12</Num></Compare></Assert>
237.363 -
237.364 - # Now only day can be out of bounds (year may also be out of bounds
237.365 - # for a datetime object, but we don't care about that here).
237.366 - # If day is out of bounds, what to do is arguable, but at least the
237.367 - # method here is principled and explainable.
237.368 - </If> <Assign><Name>dim</Name> = <Call><Name>_days_in_month</Name>(<Name>year</Name>, <Name>month</Name>)</Call></Assign>
237.369 - <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>day</Name> <= <Name>dim</Name></Compare></UnaryOp>:
237.370 - # Move day-1 days from the first of the month. First try to
237.371 - # get off cheap if we're only one day out of range (adjustments
237.372 - # for timezone alone can't be worse than that).
237.373 - <If>if <Compare><Name>day</Name> == <Num>0</Num></Compare>: # move back a day
237.374 - <AugAssign><Name>month</Name> -= <Num>1</Num></AugAssign>
237.375 - <If>if <Compare><Name>month</Name> > <Num>0</Num></Compare>:
237.376 - <Assign><Name>day</Name> = <Call><Name>_days_in_month</Name>(<Name>year</Name>, <Name>month</Name>)</Call></Assign>
237.377 - else:
237.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>
237.379 - </If> <If>elif <Compare><Name>day</Name> == <BinOp><Name>dim</Name> + <Num>1</Num></BinOp></Compare>: # move forward a day
237.380 - <AugAssign><Name>month</Name> += <Num>1</Num></AugAssign>
237.381 - <Assign><Name>day</Name> = <Num>1</Num></Assign>
237.382 - <If>if <Compare><Name>month</Name> > <Num>12</Num></Compare>:
237.383 - <Assign><Name>month</Name> = <Num>1</Num></Assign>
237.384 - <AugAssign><Name>year</Name> += <Num>1</Num></AugAssign>
237.385 - </If> else:
237.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>
237.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>
237.388 -
237.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>
237.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>
237.391 - <Assign><Attribute><Name>self</Name>.microsecond</Attribute> = <Name>microsecond</Name></Assign>
237.392 -
237.393 - </FunctionDef> <FunctionDef>def toordinal(<Name>self</Name>):
237.394 - <Expr><Str>"""Return proleptic Gregorian ordinal for the year, month and day.
237.395 -
237.396 - January 1 of year 1 is day 1. Only the year, month and day values
237.397 - contribute to the result.
237.398 - """</Str></Expr>
237.399 - <If>if <Compare><Attribute><Name>self</Name>.ordinal</Attribute> is <Name>None</Name></Compare>:
237.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>
237.401 - </If> <Return>return <Attribute><Name>self</Name>.ordinal</Attribute></Return>
237.402 -
237.403 - </FunctionDef> <FunctionDef>def time(<Name>self</Name>):
237.404 - <Expr><Str>"Return Unixish timestamp, as a float (assuming UTC)."</Str></Expr>
237.405 - <Assign><Name>days</Name> = <BinOp><Call><Attribute><Name>self</Name>.toordinal</Attribute>()</Call> - <Name>_ORD1970</Name></BinOp></Assign> # convert to UNIX epoch
237.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>
237.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>
237.408 -
237.409 - </FunctionDef> <FunctionDef>def ctime(<Name>self</Name>):
237.410 - <Expr><Str>"Return ctime() style string."</Str></Expr>
237.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>
237.412 - <Return>return <BinOp><Str>"%s %s %2d %02d:%02d:%02d %04d"</Str> % <Tuple>(
237.413 - <Subscript><Name>_DAYNAMES</Name>[<Index><Name>weekday</Name></Index>]</Subscript>,
237.414 - <Subscript><Name>_MONTHNAMES</Name>[<Index><Attribute><Name>self</Name>.month</Attribute></Index>]</Subscript>,
237.415 - <Attribute><Name>self</Name>.day</Attribute>,
237.416 - <Attribute><Name>self</Name>.hour</Attribute>, <Attribute><Name>self</Name>.minute</Attribute>, <Attribute><Name>self</Name>.second</Attribute>,
237.417 - <Attribute><Name>self</Name>.year</Attribute>)</Tuple></BinOp></Return>
237.418 -
237.419 -</FunctionDef></ClassDef><ClassDef>class timedelta(<Name>object</Name>):
237.420 - <Expr><Str>"""Represent the difference between two datetime objects.
237.421 -
237.422 - Supported operators:
237.423 -
237.424 - - add, subtract timedelta
237.425 - - unary plus, minus, abs
237.426 - - compare to timedelta
237.427 - - multiply, divide by int/long
237.428 -
237.429 - In addition, datetime supports subtraction of two datetime objects
237.430 - returning a timedelta, and addition or subtraction of a datetime
237.431 - and a timedelta giving a datetime.
237.432 -
237.433 - Representation: (days, seconds, microseconds). Why? Because I
237.434 - felt like it.
237.435 - """</Str></Expr>
237.436 -
237.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>,
237.438 - # XXX The following should only be used as keyword args:
237.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>):
237.440 - # Doing this efficiently and accurately in C is going to be difficult
237.441 - # and error-prone, due to ubiquitous overflow possibilities, and that
237.442 - # C double doesn't have enough bits of precision to represent
237.443 - # microseconds over 10K years faithfully. The code here tries to make
237.444 - # explicit where go-fast assumptions can be relied on, in order to
237.445 - # guide the C implementation; it's way more convoluted than speed-
237.446 - # ignoring auto-overflow-to-long idiomatic Python could be.
237.447 -
237.448 - # XXX Check that all inputs are ints, longs or floats.
237.449 -
237.450 - # Final values, all integer.
237.451 - # s and us fit in 32-bit signed ints; d isn't bounded.
237.452 - <Assign><Name>d</Name> = <Name>s</Name> = <Name>us</Name> = <Num>0</Num></Assign>
237.453 -
237.454 - # Normalize everything to days, seconds, microseconds.
237.455 - <AugAssign><Name>days</Name> += <BinOp><Name>weeks</Name>*<Num>7</Num></BinOp></AugAssign>
237.456 - <AugAssign><Name>seconds</Name> += <BinOp><BinOp><Name>minutes</Name></BinOp>*<Num>60</Num> + <BinOp><Name>hours</Name></BinOp>*<Num>3600</Num></BinOp></AugAssign>
237.457 - <AugAssign><Name>microseconds</Name> += <BinOp><Name>milliseconds</Name>*<Num>1000</Num></BinOp></AugAssign>
237.458 -
237.459 - # Get rid of all fractions, and normalize s and us.
237.460 - # Take a deep breath <wink>.
237.461 - <If>if <Call><Name>isinstance</Name>(<Name>days</Name>, <Name>float</Name>)</Call>:
237.462 - <Assign><Tuple><Name>dayfrac</Name>, <Name>days</Name></Tuple> = <Call><Attribute><Name>_math</Name>.modf</Attribute>(<Name>days</Name>)</Call></Assign>
237.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>
237.464 - <Assert>assert <Compare><Name>daysecondswhole</Name> == <Call><Name>int</Name>(<Name>daysecondswhole</Name>)</Call></Compare></Assert> # can't overflow
237.465 - <Assign><Name>s</Name> = <Call><Name>int</Name>(<Name>daysecondswhole</Name>)</Call></Assign>
237.466 - <Assert>assert <Compare><Name>days</Name> == <Call><Name>long</Name>(<Name>days</Name>)</Call></Compare></Assert>
237.467 - <Assign><Name>d</Name> = <Call><Name>long</Name>(<Name>days</Name>)</Call></Assign>
237.468 - else:
237.469 - <Assign><Name>daysecondsfrac</Name> = <Num>0.0</Num></Assign>
237.470 - <Assign><Name>d</Name> = <Name>days</Name></Assign>
237.471 - </If> <Assert>assert <Call><Name>isinstance</Name>(<Name>daysecondsfrac</Name>, <Name>float</Name>)</Call></Assert>
237.472 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>daysecondsfrac</Name>)</Call> <= <Num>1.0</Num></Compare></Assert>
237.473 - <Assert>assert <Call><Name>isinstance</Name>(<Name>d</Name>, <Tuple>(<Name>int</Name>, <Name>long</Name>)</Tuple>)</Call></Assert>
237.474 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>s</Name>)</Call> <= <BinOp><Num>24</Num> * <Num>3600</Num></BinOp></Compare></Assert>
237.475 - # days isn't referenced again before redefinition
237.476 -
237.477 - <If>if <Call><Name>isinstance</Name>(<Name>seconds</Name>, <Name>float</Name>)</Call>:
237.478 - <Assign><Tuple><Name>secondsfrac</Name>, <Name>seconds</Name></Tuple> = <Call><Attribute><Name>_math</Name>.modf</Attribute>(<Name>seconds</Name>)</Call></Assign>
237.479 - <Assert>assert <Compare><Name>seconds</Name> == <Call><Name>long</Name>(<Name>seconds</Name>)</Call></Compare></Assert>
237.480 - <Assign><Name>seconds</Name> = <Call><Name>long</Name>(<Name>seconds</Name>)</Call></Assign>
237.481 - <AugAssign><Name>secondsfrac</Name> += <Name>daysecondsfrac</Name></AugAssign>
237.482 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>secondsfrac</Name>)</Call> <= <Num>2.0</Num></Compare></Assert>
237.483 - else:
237.484 - <Assign><Name>secondsfrac</Name> = <Name>daysecondsfrac</Name></Assign>
237.485 - # daysecondsfrac isn't referenced again
237.486 - </If> <Assert>assert <Call><Name>isinstance</Name>(<Name>secondsfrac</Name>, <Name>float</Name>)</Call></Assert>
237.487 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>secondsfrac</Name>)</Call> <= <Num>2.0</Num></Compare></Assert>
237.488 -
237.489 - <Assert>assert <Call><Name>isinstance</Name>(<Name>seconds</Name>, <Tuple>(<Name>int</Name>, <Name>long</Name>)</Tuple>)</Call></Assert>
237.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>
237.491 - <AugAssign><Name>d</Name> += <Name>days</Name></AugAssign>
237.492 - <AugAssign><Name>s</Name> += <Call><Name>int</Name>(<Name>seconds</Name>)</Call></AugAssign> # can't overflow
237.493 - <Assert>assert <Call><Name>isinstance</Name>(<Name>s</Name>, <Name>int</Name>)</Call></Assert>
237.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>
237.495 - # seconds isn't referenced again before redefinition
237.496 -
237.497 - <Assign><Name>usdouble</Name> = <BinOp><Name>secondsfrac</Name> * <Num>1e6</Num></BinOp></Assign>
237.498 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>usdouble</Name>)</Call> < <Num>2.1e6</Num></Compare></Assert> # exact value not critical
237.499 - # secondsfrac isn't referenced again
237.500 -
237.501 - <If>if <Call><Name>isinstance</Name>(<Name>microseconds</Name>, <Name>float</Name>)</Call>:
237.502 - <AugAssign><Name>microseconds</Name> += <Name>usdouble</Name></AugAssign>
237.503 - <Assign><Name>microseconds</Name> = <Call><Name>round</Name>(<Name>microseconds</Name>)</Call></Assign>
237.504 - <Assign><Tuple><Name>seconds</Name>, <Name>microseconds</Name></Tuple> = <Call><Name>divmod</Name>(<Name>microseconds</Name>, <Num>1e6</Num>)</Call></Assign>
237.505 - <Assert>assert <Compare><Name>microseconds</Name> == <Call><Name>int</Name>(<Name>microseconds</Name>)</Call></Compare></Assert>
237.506 - <Assert>assert <Compare><Name>seconds</Name> == <Call><Name>long</Name>(<Name>seconds</Name>)</Call></Compare></Assert>
237.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>
237.508 - <Assert>assert <Compare><Name>days</Name> == <Call><Name>long</Name>(<Name>days</Name>)</Call></Compare></Assert>
237.509 - <Assert>assert <Compare><Name>seconds</Name> == <Call><Name>int</Name>(<Name>seconds</Name>)</Call></Compare></Assert>
237.510 - <AugAssign><Name>d</Name> += <Call><Name>long</Name>(<Name>days</Name>)</Call></AugAssign>
237.511 - <AugAssign><Name>s</Name> += <Call><Name>int</Name>(<Name>seconds</Name>)</Call></AugAssign> # can't overflow
237.512 - <Assert>assert <Call><Name>isinstance</Name>(<Name>s</Name>, <Name>int</Name>)</Call></Assert>
237.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>
237.514 - else:
237.515 - <Assign><Tuple><Name>seconds</Name>, <Name>microseconds</Name></Tuple> = <Call><Name>divmod</Name>(<Name>microseconds</Name>, <Num>1000000</Num>)</Call></Assign>
237.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>
237.517 - <AugAssign><Name>d</Name> += <Name>days</Name></AugAssign>
237.518 - <AugAssign><Name>s</Name> += <Call><Name>int</Name>(<Name>seconds</Name>)</Call></AugAssign> # can't overflow
237.519 - <Assert>assert <Call><Name>isinstance</Name>(<Name>s</Name>, <Name>int</Name>)</Call></Assert>
237.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>
237.521 - <Assign><Name>microseconds</Name> = <Call><Name>float</Name>(<Name>microseconds</Name>)</Call></Assign>
237.522 - <AugAssign><Name>microseconds</Name> += <Name>usdouble</Name></AugAssign>
237.523 - <Assign><Name>microseconds</Name> = <Call><Name>round</Name>(<Name>microseconds</Name>)</Call></Assign>
237.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>
237.525 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>microseconds</Name>)</Call> < <Num>3.1e6</Num></Compare></Assert>
237.526 -
237.527 - # Just a little bit of carrying possible for microseconds and seconds.
237.528 - <Assert>assert <Call><Name>isinstance</Name>(<Name>microseconds</Name>, <Name>float</Name>)</Call></Assert>
237.529 - <Assert>assert <Compare><Call><Name>int</Name>(<Name>microseconds</Name>)</Call> == <Name>microseconds</Name></Compare></Assert>
237.530 - <Assign><Name>us</Name> = <Call><Name>int</Name>(<Name>microseconds</Name>)</Call></Assign>
237.531 - <Assign><Tuple><Name>seconds</Name>, <Name>us</Name></Tuple> = <Call><Name>divmod</Name>(<Name>us</Name>, <Num>1000000</Num>)</Call></Assign>
237.532 - <AugAssign><Name>s</Name> += <Name>seconds</Name></AugAssign> # cant't overflow
237.533 - <Assert>assert <Call><Name>isinstance</Name>(<Name>s</Name>, <Name>int</Name>)</Call></Assert>
237.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>
237.535 - <AugAssign><Name>d</Name> += <Name>days</Name></AugAssign>
237.536 -
237.537 - <Assert>assert <Call><Name>isinstance</Name>(<Name>d</Name>, <Tuple>(<Name>int</Name>, <Name>long</Name>)</Tuple>)</Call></Assert>
237.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>
237.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>
237.540 -
237.541 - <Assign><Name>self</Name> = <Call><Attribute><Name>object</Name>.__new__</Attribute>(<Name>cls</Name>)</Call></Assign>
237.542 -
237.543 - <Assign><Attribute><Name>self</Name>.__days</Attribute> = <Name>d</Name></Assign>
237.544 - <Assign><Attribute><Name>self</Name>.__seconds</Attribute> = <Name>s</Name></Assign>
237.545 - <Assign><Attribute><Name>self</Name>.__microseconds</Attribute> = <Name>us</Name></Assign>
237.546 - <If>if <Compare><Call><Name>abs</Name>(<Name>d</Name>)</Call> > <Num>999999999</Num></Compare>:
237.547 - <Raise>raise <Call><Name>OverflowError</Name>(<BinOp><Str>"timedelta # of days is too large: %d"</Str> % <Name>d</Name></BinOp>)</Call></Raise>
237.548 -
237.549 - </If> <Return>return <Name>self</Name></Return>
237.550 -
237.551 - </FunctionDef> <FunctionDef>def __repr__(<Name>self</Name>):
237.552 - <If>if <Attribute><Name>self</Name>.__microseconds</Attribute>:
237.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>,
237.554 - <Attribute><Name>self</Name>.__days</Attribute>,
237.555 - <Attribute><Name>self</Name>.__seconds</Attribute>,
237.556 - <Attribute><Name>self</Name>.__microseconds</Attribute>)</Tuple></BinOp></Return>
237.557 - </If> <If>if <Attribute><Name>self</Name>.__seconds</Attribute>:
237.558 - <Return>return <BinOp><Str>"%s(%d, %d)"</Str> % <Tuple>(<BinOp><Str>'datetime.'</Str> + <Attribute><Attribute><Name>self</Name>.__class__</Attribute>.__name__</Attribute></BinOp>,
237.559 - <Attribute><Name>self</Name>.__days</Attribute>,
237.560 - <Attribute><Name>self</Name>.__seconds</Attribute>)</Tuple></BinOp></Return>
237.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>
237.562 -
237.563 - </FunctionDef> <FunctionDef>def __str__(<Name>self</Name>):
237.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>
237.565 - <Assign><Tuple><Name>hh</Name>, <Name>mm</Name></Tuple> = <Call><Name>divmod</Name>(<Name>mm</Name>, <Num>60</Num>)</Call></Assign>
237.566 - <Assign><Name>s</Name> = <BinOp><Str>"%d:%02d:%02d"</Str> % <Tuple>(<Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>)</Tuple></BinOp></Assign>
237.567 - <If>if <Attribute><Name>self</Name>.__days</Attribute>:
237.568 - <FunctionDef>def plural(<Name>n</Name>):
237.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>
237.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>
237.571 - </If> <If>if <Attribute><Name>self</Name>.__microseconds</Attribute>:
237.572 - <Assign><Name>s</Name> = <BinOp><Name>s</Name> + <BinOp><Str>".%06d"</Str></BinOp> % <Attribute><Name>self</Name>.__microseconds</Attribute></BinOp></Assign>
237.573 - </If> <Return>return <Name>s</Name></Return>
237.574 -
237.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>
237.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>
237.577 - <Assign><Name>microseconds</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__microseconds</Attribute></Lambda>,
237.578 - doc=<Str>"microseconds"</Str>)</Call></Assign>
237.579 -
237.580 - <FunctionDef>def __add__(<Name>self</Name>, <Name>other</Name>):
237.581 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
237.582 - <Return>return <Call><Name>timedelta</Name>(<BinOp><Attribute><Name>self</Name>.__days</Attribute> + <Attribute><Name>other</Name>.__days</Attribute></BinOp>,
237.583 - <BinOp><Attribute><Name>self</Name>.__seconds</Attribute> + <Attribute><Name>other</Name>.__seconds</Attribute></BinOp>,
237.584 - <BinOp><Attribute><Name>self</Name>.__microseconds</Attribute> + <Attribute><Name>other</Name>.__microseconds</Attribute></BinOp>)</Call></Return>
237.585 - </If> <Return>return <Name>NotImplemented</Name></Return>
237.586 -
237.587 - </FunctionDef> <Assign><Name>__radd__</Name> = <Name>__add__</Name></Assign>
237.588 -
237.589 - <FunctionDef>def __sub__(<Name>self</Name>, <Name>other</Name>):
237.590 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
237.591 - <Return>return <BinOp><Name>self</Name> + <UnaryOp>-<Name>other</Name></UnaryOp></BinOp></Return>
237.592 - </If> <Return>return <Name>NotImplemented</Name></Return>
237.593 -
237.594 - </FunctionDef> <FunctionDef>def __rsub__(<Name>self</Name>, <Name>other</Name>):
237.595 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
237.596 - <Return>return <BinOp><UnaryOp>-<Name>self</Name></UnaryOp> + <Name>other</Name></BinOp></Return>
237.597 - </If> <Return>return <Name>NotImplemented</Name></Return>
237.598 -
237.599 - </FunctionDef> <FunctionDef>def __neg__(<Name>self</Name>):
237.600 - <Return>return <Call><Attribute><Name>self</Name>.__class__</Attribute>(<UnaryOp>-<Attribute><Name>self</Name>.__days</Attribute></UnaryOp>,
237.601 - <UnaryOp>-<Attribute><Name>self</Name>.__seconds</Attribute></UnaryOp>,
237.602 - <UnaryOp>-<Attribute><Name>self</Name>.__microseconds</Attribute></UnaryOp>)</Call></Return>
237.603 -
237.604 - </FunctionDef> <FunctionDef>def __pos__(<Name>self</Name>):
237.605 - <Return>return <Name>self</Name></Return>
237.606 -
237.607 - </FunctionDef> <FunctionDef>def __abs__(<Name>self</Name>):
237.608 - <If>if <Compare><Attribute><Name>self</Name>.__days</Attribute> < <Num>0</Num></Compare>:
237.609 - <Return>return <UnaryOp>-<Name>self</Name></UnaryOp></Return>
237.610 - else:
237.611 - <Return>return <Name>self</Name></Return>
237.612 -
237.613 - </If></FunctionDef> <FunctionDef>def __mul__(<Name>self</Name>, <Name>other</Name>):
237.614 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Tuple>(<Name>int</Name>, <Name>long</Name>)</Tuple>)</Call>:
237.615 - <Return>return <Call><Attribute><Name>self</Name>.__class__</Attribute>(<BinOp><Attribute><Name>self</Name>.__days</Attribute> * <Name>other</Name></BinOp>,
237.616 - <BinOp><Attribute><Name>self</Name>.__seconds</Attribute> * <Name>other</Name></BinOp>,
237.617 - <BinOp><Attribute><Name>self</Name>.__microseconds</Attribute> * <Name>other</Name></BinOp>)</Call></Return>
237.618 - </If> <Return>return <Name>NotImplemented</Name></Return>
237.619 -
237.620 - </FunctionDef> <Assign><Name>__rmul__</Name> = <Name>__mul__</Name></Assign>
237.621 -
237.622 - <FunctionDef>def __div__(<Name>self</Name>, <Name>other</Name>):
237.623 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Tuple>(<Name>int</Name>, <Name>long</Name>)</Tuple>)</Call>:
237.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> +
237.625 - <Attribute><Name>self</Name>.__microseconds</Attribute>)</BinOp></Assign>
237.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>
237.627 - </If> <Return>return <Name>NotImplemented</Name></Return>
237.628 -
237.629 - </FunctionDef> <Assign><Name>__floordiv__</Name> = <Name>__div__</Name></Assign>
237.630 -
237.631 - # Comparisons.
237.632 -
237.633 - <FunctionDef>def __eq__(<Name>self</Name>, <Name>other</Name>):
237.634 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
237.635 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> == <Num>0</Num></Compare></Return>
237.636 - else:
237.637 - <Return>return <Name>False</Name></Return>
237.638 -
237.639 - </If></FunctionDef> <FunctionDef>def __ne__(<Name>self</Name>, <Name>other</Name>):
237.640 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
237.641 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> != <Num>0</Num></Compare></Return>
237.642 - else:
237.643 - <Return>return <Name>True</Name></Return>
237.644 -
237.645 - </If></FunctionDef> <FunctionDef>def __le__(<Name>self</Name>, <Name>other</Name>):
237.646 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
237.647 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> <= <Num>0</Num></Compare></Return>
237.648 - else:
237.649 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.650 -
237.651 - </If></FunctionDef> <FunctionDef>def __lt__(<Name>self</Name>, <Name>other</Name>):
237.652 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
237.653 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> < <Num>0</Num></Compare></Return>
237.654 - else:
237.655 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.656 -
237.657 - </If></FunctionDef> <FunctionDef>def __ge__(<Name>self</Name>, <Name>other</Name>):
237.658 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
237.659 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> >= <Num>0</Num></Compare></Return>
237.660 - else:
237.661 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.662 -
237.663 - </If></FunctionDef> <FunctionDef>def __gt__(<Name>self</Name>, <Name>other</Name>):
237.664 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
237.665 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> > <Num>0</Num></Compare></Return>
237.666 - else:
237.667 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.668 -
237.669 - </If></FunctionDef> <FunctionDef>def __cmp(<Name>self</Name>, <Name>other</Name>):
237.670 - <Assert>assert <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call></Assert>
237.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>
237.672 -
237.673 - </FunctionDef> <FunctionDef>def __hash__(<Name>self</Name>):
237.674 - <Return>return <Call><Name>hash</Name>(<Call><Attribute><Name>self</Name>.__getstate</Attribute>()</Call>)</Call></Return>
237.675 -
237.676 - </FunctionDef> <FunctionDef>def __nonzero__(<Name>self</Name>):
237.677 - <Return>return <BoolOp>(<Compare><Attribute><Name>self</Name>.__days</Attribute> != <Num>0</Num></Compare> or
237.678 - <Compare><Attribute><Name>self</Name>.__seconds</Attribute> != <Num>0</Num></Compare> or
237.679 - <Compare><Attribute><Name>self</Name>.__microseconds</Attribute> != <Num>0</Num></Compare>)</BoolOp></Return>
237.680 -
237.681 - # Pickle support.
237.682 -
237.683 - </FunctionDef> <Assign><Name>__safe_for_unpickling__</Name> = <Name>True</Name></Assign> # For Python 2.2
237.684 -
237.685 - <FunctionDef>def __getstate(<Name>self</Name>):
237.686 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__days</Attribute>, <Attribute><Name>self</Name>.__seconds</Attribute>, <Attribute><Name>self</Name>.__microseconds</Attribute>)</Tuple></Return>
237.687 -
237.688 - </FunctionDef> <FunctionDef>def __reduce__(<Name>self</Name>):
237.689 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__class__</Attribute>, <Call><Attribute><Name>self</Name>.__getstate</Attribute>()</Call>)</Tuple></Return>
237.690 -
237.691 -</FunctionDef></ClassDef><Assign><Attribute><Name>timedelta</Name>.min</Attribute> = <Call><Name>timedelta</Name>(<Num>-999999999</Num>)</Call></Assign>
237.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>,
237.693 - microseconds=<Num>999999</Num>)</Call></Assign>
237.694 -<Assign><Attribute><Name>timedelta</Name>.resolution</Attribute> = <Call><Name>timedelta</Name>(microseconds=<Num>1</Num>)</Call></Assign>
237.695 -
237.696 -<ClassDef>class date(<Name>object</Name>):
237.697 - <Expr><Str>"""Concrete date type.
237.698 -
237.699 - Constructors:
237.700 -
237.701 - __new__()
237.702 - fromtimestamp()
237.703 - today()
237.704 - fromordinal()
237.705 -
237.706 - Operators:
237.707 -
237.708 - __repr__, __str__
237.709 - __cmp__, __hash__
237.710 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
237.711 -
237.712 - Methods:
237.713 -
237.714 - timetuple()
237.715 - toordinal()
237.716 - weekday()
237.717 - isoweekday(), isocalendar(), isoformat()
237.718 - ctime()
237.719 - strftime()
237.720 -
237.721 - Properties (readonly):
237.722 - year, month, day
237.723 - """</Str></Expr>
237.724 -
237.725 - <FunctionDef>def __new__(<Name>cls</Name>, <Name>year</Name>, <Name>month</Name>=<Name>None</Name>, <Name>day</Name>=<Name>None</Name>):
237.726 - <Expr><Str>"""Constructor.
237.727 -
237.728 - Arguments:
237.729 -
237.730 - year, month, day (required, base 1)
237.731 - """</Str></Expr>
237.732 - <If>if <Call><Name>isinstance</Name>(<Name>year</Name>, <Name>str</Name>)</Call>:
237.733 - # Pickle support
237.734 - <Assign><Name>self</Name> = <Call><Attribute><Name>object</Name>.__new__</Attribute>(<Name>cls</Name>)</Call></Assign>
237.735 - <Expr><Call><Attribute><Name>self</Name>.__setstate</Attribute>(<Tuple>(<Name>year</Name>,)</Tuple>)</Call></Expr>
237.736 - <Return>return <Name>self</Name></Return>
237.737 - </If> <Expr><Call><Name>_check_date_fields</Name>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)</Call></Expr>
237.738 - <Assign><Name>self</Name> = <Call><Attribute><Name>object</Name>.__new__</Attribute>(<Name>cls</Name>)</Call></Assign>
237.739 - <Assign><Attribute><Name>self</Name>.__year</Attribute> = <Name>year</Name></Assign>
237.740 - <Assign><Attribute><Name>self</Name>.__month</Attribute> = <Name>month</Name></Assign>
237.741 - <Assign><Attribute><Name>self</Name>.__day</Attribute> = <Name>day</Name></Assign>
237.742 - <Return>return <Name>self</Name></Return>
237.743 -
237.744 - # Additional constructors
237.745 -
237.746 - </FunctionDef> <FunctionDef>def fromtimestamp(<Name>cls</Name>, <Name>t</Name>):
237.747 - <Expr><Str>"Construct a date from a POSIX timestamp (like time.time())."</Str></Expr>
237.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>
237.749 - <Return>return <Call><Name>cls</Name>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>)</Call></Return>
237.750 - </FunctionDef> <Assign><Name>fromtimestamp</Name> = <Call><Name>classmethod</Name>(<Name>fromtimestamp</Name>)</Call></Assign>
237.751 -
237.752 - <FunctionDef>def today(<Name>cls</Name>):
237.753 - <Expr><Str>"Construct a date from time.time()."</Str></Expr>
237.754 - <Assign><Name>t</Name> = <Call><Attribute><Name>_time</Name>.time</Attribute>()</Call></Assign>
237.755 - <Return>return <Call><Attribute><Name>cls</Name>.fromtimestamp</Attribute>(<Name>t</Name>)</Call></Return>
237.756 - </FunctionDef> <Assign><Name>today</Name> = <Call><Name>classmethod</Name>(<Name>today</Name>)</Call></Assign>
237.757 -
237.758 - <FunctionDef>def fromordinal(<Name>cls</Name>, <Name>n</Name>):
237.759 - <Expr><Str>"""Contruct a date from a proleptic Gregorian ordinal.
237.760 -
237.761 - January 1 of year 1 is day 1. Only the year, month and day are
237.762 - non-zero in the result.
237.763 - """</Str></Expr>
237.764 - <Assign><Tuple><Name>y</Name>, <Name>m</Name>, <Name>d</Name></Tuple> = <Call><Name>_ord2ymd</Name>(<Name>n</Name>)</Call></Assign>
237.765 - <Return>return <Call><Name>cls</Name>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>)</Call></Return>
237.766 - </FunctionDef> <Assign><Name>fromordinal</Name> = <Call><Name>classmethod</Name>(<Name>fromordinal</Name>)</Call></Assign>
237.767 -
237.768 - # Conversions to string
237.769 -
237.770 - <FunctionDef>def __repr__(<Name>self</Name>):
237.771 - <Expr><Str>"Convert to formal string, for repr()."</Str></Expr>
237.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>,
237.773 - <Attribute><Name>self</Name>.__year</Attribute>,
237.774 - <Attribute><Name>self</Name>.__month</Attribute>,
237.775 - <Attribute><Name>self</Name>.__day</Attribute>)</Tuple></BinOp></Return>
237.776 - # XXX These shouldn't depend on time.localtime(), because that
237.777 - # clips the usable dates to [1970 .. 2038). At least ctime() is
237.778 - # easily done without using strftime() -- that's better too because
237.779 - # strftime("%c", ...) is locale specific.
237.780 -
237.781 - </FunctionDef> <FunctionDef>def ctime(<Name>self</Name>):
237.782 - <Expr><Str>"Format a la ctime()."</Str></Expr>
237.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>
237.784 -
237.785 - </FunctionDef> <FunctionDef>def strftime(<Name>self</Name>, <Name>fmt</Name>):
237.786 - <Expr><Str>"Format using strftime()."</Str></Expr>
237.787 - <Return>return <Call><Name>_wrap_strftime</Name>(<Name>self</Name>, <Name>fmt</Name>, <Call><Attribute><Name>self</Name>.timetuple</Attribute>()</Call>)</Call></Return>
237.788 -
237.789 - </FunctionDef> <FunctionDef>def isoformat(<Name>self</Name>):
237.790 - <Expr><Str>"""Return the date formatted according to ISO.
237.791 -
237.792 - This is 'YYYY-MM-DD'.
237.793 -
237.794 - References:
237.795 - - http://www.w3.org/TR/NOTE-datetime
237.796 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
237.797 - """</Str></Expr>
237.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>
237.799 -
237.800 - </FunctionDef> <Assign><Name>__str__</Name> = <Name>isoformat</Name></Assign>
237.801 -
237.802 - # Read-only field accessors
237.803 - <Assign><Name>year</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__year</Attribute></Lambda>,
237.804 - doc=<BinOp><Str>"year (%d-%d)"</Str> % <Tuple>(<Name>MINYEAR</Name>, <Name>MAXYEAR</Name>)</Tuple></BinOp>)</Call></Assign>
237.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>
237.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>
237.807 -
237.808 - # Standard conversions, __cmp__, __hash__ (and helpers)
237.809 -
237.810 - <FunctionDef>def timetuple(<Name>self</Name>):
237.811 - <Expr><Str>"Return local time tuple compatible with time.localtime()."</Str></Expr>
237.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>,
237.813 - <Num>0</Num>, <Num>0</Num>, <Num>0</Num>, <Num>-1</Num>)</Call></Return>
237.814 -
237.815 - </FunctionDef> <FunctionDef>def toordinal(<Name>self</Name>):
237.816 - <Expr><Str>"""Return proleptic Gregorian ordinal for the year, month and day.
237.817 -
237.818 - January 1 of year 1 is day 1. Only the year, month and day values
237.819 - contribute to the result.
237.820 - """</Str></Expr>
237.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>
237.822 -
237.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>):
237.824 - <Expr><Str>"""Return a new date with new values for the specified fields."""</Str></Expr>
237.825 - <If>if <Compare><Name>year</Name> is <Name>None</Name></Compare>:
237.826 - <Assign><Name>year</Name> = <Attribute><Name>self</Name>.__year</Attribute></Assign>
237.827 - </If> <If>if <Compare><Name>month</Name> is <Name>None</Name></Compare>:
237.828 - <Assign><Name>month</Name> = <Attribute><Name>self</Name>.__month</Attribute></Assign>
237.829 - </If> <If>if <Compare><Name>day</Name> is <Name>None</Name></Compare>:
237.830 - <Assign><Name>day</Name> = <Attribute><Name>self</Name>.__day</Attribute></Assign>
237.831 - </If> <Expr><Call><Name>_check_date_fields</Name>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)</Call></Expr>
237.832 - <Return>return <Call><Name>date</Name>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)</Call></Return>
237.833 -
237.834 - # Comparisons.
237.835 -
237.836 - </FunctionDef> <FunctionDef>def __eq__(<Name>self</Name>, <Name>other</Name>):
237.837 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
237.838 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> == <Num>0</Num></Compare></Return>
237.839 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
237.840 - <Return>return <Name>NotImplemented</Name></Return>
237.841 - else:
237.842 - <Return>return <Name>False</Name></Return>
237.843 -
237.844 - </If></If></FunctionDef> <FunctionDef>def __ne__(<Name>self</Name>, <Name>other</Name>):
237.845 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
237.846 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> != <Num>0</Num></Compare></Return>
237.847 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
237.848 - <Return>return <Name>NotImplemented</Name></Return>
237.849 - else:
237.850 - <Return>return <Name>True</Name></Return>
237.851 -
237.852 - </If></If></FunctionDef> <FunctionDef>def __le__(<Name>self</Name>, <Name>other</Name>):
237.853 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
237.854 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> <= <Num>0</Num></Compare></Return>
237.855 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
237.856 - <Return>return <Name>NotImplemented</Name></Return>
237.857 - else:
237.858 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.859 -
237.860 - </If></If></FunctionDef> <FunctionDef>def __lt__(<Name>self</Name>, <Name>other</Name>):
237.861 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
237.862 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> < <Num>0</Num></Compare></Return>
237.863 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
237.864 - <Return>return <Name>NotImplemented</Name></Return>
237.865 - else:
237.866 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.867 -
237.868 - </If></If></FunctionDef> <FunctionDef>def __ge__(<Name>self</Name>, <Name>other</Name>):
237.869 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
237.870 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> >= <Num>0</Num></Compare></Return>
237.871 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
237.872 - <Return>return <Name>NotImplemented</Name></Return>
237.873 - else:
237.874 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.875 -
237.876 - </If></If></FunctionDef> <FunctionDef>def __gt__(<Name>self</Name>, <Name>other</Name>):
237.877 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
237.878 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> > <Num>0</Num></Compare></Return>
237.879 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
237.880 - <Return>return <Name>NotImplemented</Name></Return>
237.881 - else:
237.882 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.883 -
237.884 - </If></If></FunctionDef> <FunctionDef>def __cmp(<Name>self</Name>, <Name>other</Name>):
237.885 - <Assert>assert <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call></Assert>
237.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>
237.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>
237.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>
237.889 -
237.890 - </FunctionDef> <FunctionDef>def __hash__(<Name>self</Name>):
237.891 - <Expr><Str>"Hash."</Str></Expr>
237.892 - <Return>return <Call><Name>hash</Name>(<Call><Attribute><Name>self</Name>.__getstate</Attribute>()</Call>)</Call></Return>
237.893 -
237.894 - # Computations
237.895 -
237.896 - </FunctionDef> <FunctionDef>def _checkOverflow(<Name>self</Name>, <Name>year</Name>):
237.897 - <If>if <UnaryOp>not <Compare><Name>MINYEAR</Name> <= <Name>year</Name> <= <Name>MAXYEAR</Name></Compare></UnaryOp>:
237.898 - <Raise>raise <Call><Name>OverflowError</Name>(<BinOp><Str>"date +/-: result year %d not in %d..%d"</Str> %
237.899 - <Tuple>(<Name>year</Name>, <Name>MINYEAR</Name>, <Name>MAXYEAR</Name>)</Tuple></BinOp>)</Call></Raise>
237.900 -
237.901 - </If></FunctionDef> <FunctionDef>def __add__(<Name>self</Name>, <Name>other</Name>):
237.902 - <Expr><Str>"Add a date to a timedelta."</Str></Expr>
237.903 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
237.904 - <Assign><Name>t</Name> = <Call><Name>tmxxx</Name>(<Attribute><Name>self</Name>.__year</Attribute>,
237.905 - <Attribute><Name>self</Name>.__month</Attribute>,
237.906 - <BinOp><Attribute><Name>self</Name>.__day</Attribute> + <Attribute><Name>other</Name>.days</Attribute></BinOp>)</Call></Assign>
237.907 - <Expr><Call><Attribute><Name>self</Name>._checkOverflow</Attribute>(<Attribute><Name>t</Name>.year</Attribute>)</Call></Expr>
237.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>
237.909 - <Return>return <Name>result</Name></Return>
237.910 - </If> <Return>return <Name>NotImplemented</Name></Return>
237.911 -
237.912 - </FunctionDef> <Assign><Name>__radd__</Name> = <Name>__add__</Name></Assign>
237.913 -
237.914 - <FunctionDef>def __sub__(<Name>self</Name>, <Name>other</Name>):
237.915 - <Expr><Str>"""Subtract two dates, or a date and a timedelta."""</Str></Expr>
237.916 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
237.917 - <Return>return <BinOp><Name>self</Name> + <Call><Name>timedelta</Name>(<UnaryOp>-<Attribute><Name>other</Name>.days</Attribute></UnaryOp>)</Call></BinOp></Return>
237.918 - </If> <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
237.919 - <Assign><Name>days1</Name> = <Call><Attribute><Name>self</Name>.toordinal</Attribute>()</Call></Assign>
237.920 - <Assign><Name>days2</Name> = <Call><Attribute><Name>other</Name>.toordinal</Attribute>()</Call></Assign>
237.921 - <Return>return <Call><Name>timedelta</Name>(<BinOp><Name>days1</Name> - <Name>days2</Name></BinOp>)</Call></Return>
237.922 - </If> <Return>return <Name>NotImplemented</Name></Return>
237.923 -
237.924 - </FunctionDef> <FunctionDef>def weekday(<Name>self</Name>):
237.925 - <Expr><Str>"Return day of the week, where Monday == 0 ... Sunday == 6."</Str></Expr>
237.926 - <Return>return <BinOp><BinOp>(<Call><Attribute><Name>self</Name>.toordinal</Attribute>()</Call> + <Num>6</Num>)</BinOp> % <Num>7</Num></BinOp></Return>
237.927 -
237.928 - # Day-of-the-week and week-of-the-year, according to ISO
237.929 -
237.930 - </FunctionDef> <FunctionDef>def isoweekday(<Name>self</Name>):
237.931 - <Expr><Str>"Return day of the week, where Monday == 1 ... Sunday == 7."</Str></Expr>
237.932 - # 1-Jan-0001 is a Monday
237.933 - <Return>return <BoolOp><BinOp><Call><Attribute><Name>self</Name>.toordinal</Attribute>()</Call> % <Num>7</Num></BinOp> or <Num>7</Num></BoolOp></Return>
237.934 -
237.935 - </FunctionDef> <FunctionDef>def isocalendar(<Name>self</Name>):
237.936 - <Expr><Str>"""Return a 3-tuple containing ISO year, week number, and weekday.
237.937 -
237.938 - The first ISO week of the year is the (Mon-Sun) week
237.939 - containing the year's first Thursday; everything else derives
237.940 - from that.
237.941 -
237.942 - The first week is 1; Monday is 1 ... Sunday is 7.
237.943 -
237.944 - ISO calendar algorithm taken from
237.945 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
237.946 - """</Str></Expr>
237.947 - <Assign><Name>year</Name> = <Attribute><Name>self</Name>.__year</Attribute></Assign>
237.948 - <Assign><Name>week1monday</Name> = <Call><Name>_isoweek1monday</Name>(<Name>year</Name>)</Call></Assign>
237.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>
237.950 - # Internally, week and day have origin 0
237.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>
237.952 - <If>if <Compare><Name>week</Name> < <Num>0</Num></Compare>:
237.953 - <AugAssign><Name>year</Name> -= <Num>1</Num></AugAssign>
237.954 - <Assign><Name>week1monday</Name> = <Call><Name>_isoweek1monday</Name>(<Name>year</Name>)</Call></Assign>
237.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>
237.956 - <If>elif <Compare><Name>week</Name> >= <Num>52</Num></Compare>:
237.957 - <If>if <Compare><Name>today</Name> >= <Call><Name>_isoweek1monday</Name>(<BinOp><Name>year</Name>+<Num>1</Num></BinOp>)</Call></Compare>:
237.958 - <AugAssign><Name>year</Name> += <Num>1</Num></AugAssign>
237.959 - <Assign><Name>week</Name> = <Num>0</Num></Assign>
237.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>
237.961 -
237.962 - # Pickle support.
237.963 -
237.964 - </FunctionDef> <Assign><Name>__safe_for_unpickling__</Name> = <Name>True</Name></Assign> # For Python 2.2
237.965 -
237.966 - <FunctionDef>def __getstate(<Name>self</Name>):
237.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>
237.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>
237.969 -
237.970 - </FunctionDef> <FunctionDef>def __setstate(<Name>self</Name>, <Name>t</Name>):
237.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>
237.972 - <Assign><Name>string</Name> = <Subscript><Name>t</Name>[<Index><Num>0</Num></Index>]</Subscript></Assign>
237.973 - <Assert>assert <Compare><Call><Name>len</Name>(<Name>string</Name>)</Call> == <Num>4</Num></Compare></Assert>
237.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>
237.975 - <Assign><Attribute><Name>self</Name>.__year</Attribute> = <BinOp><BinOp><Name>yhi</Name></BinOp> * <Num>256</Num> + <Name>ylo</Name></BinOp></Assign>
237.976 -
237.977 - </FunctionDef> <FunctionDef>def __reduce__(<Name>self</Name>):
237.978 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__class__</Attribute>, <Call><Attribute><Name>self</Name>.__getstate</Attribute>()</Call>)</Tuple></Return>
237.979 -
237.980 -</FunctionDef></ClassDef><Assign><Name>_date_class</Name> = <Name>date</Name></Assign> # so functions w/ args named "date" can get at the class
237.981 -
237.982 -<Assign><Attribute><Name>date</Name>.min</Attribute> = <Call><Name>date</Name>(<Num>1</Num>, <Num>1</Num>, <Num>1</Num>)</Call></Assign>
237.983 -<Assign><Attribute><Name>date</Name>.max</Attribute> = <Call><Name>date</Name>(<Num>9999</Num>, <Num>12</Num>, <Num>31</Num>)</Call></Assign>
237.984 -<Assign><Attribute><Name>date</Name>.resolution</Attribute> = <Call><Name>timedelta</Name>(days=<Num>1</Num>)</Call></Assign>
237.985 -
237.986 -<ClassDef>class tzinfo(<Name>object</Name>):
237.987 - <Expr><Str>"""Abstract base class for time zone info classes.
237.988 -
237.989 - Subclasses must override the name(), utcoffset() and dst() methods.
237.990 - """</Str></Expr>
237.991 -
237.992 - <FunctionDef>def tzname(<Name>self</Name>, <Name>dt</Name>):
237.993 - <Expr><Str>"datetime -> string name of time zone."</Str></Expr>
237.994 - <Raise>raise <Call><Name>NotImplementedError</Name>(<Str>"tzinfo subclass must override tzname()"</Str>)</Call></Raise>
237.995 -
237.996 - </FunctionDef> <FunctionDef>def utcoffset(<Name>self</Name>, <Name>dt</Name>):
237.997 - <Expr><Str>"datetime -> minutes east of UTC (negative for west of UTC)"</Str></Expr>
237.998 - <Raise>raise <Call><Name>NotImplementedError</Name>(<Str>"tzinfo subclass must override utcoffset()"</Str>)</Call></Raise>
237.999 -
237.1000 - </FunctionDef> <FunctionDef>def dst(<Name>self</Name>, <Name>dt</Name>):
237.1001 - <Expr><Str>"""datetime -> DST offset in minutes east of UTC.
237.1002 -
237.1003 - Return 0 if DST not in effect. utcoffset() must include the DST
237.1004 - offset.
237.1005 - """</Str></Expr>
237.1006 - <Raise>raise <Call><Name>NotImplementedError</Name>(<Str>"tzinfo subclass must override dst()"</Str>)</Call></Raise>
237.1007 -
237.1008 - </FunctionDef> <FunctionDef>def fromutc(<Name>self</Name>, <Name>dt</Name>):
237.1009 - <Expr><Str>"datetime in UTC -> datetime in local time."</Str></Expr>
237.1010 -
237.1011 - <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>dt</Name>, <Name>datetime</Name>)</Call></UnaryOp>:
237.1012 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"fromutc() requires a datetime argument"</Str>)</Call></Raise>
237.1013 - </If> <If>if <Compare><Attribute><Name>dt</Name>.tzinfo</Attribute> is not <Name>self</Name></Compare>:
237.1014 - <Raise>raise <Call><Name>ValueError</Name>(<Str>"dt.tzinfo is not self"</Str>)</Call></Raise>
237.1015 -
237.1016 - </If> <Assign><Name>dtoff</Name> = <Call><Attribute><Name>dt</Name>.utcoffset</Attribute>()</Call></Assign>
237.1017 - <If>if <Compare><Name>dtoff</Name> is <Name>None</Name></Compare>:
237.1018 - <Raise>raise <Call><Name>ValueError</Name>(<Str>"fromutc() requires a non-None utcoffset() "
237.1019 - "result"</Str>)</Call></Raise>
237.1020 -
237.1021 - # See the long comment block at the end of this file for an
237.1022 - # explanation of this algorithm.
237.1023 - </If> <Assign><Name>dtdst</Name> = <Call><Attribute><Name>dt</Name>.dst</Attribute>()</Call></Assign>
237.1024 - <If>if <Compare><Name>dtdst</Name> is <Name>None</Name></Compare>:
237.1025 - <Raise>raise <Call><Name>ValueError</Name>(<Str>"fromutc() requires a non-None dst() result"</Str>)</Call></Raise>
237.1026 - </If> <Assign><Name>delta</Name> = <BinOp><Name>dtoff</Name> - <Name>dtdst</Name></BinOp></Assign>
237.1027 - <If>if <Name>delta</Name>:
237.1028 - <AugAssign><Name>dt</Name> += <Name>delta</Name></AugAssign>
237.1029 - <Assign><Name>dtdst</Name> = <Call><Attribute><Name>dt</Name>.dst</Attribute>()</Call></Assign>
237.1030 - <If>if <Compare><Name>dtdst</Name> is <Name>None</Name></Compare>:
237.1031 - <Raise>raise <Call><Name>ValueError</Name>(<Str>"fromutc(): dt.dst gave inconsistent "
237.1032 - "results; cannot convert"</Str>)</Call></Raise>
237.1033 - </If></If> <If>if <Name>dtdst</Name>:
237.1034 - <Return>return <BinOp><Name>dt</Name> + <Name>dtdst</Name></BinOp></Return>
237.1035 - else:
237.1036 - <Return>return <Name>dt</Name></Return>
237.1037 -
237.1038 - # Pickle support.
237.1039 -
237.1040 - </If></FunctionDef> <Assign><Name>__safe_for_unpickling__</Name> = <Name>True</Name></Assign> # For Python 2.2
237.1041 -
237.1042 - <FunctionDef>def __reduce__(<Name>self</Name>):
237.1043 - <Assign><Name>getinitargs</Name> = <Call><Name>getattr</Name>(<Name>self</Name>, <Str>"__getinitargs__"</Str>, <Name>None</Name>)</Call></Assign>
237.1044 - <If>if <Name>getinitargs</Name>:
237.1045 - <Assign><Name>args</Name> = <Call><Name>getinitargs</Name>()</Call></Assign>
237.1046 - else:
237.1047 - <Assign><Name>args</Name> = <Tuple>()</Tuple></Assign>
237.1048 - </If> <Assign><Name>getstate</Name> = <Call><Name>getattr</Name>(<Name>self</Name>, <Str>"__getstate__"</Str>, <Name>None</Name>)</Call></Assign>
237.1049 - <If>if <Name>getstate</Name>:
237.1050 - <Assign><Name>state</Name> = <Call><Name>getstate</Name>()</Call></Assign>
237.1051 - else:
237.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>
237.1053 - </If> <If>if <Compare><Name>state</Name> is <Name>None</Name></Compare>:
237.1054 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__class__</Attribute>, <Name>args</Name>)</Tuple></Return>
237.1055 - else:
237.1056 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__class__</Attribute>, <Name>args</Name>, <Name>state</Name>)</Tuple></Return>
237.1057 -
237.1058 -</If></FunctionDef></ClassDef><Assign><Name>_tzinfo_class</Name> = <Name>tzinfo</Name></Assign> # so functions w/ args named "tinfo" can get at it
237.1059 -
237.1060 -<ClassDef>class time(<Name>object</Name>):
237.1061 - <Expr><Str>"""Time with time zone.
237.1062 -
237.1063 - Constructors:
237.1064 -
237.1065 - __new__()
237.1066 -
237.1067 - Operators:
237.1068 -
237.1069 - __repr__, __str__
237.1070 - __cmp__, __hash__
237.1071 -
237.1072 - Methods:
237.1073 -
237.1074 - strftime()
237.1075 - isoformat()
237.1076 - utcoffset()
237.1077 - tzname()
237.1078 - dst()
237.1079 -
237.1080 - Properties (readonly):
237.1081 - hour, minute, second, microsecond, tzinfo
237.1082 - """</Str></Expr>
237.1083 -
237.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>):
237.1085 - <Expr><Str>"""Constructor.
237.1086 -
237.1087 - Arguments:
237.1088 -
237.1089 - hour, minute (required)
237.1090 - second, microsecond (default to zero)
237.1091 - tzinfo (default to None)
237.1092 - """</Str></Expr>
237.1093 - <Assign><Name>self</Name> = <Call><Attribute><Name>object</Name>.__new__</Attribute>(<Name>cls</Name>)</Call></Assign>
237.1094 - <If>if <Call><Name>isinstance</Name>(<Name>hour</Name>, <Name>str</Name>)</Call>:
237.1095 - # Pickle support
237.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>
237.1097 - <Return>return <Name>self</Name></Return>
237.1098 - </If> <Expr><Call><Name>_check_tzinfo_arg</Name>(<Name>tzinfo</Name>)</Call></Expr>
237.1099 - <Expr><Call><Name>_check_time_fields</Name>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)</Call></Expr>
237.1100 - <Assign><Attribute><Name>self</Name>.__hour</Attribute> = <Name>hour</Name></Assign>
237.1101 - <Assign><Attribute><Name>self</Name>.__minute</Attribute> = <Name>minute</Name></Assign>
237.1102 - <Assign><Attribute><Name>self</Name>.__second</Attribute> = <Name>second</Name></Assign>
237.1103 - <Assign><Attribute><Name>self</Name>.__microsecond</Attribute> = <Name>microsecond</Name></Assign>
237.1104 - <Assign><Attribute><Name>self</Name>._tzinfo</Attribute> = <Name>tzinfo</Name></Assign>
237.1105 - <Return>return <Name>self</Name></Return>
237.1106 -
237.1107 - # Read-only field accessors
237.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>
237.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>
237.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>
237.1111 - <Assign><Name>microsecond</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__microsecond</Attribute></Lambda>,
237.1112 - doc=<Str>"microsecond (0-999999)"</Str>)</Call></Assign>
237.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>
237.1114 -
237.1115 - # Standard conversions, __hash__ (and helpers)
237.1116 -
237.1117 - # Comparisons.
237.1118 -
237.1119 - <FunctionDef>def __eq__(<Name>self</Name>, <Name>other</Name>):
237.1120 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call>:
237.1121 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> == <Num>0</Num></Compare></Return>
237.1122 - else:
237.1123 - <Return>return <Name>False</Name></Return>
237.1124 -
237.1125 - </If></FunctionDef> <FunctionDef>def __ne__(<Name>self</Name>, <Name>other</Name>):
237.1126 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call>:
237.1127 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> != <Num>0</Num></Compare></Return>
237.1128 - else:
237.1129 - <Return>return <Name>True</Name></Return>
237.1130 -
237.1131 - </If></FunctionDef> <FunctionDef>def __le__(<Name>self</Name>, <Name>other</Name>):
237.1132 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call>:
237.1133 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> <= <Num>0</Num></Compare></Return>
237.1134 - else:
237.1135 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.1136 -
237.1137 - </If></FunctionDef> <FunctionDef>def __lt__(<Name>self</Name>, <Name>other</Name>):
237.1138 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call>:
237.1139 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> < <Num>0</Num></Compare></Return>
237.1140 - else:
237.1141 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.1142 -
237.1143 - </If></FunctionDef> <FunctionDef>def __ge__(<Name>self</Name>, <Name>other</Name>):
237.1144 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call>:
237.1145 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> >= <Num>0</Num></Compare></Return>
237.1146 - else:
237.1147 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.1148 -
237.1149 - </If></FunctionDef> <FunctionDef>def __gt__(<Name>self</Name>, <Name>other</Name>):
237.1150 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call>:
237.1151 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> > <Num>0</Num></Compare></Return>
237.1152 - else:
237.1153 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.1154 -
237.1155 - </If></FunctionDef> <FunctionDef>def __cmp(<Name>self</Name>, <Name>other</Name>):
237.1156 - <Assert>assert <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call></Assert>
237.1157 - <Assign><Name>mytz</Name> = <Attribute><Name>self</Name>._tzinfo</Attribute></Assign>
237.1158 - <Assign><Name>ottz</Name> = <Attribute><Name>other</Name>._tzinfo</Attribute></Assign>
237.1159 - <Assign><Name>myoff</Name> = <Name>otoff</Name> = <Name>None</Name></Assign>
237.1160 -
237.1161 - <If>if <Compare><Name>mytz</Name> is <Name>ottz</Name></Compare>:
237.1162 - <Assign><Name>base_compare</Name> = <Name>True</Name></Assign>
237.1163 - else:
237.1164 - <Assign><Name>myoff</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
237.1165 - <Assign><Name>otoff</Name> = <Call><Attribute><Name>other</Name>._utcoffset</Attribute>()</Call></Assign>
237.1166 - <Assign><Name>base_compare</Name> = <Compare><Name>myoff</Name> == <Name>otoff</Name></Compare></Assign>
237.1167 -
237.1168 - </If> <If>if <Name>base_compare</Name>:
237.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>,
237.1170 - <Attribute><Name>self</Name>.__microsecond</Attribute>)</Tuple>,
237.1171 - <Tuple>(<Attribute><Name>other</Name>.__hour</Attribute>, <Attribute><Name>other</Name>.__minute</Attribute>, <Attribute><Name>other</Name>.__second</Attribute>,
237.1172 - <Attribute><Name>other</Name>.__microsecond</Attribute>)</Tuple>)</Call></Return>
237.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>:
237.1174 - # XXX Buggy in 2.2.2.
237.1175 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"cannot compare naive and aware times"</Str>)</Call></Raise>
237.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>
237.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>
237.1178 - <Return>return <Call><Name>cmp</Name>(<Tuple>(<Name>myhhmm</Name>, <Attribute><Name>self</Name>.__second</Attribute>, <Attribute><Name>self</Name>.__microsecond</Attribute>)</Tuple>,
237.1179 - <Tuple>(<Name>othhmm</Name>, <Attribute><Name>other</Name>.__second</Attribute>, <Attribute><Name>other</Name>.__microsecond</Attribute>)</Tuple>)</Call></Return>
237.1180 -
237.1181 - </FunctionDef> <FunctionDef>def __hash__(<Name>self</Name>):
237.1182 - <Expr><Str>"""Hash."""</Str></Expr>
237.1183 - <Assign><Name>tzoff</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
237.1184 - <If>if <UnaryOp>not <Name>tzoff</Name></UnaryOp>: # zero or None
237.1185 - <Return>return <Call><Name>hash</Name>(<Subscript><Attribute><Name>self</Name>.__getstate</Attribute><Call>()</Call>[<Index><Num>0</Num></Index>]</Subscript>)</Call></Return>
237.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>
237.1187 - <If>if <Compare><Num>0</Num> <= <Name>h</Name> < <Num>24</Num></Compare>:
237.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>
237.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>
237.1190 -
237.1191 - # Conversion to string
237.1192 -
237.1193 - </FunctionDef> <FunctionDef>def _tzstr(<Name>self</Name>, <Name>sep</Name>=<Str>":"</Str>):
237.1194 - <Expr><Str>"""Return formatted timezone offset (+xx:xx) or None."""</Str></Expr>
237.1195 - <Assign><Name>off</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
237.1196 - <If>if <Compare><Name>off</Name> is not <Name>None</Name></Compare>:
237.1197 - <If>if <Compare><Name>off</Name> < <Num>0</Num></Compare>:
237.1198 - <Assign><Name>sign</Name> = <Str>"-"</Str></Assign>
237.1199 - <Assign><Name>off</Name> = <UnaryOp>-<Name>off</Name></UnaryOp></Assign>
237.1200 - else:
237.1201 - <Assign><Name>sign</Name> = <Str>"+"</Str></Assign>
237.1202 - </If> <Assign><Tuple><Name>hh</Name>, <Name>mm</Name></Tuple> = <Call><Name>divmod</Name>(<Name>off</Name>, <Num>60</Num>)</Call></Assign>
237.1203 - <Assert>assert <Compare><Num>0</Num> <= <Name>hh</Name> < <Num>24</Num></Compare></Assert>
237.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>
237.1205 - </If> <Return>return <Name>off</Name></Return>
237.1206 -
237.1207 - </FunctionDef> <FunctionDef>def __repr__(<Name>self</Name>):
237.1208 - <Expr><Str>"""Convert to formal string, for repr()."""</Str></Expr>
237.1209 - <If>if <Compare><Attribute><Name>self</Name>.__microsecond</Attribute> != <Num>0</Num></Compare>:
237.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>
237.1211 - <If>elif <Compare><Attribute><Name>self</Name>.__second</Attribute> != <Num>0</Num></Compare>:
237.1212 - <Assign><Name>s</Name> = <BinOp><Str>", %d"</Str> % <Attribute><Name>self</Name>.__second</Attribute></BinOp></Assign>
237.1213 - else:
237.1214 - <Assign><Name>s</Name> = <Str>""</Str></Assign>
237.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>,
237.1216 - <Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Name>s</Name>)</Tuple></BinOp></Assign>
237.1217 - <If>if <Compare><Attribute><Name>self</Name>._tzinfo</Attribute> is not <Name>None</Name></Compare>:
237.1218 - <Assert>assert <Compare><Subscript><Name>s</Name>[<Slice><Num>-1</Num>:</Slice>]</Subscript> == <Str>")"</Str></Compare></Assert>
237.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>
237.1220 - </If> <Return>return <Name>s</Name></Return>
237.1221 -
237.1222 - </FunctionDef> <FunctionDef>def isoformat(<Name>self</Name>):
237.1223 - <Expr><Str>"""Return the time formatted according to ISO.
237.1224 -
237.1225 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
237.1226 - self.microsecond == 0.
237.1227 - """</Str></Expr>
237.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>,
237.1229 - <Attribute><Name>self</Name>.__microsecond</Attribute>)</Call></Assign>
237.1230 - <Assign><Name>tz</Name> = <Call><Attribute><Name>self</Name>._tzstr</Attribute>()</Call></Assign>
237.1231 - <If>if <Name>tz</Name>:
237.1232 - <AugAssign><Name>s</Name> += <Name>tz</Name></AugAssign>
237.1233 - </If> <Return>return <Name>s</Name></Return>
237.1234 -
237.1235 - </FunctionDef> <Assign><Name>__str__</Name> = <Name>isoformat</Name></Assign>
237.1236 -
237.1237 - <FunctionDef>def strftime(<Name>self</Name>, <Name>fmt</Name>):
237.1238 - <Expr><Str>"""Format using strftime(). The date part of the timestamp passed
237.1239 - to underlying strftime should not be used.
237.1240 - """</Str></Expr>
237.1241 - # The year must be >= 1900 else Python's strftime implementation
237.1242 - # can raise a bogus exception.
237.1243 - <Assign><Name>timetuple</Name> = <Tuple>(<Num>1900</Num>, <Num>1</Num>, <Num>1</Num>,
237.1244 - <Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>,
237.1245 - <Num>0</Num>, <Num>1</Num>, <Num>-1</Num>)</Tuple></Assign>
237.1246 - <Return>return <Call><Name>_wrap_strftime</Name>(<Name>self</Name>, <Name>fmt</Name>, <Name>timetuple</Name>)</Call></Return>
237.1247 -
237.1248 - # Timezone functions
237.1249 -
237.1250 - </FunctionDef> <FunctionDef>def utcoffset(<Name>self</Name>):
237.1251 - <Expr><Str>"""Return the timezone offset in minutes east of UTC (negative west of
237.1252 - UTC)."""</Str></Expr>
237.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>
237.1254 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"utcoffset"</Str>, <Name>offset</Name>)</Call></Assign>
237.1255 - <If>if <Compare><Name>offset</Name> is not <Name>None</Name></Compare>:
237.1256 - <Assign><Name>offset</Name> = <Call><Name>timedelta</Name>(minutes=<Name>offset</Name>)</Call></Assign>
237.1257 - </If> <Return>return <Name>offset</Name></Return>
237.1258 -
237.1259 - # Return an integer (or None) instead of a timedelta (or None).
237.1260 - </FunctionDef> <FunctionDef>def _utcoffset(<Name>self</Name>):
237.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>
237.1262 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"utcoffset"</Str>, <Name>offset</Name>)</Call></Assign>
237.1263 - <Return>return <Name>offset</Name></Return>
237.1264 -
237.1265 - </FunctionDef> <FunctionDef>def tzname(<Name>self</Name>):
237.1266 - <Expr><Str>"""Return the timezone name.
237.1267 -
237.1268 - Note that the name is 100% informational -- there's no requirement that
237.1269 - it mean anything in particular. For example, "GMT", "UTC", "-500",
237.1270 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
237.1271 - """</Str></Expr>
237.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>
237.1273 - <Expr><Call><Name>_check_tzname</Name>(<Name>name</Name>)</Call></Expr>
237.1274 - <Return>return <Name>name</Name></Return>
237.1275 -
237.1276 - </FunctionDef> <FunctionDef>def dst(<Name>self</Name>):
237.1277 - <Expr><Str>"""Return 0 if DST is not in effect, or the DST offset (in minutes
237.1278 - eastward) if DST is in effect.
237.1279 -
237.1280 - This is purely informational; the DST offset has already been added to
237.1281 - the UTC offset returned by utcoffset() if applicable, so there's no
237.1282 - need to consult dst() unless you're interested in displaying the DST
237.1283 - info.
237.1284 - """</Str></Expr>
237.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>
237.1286 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"dst"</Str>, <Name>offset</Name>)</Call></Assign>
237.1287 - <If>if <Compare><Name>offset</Name> is not <Name>None</Name></Compare>:
237.1288 - <Assign><Name>offset</Name> = <Call><Name>timedelta</Name>(minutes=<Name>offset</Name>)</Call></Assign>
237.1289 - </If> <Return>return <Name>offset</Name></Return>
237.1290 -
237.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>,
237.1292 - <Name>tzinfo</Name>=<Name>True</Name>):
237.1293 - <Expr><Str>"""Return a new time with new values for the specified fields."""</Str></Expr>
237.1294 - <If>if <Compare><Name>hour</Name> is <Name>None</Name></Compare>:
237.1295 - <Assign><Name>hour</Name> = <Attribute><Name>self</Name>.hour</Attribute></Assign>
237.1296 - </If> <If>if <Compare><Name>minute</Name> is <Name>None</Name></Compare>:
237.1297 - <Assign><Name>minute</Name> = <Attribute><Name>self</Name>.minute</Attribute></Assign>
237.1298 - </If> <If>if <Compare><Name>second</Name> is <Name>None</Name></Compare>:
237.1299 - <Assign><Name>second</Name> = <Attribute><Name>self</Name>.second</Attribute></Assign>
237.1300 - </If> <If>if <Compare><Name>microsecond</Name> is <Name>None</Name></Compare>:
237.1301 - <Assign><Name>microsecond</Name> = <Attribute><Name>self</Name>.microsecond</Attribute></Assign>
237.1302 - </If> <If>if <Compare><Name>tzinfo</Name> is <Name>True</Name></Compare>:
237.1303 - <Assign><Name>tzinfo</Name> = <Attribute><Name>self</Name>.tzinfo</Attribute></Assign>
237.1304 - </If> <Expr><Call><Name>_check_time_fields</Name>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)</Call></Expr>
237.1305 - <Expr><Call><Name>_check_tzinfo_arg</Name>(<Name>tzinfo</Name>)</Call></Expr>
237.1306 - <Return>return <Call><Name>time</Name>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>, <Name>tzinfo</Name>)</Call></Return>
237.1307 -
237.1308 - # Return an integer (or None) instead of a timedelta (or None).
237.1309 - </FunctionDef> <FunctionDef>def _dst(<Name>self</Name>):
237.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>
237.1311 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"dst"</Str>, <Name>offset</Name>)</Call></Assign>
237.1312 - <Return>return <Name>offset</Name></Return>
237.1313 -
237.1314 - </FunctionDef> <FunctionDef>def __nonzero__(<Name>self</Name>):
237.1315 - <If>if <BoolOp><Attribute><Name>self</Name>.second</Attribute> or <Attribute><Name>self</Name>.microsecond</Attribute></BoolOp>:
237.1316 - <Return>return <Num>1</Num></Return>
237.1317 - </If> <Assign><Name>offset</Name> = <BoolOp><Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call> or <Num>0</Num></BoolOp></Assign>
237.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>
237.1319 -
237.1320 - # Pickle support.
237.1321 -
237.1322 - </FunctionDef> <Assign><Name>__safe_for_unpickling__</Name> = <Name>True</Name></Assign> # For Python 2.2
237.1323 -
237.1324 - <FunctionDef>def __getstate(<Name>self</Name>):
237.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>
237.1326 - <Assign><Tuple><Name>us1</Name>, <Name>us2</Name></Tuple> = <Call><Name>divmod</Name>(<Name>us2</Name>, <Num>256</Num>)</Call></Assign>
237.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>,
237.1328 - <Name>us1</Name>, <Name>us2</Name>, <Name>us3</Name>)</Tuple></BinOp></Assign>
237.1329 - <If>if <Compare><Attribute><Name>self</Name>._tzinfo</Attribute> is <Name>None</Name></Compare>:
237.1330 - <Return>return <Tuple>(<Name>basestate</Name>,)</Tuple></Return>
237.1331 - else:
237.1332 - <Return>return <Tuple>(<Name>basestate</Name>, <Attribute><Name>self</Name>._tzinfo</Attribute>)</Tuple></Return>
237.1333 -
237.1334 - </If></FunctionDef> <FunctionDef>def __setstate(<Name>self</Name>, <Name>state</Name>):
237.1335 - <Assert>assert <Call><Name>isinstance</Name>(<Name>state</Name>, <Name>tuple</Name>)</Call></Assert>
237.1336 - <Assert>assert <Compare><Num>1</Num> <= <Call><Name>len</Name>(<Name>state</Name>)</Call> <= <Num>2</Num></Compare></Assert>
237.1337 - <Assign><Name>string</Name> = <Subscript><Name>state</Name>[<Index><Num>0</Num></Index>]</Subscript></Assign>
237.1338 - <Assert>assert <Compare><Call><Name>len</Name>(<Name>string</Name>)</Call> == <Num>6</Num></Compare></Assert>
237.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> = \
237.1340 - <Call><Name>map</Name>(<Name>ord</Name>, <Name>string</Name>)</Call></Assign>
237.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>
237.1342 - <If>if <Compare><Call><Name>len</Name>(<Name>state</Name>)</Call> == <Num>1</Num></Compare>:
237.1343 - <Assign><Attribute><Name>self</Name>._tzinfo</Attribute> = <Name>None</Name></Assign>
237.1344 - else:
237.1345 - <Assign><Attribute><Name>self</Name>._tzinfo</Attribute> = <Subscript><Name>state</Name>[<Index><Num>1</Num></Index>]</Subscript></Assign>
237.1346 -
237.1347 - </If></FunctionDef> <FunctionDef>def __reduce__(<Name>self</Name>):
237.1348 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__class__</Attribute>, <Call><Attribute><Name>self</Name>.__getstate</Attribute>()</Call>)</Tuple></Return>
237.1349 -
237.1350 -</FunctionDef></ClassDef><Assign><Name>_time_class</Name> = <Name>time</Name></Assign> # so functions w/ args named "time" can get at the class
237.1351 -
237.1352 -<Assign><Attribute><Name>time</Name>.min</Attribute> = <Call><Name>time</Name>(<Num>0</Num>, <Num>0</Num>, <Num>0</Num>)</Call></Assign>
237.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>
237.1354 -<Assign><Attribute><Name>time</Name>.resolution</Attribute> = <Call><Name>timedelta</Name>(microseconds=<Num>1</Num>)</Call></Assign>
237.1355 -
237.1356 -<ClassDef>class datetime(<Name>date</Name>):
237.1357 -
237.1358 - # XXX needs docstrings
237.1359 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
237.1360 -
237.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>,
237.1362 - <Name>microsecond</Name>=<Num>0</Num>, <Name>tzinfo</Name>=<Name>None</Name>):
237.1363 - <If>if <Call><Name>isinstance</Name>(<Name>year</Name>, <Name>str</Name>)</Call>:
237.1364 - # Pickle support
237.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>
237.1366 - <Expr><Call><Attribute><Name>self</Name>.__setstate</Attribute>(<Tuple>(<Name>year</Name>, <Name>month</Name>)</Tuple>)</Call></Expr>
237.1367 - <Return>return <Name>self</Name></Return>
237.1368 - </If> <Expr><Call><Name>_check_tzinfo_arg</Name>(<Name>tzinfo</Name>)</Call></Expr>
237.1369 - <Expr><Call><Name>_check_time_fields</Name>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)</Call></Expr>
237.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>
237.1371 - # XXX This duplicates __year, __month, __day for convenience :-(
237.1372 - <Assign><Attribute><Name>self</Name>.__year</Attribute> = <Name>year</Name></Assign>
237.1373 - <Assign><Attribute><Name>self</Name>.__month</Attribute> = <Name>month</Name></Assign>
237.1374 - <Assign><Attribute><Name>self</Name>.__day</Attribute> = <Name>day</Name></Assign>
237.1375 - <Assign><Attribute><Name>self</Name>.__hour</Attribute> = <Name>hour</Name></Assign>
237.1376 - <Assign><Attribute><Name>self</Name>.__minute</Attribute> = <Name>minute</Name></Assign>
237.1377 - <Assign><Attribute><Name>self</Name>.__second</Attribute> = <Name>second</Name></Assign>
237.1378 - <Assign><Attribute><Name>self</Name>.__microsecond</Attribute> = <Name>microsecond</Name></Assign>
237.1379 - <Assign><Attribute><Name>self</Name>._tzinfo</Attribute> = <Name>tzinfo</Name></Assign>
237.1380 - <Return>return <Name>self</Name></Return>
237.1381 -
237.1382 - # Read-only field accessors
237.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>
237.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>
237.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>
237.1386 - <Assign><Name>microsecond</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__microsecond</Attribute></Lambda>,
237.1387 - doc=<Str>"microsecond (0-999999)"</Str>)</Call></Assign>
237.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>
237.1389 -
237.1390 - <FunctionDef>def fromtimestamp(<Name>cls</Name>, <Name>t</Name>, <Name>tz</Name>=<Name>None</Name>):
237.1391 - <Expr><Str>"""Construct a datetime from a POSIX timestamp (like time.time()).
237.1392 -
237.1393 - A timezone info object may be passed in as well.
237.1394 - """</Str></Expr>
237.1395 -
237.1396 - <Expr><Call><Name>_check_tzinfo_arg</Name>(<Name>tz</Name>)</Call></Expr>
237.1397 - <If>if <Compare><Name>tz</Name> is <Name>None</Name></Compare>:
237.1398 - <Assign><Name>converter</Name> = <Attribute><Name>_time</Name>.localtime</Attribute></Assign>
237.1399 - else:
237.1400 - <Assign><Name>converter</Name> = <Attribute><Name>_time</Name>.gmtime</Attribute></Assign>
237.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>
237.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>
237.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
237.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>
237.1405 - <If>if <Compare><Name>tz</Name> is not <Name>None</Name></Compare>:
237.1406 - <Assign><Name>result</Name> = <Call><Attribute><Name>tz</Name>.fromutc</Attribute>(<Name>result</Name>)</Call></Assign>
237.1407 - </If> <Return>return <Name>result</Name></Return>
237.1408 - </FunctionDef> <Assign><Name>fromtimestamp</Name> = <Call><Name>classmethod</Name>(<Name>fromtimestamp</Name>)</Call></Assign>
237.1409 -
237.1410 - <FunctionDef>def utcfromtimestamp(<Name>cls</Name>, <Name>t</Name>):
237.1411 - <Expr><Str>"Construct a UTC datetime from a POSIX timestamp (like time.time())."</Str></Expr>
237.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>
237.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>
237.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
237.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>
237.1416 - </FunctionDef> <Assign><Name>utcfromtimestamp</Name> = <Call><Name>classmethod</Name>(<Name>utcfromtimestamp</Name>)</Call></Assign>
237.1417 -
237.1418 - # XXX This is supposed to do better than we *can* do by using time.time(),
237.1419 - # XXX if the platform supports a more accurate way. The C implementation
237.1420 - # XXX uses gettimeofday on platforms that have it, but that isn't
237.1421 - # XXX available from Python. So now() may return different results
237.1422 - # XXX across the implementations.
237.1423 - <FunctionDef>def now(<Name>cls</Name>, <Name>tz</Name>=<Name>None</Name>):
237.1424 - <Expr><Str>"Construct a datetime from time.time() and optional time zone info."</Str></Expr>
237.1425 - <Assign><Name>t</Name> = <Call><Attribute><Name>_time</Name>.time</Attribute>()</Call></Assign>
237.1426 - <Return>return <Call><Attribute><Name>cls</Name>.fromtimestamp</Attribute>(<Name>t</Name>, <Name>tz</Name>)</Call></Return>
237.1427 - </FunctionDef> <Assign><Name>now</Name> = <Call><Name>classmethod</Name>(<Name>now</Name>)</Call></Assign>
237.1428 -
237.1429 - <FunctionDef>def utcnow(<Name>cls</Name>):
237.1430 - <Expr><Str>"Construct a UTC datetime from time.time()."</Str></Expr>
237.1431 - <Assign><Name>t</Name> = <Call><Attribute><Name>_time</Name>.time</Attribute>()</Call></Assign>
237.1432 - <Return>return <Call><Attribute><Name>cls</Name>.utcfromtimestamp</Attribute>(<Name>t</Name>)</Call></Return>
237.1433 - </FunctionDef> <Assign><Name>utcnow</Name> = <Call><Name>classmethod</Name>(<Name>utcnow</Name>)</Call></Assign>
237.1434 -
237.1435 - <FunctionDef>def combine(<Name>cls</Name>, <Name>date</Name>, <Name>time</Name>):
237.1436 - <Expr><Str>"Construct a datetime from a given date and a given time."</Str></Expr>
237.1437 - <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>date</Name>, <Name>_date_class</Name>)</Call></UnaryOp>:
237.1438 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"date argument must be a date instance"</Str>)</Call></Raise>
237.1439 - </If> <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>time</Name>, <Name>_time_class</Name>)</Call></UnaryOp>:
237.1440 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"time argument must be a time instance"</Str>)</Call></Raise>
237.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>,
237.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>,
237.1443 - <Attribute><Name>time</Name>.tzinfo</Attribute>)</Call></Return>
237.1444 - </FunctionDef> <Assign><Name>combine</Name> = <Call><Name>classmethod</Name>(<Name>combine</Name>)</Call></Assign>
237.1445 -
237.1446 - <FunctionDef>def timetuple(<Name>self</Name>):
237.1447 - <Expr><Str>"Return local time tuple compatible with time.localtime()."</Str></Expr>
237.1448 - <Assign><Name>dst</Name> = <Call><Attribute><Name>self</Name>._dst</Attribute>()</Call></Assign>
237.1449 - <If>if <Compare><Name>dst</Name> is <Name>None</Name></Compare>:
237.1450 - <Assign><Name>dst</Name> = <Num>-1</Num></Assign>
237.1451 - <If>elif <Name>dst</Name>:
237.1452 - <Assign><Name>dst</Name> = <Num>1</Num></Assign>
237.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>,
237.1454 - <Attribute><Name>self</Name>.hour</Attribute>, <Attribute><Name>self</Name>.minute</Attribute>, <Attribute><Name>self</Name>.second</Attribute>,
237.1455 - <Name>dst</Name>)</Call></Return>
237.1456 -
237.1457 - </FunctionDef> <FunctionDef>def utctimetuple(<Name>self</Name>):
237.1458 - <Expr><Str>"Return UTC time tuple compatible with time.gmtime()."</Str></Expr>
237.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>
237.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>
237.1461 - <Assign><Name>offset</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
237.1462 - <If>if <Name>offset</Name>: # neither None nor 0
237.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>
237.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>
237.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>
237.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>
237.1467 -
237.1468 - </FunctionDef> <FunctionDef>def date(<Name>self</Name>):
237.1469 - <Expr><Str>"Return the date part."</Str></Expr>
237.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>
237.1471 -
237.1472 - </FunctionDef> <FunctionDef>def time(<Name>self</Name>):
237.1473 - <Expr><Str>"Return the time part, with tzinfo None."</Str></Expr>
237.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>
237.1475 -
237.1476 - </FunctionDef> <FunctionDef>def timetz(<Name>self</Name>):
237.1477 - <Expr><Str>"Return the time part, with same tzinfo."</Str></Expr>
237.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>,
237.1479 - <Attribute><Name>self</Name>._tzinfo</Attribute>)</Call></Return>
237.1480 -
237.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>,
237.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>):
237.1483 - <Expr><Str>"""Return a new datetime with new values for the specified fields."""</Str></Expr>
237.1484 - <If>if <Compare><Name>year</Name> is <Name>None</Name></Compare>:
237.1485 - <Assign><Name>year</Name> = <Attribute><Name>self</Name>.year</Attribute></Assign>
237.1486 - </If> <If>if <Compare><Name>month</Name> is <Name>None</Name></Compare>:
237.1487 - <Assign><Name>month</Name> = <Attribute><Name>self</Name>.month</Attribute></Assign>
237.1488 - </If> <If>if <Compare><Name>day</Name> is <Name>None</Name></Compare>:
237.1489 - <Assign><Name>day</Name> = <Attribute><Name>self</Name>.day</Attribute></Assign>
237.1490 - </If> <If>if <Compare><Name>hour</Name> is <Name>None</Name></Compare>:
237.1491 - <Assign><Name>hour</Name> = <Attribute><Name>self</Name>.hour</Attribute></Assign>
237.1492 - </If> <If>if <Compare><Name>minute</Name> is <Name>None</Name></Compare>:
237.1493 - <Assign><Name>minute</Name> = <Attribute><Name>self</Name>.minute</Attribute></Assign>
237.1494 - </If> <If>if <Compare><Name>second</Name> is <Name>None</Name></Compare>:
237.1495 - <Assign><Name>second</Name> = <Attribute><Name>self</Name>.second</Attribute></Assign>
237.1496 - </If> <If>if <Compare><Name>microsecond</Name> is <Name>None</Name></Compare>:
237.1497 - <Assign><Name>microsecond</Name> = <Attribute><Name>self</Name>.microsecond</Attribute></Assign>
237.1498 - </If> <If>if <Compare><Name>tzinfo</Name> is <Name>True</Name></Compare>:
237.1499 - <Assign><Name>tzinfo</Name> = <Attribute><Name>self</Name>.tzinfo</Attribute></Assign>
237.1500 - </If> <Expr><Call><Name>_check_date_fields</Name>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)</Call></Expr>
237.1501 - <Expr><Call><Name>_check_time_fields</Name>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)</Call></Expr>
237.1502 - <Expr><Call><Name>_check_tzinfo_arg</Name>(<Name>tzinfo</Name>)</Call></Expr>
237.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>,
237.1504 - <Name>microsecond</Name>, <Name>tzinfo</Name>)</Call></Return>
237.1505 -
237.1506 - </FunctionDef> <FunctionDef>def astimezone(<Name>self</Name>, <Name>tz</Name>):
237.1507 - <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>tz</Name>, <Name>tzinfo</Name>)</Call></UnaryOp>:
237.1508 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"tz argument must be an instance of tzinfo"</Str>)</Call></Raise>
237.1509 -
237.1510 - </If> <Assign><Name>mytz</Name> = <Attribute><Name>self</Name>.tzinfo</Attribute></Assign>
237.1511 - <If>if <Compare><Name>mytz</Name> is <Name>None</Name></Compare>:
237.1512 - <Raise>raise <Call><Name>ValueError</Name>(<Str>"astimezone() requires an aware datetime"</Str>)</Call></Raise>
237.1513 -
237.1514 - </If> <If>if <Compare><Name>tz</Name> is <Name>mytz</Name></Compare>:
237.1515 - <Return>return <Name>self</Name></Return>
237.1516 -
237.1517 - # Convert self to UTC, and attach the new time zone object.
237.1518 - </If> <Assign><Name>myoffset</Name> = <Call><Attribute><Name>self</Name>.utcoffset</Attribute>()</Call></Assign>
237.1519 - <If>if <Compare><Name>myoffset</Name> is <Name>None</Name></Compare>:
237.1520 - <Raise>raise <Call><Name>ValuError</Name>(<Str>"astimezone() requires an aware datetime"</Str>)</Call></Raise>
237.1521 - </If> <Assign><Name>utc</Name> = <Call><Attribute><BinOp>(<Name>self</Name> - <Name>myoffset</Name>)</BinOp>.replace</Attribute>(tzinfo=<Name>tz</Name>)</Call></Assign>
237.1522 -
237.1523 - # Convert from UTC to tz's local time.
237.1524 - <Return>return <Call><Attribute><Name>tz</Name>.fromutc</Attribute>(<Name>utc</Name>)</Call></Return>
237.1525 -
237.1526 - # Ways to produce a string.
237.1527 -
237.1528 - </FunctionDef> <FunctionDef>def ctime(<Name>self</Name>):
237.1529 - <Expr><Str>"Format a la ctime()."</Str></Expr>
237.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>,
237.1531 - <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>)</Call></Assign>
237.1532 - <Return>return <Call><Attribute><Name>t</Name>.ctime</Attribute>()</Call></Return>
237.1533 -
237.1534 - </FunctionDef> <FunctionDef>def isoformat(<Name>self</Name>, <Name>sep</Name>=<Str>'T'</Str>):
237.1535 - <Expr><Str>"""Return the time formatted according to ISO.
237.1536 -
237.1537 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
237.1538 - self.microsecond == 0.
237.1539 -
237.1540 - If self.tzinfo is not None, the UTC offset is also attached, giving
237.1541 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
237.1542 -
237.1543 - Optional argument sep specifies the separator between date and
237.1544 - time, default 'T'.
237.1545 - """</Str></Expr>
237.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>,
237.1547 - <Name>sep</Name>)</Tuple> +
237.1548 - <Call><Name>_format_time</Name>(<Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>,
237.1549 - <Attribute><Name>self</Name>.__microsecond</Attribute>)</Call>)</BinOp></Assign>
237.1550 - <Assign><Name>off</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
237.1551 - <If>if <Compare><Name>off</Name> is not <Name>None</Name></Compare>:
237.1552 - <If>if <Compare><Name>off</Name> < <Num>0</Num></Compare>:
237.1553 - <Assign><Name>sign</Name> = <Str>"-"</Str></Assign>
237.1554 - <Assign><Name>off</Name> = <UnaryOp>-<Name>off</Name></UnaryOp></Assign>
237.1555 - else:
237.1556 - <Assign><Name>sign</Name> = <Str>"+"</Str></Assign>
237.1557 - </If> <Assign><Tuple><Name>hh</Name>, <Name>mm</Name></Tuple> = <Call><Name>divmod</Name>(<Name>off</Name>, <Num>60</Num>)</Call></Assign>
237.1558 - <AugAssign><Name>s</Name> += <BinOp><Str>"%s%02d:%02d"</Str> % <Tuple>(<Name>sign</Name>, <Name>hh</Name>, <Name>mm</Name>)</Tuple></BinOp></AugAssign>
237.1559 - </If> <Return>return <Name>s</Name></Return>
237.1560 -
237.1561 - </FunctionDef> <FunctionDef>def __repr__(<Name>self</Name>):
237.1562 - <Expr><Str>"Convert to formal string, for repr()."</Str></Expr>
237.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
237.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>
237.1565 - <If>if <Compare><Subscript><Name>L</Name>[<Index><Num>-1</Num></Index>]</Subscript> == <Num>0</Num></Compare>:
237.1566 - <Delete>del <Subscript><Name>L</Name>[<Index><Num>-1</Num></Index>]</Subscript></Delete>
237.1567 - </If> <If>if <Compare><Subscript><Name>L</Name>[<Index><Num>-1</Num></Index>]</Subscript> == <Num>0</Num></Compare>:
237.1568 - <Delete>del <Subscript><Name>L</Name>[<Index><Num>-1</Num></Index>]</Subscript></Delete>
237.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>
237.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>
237.1571 - <If>if <Compare><Attribute><Name>self</Name>._tzinfo</Attribute> is not <Name>None</Name></Compare>:
237.1572 - <Assert>assert <Compare><Subscript><Name>s</Name>[<Slice><Num>-1</Num>:</Slice>]</Subscript> == <Str>")"</Str></Compare></Assert>
237.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>
237.1574 - </If> <Return>return <Name>s</Name></Return>
237.1575 -
237.1576 - </FunctionDef> <FunctionDef>def __str__(<Name>self</Name>):
237.1577 - <Expr><Str>"Convert to string, for str()."</Str></Expr>
237.1578 - <Return>return <Call><Attribute><Name>self</Name>.isoformat</Attribute>(sep=<Str>' '</Str>)</Call></Return>
237.1579 -
237.1580 - </FunctionDef> <FunctionDef>def utcoffset(<Name>self</Name>):
237.1581 - <Expr><Str>"""Return the timezone offset in minutes east of UTC (negative west of
237.1582 - UTC)."""</Str></Expr>
237.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>
237.1584 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"utcoffset"</Str>, <Name>offset</Name>)</Call></Assign>
237.1585 - <If>if <Compare><Name>offset</Name> is not <Name>None</Name></Compare>:
237.1586 - <Assign><Name>offset</Name> = <Call><Name>timedelta</Name>(minutes=<Name>offset</Name>)</Call></Assign>
237.1587 - </If> <Return>return <Name>offset</Name></Return>
237.1588 -
237.1589 - # Return an integer (or None) instead of a timedelta (or None).
237.1590 - </FunctionDef> <FunctionDef>def _utcoffset(<Name>self</Name>):
237.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>
237.1592 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"utcoffset"</Str>, <Name>offset</Name>)</Call></Assign>
237.1593 - <Return>return <Name>offset</Name></Return>
237.1594 -
237.1595 - </FunctionDef> <FunctionDef>def tzname(<Name>self</Name>):
237.1596 - <Expr><Str>"""Return the timezone name.
237.1597 -
237.1598 - Note that the name is 100% informational -- there's no requirement that
237.1599 - it mean anything in particular. For example, "GMT", "UTC", "-500",
237.1600 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
237.1601 - """</Str></Expr>
237.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>
237.1603 - <Expr><Call><Name>_check_tzname</Name>(<Name>name</Name>)</Call></Expr>
237.1604 - <Return>return <Name>name</Name></Return>
237.1605 -
237.1606 - </FunctionDef> <FunctionDef>def dst(<Name>self</Name>):
237.1607 - <Expr><Str>"""Return 0 if DST is not in effect, or the DST offset (in minutes
237.1608 - eastward) if DST is in effect.
237.1609 -
237.1610 - This is purely informational; the DST offset has already been added to
237.1611 - the UTC offset returned by utcoffset() if applicable, so there's no
237.1612 - need to consult dst() unless you're interested in displaying the DST
237.1613 - info.
237.1614 - """</Str></Expr>
237.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>
237.1616 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"dst"</Str>, <Name>offset</Name>)</Call></Assign>
237.1617 - <If>if <Compare><Name>offset</Name> is not <Name>None</Name></Compare>:
237.1618 - <Assign><Name>offset</Name> = <Call><Name>timedelta</Name>(minutes=<Name>offset</Name>)</Call></Assign>
237.1619 - </If> <Return>return <Name>offset</Name></Return>
237.1620 -
237.1621 - # Return an integer (or None) instead of a timedelta (or None).1573
237.1622 - </FunctionDef> <FunctionDef>def _dst(<Name>self</Name>):
237.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>
237.1624 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"dst"</Str>, <Name>offset</Name>)</Call></Assign>
237.1625 - <Return>return <Name>offset</Name></Return>
237.1626 -
237.1627 - # Comparisons.
237.1628 -
237.1629 - </FunctionDef> <FunctionDef>def __eq__(<Name>self</Name>, <Name>other</Name>):
237.1630 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call>:
237.1631 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> == <Num>0</Num></Compare></Return>
237.1632 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
237.1633 - <Return>return <Name>NotImplemented</Name></Return>
237.1634 - else:
237.1635 - <Return>return <Name>False</Name></Return>
237.1636 -
237.1637 - </If></If></FunctionDef> <FunctionDef>def __ne__(<Name>self</Name>, <Name>other</Name>):
237.1638 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call>:
237.1639 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> != <Num>0</Num></Compare></Return>
237.1640 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
237.1641 - <Return>return <Name>NotImplemented</Name></Return>
237.1642 - else:
237.1643 - <Return>return <Name>True</Name></Return>
237.1644 -
237.1645 - </If></If></FunctionDef> <FunctionDef>def __le__(<Name>self</Name>, <Name>other</Name>):
237.1646 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call>:
237.1647 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> <= <Num>0</Num></Compare></Return>
237.1648 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
237.1649 - <Return>return <Name>NotImplemented</Name></Return>
237.1650 - else:
237.1651 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.1652 -
237.1653 - </If></If></FunctionDef> <FunctionDef>def __lt__(<Name>self</Name>, <Name>other</Name>):
237.1654 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call>:
237.1655 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> < <Num>0</Num></Compare></Return>
237.1656 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
237.1657 - <Return>return <Name>NotImplemented</Name></Return>
237.1658 - else:
237.1659 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.1660 -
237.1661 - </If></If></FunctionDef> <FunctionDef>def __ge__(<Name>self</Name>, <Name>other</Name>):
237.1662 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call>:
237.1663 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> >= <Num>0</Num></Compare></Return>
237.1664 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
237.1665 - <Return>return <Name>NotImplemented</Name></Return>
237.1666 - else:
237.1667 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.1668 -
237.1669 - </If></If></FunctionDef> <FunctionDef>def __gt__(<Name>self</Name>, <Name>other</Name>):
237.1670 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call>:
237.1671 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> > <Num>0</Num></Compare></Return>
237.1672 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
237.1673 - <Return>return <Name>NotImplemented</Name></Return>
237.1674 - else:
237.1675 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
237.1676 -
237.1677 - </If></If></FunctionDef> <FunctionDef>def __cmp(<Name>self</Name>, <Name>other</Name>):
237.1678 - <Assert>assert <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call></Assert>
237.1679 - <Assign><Name>mytz</Name> = <Attribute><Name>self</Name>._tzinfo</Attribute></Assign>
237.1680 - <Assign><Name>ottz</Name> = <Attribute><Name>other</Name>._tzinfo</Attribute></Assign>
237.1681 - <Assign><Name>myoff</Name> = <Name>otoff</Name> = <Name>None</Name></Assign>
237.1682 -
237.1683 - <If>if <Compare><Name>mytz</Name> is <Name>ottz</Name></Compare>:
237.1684 - <Assign><Name>base_compare</Name> = <Name>True</Name></Assign>
237.1685 - else:
237.1686 - <If>if <Compare><Name>mytz</Name> is not <Name>None</Name></Compare>:
237.1687 - <Assign><Name>myoff</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
237.1688 - </If> <If>if <Compare><Name>ottz</Name> is not <Name>None</Name></Compare>:
237.1689 - <Assign><Name>otoff</Name> = <Call><Attribute><Name>other</Name>._utcoffset</Attribute>()</Call></Assign>
237.1690 - </If> <Assign><Name>base_compare</Name> = <Compare><Name>myoff</Name> == <Name>otoff</Name></Compare></Assign>
237.1691 -
237.1692 - </If> <If>if <Name>base_compare</Name>:
237.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>,
237.1694 - <Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>,
237.1695 - <Attribute><Name>self</Name>.__microsecond</Attribute>)</Tuple>,
237.1696 - <Tuple>(<Attribute><Name>other</Name>.__year</Attribute>, <Attribute><Name>other</Name>.__month</Attribute>, <Attribute><Name>other</Name>.__day</Attribute>,
237.1697 - <Attribute><Name>other</Name>.__hour</Attribute>, <Attribute><Name>other</Name>.__minute</Attribute>, <Attribute><Name>other</Name>.__second</Attribute>,
237.1698 - <Attribute><Name>other</Name>.__microsecond</Attribute>)</Tuple>)</Call></Return>
237.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>:
237.1700 - # XXX Buggy in 2.2.2.
237.1701 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"cannot compare naive and aware datetimes"</Str>)</Call></Raise>
237.1702 - # XXX What follows could be done more efficiently...
237.1703 - </If> <Assign><Name>diff</Name> = <BinOp><Name>self</Name> - <Name>other</Name></BinOp></Assign> # this will take offsets into account
237.1704 - <If>if <Compare><Attribute><Name>diff</Name>.days</Attribute> < <Num>0</Num></Compare>:
237.1705 - <Return>return <Num>-1</Num></Return>
237.1706 - </If> <Return>return <BoolOp><BoolOp><Name>diff</Name></BoolOp> and <Num>1</Num> or <Num>0</Num></BoolOp></Return>
237.1707 -
237.1708 - </FunctionDef> <FunctionDef>def __add__(<Name>self</Name>, <Name>other</Name>):
237.1709 - <Expr><Str>"Add a datetime and a timedelta."</Str></Expr>
237.1710 - <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call></UnaryOp>:
237.1711 - <Return>return <Name>NotImplemented</Name></Return>
237.1712 - </If> <Assign><Name>t</Name> = <Call><Name>tmxxx</Name>(<Attribute><Name>self</Name>.__year</Attribute>,
237.1713 - <Attribute><Name>self</Name>.__month</Attribute>,
237.1714 - <BinOp><Attribute><Name>self</Name>.__day</Attribute> + <Attribute><Name>other</Name>.days</Attribute></BinOp>,
237.1715 - <Attribute><Name>self</Name>.__hour</Attribute>,
237.1716 - <Attribute><Name>self</Name>.__minute</Attribute>,
237.1717 - <BinOp><Attribute><Name>self</Name>.__second</Attribute> + <Attribute><Name>other</Name>.seconds</Attribute></BinOp>,
237.1718 - <BinOp><Attribute><Name>self</Name>.__microsecond</Attribute> + <Attribute><Name>other</Name>.microseconds</Attribute></BinOp>)</Call></Assign>
237.1719 - <Expr><Call><Attribute><Name>self</Name>._checkOverflow</Attribute>(<Attribute><Name>t</Name>.year</Attribute>)</Call></Expr>
237.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>,
237.1721 - <Attribute><Name>t</Name>.hour</Attribute>, <Attribute><Name>t</Name>.minute</Attribute>, <Attribute><Name>t</Name>.second</Attribute>,
237.1722 - <Attribute><Name>t</Name>.microsecond</Attribute>, tzinfo=<Attribute><Name>self</Name>._tzinfo</Attribute>)</Call></Assign>
237.1723 - <Return>return <Name>result</Name></Return>
237.1724 -
237.1725 - </FunctionDef> <Assign><Name>__radd__</Name> = <Name>__add__</Name></Assign>
237.1726 -
237.1727 - <FunctionDef>def __sub__(<Name>self</Name>, <Name>other</Name>):
237.1728 - <Expr><Str>"Subtract two datetimes, or a datetime and a timedelta."</Str></Expr>
237.1729 - <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call></UnaryOp>:
237.1730 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
237.1731 - <Return>return <BinOp><Name>self</Name> + <UnaryOp>-<Name>other</Name></UnaryOp></BinOp></Return>
237.1732 - </If> <Return>return <Name>NotImplemented</Name></Return>
237.1733 -
237.1734 - </If> <Assign><Name>days1</Name> = <Call><Attribute><Name>self</Name>.toordinal</Attribute>()</Call></Assign>
237.1735 - <Assign><Name>days2</Name> = <Call><Attribute><Name>other</Name>.toordinal</Attribute>()</Call></Assign>
237.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>
237.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>
237.1738 - <Assign><Name>base</Name> = <Call><Name>timedelta</Name>(<BinOp><Name>days1</Name> - <Name>days2</Name></BinOp>,
237.1739 - <BinOp><Name>secs1</Name> - <Name>secs2</Name></BinOp>,
237.1740 - <BinOp><Attribute><Name>self</Name>.__microsecond</Attribute> - <Attribute><Name>other</Name>.__microsecond</Attribute></BinOp>)</Call></Assign>
237.1741 - <If>if <Compare><Attribute><Name>self</Name>._tzinfo</Attribute> is <Attribute><Name>other</Name>._tzinfo</Attribute></Compare>:
237.1742 - <Return>return <Name>base</Name></Return>
237.1743 - </If> <Assign><Name>myoff</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
237.1744 - <Assign><Name>otoff</Name> = <Call><Attribute><Name>other</Name>._utcoffset</Attribute>()</Call></Assign>
237.1745 - <If>if <Compare><Name>myoff</Name> == <Name>otoff</Name></Compare>:
237.1746 - <Return>return <Name>base</Name></Return>
237.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>:
237.1748 - <Raise>raise <Name>TypeError</Name>, <Str>"cannot mix naive and timezone-aware time"</Str></Raise>
237.1749 - </If> <Return>return <BinOp><Name>base</Name> + <Call><Name>timedelta</Name>(minutes = <BinOp><Name>otoff</Name>-<Name>myoff</Name></BinOp>)</Call></BinOp></Return>
237.1750 -
237.1751 - </FunctionDef> <FunctionDef>def __hash__(<Name>self</Name>):
237.1752 - <Assign><Name>tzoff</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
237.1753 - <If>if <Compare><Name>tzoff</Name> is <Name>None</Name></Compare>:
237.1754 - <Return>return <Call><Name>hash</Name>(<Subscript><Attribute><Name>self</Name>.__getstate</Attribute><Call>()</Call>[<Index><Num>0</Num></Index>]</Subscript>)</Call></Return>
237.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>
237.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>
237.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>
237.1758 -
237.1759 - # Pickle support.
237.1760 -
237.1761 - </FunctionDef> <Assign><Name>__safe_for_unpickling__</Name> = <Name>True</Name></Assign> # For Python 2.2
237.1762 -
237.1763 - <FunctionDef>def __getstate(<Name>self</Name>):
237.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>
237.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>
237.1766 - <Assign><Tuple><Name>us1</Name>, <Name>us2</Name></Tuple> = <Call><Name>divmod</Name>(<Name>us2</Name>, <Num>256</Num>)</Call></Assign>
237.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>,
237.1768 - <Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>,
237.1769 - <Name>us1</Name>, <Name>us2</Name>, <Name>us3</Name>)</Tuple></BinOp></Assign>
237.1770 - <If>if <Compare><Attribute><Name>self</Name>._tzinfo</Attribute> is <Name>None</Name></Compare>:
237.1771 - <Return>return <Tuple>(<Name>basestate</Name>,)</Tuple></Return>
237.1772 - else:
237.1773 - <Return>return <Tuple>(<Name>basestate</Name>, <Attribute><Name>self</Name>._tzinfo</Attribute>)</Tuple></Return>
237.1774 -
237.1775 - </If></FunctionDef> <FunctionDef>def __setstate(<Name>self</Name>, <Name>state</Name>):
237.1776 - <Assert>assert <Call><Name>isinstance</Name>(<Name>state</Name>, <Name>tuple</Name>)</Call></Assert>
237.1777 - <Assert>assert <Compare><Num>1</Num> <= <Call><Name>len</Name>(<Name>state</Name>)</Call> <= <Num>2</Num></Compare></Assert>
237.1778 - <Assign><Name>string</Name> = <Subscript><Name>state</Name>[<Index><Num>0</Num></Index>]</Subscript></Assign>
237.1779 - <Assert>assert <Compare><Call><Name>len</Name>(<Name>string</Name>)</Call> == <Num>10</Num></Compare></Assert>
237.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>,
237.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>
237.1782 - <Assign><Attribute><Name>self</Name>.__year</Attribute> = <BinOp><BinOp><Name>yhi</Name></BinOp> * <Num>256</Num> + <Name>ylo</Name></BinOp></Assign>
237.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>
237.1784 - <If>if <Compare><Call><Name>len</Name>(<Name>state</Name>)</Call> == <Num>1</Num></Compare>:
237.1785 - <Assign><Attribute><Name>self</Name>._tzinfo</Attribute> = <Name>None</Name></Assign>
237.1786 - else:
237.1787 - <Assign><Attribute><Name>self</Name>._tzinfo</Attribute> = <Subscript><Name>state</Name>[<Index><Num>1</Num></Index>]</Subscript></Assign>
237.1788 -
237.1789 - </If></FunctionDef> <FunctionDef>def __reduce__(<Name>self</Name>):
237.1790 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__class__</Attribute>, <Call><Attribute><Name>self</Name>.__getstate</Attribute>()</Call>)</Tuple></Return>
237.1791 -
237.1792 -
237.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>
237.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>
237.1795 -<Assign><Attribute><Name>datetime</Name>.resolution</Attribute> = <Call><Name>timedelta</Name>(microseconds=<Num>1</Num>)</Call></Assign>
237.1796 -
237.1797 -
237.1798 -<FunctionDef>def _isoweek1monday(<Name>year</Name>):
237.1799 - # Helper to calculate the day number of the Monday starting week 1
237.1800 - # XXX This could be done more efficiently
237.1801 - <Assign><Name>THURSDAY</Name> = <Num>3</Num></Assign>
237.1802 - <Assign><Name>firstday</Name> = <Call><Name>_ymd2ord</Name>(<Name>year</Name>, <Num>1</Num>, <Num>1</Num>)</Call></Assign>
237.1803 - <Assign><Name>firstweekday</Name> = <BinOp><BinOp>(<Name>firstday</Name> + <Num>6</Num>)</BinOp> % <Num>7</Num></BinOp></Assign> # See weekday() above
237.1804 - <Assign><Name>week1monday</Name> = <BinOp><Name>firstday</Name> - <Name>firstweekday</Name></BinOp></Assign>
237.1805 - <If>if <Compare><Name>firstweekday</Name> > <Name>THURSDAY</Name></Compare>:
237.1806 - <AugAssign><Name>week1monday</Name> += <Num>7</Num></AugAssign>
237.1807 - </If> <Return>return <Name>week1monday</Name></Return>
237.1808 -
237.1809 -</FunctionDef><Expr><Str>"""
237.1810 -Some time zone algebra. For a datetime x, let
237.1811 - x.n = x stripped of its timezone -- its naive time.
237.1812 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
237.1813 - return None
237.1814 - x.d = x.dst(), and assuming that doesn't raise an exception or
237.1815 - return None
237.1816 - x.s = x's standard offset, x.o - x.d
237.1817 -
237.1818 -Now some derived rules, where k is a duration (timedelta).
237.1819 -
237.1820 -1. x.o = x.s + x.d
237.1821 - This follows from the definition of x.s.
237.1822 -
237.1823 -2. If x and y have the same tzinfo member, x.s = y.s.
237.1824 - This is actually a requirement, an assumption we need to make about
237.1825 - sane tzinfo classes.
237.1826 -
237.1827 -3. The naive UTC time corresponding to x is x.n - x.o.
237.1828 - This is again a requirement for a sane tzinfo class.
237.1829 -
237.1830 -4. (x+k).s = x.s
237.1831 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
237.1832 -
237.1833 -5. (x+k).n = x.n + k
237.1834 - Again follows from how arithmetic is defined.
237.1835 -
237.1836 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
237.1837 -(meaning that the various tzinfo methods exist, and don't blow up or return
237.1838 -None when called).
237.1839 -
237.1840 -The function wants to return a datetime y with timezone tz, equivalent to x.
237.1841 -x is already in UTC.
237.1842 -
237.1843 -By #3, we want
237.1844 -
237.1845 - y.n - y.o = x.n [1]
237.1846 -
237.1847 -The algorithm starts by attaching tz to x.n, and calling that y. So
237.1848 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
237.1849 -becomes true; in effect, we want to solve [2] for k:
237.1850 -
237.1851 - (y+k).n - (y+k).o = x.n [2]
237.1852 -
237.1853 -By #1, this is the same as
237.1854 -
237.1855 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
237.1856 -
237.1857 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
237.1858 -Substituting that into [3],
237.1859 -
237.1860 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
237.1861 - k - (y+k).s - (y+k).d = 0; rearranging,
237.1862 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
237.1863 - k = y.s - (y+k).d
237.1864 -
237.1865 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
237.1866 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
237.1867 -very large, since all offset-returning methods return a duration of magnitude
237.1868 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
237.1869 -be 0, so ignoring it has no consequence then.
237.1870 -
237.1871 -In any case, the new value is
237.1872 -
237.1873 - z = y + y.s [4]
237.1874 -
237.1875 -It's helpful to step back at look at [4] from a higher level: it's simply
237.1876 -mapping from UTC to tz's standard time.
237.1877 -
237.1878 -At this point, if
237.1879 -
237.1880 - z.n - z.o = x.n [5]
237.1881 -
237.1882 -we have an equivalent time, and are almost done. The insecurity here is
237.1883 -at the start of daylight time. Picture US Eastern for concreteness. The wall
237.1884 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
237.1885 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
237.1886 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
237.1887 -on the day DST starts. We want to return the 1:MM EST spelling because that's
237.1888 -the only spelling that makes sense on the local wall clock.
237.1889 -
237.1890 -In fact, if [5] holds at this point, we do have the standard-time spelling,
237.1891 -but that takes a bit of proof. We first prove a stronger result. What's the
237.1892 -difference between the LHS and RHS of [5]? Let
237.1893 -
237.1894 - diff = x.n - (z.n - z.o) [6]
237.1895 -
237.1896 -Now
237.1897 - z.n = by [4]
237.1898 - (y + y.s).n = by #5
237.1899 - y.n + y.s = since y.n = x.n
237.1900 - x.n + y.s = since z and y are have the same tzinfo member,
237.1901 - y.s = z.s by #2
237.1902 - x.n + z.s
237.1903 -
237.1904 -Plugging that back into [6] gives
237.1905 -
237.1906 - diff =
237.1907 - x.n - ((x.n + z.s) - z.o) = expanding
237.1908 - x.n - x.n - z.s + z.o = cancelling
237.1909 - - z.s + z.o = by #2
237.1910 - z.d
237.1911 -
237.1912 -So diff = z.d.
237.1913 -
237.1914 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
237.1915 -spelling we wanted in the endcase described above. We're done. Contrarily,
237.1916 -if z.d = 0, then we have a UTC equivalent, and are also done.
237.1917 -
237.1918 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
237.1919 -add to z (in effect, z is in tz's standard time, and we need to shift the
237.1920 -local clock into tz's daylight time).
237.1921 -
237.1922 -Let
237.1923 -
237.1924 - z' = z + z.d = z + diff [7]
237.1925 -
237.1926 -and we can again ask whether
237.1927 -
237.1928 - z'.n - z'.o = x.n [8]
237.1929 -
237.1930 -If so, we're done. If not, the tzinfo class is insane, according to the
237.1931 -assumptions we've made. This also requires a bit of proof. As before, let's
237.1932 -compute the difference between the LHS and RHS of [8] (and skipping some of
237.1933 -the justifications for the kinds of substitutions we've done several times
237.1934 -already):
237.1935 -
237.1936 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
237.1937 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
237.1938 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
237.1939 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
237.1940 - - z.n + z.n - z.o + z'.o = cancel z.n
237.1941 - - z.o + z'.o = #1 twice
237.1942 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
237.1943 - z'.d - z.d
237.1944 -
237.1945 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
237.1946 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
237.1947 -return z', not bothering to compute z'.d.
237.1948 -
237.1949 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
237.1950 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
237.1951 -would have to change the result dst() returns: we start in DST, and moving
237.1952 -a little further into it takes us out of DST.
237.1953 -
237.1954 -There isn't a sane case where this can happen. The closest it gets is at
237.1955 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
237.1956 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
237.1957 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
237.1958 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
237.1959 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
237.1960 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
237.1961 -standard time. Since that's what the local clock *does*, we want to map both
237.1962 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
237.1963 -in local time, but so it goes -- it's the way the local clock works.
237.1964 -
237.1965 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
237.1966 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
237.1967 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
237.1968 -(correctly) concludes that z' is not UTC-equivalent to x.
237.1969 -
237.1970 -Because we know z.d said z was in daylight time (else [5] would have held and
237.1971 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
237.1972 -and we we have stopped then), and there are only 2 possible values dst() can
237.1973 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
237.1974 -but the reasoning doesn't depend on the example -- it depends on there being
237.1975 -two possible dst() outcomes, one zero and the other non-zero). Therefore
237.1976 -z' must be in standard time, and is the spelling we want in this case.
237.1977 -
237.1978 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
237.1979 -concerned (because it takes z' as being in standard time rather than the
237.1980 -daylight time we intend here), but returning it gives the real-life "local
237.1981 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
237.1982 -tz.
237.1983 -
237.1984 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
237.1985 -the 1:MM standard time spelling we want.
237.1986 -
237.1987 -So how can this break? One of the assumptions must be violated. Two
237.1988 -possibilities:
237.1989 -
237.1990 -1) [2] effectively says that y.s is invariant across all y belong to a given
237.1991 - time zone. This isn't true if, for political reasons or continental drift,
237.1992 - a region decides to change its base offset from UTC.
237.1993 -
237.1994 -2) There may be versions of "double daylight" time where the tail end of
237.1995 - the analysis gives up a step too early. I haven't thought about that
237.1996 - enough to say.
237.1997 -
237.1998 -In any case, it's clear that the default fromutc() is strong enough to handle
237.1999 -"almost all" time zones: so long as the standard offset is invariant, it
237.2000 -doesn't matter if daylight time transition points change from year to year, or
237.2001 -if daylight time is skipped in some years; it doesn't matter how large or
237.2002 -small dst() may get within its bounds; and it doesn't even matter if some
237.2003 -perverse time zone returns a negative dst()). So a breaking case must be
237.2004 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
237.2005 -"""</Str></Expr>
237.2006 -
237.2007 -<FunctionDef>def _test():
237.2008 - <Import>import test_datetime</Import>
237.2009 - <Expr><Call><Attribute><Name>test_datetime</Name>.test_main</Attribute>()</Call></Expr>
237.2010 -
237.2011 -</FunctionDef><If>if <Compare><Name>__name__</Name> == <Str>"__main__"</Str></Compare>:
237.2012 - <Expr><Call><Name>_test</Name>()</Call></Expr></If></Module>
238.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.scopes Sun Jan 04 13:11:53 2015 -0600
238.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
238.3 @@ -1,1967 +0,0 @@
238.4 -=============================================
238.5 -<file-top>: Module : OffsetRange[0,71801>
238.6 -MAXYEAR [bound][data][read][node=Name]
238.7 -MINYEAR [bound][data][read][node=Name]
238.8 -None [read][UNRESOLVED][node=Name]
238.9 -_DAYNAMES [bound][private][data][read][node=Name]
238.10 -_DAYS_BEFORE_MONTH [bound][private][data][read][node=Name]
238.11 -_DAYS_IN_MONTH [bound][private][data][read][node=Name]
238.12 -_DI100Y [bound][private][data][read][node=Name]
238.13 -_DI400Y [bound][private][data][read][node=Name]
238.14 -_DI4Y [bound][private][data][read][node=Name]
238.15 -_MONTHNAMES [bound][private][data][read][node=Name]
238.16 -_ORD1970 [bound][private][data][read][node=Name]
238.17 -__name__ [read][UNRESOLVED][node=Name]
238.18 -_build_struct_time [bound][private][function][def][read][called][node=FunctionDef]
238.19 -_call_tzinfo_method [bound][private][function][def][read][called][node=FunctionDef]
238.20 -_check_date_fields [bound][private][function][def][read][called][node=FunctionDef]
238.21 -_check_time_fields [bound][private][function][def][read][called][node=FunctionDef]
238.22 -_check_tzinfo_arg [bound][private][function][def][read][called][node=FunctionDef]
238.23 -_check_tzname [bound][private][function][def][read][called][node=FunctionDef]
238.24 -_check_utc_offset [bound][private][function][def][read][called][node=FunctionDef]
238.25 -_cmperror [bound][private][function][def][read][called][node=FunctionDef]
238.26 -_date_class [bound][private][class][read][alias][node=ClassDef]
238.27 -_days_before_month [bound][private][function][def][read][called][node=FunctionDef]
238.28 -_days_before_year [bound][private][function][def][read][called][node=FunctionDef]
238.29 -_days_in_month [bound][private][function][def][read][called][node=FunctionDef]
238.30 -_days_in_year [bound][private][function][def][node=FunctionDef]
238.31 -_format_time [bound][private][function][def][read][called][node=FunctionDef]
238.32 -_is_leap [bound][private][function][def][read][called][node=FunctionDef]
238.33 -_isoweek1monday [bound][private][function][def][node=FunctionDef]
238.34 -_math [bound][imported][private][data][read][node=Import]
238.35 -_ord2ymd [bound][private][function][def][read][called][node=FunctionDef]
238.36 -_test [bound][private][function][def][read][called][node=FunctionDef]
238.37 -_time [bound][imported][private][data][read][node=Import]
238.38 -_time_class [bound][private][class][read][alias][node=ClassDef]
238.39 -_tzinfo_class [bound][private][class][alias][node=ClassDef]
238.40 -_wrap_strftime [bound][private][function][def][read][called][node=FunctionDef]
238.41 -_ymd2ord [bound][private][function][def][read][called][node=FunctionDef]
238.42 -date [bound][class][def][read][called][node=ClassDef]
238.43 -datetime [bound][class][def][read][called][node=ClassDef]
238.44 -dbm [bound][data][read][node=Name]
238.45 -dim [bound][data][read][node=Name]
238.46 -object [read][UNRESOLVED][node=Name]
238.47 -time [bound][class][def][read][called][node=ClassDef]
238.48 -timedelta [bound][class][def][read][called][node=ClassDef]
238.49 -tmxxx [bound][class][def][read][called][node=ClassDef]
238.50 -tzinfo [bound][class][def][read][node=ClassDef]
238.51 -
238.52 - =============================================
238.53 - _is_leap: FunctionDef : OffsetRange[1313,1438>
238.54 - year [bound][param][data][read][node=Name]
238.55 -
238.56 - =============================================
238.57 - _days_in_year: FunctionDef : OffsetRange[1438,1565>
238.58 - _is_leap [free][read][called][node=Name]
238.59 - year [bound][param][data][read][node=Name]
238.60 -
238.61 - =============================================
238.62 - _days_before_year: FunctionDef : OffsetRange[1565,1711>
238.63 - y [bound][data][read][node=Name]
238.64 - year [bound][param][data][read][node=Name]
238.65 -
238.66 - =============================================
238.67 - _days_in_month: FunctionDef : OffsetRange[1711,1933>
238.68 - _DAYS_IN_MONTH [free][read][node=Name]
238.69 - _is_leap [free][read][called][node=Name]
238.70 - month [bound][param][data][read][node=Name]
238.71 - year [bound][param][data][read][node=Name]
238.72 -
238.73 - =============================================
238.74 - _days_before_month: FunctionDef : OffsetRange[1933,2203>
238.75 - ValueError [free][read][called][node=Name]
238.76 - _DAYS_BEFORE_MONTH [free][read][node=Name]
238.77 - _is_leap [free][read][called][node=Name]
238.78 - month [bound][param][data][read][node=Name]
238.79 - year [bound][param][data][read][node=Name]
238.80 -
238.81 - =============================================
238.82 - _ymd2ord: FunctionDef : OffsetRange[2203,2619>
238.83 - ValueError [free][read][called][node=Name]
238.84 - _days_before_month [free][read][called][node=Name]
238.85 - _days_before_year [free][read][called][node=Name]
238.86 - _days_in_month [free][read][called][node=Name]
238.87 - day [bound][param][data][read][node=Name]
238.88 - dim [bound][data][read][node=Name]
238.89 - month [bound][param][data][read][node=Name]
238.90 - year [bound][param][data][read][node=Name]
238.91 -
238.92 - =============================================
238.93 - _ord2ymd: FunctionDef : OffsetRange[3228,6007>
238.94 - _DAYS_BEFORE_MONTH [free][read][node=Name]
238.95 - _DAYS_IN_MONTH [free][read][node=Name]
238.96 - _DI100Y [free][read][node=Name]
238.97 - _DI400Y [free][read][node=Name]
238.98 - _DI4Y [free][read][node=Name]
238.99 - _days_in_month [free][read][called][node=Name]
238.100 - _is_leap [free][read][called][node=Name]
238.101 - divmod [free][read][called][node=Name]
238.102 - leapyear [bound][data][read][node=Name]
238.103 - month [bound][data][read][node=Name]
238.104 - n [bound][param][data][read][node=Name]
238.105 - n1 [bound][data][read][node=Name]
238.106 - n100 [bound][data][read][node=Name]
238.107 - n4 [bound][data][read][node=Name]
238.108 - n400 [bound][data][read][node=Name]
238.109 - preceding [bound][data][read][node=Name]
238.110 - year [bound][data][read][node=Name]
238.111 -
238.112 - =============================================
238.113 - _build_struct_time: FunctionDef : OffsetRange[6203,6410>
238.114 - _days_before_month [free][read][called][node=Name]
238.115 - _time [free][read][node=Name]
238.116 - _ymd2ord [free][read][called][node=Name]
238.117 - d [bound][param][data][read][node=Name]
238.118 - dnum [bound][data][read][node=Name]
238.119 - dstflag [bound][param][data][read][node=Name]
238.120 - hh [bound][param][data][read][node=Name]
238.121 - m [bound][param][data][read][node=Name]
238.122 - mm [bound][param][data][read][node=Name]
238.123 - ss [bound][param][data][read][node=Name]
238.124 - wday [bound][data][read][node=Name]
238.125 - y [bound][param][data][read][node=Name]
238.126 -
238.127 - =============================================
238.128 - _format_time: FunctionDef : OffsetRange[6410,6661>
238.129 - hh [bound][param][data][read][node=Name]
238.130 - mm [bound][param][data][read][node=Name]
238.131 - result [bound][data][read][node=Name]
238.132 - ss [bound][param][data][read][node=Name]
238.133 - us [bound][param][data][read][node=Name]
238.134 -
238.135 - =============================================
238.136 - _wrap_strftime: FunctionDef : OffsetRange[6661,8721>
238.137 - None [free][read][node=Name]
238.138 - ValueError [free][read][called][node=Name]
238.139 - Zreplace [bound][data][read][node=Name]
238.140 - _time [free][read][node=Name]
238.141 - ch [bound][data][read][node=Name]
238.142 - divmod [free][read][called][node=Name]
238.143 - format [bound][param][data][read][node=Name]
238.144 - h [bound][data][read][node=Name]
238.145 - hasattr [free][read][called][node=Name]
238.146 - i [bound][data][read][node=Name]
238.147 - len [free][read][called][node=Name]
238.148 - m [bound][data][read][node=Name]
238.149 - n [bound][data][read][node=Name]
238.150 - newformat [bound][data][read][node=Name]
238.151 - object [bound][param][data][read][node=Name]
238.152 - offset [bound][data][read][node=Name]
238.153 - push [bound][data][read][called][node=Name]
238.154 - s [bound][data][read][node=Name]
238.155 - sign [bound][data][read][node=Name]
238.156 - timetuple [bound][param][data][read][node=Name]
238.157 - year [bound][data][read][node=Name]
238.158 - zreplace [bound][data][read][node=Name]
238.159 -
238.160 - =============================================
238.161 - _call_tzinfo_method: FunctionDef : OffsetRange[8721,8925>
238.162 - None [free][read][node=Name]
238.163 - getattr [free][read][called][node=Name]
238.164 - methname [bound][param][data][read][node=Name]
238.165 - tzinfo [bound][param][data][read][node=Name]
238.166 - tzinfoarg [bound][param][data][read][node=Name]
238.167 -
238.168 - =============================================
238.169 - _check_tzname: FunctionDef : OffsetRange[8925,9449>
238.170 - None [free][read][node=Name]
238.171 - TypeError [free][read][called][node=Name]
238.172 - isinstance [free][read][called][node=Name]
238.173 - name [bound][param][data][read][node=Name]
238.174 - str [free][read][node=Name]
238.175 - type [free][read][called][node=Name]
238.176 -
238.177 - =============================================
238.178 - _check_utc_offset: FunctionDef : OffsetRange[9449,10259>
238.179 - None [free][read][node=Name]
238.180 - TypeError [free][read][called][node=Name]
238.181 - ValueError [free][read][called][node=Name]
238.182 - days [bound][data][read][node=Name]
238.183 - divmod [free][read][called][node=Name]
238.184 - isinstance [free][read][called][node=Name]
238.185 - minutes [bound][data][read][node=Name]
238.186 - name [bound][param][data][read][node=Name]
238.187 - offset [bound][param][data][read][node=Name]
238.188 - seconds [bound][data][read][node=Name]
238.189 - timedelta [free][read][node=Name]
238.190 - type [free][read][called][node=Name]
238.191 -
238.192 - =============================================
238.193 - _check_date_fields: FunctionDef : OffsetRange[10259,10632>
238.194 - MAXYEAR [free][read][node=Name]
238.195 - MINYEAR [free][read][node=Name]
238.196 - ValueError [free][read][called][node=Name]
238.197 - _days_in_month [free][read][called][node=Name]
238.198 - day [bound][param][data][read][node=Name]
238.199 - dim [bound][data][read][node=Name]
238.200 - month [bound][param][data][read][node=Name]
238.201 - year [bound][param][data][read][node=Name]
238.202 -
238.203 - =============================================
238.204 - _check_time_fields: FunctionDef : OffsetRange[10632,11069>
238.205 - ValueError [free][read][called][node=Name]
238.206 - hour [bound][param][data][read][node=Name]
238.207 - microsecond [bound][param][data][read][node=Name]
238.208 - minute [bound][param][data][read][node=Name]
238.209 - second [bound][param][data][read][node=Name]
238.210 -
238.211 - =============================================
238.212 - _check_tzinfo_arg: FunctionDef : OffsetRange[11069,12221>
238.213 - None [free][read][node=Name]
238.214 - TypeError [free][read][called][node=Name]
238.215 - isinstance [free][read][called][node=Name]
238.216 - tz [bound][param][data][read][node=Name]
238.217 - tzinfo [free][read][node=Name]
238.218 -
238.219 - =============================================
238.220 - _cmperror: FunctionDef : OffsetRange[12221,12741>
238.221 - TypeError [free][read][called][node=Name]
238.222 - type [free][read][called][node=Name]
238.223 - x [bound][param][data][read][node=Name]
238.224 - y [bound][param][data][read][node=Name]
238.225 -
238.226 - =============================================
238.227 - class tmxxx: ClassDef : OffsetRange[12804,16258>
238.228 - None [free][read][node=Name]
238.229 - __init__ [bound][function][def][node=FunctionDef]
238.230 - ctime [bound][function][def][node=FunctionDef]
238.231 - ordinal [bound][data][node=Name]
238.232 - time [bound][function][def][node=FunctionDef]
238.233 - toordinal [bound][function][def][node=FunctionDef]
238.234 - ------ Attributes ---------------------------------------
238.235 - day : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.236 - hour : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.237 - microsecond : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.238 - minute : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.239 - month : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.240 - ordinal : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.241 - second : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.242 - year : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.243 -
238.244 - =============================================
238.245 - __init__: FunctionDef : OffsetRange[12842,15307>
238.246 - _days_in_month [free][read][called][node=Name]
238.247 - _ord2ymd [free][read][called][node=Name]
238.248 - _ymd2ord [free][read][called][node=Name]
238.249 - carry [bound][data][read][node=Name]
238.250 - day [bound][param][data][read][node=Name]
238.251 - dim [bound][data][read][node=Name]
238.252 - divmod [free][read][called][node=Name]
238.253 - hour [bound][param][data][read][node=Name]
238.254 - microsecond [bound][param][data][read][node=Name]
238.255 - minute [bound][param][data][read][node=Name]
238.256 - month [bound][param][data][read][node=Name]
238.257 - second [bound][param][data][read][node=Name]
238.258 - self [bound][param][data][read][node=Name]
238.259 - year [bound][param][data][read][node=Name]
238.260 - ------ Attributes ---------------------------------------
238.261 - ordinal : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.262 -
238.263 - =============================================
238.264 - toordinal: FunctionDef : OffsetRange[15308,15660>
238.265 - None [free][read][node=Name]
238.266 - _ymd2ord [free][read][called][node=Name]
238.267 - self [bound][param][data][read][node=Name]
238.268 - ------ Attributes ---------------------------------------
238.269 - day : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.270 - month : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.271 - ordinal : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.272 - year : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.273 -
238.274 - =============================================
238.275 - time: FunctionDef : OffsetRange[15661,15942>
238.276 - _ORD1970 [free][read][node=Name]
238.277 - days [bound][data][read][node=Name]
238.278 - seconds [bound][data][read][node=Name]
238.279 - self [bound][param][data][read][node=Name]
238.280 - ------ Attributes ---------------------------------------
238.281 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.282 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.283 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.284 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.285 - toordinal : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.286 -
238.287 - =============================================
238.288 - ctime: FunctionDef : OffsetRange[15943,16258>
238.289 - _DAYNAMES [free][read][node=Name]
238.290 - _MONTHNAMES [free][read][node=Name]
238.291 - self [bound][param][data][read][node=Name]
238.292 - weekday [bound][data][read][node=Name]
238.293 - ------ Attributes ---------------------------------------
238.294 - day : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.295 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.296 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.297 - month : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.298 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.299 - toordinal : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.300 - year : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.301 -
238.302 - =============================================
238.303 - class timedelta: ClassDef : OffsetRange[16258,25637>
238.304 - True [free][read][node=Name]
238.305 - __abs__ [bound][function][def][node=FunctionDef]
238.306 - __add__ [bound][function][def][read][node=FunctionDef]
238.307 - __cmp [bound][private][function][def][node=FunctionDef]
238.308 - __div__ [bound][function][def][read][node=FunctionDef]
238.309 - __eq__ [bound][function][def][node=FunctionDef]
238.310 - __floordiv__ [bound][function][alias][node=FunctionDef]
238.311 - __ge__ [bound][function][def][node=FunctionDef]
238.312 - __getstate [bound][private][function][def][node=FunctionDef]
238.313 - __gt__ [bound][function][def][node=FunctionDef]
238.314 - __hash__ [bound][function][def][node=FunctionDef]
238.315 - __le__ [bound][function][def][node=FunctionDef]
238.316 - __lt__ [bound][function][def][node=FunctionDef]
238.317 - __mul__ [bound][function][def][read][node=FunctionDef]
238.318 - __ne__ [bound][function][def][node=FunctionDef]
238.319 - __neg__ [bound][function][def][node=FunctionDef]
238.320 - __new__ [bound][function][def][node=FunctionDef]
238.321 - __nonzero__ [bound][function][def][node=FunctionDef]
238.322 - __pos__ [bound][function][def][node=FunctionDef]
238.323 - __radd__ [bound][function][alias][node=FunctionDef]
238.324 - __reduce__ [bound][function][def][node=FunctionDef]
238.325 - __repr__ [bound][function][def][node=FunctionDef]
238.326 - __rmul__ [bound][function][alias][node=FunctionDef]
238.327 - __rsub__ [bound][function][def][node=FunctionDef]
238.328 - __safe_for_unpickling__ [bound][data][node=Name]
238.329 - __str__ [bound][function][def][node=FunctionDef]
238.330 - __sub__ [bound][function][def][node=FunctionDef]
238.331 - days [bound][data][node=Name]
238.332 - microseconds [bound][data][node=Name]
238.333 - property [free][read][called][node=Name]
238.334 - seconds [bound][data][node=Name]
238.335 - ------ Attributes ---------------------------------------
238.336 - __days : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.337 - __microseconds : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.338 - __seconds : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.339 -
238.340 - =============================================
238.341 - __new__: FunctionDef : OffsetRange[16773,21337>
238.342 - OverflowError [free][read][called][node=Name]
238.343 - _math [free][read][node=Name]
238.344 - abs [free][read][called][node=Name]
238.345 - cls [bound][param][data][read][node=Name]
238.346 - d [bound][data][read][node=Name]
238.347 - dayfrac [bound][data][read][node=Name]
238.348 - days [bound][param][data][read][node=Name]
238.349 - daysecondsfrac [bound][data][read][node=Name]
238.350 - daysecondswhole [bound][data][read][node=Name]
238.351 - divmod [free][read][called][node=Name]
238.352 - float [free][read][called][node=Name]
238.353 - hours [bound][param][data][read][node=Name]
238.354 - int [free][read][called][node=Name]
238.355 - isinstance [free][read][called][node=Name]
238.356 - long [free][read][called][node=Name]
238.357 - microseconds [bound][param][data][read][node=Name]
238.358 - milliseconds [bound][param][data][read][node=Name]
238.359 - minutes [bound][param][data][read][node=Name]
238.360 - object [free][read][node=Name]
238.361 - round [free][read][called][node=Name]
238.362 - s [bound][data][read][node=Name]
238.363 - seconds [bound][param][data][read][node=Name]
238.364 - secondsfrac [bound][data][read][node=Name]
238.365 - self [bound][data][read][node=Name]
238.366 - us [bound][data][read][node=Name]
238.367 - usdouble [bound][data][read][node=Name]
238.368 - weeks [bound][param][data][read][node=Name]
238.369 - ------ Attributes ---------------------------------------
238.370 - __new__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.371 -
238.372 - =============================================
238.373 - __repr__: FunctionDef : OffsetRange[21338,21918>
238.374 - self [bound][param][data][read][node=Name]
238.375 - ------ Attributes ---------------------------------------
238.376 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.377 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.378 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.379 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.380 -
238.381 - =============================================
238.382 - __str__: FunctionDef : OffsetRange[21919,22319>
238.383 - abs [free][node=null]
238.384 - divmod [free][read][called][node=Name]
238.385 - hh [bound][data][read][node=Name]
238.386 - mm [bound][data][read][node=Name]
238.387 - plural [bound][function][def][read][called][node=FunctionDef]
238.388 - s [bound][data][read][node=Name]
238.389 - self [bound][param][data][read][node=Name]
238.390 - ss [bound][data][read][node=Name]
238.391 - ---------------------------------------------
238.392 - inner_free: {abs=PRESENT}
238.393 - ------ Attributes ---------------------------------------
238.394 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.395 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.396 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.397 -
238.398 - =============================================
238.399 - plural: FunctionDef : OffsetRange[22092,22170>
238.400 - abs [free][read][called][node=Name]
238.401 - n [bound][param][data][read][node=Name]
238.402 -
238.403 - =============================================
238.404 - <lambda>: Lambda : OffsetRange[22336,22360>
238.405 - self [bound][param][data][read][node=Name]
238.406 -
238.407 - =============================================
238.408 - <lambda>: Lambda : OffsetRange[22397,22424>
238.409 - self [bound][param][data][read][node=Name]
238.410 -
238.411 - =============================================
238.412 - <lambda>: Lambda : OffsetRange[22469,22501>
238.413 - self [bound][param][data][read][node=Name]
238.414 -
238.415 - =============================================
238.416 - __add__: FunctionDef : OffsetRange[22556,22850>
238.417 - NotImplemented [free][read][node=Name]
238.418 - isinstance [free][read][called][node=Name]
238.419 - other [bound][param][data][read][node=Name]
238.420 - self [bound][param][data][read][node=Name]
238.421 - timedelta [free][read][called][node=Name]
238.422 - ------ Attributes ---------------------------------------
238.423 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.424 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.425 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.426 -
238.427 - =============================================
238.428 - __sub__: FunctionDef : OffsetRange[22875,23009>
238.429 - NotImplemented [free][read][node=Name]
238.430 - isinstance [free][read][called][node=Name]
238.431 - other [bound][param][data][read][node=Name]
238.432 - self [bound][param][data][read][node=Name]
238.433 - timedelta [free][read][node=Name]
238.434 -
238.435 - =============================================
238.436 - __rsub__: FunctionDef : OffsetRange[23010,23145>
238.437 - NotImplemented [free][read][node=Name]
238.438 - isinstance [free][read][called][node=Name]
238.439 - other [bound][param][data][read][node=Name]
238.440 - self [bound][param][data][read][node=Name]
238.441 - timedelta [free][read][node=Name]
238.442 -
238.443 - =============================================
238.444 - __neg__: FunctionDef : OffsetRange[23146,23312>
238.445 - self [bound][param][data][read][node=Name]
238.446 - ------ Attributes ---------------------------------------
238.447 - __class__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.448 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.449 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.450 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.451 -
238.452 - =============================================
238.453 - __pos__: FunctionDef : OffsetRange[23313,23356>
238.454 - self [bound][param][data][read][node=Name]
238.455 -
238.456 - =============================================
238.457 - __abs__: FunctionDef : OffsetRange[23357,23471>
238.458 - self [bound][param][data][read][node=Name]
238.459 - ------ Attributes ---------------------------------------
238.460 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.461 -
238.462 - =============================================
238.463 - __mul__: FunctionDef : OffsetRange[23472,23751>
238.464 - NotImplemented [free][read][node=Name]
238.465 - int [free][read][node=Name]
238.466 - isinstance [free][read][called][node=Name]
238.467 - long [free][read][node=Name]
238.468 - other [bound][param][data][read][node=Name]
238.469 - self [bound][param][data][read][node=Name]
238.470 - ------ Attributes ---------------------------------------
238.471 - __class__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.472 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.473 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.474 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.475 -
238.476 - =============================================
238.477 - __div__: FunctionDef : OffsetRange[23776,24051>
238.478 - NotImplemented [free][read][node=Name]
238.479 - int [free][read][node=Name]
238.480 - isinstance [free][read][called][node=Name]
238.481 - long [free][read][node=Name]
238.482 - other [bound][param][data][read][node=Name]
238.483 - self [bound][param][data][read][node=Name]
238.484 - usec [bound][data][read][node=Name]
238.485 - ------ Attributes ---------------------------------------
238.486 - __class__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.487 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.488 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.489 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.490 -
238.491 - =============================================
238.492 - __eq__: FunctionDef : OffsetRange[24100,24251>
238.493 - False [free][read][node=Name]
238.494 - isinstance [free][read][called][node=Name]
238.495 - other [bound][param][data][read][node=Name]
238.496 - self [bound][param][data][read][node=Name]
238.497 - timedelta [free][read][node=Name]
238.498 - ------ Attributes ---------------------------------------
238.499 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.500 -
238.501 - =============================================
238.502 - __ne__: FunctionDef : OffsetRange[24252,24402>
238.503 - True [free][read][node=Name]
238.504 - isinstance [free][read][called][node=Name]
238.505 - other [bound][param][data][read][node=Name]
238.506 - self [bound][param][data][read][node=Name]
238.507 - timedelta [free][read][node=Name]
238.508 - ------ Attributes ---------------------------------------
238.509 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.510 -
238.511 - =============================================
238.512 - __le__: FunctionDef : OffsetRange[24403,24564>
238.513 - _cmperror [free][read][called][node=Name]
238.514 - isinstance [free][read][called][node=Name]
238.515 - other [bound][param][data][read][node=Name]
238.516 - self [bound][param][data][read][node=Name]
238.517 - timedelta [free][read][node=Name]
238.518 - ------ Attributes ---------------------------------------
238.519 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.520 -
238.521 - =============================================
238.522 - __lt__: FunctionDef : OffsetRange[24565,24725>
238.523 - _cmperror [free][read][called][node=Name]
238.524 - isinstance [free][read][called][node=Name]
238.525 - other [bound][param][data][read][node=Name]
238.526 - self [bound][param][data][read][node=Name]
238.527 - timedelta [free][read][node=Name]
238.528 - ------ Attributes ---------------------------------------
238.529 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.530 -
238.531 - =============================================
238.532 - __ge__: FunctionDef : OffsetRange[24726,24887>
238.533 - _cmperror [free][read][called][node=Name]
238.534 - isinstance [free][read][called][node=Name]
238.535 - other [bound][param][data][read][node=Name]
238.536 - self [bound][param][data][read][node=Name]
238.537 - timedelta [free][read][node=Name]
238.538 - ------ Attributes ---------------------------------------
238.539 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.540 -
238.541 - =============================================
238.542 - __gt__: FunctionDef : OffsetRange[24888,25048>
238.543 - _cmperror [free][read][called][node=Name]
238.544 - isinstance [free][read][called][node=Name]
238.545 - other [bound][param][data][read][node=Name]
238.546 - self [bound][param][data][read][node=Name]
238.547 - timedelta [free][read][node=Name]
238.548 - ------ Attributes ---------------------------------------
238.549 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.550 -
238.551 - =============================================
238.552 - __cmp: FunctionDef : OffsetRange[25049,25179>
238.553 - cmp [free][read][called][node=Name]
238.554 - isinstance [free][read][called][node=Name]
238.555 - other [bound][param][data][read][node=Name]
238.556 - self [bound][param][data][read][node=Name]
238.557 - timedelta [free][read][node=Name]
238.558 - ------ Attributes ---------------------------------------
238.559 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.560 -
238.561 - =============================================
238.562 - __hash__: FunctionDef : OffsetRange[25180,25243>
238.563 - hash [free][read][called][node=Name]
238.564 - self [bound][param][data][read][node=Name]
238.565 - ------ Attributes ---------------------------------------
238.566 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.567 -
238.568 - =============================================
238.569 - __nonzero__: FunctionDef : OffsetRange[25244,25411>
238.570 - self [bound][param][data][read][node=Name]
238.571 - ------ Attributes ---------------------------------------
238.572 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.573 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.574 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.575 -
238.576 - =============================================
238.577 - __getstate: FunctionDef : OffsetRange[25470,25562>
238.578 - self [bound][param][data][read][node=Name]
238.579 - ------ Attributes ---------------------------------------
238.580 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.581 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.582 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.583 -
238.584 - =============================================
238.585 - __reduce__: FunctionDef : OffsetRange[25563,25637>
238.586 - self [bound][param][data][read][node=Name]
238.587 - ------ Attributes ---------------------------------------
238.588 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.589 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.590 -
238.591 - =============================================
238.592 - class date: ClassDef : OffsetRange[25848,34505>
238.593 - MAXYEAR [free][read][node=Name]
238.594 - MINYEAR [free][read][node=Name]
238.595 - None [free][read][node=Name]
238.596 - True [free][read][node=Name]
238.597 - __add__ [bound][function][def][read][node=FunctionDef]
238.598 - __cmp [bound][private][function][def][node=FunctionDef]
238.599 - __eq__ [bound][function][def][node=FunctionDef]
238.600 - __ge__ [bound][function][def][node=FunctionDef]
238.601 - __getstate [bound][private][function][def][node=FunctionDef]
238.602 - __gt__ [bound][function][def][node=FunctionDef]
238.603 - __hash__ [bound][function][def][node=FunctionDef]
238.604 - __le__ [bound][function][def][node=FunctionDef]
238.605 - __lt__ [bound][function][def][node=FunctionDef]
238.606 - __ne__ [bound][function][def][node=FunctionDef]
238.607 - __new__ [bound][function][def][node=FunctionDef]
238.608 - __radd__ [bound][function][alias][node=FunctionDef]
238.609 - __reduce__ [bound][function][def][node=FunctionDef]
238.610 - __repr__ [bound][function][def][node=FunctionDef]
238.611 - __safe_for_unpickling__ [bound][data][node=Name]
238.612 - __setstate [bound][private][function][def][node=FunctionDef]
238.613 - __str__ [bound][function][alias][node=FunctionDef]
238.614 - __sub__ [bound][function][def][node=FunctionDef]
238.615 - _checkOverflow [bound][private][function][def][node=FunctionDef]
238.616 - classmethod [free][read][called][node=Name]
238.617 - ctime [bound][function][def][node=FunctionDef]
238.618 - day [bound][data][node=Name]
238.619 - fromordinal [bound][function][def][read][node=FunctionDef]
238.620 - fromtimestamp [bound][function][def][read][node=FunctionDef]
238.621 - isocalendar [bound][function][def][node=FunctionDef]
238.622 - isoformat [bound][function][def][read][node=FunctionDef]
238.623 - isoweekday [bound][function][def][node=FunctionDef]
238.624 - month [bound][data][node=Name]
238.625 - property [free][read][called][node=Name]
238.626 - replace [bound][function][def][node=FunctionDef]
238.627 - strftime [bound][function][def][node=FunctionDef]
238.628 - timetuple [bound][function][def][node=FunctionDef]
238.629 - today [bound][function][def][read][node=FunctionDef]
238.630 - toordinal [bound][function][def][node=FunctionDef]
238.631 - weekday [bound][function][def][node=FunctionDef]
238.632 - year [bound][data][node=Name]
238.633 - ------ Attributes ---------------------------------------
238.634 - __day : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.635 - __month : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.636 - __year : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.637 -
238.638 - =============================================
238.639 - __new__: FunctionDef : OffsetRange[26301,26827>
238.640 - _check_date_fields [free][read][called][node=Name]
238.641 - cls [bound][param][data][read][node=Name]
238.642 - day [bound][param][data][read][node=Name]
238.643 - isinstance [free][read][called][node=Name]
238.644 - month [bound][param][data][read][node=Name]
238.645 - object [free][read][node=Name]
238.646 - self [bound][data][read][node=Name]
238.647 - str [free][read][node=Name]
238.648 - year [bound][param][data][read][node=Name]
238.649 - ------ Attributes ---------------------------------------
238.650 - __new__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.651 - __setstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.652 -
238.653 - =============================================
238.654 - fromtimestamp: FunctionDef : OffsetRange[26828,27025>
238.655 - _time [free][read][node=Name]
238.656 - cls [bound][param][data][read][called][node=Name]
238.657 - d [bound][data][read][node=Name]
238.658 - dst [bound][data][unused][node=Name]
238.659 - hh [bound][data][unused][node=Name]
238.660 - jday [bound][data][unused][node=Name]
238.661 - m [bound][data][read][node=Name]
238.662 - mm [bound][data][unused][node=Name]
238.663 - ss [bound][data][unused][node=Name]
238.664 - t [bound][param][data][read][node=Name]
238.665 - weekday [bound][data][unused][node=Name]
238.666 - y [bound][data][read][node=Name]
238.667 -
238.668 - =============================================
238.669 - today: FunctionDef : OffsetRange[27074,27199>
238.670 - _time [free][read][node=Name]
238.671 - cls [bound][param][data][read][node=Name]
238.672 - t [bound][data][read][node=Name]
238.673 -
238.674 - =============================================
238.675 - fromordinal: FunctionDef : OffsetRange[27232,27498>
238.676 - _ord2ymd [free][read][called][node=Name]
238.677 - cls [bound][param][data][read][called][node=Name]
238.678 - d [bound][data][read][node=Name]
238.679 - m [bound][data][read][node=Name]
238.680 - n [bound][param][data][read][node=Name]
238.681 - y [bound][data][read][node=Name]
238.682 -
238.683 - =============================================
238.684 - __repr__: FunctionDef : OffsetRange[27572,28116>
238.685 - self [bound][param][data][read][node=Name]
238.686 - ------ Attributes ---------------------------------------
238.687 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.688 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.689 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.690 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.691 -
238.692 - =============================================
238.693 - ctime: FunctionDef : OffsetRange[28117,28237>
238.694 - self [bound][param][data][read][node=Name]
238.695 - tmxxx [free][read][called][node=Name]
238.696 - ------ Attributes ---------------------------------------
238.697 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.698 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.699 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.700 -
238.701 - =============================================
238.702 - strftime: FunctionDef : OffsetRange[28238,28361>
238.703 - _wrap_strftime [free][read][called][node=Name]
238.704 - fmt [bound][param][data][read][node=Name]
238.705 - self [bound][param][data][read][node=Name]
238.706 - ------ Attributes ---------------------------------------
238.707 - timetuple : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.708 -
238.709 - =============================================
238.710 - isoformat: FunctionDef : OffsetRange[28362,28680>
238.711 - self [bound][param][data][read][node=Name]
238.712 - ------ Attributes ---------------------------------------
238.713 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.714 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.715 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.716 -
238.717 - =============================================
238.718 - <lambda>: Lambda : OffsetRange[28754,28778>
238.719 - self [bound][param][data][read][node=Name]
238.720 -
238.721 - =============================================
238.722 - <lambda>: Lambda : OffsetRange[28862,28887>
238.723 - self [bound][param][data][read][node=Name]
238.724 -
238.725 - =============================================
238.726 - <lambda>: Lambda : OffsetRange[28928,28951>
238.727 - self [bound][param][data][read][node=Name]
238.728 -
238.729 - =============================================
238.730 - timetuple: FunctionDef : OffsetRange[29037,29250>
238.731 - _build_struct_time [free][read][called][node=Name]
238.732 - self [bound][param][data][read][node=Name]
238.733 - ------ Attributes ---------------------------------------
238.734 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.735 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.736 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.737 -
238.738 - =============================================
238.739 - toordinal: FunctionDef : OffsetRange[29251,29536>
238.740 - _ymd2ord [free][read][called][node=Name]
238.741 - self [bound][param][data][read][node=Name]
238.742 - ------ Attributes ---------------------------------------
238.743 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.744 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.745 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.746 -
238.747 - =============================================
238.748 - replace: FunctionDef : OffsetRange[29537,29938>
238.749 - None [free][read][node=Name]
238.750 - _check_date_fields [free][read][called][node=Name]
238.751 - date [free][read][called][node=Name]
238.752 - day [bound][param][data][read][node=Name]
238.753 - month [bound][param][data][read][node=Name]
238.754 - self [bound][param][data][read][node=Name]
238.755 - year [bound][param][data][read][node=Name]
238.756 - ------ Attributes ---------------------------------------
238.757 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.758 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.759 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.760 -
238.761 - =============================================
238.762 - __eq__: FunctionDef : OffsetRange[29939,30161>
238.763 - False [free][read][node=Name]
238.764 - NotImplemented [free][read][node=Name]
238.765 - date [free][read][node=Name]
238.766 - hasattr [free][read][called][node=Name]
238.767 - isinstance [free][read][called][node=Name]
238.768 - other [bound][param][data][read][node=Name]
238.769 - self [bound][param][data][read][node=Name]
238.770 - ------ Attributes ---------------------------------------
238.771 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.772 -
238.773 - =============================================
238.774 - __ne__: FunctionDef : OffsetRange[30162,30383>
238.775 - NotImplemented [free][read][node=Name]
238.776 - True [free][read][node=Name]
238.777 - date [free][read][node=Name]
238.778 - hasattr [free][read][called][node=Name]
238.779 - isinstance [free][read][called][node=Name]
238.780 - other [bound][param][data][read][node=Name]
238.781 - self [bound][param][data][read][node=Name]
238.782 - ------ Attributes ---------------------------------------
238.783 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.784 -
238.785 - =============================================
238.786 - __le__: FunctionDef : OffsetRange[30384,30616>
238.787 - NotImplemented [free][read][node=Name]
238.788 - _cmperror [free][read][called][node=Name]
238.789 - date [free][read][node=Name]
238.790 - hasattr [free][read][called][node=Name]
238.791 - isinstance [free][read][called][node=Name]
238.792 - other [bound][param][data][read][node=Name]
238.793 - self [bound][param][data][read][node=Name]
238.794 - ------ Attributes ---------------------------------------
238.795 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.796 -
238.797 - =============================================
238.798 - __lt__: FunctionDef : OffsetRange[30617,30848>
238.799 - NotImplemented [free][read][node=Name]
238.800 - _cmperror [free][read][called][node=Name]
238.801 - date [free][read][node=Name]
238.802 - hasattr [free][read][called][node=Name]
238.803 - isinstance [free][read][called][node=Name]
238.804 - other [bound][param][data][read][node=Name]
238.805 - self [bound][param][data][read][node=Name]
238.806 - ------ Attributes ---------------------------------------
238.807 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.808 -
238.809 - =============================================
238.810 - __ge__: FunctionDef : OffsetRange[30849,31081>
238.811 - NotImplemented [free][read][node=Name]
238.812 - _cmperror [free][read][called][node=Name]
238.813 - date [free][read][node=Name]
238.814 - hasattr [free][read][called][node=Name]
238.815 - isinstance [free][read][called][node=Name]
238.816 - other [bound][param][data][read][node=Name]
238.817 - self [bound][param][data][read][node=Name]
238.818 - ------ Attributes ---------------------------------------
238.819 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.820 -
238.821 - =============================================
238.822 - __gt__: FunctionDef : OffsetRange[31082,31313>
238.823 - NotImplemented [free][read][node=Name]
238.824 - _cmperror [free][read][called][node=Name]
238.825 - date [free][read][node=Name]
238.826 - hasattr [free][read][called][node=Name]
238.827 - isinstance [free][read][called][node=Name]
238.828 - other [bound][param][data][read][node=Name]
238.829 - self [bound][param][data][read][node=Name]
238.830 - ------ Attributes ---------------------------------------
238.831 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.832 -
238.833 - =============================================
238.834 - __cmp: FunctionDef : OffsetRange[31314,31543>
238.835 - cmp [free][read][called][node=Name]
238.836 - d [bound][data][read][node=Name]
238.837 - d2 [bound][data][read][node=Name]
238.838 - date [free][read][node=Name]
238.839 - isinstance [free][read][called][node=Name]
238.840 - m [bound][data][read][node=Name]
238.841 - m2 [bound][data][read][node=Name]
238.842 - other [bound][param][data][read][node=Name]
238.843 - self [bound][param][data][read][node=Name]
238.844 - y [bound][data][read][node=Name]
238.845 - y2 [bound][data][read][node=Name]
238.846 - ------ Attributes ---------------------------------------
238.847 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.848 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.849 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.850 -
238.851 - =============================================
238.852 - __hash__: FunctionDef : OffsetRange[31544,31643>
238.853 - hash [free][read][called][node=Name]
238.854 - self [bound][param][data][read][node=Name]
238.855 - ------ Attributes ---------------------------------------
238.856 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.857 -
238.858 - =============================================
238.859 - _checkOverflow: FunctionDef : OffsetRange[31644,31856>
238.860 - MAXYEAR [free][read][node=Name]
238.861 - MINYEAR [free][read][node=Name]
238.862 - OverflowError [free][read][called][node=Name]
238.863 - self [bound][param][data][unused][node=Name]
238.864 - year [bound][param][data][read][node=Name]
238.865 -
238.866 - =============================================
238.867 - __add__: FunctionDef : OffsetRange[31857,32239>
238.868 - NotImplemented [free][read][node=Name]
238.869 - isinstance [free][read][called][node=Name]
238.870 - other [bound][param][data][read][node=Name]
238.871 - result [bound][data][read][node=Name]
238.872 - self [bound][param][data][read][node=Name]
238.873 - t [bound][data][read][node=Name]
238.874 - timedelta [free][read][node=Name]
238.875 - tmxxx [free][read][called][node=Name]
238.876 - ------ Attributes ---------------------------------------
238.877 - __class__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.878 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.879 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.880 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.881 - _checkOverflow : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.882 -
238.883 - =============================================
238.884 - __sub__: FunctionDef : OffsetRange[32264,32630>
238.885 - NotImplemented [free][read][node=Name]
238.886 - date [free][read][node=Name]
238.887 - days1 [bound][data][read][node=Name]
238.888 - days2 [bound][data][read][node=Name]
238.889 - isinstance [free][read][called][node=Name]
238.890 - other [bound][param][data][read][node=Name]
238.891 - self [bound][param][data][read][node=Name]
238.892 - timedelta [free][read][called][node=Name]
238.893 - ------ Attributes ---------------------------------------
238.894 - toordinal : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.895 -
238.896 - =============================================
238.897 - weekday: FunctionDef : OffsetRange[32631,32827>
238.898 - self [bound][param][data][read][node=Name]
238.899 - ------ Attributes ---------------------------------------
238.900 - toordinal : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.901 -
238.902 - =============================================
238.903 - isoweekday: FunctionDef : OffsetRange[32828,32997>
238.904 - self [bound][param][data][read][node=Name]
238.905 - ------ Attributes ---------------------------------------
238.906 - toordinal : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.907 -
238.908 - =============================================
238.909 - isocalendar: FunctionDef : OffsetRange[32998,33991>
238.910 - _isoweek1monday [free][read][called][node=Name]
238.911 - _ymd2ord [free][read][called][node=Name]
238.912 - day [bound][data][read][node=Name]
238.913 - divmod [free][read][called][node=Name]
238.914 - self [bound][param][data][read][node=Name]
238.915 - today [bound][data][read][node=Name]
238.916 - week [bound][data][read][node=Name]
238.917 - week1monday [bound][data][read][node=Name]
238.918 - year [bound][data][read][node=Name]
238.919 - ------ Attributes ---------------------------------------
238.920 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.921 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.922 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.923 -
238.924 - =============================================
238.925 - __getstate: FunctionDef : OffsetRange[34050,34189>
238.926 - divmod [free][read][called][node=Name]
238.927 - self [bound][param][data][read][node=Name]
238.928 - yhi [bound][data][read][node=Name]
238.929 - ylo [bound][data][read][node=Name]
238.930 - ------ Attributes ---------------------------------------
238.931 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.932 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.933 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.934 -
238.935 - =============================================
238.936 - __setstate: FunctionDef : OffsetRange[34190,34430>
238.937 - isinstance [free][read][called][node=Name]
238.938 - len [free][read][called][node=Name]
238.939 - map [free][read][called][node=Name]
238.940 - ord [free][read][node=Name]
238.941 - self [bound][param][data][read][node=Name]
238.942 - string [bound][data][read][node=Name]
238.943 - t [bound][param][data][read][node=Name]
238.944 - tuple [free][read][node=Name]
238.945 - yhi [bound][data][read][node=Name]
238.946 - ylo [bound][data][read][node=Name]
238.947 -
238.948 - =============================================
238.949 - __reduce__: FunctionDef : OffsetRange[34431,34505>
238.950 - self [bound][param][data][read][node=Name]
238.951 - ------ Attributes ---------------------------------------
238.952 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.953 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.954 -
238.955 - =============================================
238.956 - class tzinfo: ClassDef : OffsetRange[34675,37029>
238.957 - True [free][read][node=Name]
238.958 - __reduce__ [bound][function][def][node=FunctionDef]
238.959 - __safe_for_unpickling__ [bound][data][node=Name]
238.960 - dst [bound][function][def][node=FunctionDef]
238.961 - fromutc [bound][function][def][node=FunctionDef]
238.962 - tzname [bound][function][def][node=FunctionDef]
238.963 - utcoffset [bound][function][def][node=FunctionDef]
238.964 -
238.965 - =============================================
238.966 - tzname: FunctionDef : OffsetRange[34838,34988>
238.967 - NotImplementedError [free][read][called][node=Name]
238.968 - dt [bound][param][data][unused][node=Name]
238.969 - self [bound][param][data][unused][node=Name]
238.970 -
238.971 - =============================================
238.972 - utcoffset: FunctionDef : OffsetRange[34989,35166>
238.973 - NotImplementedError [free][read][called][node=Name]
238.974 - dt [bound][param][data][unused][node=Name]
238.975 - self [bound][param][data][unused][node=Name]
238.976 -
238.977 - =============================================
238.978 - dst: FunctionDef : OffsetRange[35167,35423>
238.979 - NotImplementedError [free][read][called][node=Name]
238.980 - dt [bound][param][data][unused][node=Name]
238.981 - self [bound][param][data][unused][node=Name]
238.982 -
238.983 - =============================================
238.984 - fromutc: FunctionDef : OffsetRange[35424,36481>
238.985 - None [free][read][node=Name]
238.986 - TypeError [free][read][called][node=Name]
238.987 - ValueError [free][read][called][node=Name]
238.988 - datetime [free][read][node=Name]
238.989 - delta [bound][data][read][node=Name]
238.990 - dt [bound][param][data][read][node=Name]
238.991 - dtdst [bound][data][read][node=Name]
238.992 - dtoff [bound][data][read][node=Name]
238.993 - isinstance [free][read][called][node=Name]
238.994 - self [bound][param][data][read][node=Name]
238.995 -
238.996 - =============================================
238.997 - __reduce__: FunctionDef : OffsetRange[36540,37029>
238.998 - None [free][read][node=Name]
238.999 - args [bound][data][read][node=Name]
238.1000 - getattr [free][read][called][node=Name]
238.1001 - getinitargs [bound][data][read][called][node=Name]
238.1002 - getstate [bound][data][read][called][node=Name]
238.1003 - self [bound][param][data][read][node=Name]
238.1004 - state [bound][data][read][node=Name]
238.1005 - ------ Attributes ---------------------------------------
238.1006 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1007 -
238.1008 - =============================================
238.1009 - class time: ClassDef : OffsetRange[37106,46501>
238.1010 - None [free][read][node=Name]
238.1011 - True [free][read][node=Name]
238.1012 - __cmp [bound][private][function][def][node=FunctionDef]
238.1013 - __eq__ [bound][function][def][node=FunctionDef]
238.1014 - __ge__ [bound][function][def][node=FunctionDef]
238.1015 - __getstate [bound][private][function][def][node=FunctionDef]
238.1016 - __gt__ [bound][function][def][node=FunctionDef]
238.1017 - __hash__ [bound][function][def][node=FunctionDef]
238.1018 - __le__ [bound][function][def][node=FunctionDef]
238.1019 - __lt__ [bound][function][def][node=FunctionDef]
238.1020 - __ne__ [bound][function][def][node=FunctionDef]
238.1021 - __new__ [bound][function][def][node=FunctionDef]
238.1022 - __nonzero__ [bound][function][def][node=FunctionDef]
238.1023 - __reduce__ [bound][function][def][node=FunctionDef]
238.1024 - __repr__ [bound][function][def][node=FunctionDef]
238.1025 - __safe_for_unpickling__ [bound][data][node=Name]
238.1026 - __setstate [bound][private][function][def][node=FunctionDef]
238.1027 - __str__ [bound][function][alias][node=FunctionDef]
238.1028 - _dst [bound][private][function][def][node=FunctionDef]
238.1029 - _tzstr [bound][private][function][def][node=FunctionDef]
238.1030 - _utcoffset [bound][private][function][def][node=FunctionDef]
238.1031 - dst [bound][function][def][node=FunctionDef]
238.1032 - hour [bound][data][node=Name]
238.1033 - isoformat [bound][function][def][read][node=FunctionDef]
238.1034 - microsecond [bound][data][node=Name]
238.1035 - minute [bound][data][node=Name]
238.1036 - property [free][read][called][node=Name]
238.1037 - replace [bound][function][def][node=FunctionDef]
238.1038 - second [bound][data][node=Name]
238.1039 - strftime [bound][function][def][node=FunctionDef]
238.1040 - tzinfo [bound][data][node=Name]
238.1041 - tzname [bound][function][def][node=FunctionDef]
238.1042 - utcoffset [bound][function][def][node=FunctionDef]
238.1043 - ------ Attributes ---------------------------------------
238.1044 - __hour : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.1045 - __microsecond : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.1046 - __minute : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.1047 - __second : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.1048 - _tzinfo : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.1049 -
238.1050 - =============================================
238.1051 - __new__: FunctionDef : OffsetRange[37421,38149>
238.1052 - None [free][read][node=Name]
238.1053 - _check_time_fields [free][read][called][node=Name]
238.1054 - _check_tzinfo_arg [free][read][called][node=Name]
238.1055 - cls [bound][param][data][read][node=Name]
238.1056 - hour [bound][param][data][read][node=Name]
238.1057 - isinstance [free][read][called][node=Name]
238.1058 - microsecond [bound][param][data][read][node=Name]
238.1059 - minute [bound][param][data][read][node=Name]
238.1060 - object [free][read][node=Name]
238.1061 - second [bound][param][data][read][node=Name]
238.1062 - self [bound][data][read][node=Name]
238.1063 - str [free][read][node=Name]
238.1064 - tzinfo [bound][param][data][read][node=Name]
238.1065 - ------ Attributes ---------------------------------------
238.1066 - __new__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.1067 - __setstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1068 -
238.1069 - =============================================
238.1070 - <lambda>: Lambda : OffsetRange[38166,38190>
238.1071 - self [bound][param][data][read][node=Name]
238.1072 -
238.1073 - =============================================
238.1074 - <lambda>: Lambda : OffsetRange[38233,38259>
238.1075 - self [bound][param][data][read][node=Name]
238.1076 -
238.1077 - =============================================
238.1078 - <lambda>: Lambda : OffsetRange[38304,38330>
238.1079 - self [bound][param][data][read][node=Name]
238.1080 -
238.1081 - =============================================
238.1082 - <lambda>: Lambda : OffsetRange[38380,38411>
238.1083 - self [bound][param][data][read][node=Name]
238.1084 -
238.1085 - =============================================
238.1086 - <lambda>: Lambda : OffsetRange[38492,38517>
238.1087 - self [bound][param][data][read][node=Name]
238.1088 -
238.1089 - =============================================
238.1090 - __eq__: FunctionDef : OffsetRange[38624,38770>
238.1091 - False [free][read][node=Name]
238.1092 - isinstance [free][read][called][node=Name]
238.1093 - other [bound][param][data][read][node=Name]
238.1094 - self [bound][param][data][read][node=Name]
238.1095 - time [free][read][node=Name]
238.1096 - ------ Attributes ---------------------------------------
238.1097 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1098 -
238.1099 - =============================================
238.1100 - __ne__: FunctionDef : OffsetRange[38771,38916>
238.1101 - True [free][read][node=Name]
238.1102 - isinstance [free][read][called][node=Name]
238.1103 - other [bound][param][data][read][node=Name]
238.1104 - self [bound][param][data][read][node=Name]
238.1105 - time [free][read][node=Name]
238.1106 - ------ Attributes ---------------------------------------
238.1107 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1108 -
238.1109 - =============================================
238.1110 - __le__: FunctionDef : OffsetRange[38917,39073>
238.1111 - _cmperror [free][read][called][node=Name]
238.1112 - isinstance [free][read][called][node=Name]
238.1113 - other [bound][param][data][read][node=Name]
238.1114 - self [bound][param][data][read][node=Name]
238.1115 - time [free][read][node=Name]
238.1116 - ------ Attributes ---------------------------------------
238.1117 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1118 -
238.1119 - =============================================
238.1120 - __lt__: FunctionDef : OffsetRange[39074,39229>
238.1121 - _cmperror [free][read][called][node=Name]
238.1122 - isinstance [free][read][called][node=Name]
238.1123 - other [bound][param][data][read][node=Name]
238.1124 - self [bound][param][data][read][node=Name]
238.1125 - time [free][read][node=Name]
238.1126 - ------ Attributes ---------------------------------------
238.1127 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1128 -
238.1129 - =============================================
238.1130 - __ge__: FunctionDef : OffsetRange[39230,39386>
238.1131 - _cmperror [free][read][called][node=Name]
238.1132 - isinstance [free][read][called][node=Name]
238.1133 - other [bound][param][data][read][node=Name]
238.1134 - self [bound][param][data][read][node=Name]
238.1135 - time [free][read][node=Name]
238.1136 - ------ Attributes ---------------------------------------
238.1137 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1138 -
238.1139 - =============================================
238.1140 - __gt__: FunctionDef : OffsetRange[39387,39542>
238.1141 - _cmperror [free][read][called][node=Name]
238.1142 - isinstance [free][read][called][node=Name]
238.1143 - other [bound][param][data][read][node=Name]
238.1144 - self [bound][param][data][read][node=Name]
238.1145 - time [free][read][node=Name]
238.1146 - ------ Attributes ---------------------------------------
238.1147 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1148 -
238.1149 - =============================================
238.1150 - __cmp: FunctionDef : OffsetRange[39543,40534>
238.1151 - None [free][read][node=Name]
238.1152 - True [free][read][node=Name]
238.1153 - TypeError [free][read][called][node=Name]
238.1154 - base_compare [bound][data][read][node=Name]
238.1155 - cmp [free][read][called][node=Name]
238.1156 - isinstance [free][read][called][node=Name]
238.1157 - myhhmm [bound][data][read][node=Name]
238.1158 - myoff [bound][data][read][node=Name]
238.1159 - mytz [bound][data][read][node=Name]
238.1160 - other [bound][param][data][read][node=Name]
238.1161 - othhmm [bound][data][read][node=Name]
238.1162 - otoff [bound][data][read][node=Name]
238.1163 - ottz [bound][data][read][node=Name]
238.1164 - self [bound][param][data][read][node=Name]
238.1165 - time [free][read][node=Name]
238.1166 - ------ Attributes ---------------------------------------
238.1167 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1168 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1169 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1170 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1171 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1172 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1173 -
238.1174 - =============================================
238.1175 - __hash__: FunctionDef : OffsetRange[40535,40938>
238.1176 - divmod [free][read][called][node=Name]
238.1177 - h [bound][data][read][node=Name]
238.1178 - hash [free][read][called][node=Name]
238.1179 - m [bound][data][read][node=Name]
238.1180 - self [bound][param][data][read][node=Name]
238.1181 - time [free][read][called][node=Name]
238.1182 - tzoff [bound][data][read][node=Name]
238.1183 - ------ Attributes ---------------------------------------
238.1184 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1185 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1186 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1187 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1188 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1189 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1190 -
238.1191 - =============================================
238.1192 - _tzstr: FunctionDef : OffsetRange[40939,41361>
238.1193 - None [free][read][node=Name]
238.1194 - divmod [free][read][called][node=Name]
238.1195 - hh [bound][data][read][node=Name]
238.1196 - mm [bound][data][read][node=Name]
238.1197 - off [bound][data][read][node=Name]
238.1198 - self [bound][param][data][read][node=Name]
238.1199 - sep [bound][param][data][read][node=Name]
238.1200 - sign [bound][data][read][node=Name]
238.1201 - ------ Attributes ---------------------------------------
238.1202 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1203 -
238.1204 - =============================================
238.1205 - __repr__: FunctionDef : OffsetRange[41362,41919>
238.1206 - None [free][read][node=Name]
238.1207 - s [bound][data][read][node=Name]
238.1208 - self [bound][param][data][read][node=Name]
238.1209 - ------ Attributes ---------------------------------------
238.1210 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1211 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1212 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1213 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1214 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1215 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1216 -
238.1217 - =============================================
238.1218 - isoformat: FunctionDef : OffsetRange[41920,42300>
238.1219 - _format_time [free][read][called][node=Name]
238.1220 - s [bound][data][read][node=Name]
238.1221 - self [bound][param][data][read][node=Name]
238.1222 - tz [bound][data][read][node=Name]
238.1223 - ------ Attributes ---------------------------------------
238.1224 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1225 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1226 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1227 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1228 - _tzstr : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1229 -
238.1230 - =============================================
238.1231 - strftime: FunctionDef : OffsetRange[42326,42811>
238.1232 - _wrap_strftime [free][read][called][node=Name]
238.1233 - fmt [bound][param][data][read][node=Name]
238.1234 - self [bound][param][data][read][node=Name]
238.1235 - timetuple [bound][data][read][node=Name]
238.1236 - ------ Attributes ---------------------------------------
238.1237 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1238 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1239 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1240 -
238.1241 - =============================================
238.1242 - utcoffset: FunctionDef : OffsetRange[42812,43227>
238.1243 - None [free][read][node=Name]
238.1244 - _call_tzinfo_method [free][read][called][node=Name]
238.1245 - _check_utc_offset [free][read][called][node=Name]
238.1246 - offset [bound][data][read][node=Name]
238.1247 - self [bound][param][data][read][node=Name]
238.1248 - timedelta [free][read][called][node=Name]
238.1249 - ------ Attributes ---------------------------------------
238.1250 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1251 -
238.1252 - =============================================
238.1253 - _utcoffset: FunctionDef : OffsetRange[43228,43402>
238.1254 - None [free][read][node=Name]
238.1255 - _call_tzinfo_method [free][read][called][node=Name]
238.1256 - _check_utc_offset [free][read][called][node=Name]
238.1257 - offset [bound][data][read][node=Name]
238.1258 - self [bound][param][data][read][node=Name]
238.1259 - ------ Attributes ---------------------------------------
238.1260 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1261 -
238.1262 - =============================================
238.1263 - tzname: FunctionDef : OffsetRange[43403,43823>
238.1264 - None [free][read][node=Name]
238.1265 - _call_tzinfo_method [free][read][called][node=Name]
238.1266 - _check_tzname [free][read][called][node=Name]
238.1267 - name [bound][data][read][node=Name]
238.1268 - self [bound][param][data][read][node=Name]
238.1269 - ------ Attributes ---------------------------------------
238.1270 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1271 -
238.1272 - =============================================
238.1273 - dst: FunctionDef : OffsetRange[43824,44430>
238.1274 - None [free][read][node=Name]
238.1275 - _call_tzinfo_method [free][read][called][node=Name]
238.1276 - _check_utc_offset [free][read][called][node=Name]
238.1277 - offset [bound][data][read][node=Name]
238.1278 - self [bound][param][data][read][node=Name]
238.1279 - timedelta [free][read][called][node=Name]
238.1280 - ------ Attributes ---------------------------------------
238.1281 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1282 -
238.1283 - =============================================
238.1284 - replace: FunctionDef : OffsetRange[44431,45148>
238.1285 - None [free][read][node=Name]
238.1286 - True [free][read][node=Name]
238.1287 - _check_time_fields [free][read][called][node=Name]
238.1288 - _check_tzinfo_arg [free][read][called][node=Name]
238.1289 - hour [bound][param][data][read][node=Name]
238.1290 - microsecond [bound][param][data][read][node=Name]
238.1291 - minute [bound][param][data][read][node=Name]
238.1292 - second [bound][param][data][read][node=Name]
238.1293 - self [bound][param][data][read][node=Name]
238.1294 - time [free][read][called][node=Name]
238.1295 - tzinfo [bound][param][data][read][node=Name]
238.1296 - ------ Attributes ---------------------------------------
238.1297 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1298 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1299 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1300 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1301 - tzinfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1302 -
238.1303 - =============================================
238.1304 - _dst: FunctionDef : OffsetRange[45149,45305>
238.1305 - None [free][read][node=Name]
238.1306 - _call_tzinfo_method [free][read][called][node=Name]
238.1307 - _check_utc_offset [free][read][called][node=Name]
238.1308 - offset [bound][data][read][node=Name]
238.1309 - self [bound][param][data][read][node=Name]
238.1310 - ------ Attributes ---------------------------------------
238.1311 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1312 -
238.1313 - =============================================
238.1314 - __nonzero__: FunctionDef : OffsetRange[45306,45519>
238.1315 - offset [bound][data][read][node=Name]
238.1316 - self [bound][param][data][read][node=Name]
238.1317 - ------ Attributes ---------------------------------------
238.1318 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1319 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1320 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1321 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1322 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1323 -
238.1324 - =============================================
238.1325 - __getstate: FunctionDef : OffsetRange[45578,45941>
238.1326 - None [free][read][node=Name]
238.1327 - basestate [bound][data][read][node=Name]
238.1328 - divmod [free][read][called][node=Name]
238.1329 - self [bound][param][data][read][node=Name]
238.1330 - us1 [bound][data][read][node=Name]
238.1331 - us2 [bound][data][read][node=Name]
238.1332 - us3 [bound][data][read][node=Name]
238.1333 - ------ Attributes ---------------------------------------
238.1334 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1335 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1336 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1337 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1338 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1339 -
238.1340 - =============================================
238.1341 - __setstate: FunctionDef : OffsetRange[45942,46426>
238.1342 - None [free][read][node=Name]
238.1343 - isinstance [free][read][called][node=Name]
238.1344 - len [free][read][called][node=Name]
238.1345 - map [free][read][called][node=Name]
238.1346 - ord [free][read][node=Name]
238.1347 - self [bound][param][data][read][node=Name]
238.1348 - state [bound][param][data][read][node=Name]
238.1349 - string [bound][data][read][node=Name]
238.1350 - tuple [free][read][node=Name]
238.1351 - us1 [bound][data][read][node=Name]
238.1352 - us2 [bound][data][read][node=Name]
238.1353 - us3 [bound][data][read][node=Name]
238.1354 -
238.1355 - =============================================
238.1356 - __reduce__: FunctionDef : OffsetRange[46427,46501>
238.1357 - self [bound][param][data][read][node=Name]
238.1358 - ------ Attributes ---------------------------------------
238.1359 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1360 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1361 -
238.1362 - =============================================
238.1363 - class datetime: ClassDef : OffsetRange[46685,62681>
238.1364 - None [free][read][node=Name]
238.1365 - True [free][read][node=Name]
238.1366 - __add__ [bound][function][def][read][node=FunctionDef]
238.1367 - __cmp [bound][private][function][def][node=FunctionDef]
238.1368 - __eq__ [bound][function][def][node=FunctionDef]
238.1369 - __ge__ [bound][function][def][node=FunctionDef]
238.1370 - __getstate [bound][private][function][def][node=FunctionDef]
238.1371 - __gt__ [bound][function][def][node=FunctionDef]
238.1372 - __hash__ [bound][function][def][node=FunctionDef]
238.1373 - __le__ [bound][function][def][node=FunctionDef]
238.1374 - __lt__ [bound][function][def][node=FunctionDef]
238.1375 - __ne__ [bound][function][def][node=FunctionDef]
238.1376 - __new__ [bound][function][def][node=FunctionDef]
238.1377 - __radd__ [bound][function][alias][node=FunctionDef]
238.1378 - __reduce__ [bound][function][def][node=FunctionDef]
238.1379 - __repr__ [bound][function][def][node=FunctionDef]
238.1380 - __safe_for_unpickling__ [bound][data][node=Name]
238.1381 - __setstate [bound][private][function][def][node=FunctionDef]
238.1382 - __str__ [bound][function][def][node=FunctionDef]
238.1383 - __sub__ [bound][function][def][node=FunctionDef]
238.1384 - _dst [bound][private][function][def][node=FunctionDef]
238.1385 - _utcoffset [bound][private][function][def][node=FunctionDef]
238.1386 - astimezone [bound][function][def][node=FunctionDef]
238.1387 - classmethod [free][read][called][node=Name]
238.1388 - combine [bound][function][def][read][node=FunctionDef]
238.1389 - ctime [bound][function][def][node=FunctionDef]
238.1390 - date [bound][function][def][node=FunctionDef]
238.1391 - dst [bound][function][def][node=FunctionDef]
238.1392 - fromtimestamp [bound][function][def][read][node=FunctionDef]
238.1393 - hour [bound][data][node=Name]
238.1394 - isoformat [bound][function][def][node=FunctionDef]
238.1395 - microsecond [bound][data][node=Name]
238.1396 - minute [bound][data][node=Name]
238.1397 - now [bound][function][def][read][node=FunctionDef]
238.1398 - property [free][read][called][node=Name]
238.1399 - replace [bound][function][def][node=FunctionDef]
238.1400 - second [bound][data][node=Name]
238.1401 - time [bound][function][def][node=FunctionDef]
238.1402 - timetuple [bound][function][def][node=FunctionDef]
238.1403 - timetz [bound][function][def][node=FunctionDef]
238.1404 - tzinfo [bound][data][node=Name]
238.1405 - tzname [bound][function][def][node=FunctionDef]
238.1406 - utcfromtimestamp [bound][function][def][read][node=FunctionDef]
238.1407 - utcnow [bound][function][def][read][node=FunctionDef]
238.1408 - utcoffset [bound][function][def][node=FunctionDef]
238.1409 - utctimetuple [bound][function][def][node=FunctionDef]
238.1410 - ------ Attributes ---------------------------------------
238.1411 - __day : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.1412 - __hour : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.1413 - __microsecond : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.1414 - __minute : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.1415 - __month : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.1416 - __second : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.1417 - __year : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.1418 - _tzinfo : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
238.1419 -
238.1420 - =============================================
238.1421 - __new__: FunctionDef : OffsetRange[46811,47623>
238.1422 - _check_time_fields [free][read][called][node=Name]
238.1423 - _check_tzinfo_arg [free][read][called][node=Name]
238.1424 - cls [bound][param][data][read][node=Name]
238.1425 - date [free][read][node=Name]
238.1426 - day [bound][param][data][read][node=Name]
238.1427 - hour [bound][param][data][read][node=Name]
238.1428 - isinstance [free][read][called][node=Name]
238.1429 - microsecond [bound][param][data][read][node=Name]
238.1430 - minute [bound][param][data][read][node=Name]
238.1431 - month [bound][param][data][read][node=Name]
238.1432 - second [bound][param][data][read][node=Name]
238.1433 - self [bound][data][read][node=Name]
238.1434 - str [free][read][node=Name]
238.1435 - tzinfo [bound][param][data][read][node=Name]
238.1436 - year [bound][param][data][read][node=Name]
238.1437 - ------ Attributes ---------------------------------------
238.1438 - __new__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.1439 - __setstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1440 -
238.1441 - =============================================
238.1442 - <lambda>: Lambda : OffsetRange[47640,47664>
238.1443 - self [bound][param][data][read][node=Name]
238.1444 -
238.1445 - =============================================
238.1446 - <lambda>: Lambda : OffsetRange[47707,47733>
238.1447 - self [bound][param][data][read][node=Name]
238.1448 -
238.1449 - =============================================
238.1450 - <lambda>: Lambda : OffsetRange[47778,47804>
238.1451 - self [bound][param][data][read][node=Name]
238.1452 -
238.1453 - =============================================
238.1454 - <lambda>: Lambda : OffsetRange[47854,47885>
238.1455 - self [bound][param][data][read][node=Name]
238.1456 -
238.1457 - =============================================
238.1458 - <lambda>: Lambda : OffsetRange[47966,47991>
238.1459 - self [bound][param][data][read][node=Name]
238.1460 -
238.1461 - =============================================
238.1462 - fromtimestamp: FunctionDef : OffsetRange[48026,48673>
238.1463 - None [free][read][node=Name]
238.1464 - _check_tzinfo_arg [free][read][called][node=Name]
238.1465 - _time [free][read][node=Name]
238.1466 - cls [bound][param][data][read][called][node=Name]
238.1467 - converter [bound][data][read][called][node=Name]
238.1468 - d [bound][data][read][node=Name]
238.1469 - dst [bound][data][unused][node=Name]
238.1470 - hh [bound][data][read][node=Name]
238.1471 - int [free][read][called][node=Name]
238.1472 - jday [bound][data][unused][node=Name]
238.1473 - m [bound][data][read][node=Name]
238.1474 - min [free][read][called][node=Name]
238.1475 - mm [bound][data][read][node=Name]
238.1476 - result [bound][data][read][node=Name]
238.1477 - ss [bound][data][read][node=Name]
238.1478 - t [bound][param][data][read][node=Name]
238.1479 - tz [bound][param][data][read][node=Name]
238.1480 - us [bound][data][read][node=Name]
238.1481 - weekday [bound][data][unused][node=Name]
238.1482 - y [bound][data][read][node=Name]
238.1483 -
238.1484 - =============================================
238.1485 - utcfromtimestamp: FunctionDef : OffsetRange[48722,49059>
238.1486 - _time [free][read][node=Name]
238.1487 - cls [bound][param][data][read][called][node=Name]
238.1488 - d [bound][data][read][node=Name]
238.1489 - dst [bound][data][unused][node=Name]
238.1490 - hh [bound][data][read][node=Name]
238.1491 - int [free][read][called][node=Name]
238.1492 - jday [bound][data][unused][node=Name]
238.1493 - m [bound][data][read][node=Name]
238.1494 - min [free][read][called][node=Name]
238.1495 - mm [bound][data][read][node=Name]
238.1496 - ss [bound][data][read][node=Name]
238.1497 - t [bound][param][data][read][node=Name]
238.1498 - us [bound][data][read][node=Name]
238.1499 - weekday [bound][data][unused][node=Name]
238.1500 - y [bound][data][read][node=Name]
238.1501 -
238.1502 - =============================================
238.1503 - now: FunctionDef : OffsetRange[49451,49619>
238.1504 - _time [free][read][node=Name]
238.1505 - cls [bound][param][data][read][node=Name]
238.1506 - t [bound][data][read][node=Name]
238.1507 - tz [bound][param][data][read][node=Name]
238.1508 -
238.1509 - =============================================
238.1510 - utcnow: FunctionDef : OffsetRange[49648,49785>
238.1511 - _time [free][read][node=Name]
238.1512 - cls [bound][param][data][read][node=Name]
238.1513 - t [bound][data][read][node=Name]
238.1514 -
238.1515 - =============================================
238.1516 - combine: FunctionDef : OffsetRange[49820,50308>
238.1517 - TypeError [free][read][called][node=Name]
238.1518 - _date_class [free][read][node=Name]
238.1519 - _time_class [free][read][node=Name]
238.1520 - cls [bound][param][data][read][called][node=Name]
238.1521 - date [bound][param][data][read][node=Name]
238.1522 - isinstance [free][read][called][node=Name]
238.1523 - time [bound][param][data][read][node=Name]
238.1524 -
238.1525 - =============================================
238.1526 - timetuple: FunctionDef : OffsetRange[50345,50724>
238.1527 - None [free][read][node=Name]
238.1528 - _build_struct_time [free][read][called][node=Name]
238.1529 - dst [bound][data][read][node=Name]
238.1530 - self [bound][param][data][read][node=Name]
238.1531 - ------ Attributes ---------------------------------------
238.1532 - _dst : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1533 - day : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1534 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1535 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1536 - month : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1537 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1538 - year : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1539 -
238.1540 - =============================================
238.1541 - utctimetuple: FunctionDef : OffsetRange[50725,51194>
238.1542 - _build_struct_time [free][read][called][node=Name]
238.1543 - d [bound][data][read][node=Name]
238.1544 - hh [bound][data][read][node=Name]
238.1545 - m [bound][data][read][node=Name]
238.1546 - mm [bound][data][read][node=Name]
238.1547 - offset [bound][data][read][node=Name]
238.1548 - self [bound][param][data][read][node=Name]
238.1549 - ss [bound][data][read][node=Name]
238.1550 - tm [bound][data][read][node=Name]
238.1551 - tmxxx [free][read][called][node=Name]
238.1552 - y [bound][data][read][node=Name]
238.1553 - ------ Attributes ---------------------------------------
238.1554 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1555 - day : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1556 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1557 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1558 - month : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1559 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1560 - year : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1561 -
238.1562 - =============================================
238.1563 - date: FunctionDef : OffsetRange[51195,51306>
238.1564 - date [free][read][called][node=Name]
238.1565 - self [bound][param][data][read][node=Name]
238.1566 - ------ Attributes ---------------------------------------
238.1567 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1568 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1569 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1570 -
238.1571 - =============================================
238.1572 - time: FunctionDef : OffsetRange[51307,51452>
238.1573 - self [bound][param][data][read][node=Name]
238.1574 - time [free][read][called][node=Name]
238.1575 - ------ Attributes ---------------------------------------
238.1576 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1577 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1578 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1579 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1580 -
238.1581 - =============================================
238.1582 - timetz: FunctionDef : OffsetRange[51453,51634>
238.1583 - self [bound][param][data][read][node=Name]
238.1584 - time [free][read][called][node=Name]
238.1585 - ------ Attributes ---------------------------------------
238.1586 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1587 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1588 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1589 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1590 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1591 -
238.1592 - =============================================
238.1593 - replace: FunctionDef : OffsetRange[51635,52576>
238.1594 - None [free][read][node=Name]
238.1595 - True [free][read][node=Name]
238.1596 - _check_date_fields [free][read][called][node=Name]
238.1597 - _check_time_fields [free][read][called][node=Name]
238.1598 - _check_tzinfo_arg [free][read][called][node=Name]
238.1599 - datetime [free][read][called][node=Name]
238.1600 - day [bound][param][data][read][node=Name]
238.1601 - hour [bound][param][data][read][node=Name]
238.1602 - microsecond [bound][param][data][read][node=Name]
238.1603 - minute [bound][param][data][read][node=Name]
238.1604 - month [bound][param][data][read][node=Name]
238.1605 - second [bound][param][data][read][node=Name]
238.1606 - self [bound][param][data][read][node=Name]
238.1607 - tzinfo [bound][param][data][read][node=Name]
238.1608 - year [bound][param][data][read][node=Name]
238.1609 - ------ Attributes ---------------------------------------
238.1610 - day : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1611 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1612 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1613 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1614 - month : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1615 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1616 - tzinfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1617 - year : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1618 -
238.1619 - =============================================
238.1620 - astimezone: FunctionDef : OffsetRange[52577,53260>
238.1621 - None [free][read][node=Name]
238.1622 - TypeError [free][read][called][node=Name]
238.1623 - ValuError [free][read][called][node=Name]
238.1624 - ValueError [free][read][called][node=Name]
238.1625 - isinstance [free][read][called][node=Name]
238.1626 - myoffset [bound][data][read][node=Name]
238.1627 - mytz [bound][data][read][node=Name]
238.1628 - self [bound][param][data][read][node=Name]
238.1629 - tz [bound][param][data][read][node=Name]
238.1630 - tzinfo [free][read][node=Name]
238.1631 - utc [bound][data][read][node=Name]
238.1632 - ------ Attributes ---------------------------------------
238.1633 - tzinfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1634 - utcoffset : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.1635 -
238.1636 - =============================================
238.1637 - ctime: FunctionDef : OffsetRange[53261,53456>
238.1638 - self [bound][param][data][read][node=Name]
238.1639 - t [bound][data][read][node=Name]
238.1640 - tmxxx [free][read][called][node=Name]
238.1641 - ------ Attributes ---------------------------------------
238.1642 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1643 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1644 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1645 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1646 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1647 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1648 -
238.1649 - =============================================
238.1650 - isoformat: FunctionDef : OffsetRange[53457,54437>
238.1651 - None [free][read][node=Name]
238.1652 - _format_time [free][read][called][node=Name]
238.1653 - divmod [free][read][called][node=Name]
238.1654 - hh [bound][data][read][node=Name]
238.1655 - mm [bound][data][read][node=Name]
238.1656 - off [bound][data][read][node=Name]
238.1657 - s [bound][data][read][node=Name]
238.1658 - self [bound][param][data][read][node=Name]
238.1659 - sep [bound][param][data][read][node=Name]
238.1660 - sign [bound][data][read][node=Name]
238.1661 - ------ Attributes ---------------------------------------
238.1662 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1663 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1664 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1665 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1666 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1667 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1668 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1669 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1670 -
238.1671 - =============================================
238.1672 - __repr__: FunctionDef : OffsetRange[54438,54999>
238.1673 - L [bound][data][read][node=Name]
238.1674 - None [free][read][node=Name]
238.1675 - map [free][read][called][node=Name]
238.1676 - s [bound][data][read][node=Name]
238.1677 - self [bound][param][data][read][node=Name]
238.1678 - str [free][read][node=Name]
238.1679 - ------ Attributes ---------------------------------------
238.1680 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1681 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1682 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1683 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1684 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1685 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1686 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1687 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1688 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1689 -
238.1690 - =============================================
238.1691 - __str__: FunctionDef : OffsetRange[55000,55102>
238.1692 - self [bound][param][data][read][node=Name]
238.1693 - ------ Attributes ---------------------------------------
238.1694 - isoformat : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.1695 -
238.1696 - =============================================
238.1697 - utcoffset: FunctionDef : OffsetRange[55103,55518>
238.1698 - None [free][read][node=Name]
238.1699 - _call_tzinfo_method [free][read][called][node=Name]
238.1700 - _check_utc_offset [free][read][called][node=Name]
238.1701 - offset [bound][data][read][node=Name]
238.1702 - self [bound][param][data][read][node=Name]
238.1703 - timedelta [free][read][called][node=Name]
238.1704 - ------ Attributes ---------------------------------------
238.1705 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1706 -
238.1707 - =============================================
238.1708 - _utcoffset: FunctionDef : OffsetRange[55519,55693>
238.1709 - _call_tzinfo_method [free][read][called][node=Name]
238.1710 - _check_utc_offset [free][read][called][node=Name]
238.1711 - offset [bound][data][read][node=Name]
238.1712 - self [bound][param][data][read][node=Name]
238.1713 - ------ Attributes ---------------------------------------
238.1714 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1715 -
238.1716 - =============================================
238.1717 - tzname: FunctionDef : OffsetRange[55694,56114>
238.1718 - _call_tzinfo_method [free][read][called][node=Name]
238.1719 - _check_tzname [free][read][called][node=Name]
238.1720 - name [bound][data][read][node=Name]
238.1721 - self [bound][param][data][read][node=Name]
238.1722 - ------ Attributes ---------------------------------------
238.1723 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1724 -
238.1725 - =============================================
238.1726 - dst: FunctionDef : OffsetRange[56115,56793>
238.1727 - None [free][read][node=Name]
238.1728 - _call_tzinfo_method [free][read][called][node=Name]
238.1729 - _check_utc_offset [free][read][called][node=Name]
238.1730 - offset [bound][data][read][node=Name]
238.1731 - self [bound][param][data][read][node=Name]
238.1732 - timedelta [free][read][called][node=Name]
238.1733 - ------ Attributes ---------------------------------------
238.1734 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1735 -
238.1736 - =============================================
238.1737 - _dst: FunctionDef : OffsetRange[56794,56970>
238.1738 - _call_tzinfo_method [free][read][called][node=Name]
238.1739 - _check_utc_offset [free][read][called][node=Name]
238.1740 - offset [bound][data][read][node=Name]
238.1741 - self [bound][param][data][read][node=Name]
238.1742 - ------ Attributes ---------------------------------------
238.1743 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1744 -
238.1745 - =============================================
238.1746 - __eq__: FunctionDef : OffsetRange[56971,57197>
238.1747 - False [free][read][node=Name]
238.1748 - NotImplemented [free][read][node=Name]
238.1749 - datetime [free][read][node=Name]
238.1750 - hasattr [free][read][called][node=Name]
238.1751 - isinstance [free][read][called][node=Name]
238.1752 - other [bound][param][data][read][node=Name]
238.1753 - self [bound][param][data][read][node=Name]
238.1754 - ------ Attributes ---------------------------------------
238.1755 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1756 -
238.1757 - =============================================
238.1758 - __ne__: FunctionDef : OffsetRange[57198,57423>
238.1759 - NotImplemented [free][read][node=Name]
238.1760 - True [free][read][node=Name]
238.1761 - datetime [free][read][node=Name]
238.1762 - hasattr [free][read][called][node=Name]
238.1763 - isinstance [free][read][called][node=Name]
238.1764 - other [bound][param][data][read][node=Name]
238.1765 - self [bound][param][data][read][node=Name]
238.1766 - ------ Attributes ---------------------------------------
238.1767 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1768 -
238.1769 - =============================================
238.1770 - __le__: FunctionDef : OffsetRange[57424,57660>
238.1771 - NotImplemented [free][read][node=Name]
238.1772 - _cmperror [free][read][called][node=Name]
238.1773 - datetime [free][read][node=Name]
238.1774 - hasattr [free][read][called][node=Name]
238.1775 - isinstance [free][read][called][node=Name]
238.1776 - other [bound][param][data][read][node=Name]
238.1777 - self [bound][param][data][read][node=Name]
238.1778 - ------ Attributes ---------------------------------------
238.1779 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1780 -
238.1781 - =============================================
238.1782 - __lt__: FunctionDef : OffsetRange[57661,57896>
238.1783 - NotImplemented [free][read][node=Name]
238.1784 - _cmperror [free][read][called][node=Name]
238.1785 - datetime [free][read][node=Name]
238.1786 - hasattr [free][read][called][node=Name]
238.1787 - isinstance [free][read][called][node=Name]
238.1788 - other [bound][param][data][read][node=Name]
238.1789 - self [bound][param][data][read][node=Name]
238.1790 - ------ Attributes ---------------------------------------
238.1791 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1792 -
238.1793 - =============================================
238.1794 - __ge__: FunctionDef : OffsetRange[57897,58133>
238.1795 - NotImplemented [free][read][node=Name]
238.1796 - _cmperror [free][read][called][node=Name]
238.1797 - datetime [free][read][node=Name]
238.1798 - hasattr [free][read][called][node=Name]
238.1799 - isinstance [free][read][called][node=Name]
238.1800 - other [bound][param][data][read][node=Name]
238.1801 - self [bound][param][data][read][node=Name]
238.1802 - ------ Attributes ---------------------------------------
238.1803 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1804 -
238.1805 - =============================================
238.1806 - __gt__: FunctionDef : OffsetRange[58134,58369>
238.1807 - NotImplemented [free][read][node=Name]
238.1808 - _cmperror [free][read][called][node=Name]
238.1809 - datetime [free][read][node=Name]
238.1810 - hasattr [free][read][called][node=Name]
238.1811 - isinstance [free][read][called][node=Name]
238.1812 - other [bound][param][data][read][node=Name]
238.1813 - self [bound][param][data][read][node=Name]
238.1814 - ------ Attributes ---------------------------------------
238.1815 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1816 -
238.1817 - =============================================
238.1818 - __cmp: FunctionDef : OffsetRange[58370,59534>
238.1819 - None [free][read][node=Name]
238.1820 - True [free][read][node=Name]
238.1821 - TypeError [free][read][called][node=Name]
238.1822 - base_compare [bound][data][read][node=Name]
238.1823 - cmp [free][read][called][node=Name]
238.1824 - datetime [free][read][node=Name]
238.1825 - diff [bound][data][read][node=Name]
238.1826 - isinstance [free][read][called][node=Name]
238.1827 - myoff [bound][data][read][node=Name]
238.1828 - mytz [bound][data][read][node=Name]
238.1829 - other [bound][param][data][read][node=Name]
238.1830 - otoff [bound][data][read][node=Name]
238.1831 - ottz [bound][data][read][node=Name]
238.1832 - self [bound][param][data][read][node=Name]
238.1833 - ------ Attributes ---------------------------------------
238.1834 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1835 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1836 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1837 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1838 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1839 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1840 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1841 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1842 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1843 -
238.1844 - =============================================
238.1845 - __add__: FunctionDef : OffsetRange[59535,60206>
238.1846 - NotImplemented [free][read][node=Name]
238.1847 - isinstance [free][read][called][node=Name]
238.1848 - other [bound][param][data][read][node=Name]
238.1849 - result [bound][data][read][node=Name]
238.1850 - self [bound][param][data][read][node=Name]
238.1851 - t [bound][data][read][node=Name]
238.1852 - timedelta [free][read][node=Name]
238.1853 - tmxxx [free][read][called][node=Name]
238.1854 - ------ Attributes ---------------------------------------
238.1855 - __class__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.1856 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1857 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1858 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1859 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1860 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1861 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1862 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1863 - _checkOverflow : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1864 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1865 -
238.1866 - =============================================
238.1867 - __sub__: FunctionDef : OffsetRange[60231,61204>
238.1868 - None [free][read][node=Name]
238.1869 - NotImplemented [free][read][node=Name]
238.1870 - TypeError [free][read][node=Name]
238.1871 - base [bound][data][read][node=Name]
238.1872 - datetime [free][read][node=Name]
238.1873 - days1 [bound][data][read][node=Name]
238.1874 - days2 [bound][data][read][node=Name]
238.1875 - isinstance [free][read][called][node=Name]
238.1876 - myoff [bound][data][read][node=Name]
238.1877 - other [bound][param][data][read][node=Name]
238.1878 - otoff [bound][data][read][node=Name]
238.1879 - secs1 [bound][data][read][node=Name]
238.1880 - secs2 [bound][data][read][node=Name]
238.1881 - self [bound][param][data][read][node=Name]
238.1882 - timedelta [free][read][called][node=Name]
238.1883 - ------ Attributes ---------------------------------------
238.1884 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1885 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1886 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1887 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1888 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1889 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1890 - toordinal : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
238.1891 -
238.1892 - =============================================
238.1893 - __hash__: FunctionDef : OffsetRange[61205,61557>
238.1894 - None [free][read][node=Name]
238.1895 - _ymd2ord [free][read][called][node=Name]
238.1896 - days [bound][data][read][node=Name]
238.1897 - hash [free][read][called][node=Name]
238.1898 - seconds [bound][data][read][node=Name]
238.1899 - self [bound][param][data][read][node=Name]
238.1900 - timedelta [free][read][called][node=Name]
238.1901 - tzoff [bound][data][read][node=Name]
238.1902 - ------ Attributes ---------------------------------------
238.1903 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1904 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1905 - day : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1906 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1907 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1908 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1909 - month : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1910 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1911 - year : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1912 -
238.1913 - =============================================
238.1914 - __getstate: FunctionDef : OffsetRange[61616,62096>
238.1915 - None [free][read][node=Name]
238.1916 - basestate [bound][data][read][node=Name]
238.1917 - divmod [free][read][called][node=Name]
238.1918 - self [bound][param][data][read][node=Name]
238.1919 - us1 [bound][data][read][node=Name]
238.1920 - us2 [bound][data][read][node=Name]
238.1921 - us3 [bound][data][read][node=Name]
238.1922 - yhi [bound][data][read][node=Name]
238.1923 - ylo [bound][data][read][node=Name]
238.1924 - ------ Attributes ---------------------------------------
238.1925 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1926 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1927 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1928 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1929 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1930 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1931 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1932 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
238.1933 -
238.1934 - =============================================
238.1935 - __setstate: FunctionDef : OffsetRange[62097,62605>
238.1936 - None [free][read][node=Name]
238.1937 - isinstance [free][read][called][node=Name]
238.1938 - len [free][read][called][node=Name]
238.1939 - map [free][read][called][node=Name]
238.1940 - ord [free][read][node=Name]
238.1941 - self [bound][param][data][read][node=Name]
238.1942 - state [bound][param][data][read][node=Name]
238.1943 - string [bound][data][read][node=Name]
238.1944 - tuple [free][read][node=Name]
238.1945 - us1 [bound][data][read][node=Name]
238.1946 - us2 [bound][data][read][node=Name]
238.1947 - us3 [bound][data][read][node=Name]
238.1948 - yhi [bound][data][read][node=Name]
238.1949 - ylo [bound][data][read][node=Name]
238.1950 -
238.1951 - =============================================
238.1952 - __reduce__: FunctionDef : OffsetRange[62606,62681>
238.1953 - self [bound][param][data][read][node=Name]
238.1954 - ------ Attributes ---------------------------------------
238.1955 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
238.1956 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
238.1957 -
238.1958 - =============================================
238.1959 - _isoweek1monday: FunctionDef : OffsetRange[62822,63202>
238.1960 - THURSDAY [bound][data][read][node=Name]
238.1961 - _ymd2ord [free][read][called][node=Name]
238.1962 - firstday [bound][data][read][node=Name]
238.1963 - firstweekday [bound][data][read][node=Name]
238.1964 - week1monday [bound][data][read][node=Name]
238.1965 - year [bound][param][data][read][node=Name]
238.1966 -
238.1967 - =============================================
238.1968 - _test: FunctionDef : OffsetRange[71694,71763>
238.1969 - test_datetime [bound][imported][data][read][node=Import]
238.1970 -
239.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.semantic Sun Jan 04 13:11:53 2015 -0600
239.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
239.3 @@ -1,2008 +0,0 @@
239.4 -"""Concrete date/time and related types -- prototype implemented in Python.
239.5 -
239.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
239.7 -
239.8 -See also http://dir.yahoo.com/Reference/calendars/
239.9 -
239.10 -For a primer on DST, including many current DST rules, see
239.11 -http://webexhibits.org/daylightsaving/
239.12 -
239.13 -For more about DST than you ever wanted to know, see
239.14 -ftp://elsie.nci.nih.gov/pub/
239.15 -
239.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
239.17 -
239.18 -"""
239.19 -
239.20 -import time as _time
239.21 -import math as _math
239.22 -
239.23 -MINYEAR = 1
239.24 -MAXYEAR = 9999
239.25 -
239.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
239.27 -# also assumes the current Gregorian calendar indefinitely extended in
239.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
239.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
239.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
239.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
239.32 -# for all computations. See the book for algorithms for converting between
239.33 -# proleptic Gregorian ordinals and many other calendar systems.
239.34 -
239.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
239.36 -
239.37 -_DAYS_BEFORE_MONTH = [None]
239.38 -dbm = 0
239.39 -for dim in _DAYS_IN_MONTH[1:]:
239.40 - _DAYS_BEFORE_MONTH.append(dbm)
239.41 - dbm += dim
239.42 -del dbm, dim
239.43 -
239.44 -def |>METHOD:_is_leap<|(|>PARAMETER:year<|):
239.45 - "year -> 1 if leap year, else 0."
239.46 - return |>PARAMETER:year<| % 4 == 0 and (|>PARAMETER:year<| % 100 != 0 or |>PARAMETER:year<| % 400 == 0)
239.47 -
239.48 -def |>METHOD:_days_in_year<|(|>PARAMETER:year<|):
239.49 - "year -> number of days in year (366 if a leap year, else 365)."
239.50 - return 365 + _is_leap(|>PARAMETER:year<|)
239.51 -
239.52 -def |>METHOD:_days_before_year<|(|>PARAMETER:year<|):
239.53 - "year -> number of days before January 1st of year."
239.54 - y = |>PARAMETER:year<| - 1
239.55 - return y*365 + y//4 - y//100 + y//400
239.56 -
239.57 -def |>METHOD:_days_in_month<|(|>PARAMETER:year<|, |>PARAMETER:month<|):
239.58 - "year, month -> number of days in that month in that year."
239.59 - assert 1 <= |>PARAMETER:month<| <= 12, |>PARAMETER:month<|
239.60 - if |>PARAMETER:month<| == 2 and _is_leap(|>PARAMETER:year<|):
239.61 - return 29
239.62 - return _DAYS_IN_MONTH[|>PARAMETER:month<|]
239.63 -
239.64 -def |>METHOD:_days_before_month<|(|>PARAMETER:year<|, |>PARAMETER:month<|):
239.65 - "year, month -> number of days in year preceeding first day of month."
239.66 - if not 1 <= |>PARAMETER:month<| <= 12:
239.67 - raise ValueError('month must be in 1..12', |>PARAMETER:month<|)
239.68 - return _DAYS_BEFORE_MONTH[|>PARAMETER:month<|] + (|>PARAMETER:month<| > 2 and _is_leap(|>PARAMETER:year<|))
239.69 -
239.70 -def |>METHOD:_ymd2ord<|(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|):
239.71 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
239.72 - if not 1 <= |>PARAMETER:month<| <= 12:
239.73 - raise ValueError('month must be in 1..12', |>PARAMETER:month<|)
239.74 - dim = _days_in_month(|>PARAMETER:year<|, |>PARAMETER:month<|)
239.75 - if not 1 <= |>PARAMETER:day<| <= dim:
239.76 - raise ValueError('day must be in 1..%d' % dim, |>PARAMETER:day<|)
239.77 - return (_days_before_year(|>PARAMETER:year<|) +
239.78 - _days_before_month(|>PARAMETER:year<|, |>PARAMETER:month<|) +
239.79 - |>PARAMETER:day<|)
239.80 -
239.81 -_DI400Y = _days_before_year(401) # number of days in 400 years
239.82 -_DI100Y = _days_before_year(101) # " " " " 100 "
239.83 -_DI4Y = _days_before_year(5) # " " " " 4 "
239.84 -
239.85 -# A 4-year cycle has an extra leap day over what we'd get from pasting
239.86 -# together 4 single years.
239.87 -assert _DI4Y == 4 * 365 + 1
239.88 -
239.89 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
239.90 -# pasting together 4 100-year cycles.
239.91 -assert _DI400Y == 4 * _DI100Y + 1
239.92 -
239.93 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
239.94 -# pasting together 25 4-year cycles.
239.95 -assert _DI100Y == 25 * _DI4Y - 1
239.96 -
239.97 -def |>METHOD:_ord2ymd<|(|>PARAMETER:n<|):
239.98 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
239.99 -
239.100 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
239.101 - # repeats exactly every 400 years. The basic strategy is to find the
239.102 - # closest 400-year boundary at or before n, then work with the offset
239.103 - # from that boundary to n. Life is much clearer if we subtract 1 from
239.104 - # n first -- then the values of n at 400-year boundaries are exactly
239.105 - # those divisible by _DI400Y:
239.106 - #
239.107 - # D M Y n n-1
239.108 - # -- --- ---- ---------- ----------------
239.109 - # 31 Dec -400 -_DI400Y -_DI400Y -1
239.110 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
239.111 - # ...
239.112 - # 30 Dec 000 -1 -2
239.113 - # 31 Dec 000 0 -1
239.114 - # 1 Jan 001 1 0 400-year boundary
239.115 - # 2 Jan 001 2 1
239.116 - # 3 Jan 001 3 2
239.117 - # ...
239.118 - # 31 Dec 400 _DI400Y _DI400Y -1
239.119 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
239.120 - |>PARAMETER:n<| -= 1
239.121 - n400, |>PARAMETER:n<| = divmod(|>PARAMETER:n<|, _DI400Y)
239.122 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
239.123 -
239.124 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
239.125 - # the desired date. Now compute how many 100-year cycles precede n.
239.126 - # Note that it's possible for n100 to equal 4! In that case 4 full
239.127 - # 100-year cycles precede the desired day, which implies the desired
239.128 - # day is December 31 at the end of a 400-year cycle.
239.129 - n100, |>PARAMETER:n<| = divmod(|>PARAMETER:n<|, _DI100Y)
239.130 -
239.131 - # Now compute how many 4-year cycles precede it.
239.132 - n4, |>PARAMETER:n<| = divmod(|>PARAMETER:n<|, _DI4Y)
239.133 -
239.134 - # And now how many single years. Again n1 can be 4, and again meaning
239.135 - # that the desired day is December 31 at the end of the 4-year cycle.
239.136 - n1, |>PARAMETER:n<| = divmod(|>PARAMETER:n<|, 365)
239.137 -
239.138 - year += n100 * 100 + n4 * 4 + n1
239.139 - if n1 == 4 or n100 == 4:
239.140 - assert |>PARAMETER:n<| == 0
239.141 - return year-1, 12, 31
239.142 -
239.143 - # Now the year is correct, and n is the offset from January 1. We find
239.144 - # the month via an estimate that's either exact or one too large.
239.145 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
239.146 - assert leapyear == _is_leap(year)
239.147 - month = (|>PARAMETER:n<| + 50) >> 5
239.148 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
239.149 - if preceding > |>PARAMETER:n<|: # estimate is too large
239.150 - month -= 1
239.151 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
239.152 - |>PARAMETER:n<| -= preceding
239.153 - assert 0 <= |>PARAMETER:n<| < _days_in_month(year, month)
239.154 -
239.155 - # Now the year and month are correct, and n is the offset from the
239.156 - # start of that month: we're done!
239.157 - return year, month, |>PARAMETER:n<|+1
239.158 -
239.159 -# Month and day names. For localized versions, see the calendar module.
239.160 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
239.161 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
239.162 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
239.163 -
239.164 -
239.165 -def |>METHOD:_build_struct_time<|(|>PARAMETER:y<|, |>PARAMETER:m<|, |>PARAMETER:d<|, |>PARAMETER:hh<|, |>PARAMETER:mm<|, |>PARAMETER:ss<|, |>PARAMETER:dstflag<|):
239.166 - wday = (_ymd2ord(|>PARAMETER:y<|, |>PARAMETER:m<|, |>PARAMETER:d<|) + 6) % 7
239.167 - dnum = _days_before_month(|>PARAMETER:y<|, |>PARAMETER:m<|) + |>PARAMETER:d<|
239.168 - return _time.struct_time((|>PARAMETER:y<|, |>PARAMETER:m<|, |>PARAMETER:d<|, |>PARAMETER:hh<|, |>PARAMETER:mm<|, |>PARAMETER:ss<|, wday, dnum, |>PARAMETER:dstflag<|))
239.169 -
239.170 -def |>METHOD:_format_time<|(|>PARAMETER:hh<|, |>PARAMETER:mm<|, |>PARAMETER:ss<|, |>PARAMETER:us<|):
239.171 - # Skip trailing microseconds when us==0.
239.172 - result = "%02d:%02d:%02d" % (|>PARAMETER:hh<|, |>PARAMETER:mm<|, |>PARAMETER:ss<|)
239.173 - if |>PARAMETER:us<|:
239.174 - result += ".%06d" % |>PARAMETER:us<|
239.175 - return result
239.176 -
239.177 -# Correctly substitute for %z and %Z escapes in strftime formats.
239.178 -def |>METHOD:_wrap_strftime<|(|>PARAMETER:object<|, |>PARAMETER:format<|, |>PARAMETER:timetuple<|):
239.179 - year = |>PARAMETER:timetuple<|[0]
239.180 - if year < 1900:
239.181 - raise ValueError("year=%d is before 1900; the datetime strftime() "
239.182 - "methods require year >= 1900" % year)
239.183 - # Don't call _utcoffset() or tzname() unless actually needed.
239.184 - zreplace = None # the string to use for %z
239.185 - Zreplace = None # the string to use for %Z
239.186 -
239.187 - # Scan format for %z and %Z escapes, replacing as needed.
239.188 - newformat = []
239.189 - push = newformat.append
239.190 - i, n = 0, len(|>PARAMETER:format<|)
239.191 - while i < n:
239.192 - ch = |>PARAMETER:format<|[i]
239.193 - i += 1
239.194 - if ch == '%':
239.195 - if i < n:
239.196 - ch = |>PARAMETER:format<|[i]
239.197 - i += 1
239.198 - if ch == 'z':
239.199 - if zreplace is None:
239.200 - zreplace = ""
239.201 - if hasattr(|>PARAMETER:object<|, "_utcoffset"):
239.202 - offset = |>PARAMETER:object<|._utcoffset()
239.203 - if offset is not None:
239.204 - sign = '+'
239.205 - if offset < 0:
239.206 - offset = -offset
239.207 - sign = '-'
239.208 - h, m = divmod(offset, 60)
239.209 - zreplace = '%c%02d%02d' % (sign, h, m)
239.210 - assert '%' not in zreplace
239.211 - newformat.append(zreplace)
239.212 - elif ch == 'Z':
239.213 - if Zreplace is None:
239.214 - Zreplace = ""
239.215 - if hasattr(|>PARAMETER:object<|, "tzname"):
239.216 - s = |>PARAMETER:object<|.tzname()
239.217 - if s is not None:
239.218 - # strftime is going to have at this: escape %
239.219 - Zreplace = s.replace('%', '%%')
239.220 - newformat.append(Zreplace)
239.221 - else:
239.222 - push('%')
239.223 - push(ch)
239.224 - else:
239.225 - push('%')
239.226 - else:
239.227 - push(ch)
239.228 - newformat = "".join(newformat)
239.229 - return _time.strftime(newformat, |>PARAMETER:timetuple<|)
239.230 -
239.231 -def |>METHOD:_call_tzinfo_method<|(|>PARAMETER:tzinfo<|, |>PARAMETER:methname<|, |>PARAMETER:tzinfoarg<|):
239.232 - if |>PARAMETER:tzinfo<| is None:
239.233 - return None
239.234 - return getattr(|>PARAMETER:tzinfo<|, |>PARAMETER:methname<|)(|>PARAMETER:tzinfoarg<|)
239.235 -
239.236 -# Just raise TypeError if the arg isn't None or a string.
239.237 -def |>METHOD:_check_tzname<|(|>PARAMETER:name<|):
239.238 - if |>PARAMETER:name<| is not None and not isinstance(|>PARAMETER:name<|, str):
239.239 - raise TypeError("tzinfo.tzname() must return None or string, "
239.240 - "not '%s'" % type(|>PARAMETER:name<|))
239.241 -
239.242 -# name is the offset-producing method, "utcoffset" or "dst".
239.243 -# offset is what it returned.
239.244 -# If offset isn't None or timedelta, raises TypeError.
239.245 -# If offset is None, returns None.
239.246 -# Else offset is checked for being in range, and a whole # of minutes.
239.247 -# If it is, its integer value is returned. Else ValueError is raised.
239.248 -def |>METHOD:_check_utc_offset<|(|>PARAMETER:name<|, |>PARAMETER:offset<|):
239.249 - assert |>PARAMETER:name<| in ("utcoffset", "dst")
239.250 - if |>PARAMETER:offset<| is None:
239.251 - return None
239.252 - if not isinstance(|>PARAMETER:offset<|, timedelta):
239.253 - raise TypeError("tzinfo.%s() must return None "
239.254 - "or timedelta, not '%s'" % (|>PARAMETER:name<|, type(|>PARAMETER:offset<|)))
239.255 - days = |>PARAMETER:offset<|.days
239.256 - if days < -1 or days > 0:
239.257 - |>PARAMETER:offset<| = 1440 # trigger out-of-range
239.258 - else:
239.259 - seconds = days * 86400 + |>PARAMETER:offset<|.seconds
239.260 - minutes, seconds = divmod(seconds, 60)
239.261 - if seconds or |>PARAMETER:offset<|.microseconds:
239.262 - raise ValueError("tzinfo.%s() must return a whole number "
239.263 - "of minutes" % |>PARAMETER:name<|)
239.264 - |>PARAMETER:offset<| = minutes
239.265 - if -1440 < |>PARAMETER:offset<| < 1440:
239.266 - return |>PARAMETER:offset<|
239.267 - raise ValueError("%s()=%d, must be in -1439..1439" % (|>PARAMETER:name<|, |>PARAMETER:offset<|))
239.268 -
239.269 -def |>METHOD:_check_date_fields<|(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|):
239.270 - if not MINYEAR <= |>PARAMETER:year<| <= MAXYEAR:
239.271 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), |>PARAMETER:year<|)
239.272 - if not 1 <= |>PARAMETER:month<| <= 12:
239.273 - raise ValueError('month must be in 1..12', |>PARAMETER:month<|)
239.274 - dim = _days_in_month(|>PARAMETER:year<|, |>PARAMETER:month<|)
239.275 - if not 1 <= |>PARAMETER:day<| <= dim:
239.276 - raise ValueError('day must be in 1..%d' % dim, |>PARAMETER:day<|)
239.277 -
239.278 -def |>METHOD:_check_time_fields<|(|>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|, |>PARAMETER:microsecond<|):
239.279 - if not 0 <= |>PARAMETER:hour<| <= 23:
239.280 - raise ValueError('hour must be in 0..23', |>PARAMETER:hour<|)
239.281 - if not 0 <= |>PARAMETER:minute<| <= 59:
239.282 - raise ValueError('minute must be in 0..59', |>PARAMETER:minute<|)
239.283 - if not 0 <= |>PARAMETER:second<| <= 59:
239.284 - raise ValueError('second must be in 0..59', |>PARAMETER:second<|)
239.285 - if not 0 <= |>PARAMETER:microsecond<| <= 999999:
239.286 - raise ValueError('microsecond must be in 0..999999', |>PARAMETER:microsecond<|)
239.287 -
239.288 -def |>METHOD:_check_tzinfo_arg<|(|>PARAMETER:tz<|):
239.289 - if |>PARAMETER:tz<| is not None and not isinstance(|>PARAMETER:tz<|, tzinfo):
239.290 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
239.291 -
239.292 -
239.293 -# Notes on comparison: In general, datetime module comparison operators raise
239.294 -# TypeError when they don't know how to do a comparison themself. If they
239.295 -# returned NotImplemented instead, comparison could (silently) fall back to
239.296 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
239.297 -# and that's not helpful. There are two exceptions:
239.298 -#
239.299 -# 1. For date and datetime, if the other object has a "timetuple" attr,
239.300 -# NotImplemented is returned. This is a hook to allow other kinds of
239.301 -# datetime-like objects a chance to intercept the comparison.
239.302 -#
239.303 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
239.304 -# so opertaions like
239.305 -#
239.306 -# x == y
239.307 -# x != y
239.308 -# x in sequence
239.309 -# x not in sequence
239.310 -# dict[x] = y
239.311 -#
239.312 -# don't raise annoying TypeErrors just because a datetime object
239.313 -# is part of a heterogeneous collection. If there's no known way to
239.314 -# compare X to a datetime, saying they're not equal is reasonable.
239.315 -
239.316 -def |>METHOD:_cmperror<|(|>PARAMETER:x<|, |>PARAMETER:y<|):
239.317 - raise TypeError("can't compare '%s' to '%s'" % (
239.318 - type(|>PARAMETER:x<|).__name__, type(|>PARAMETER:y<|).__name__))
239.319 -
239.320 -# This is a start at a struct tm workalike. Goals:
239.321 -#
239.322 -# + Works the same way across platforms.
239.323 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
239.324 -#
239.325 -# Note: I suspect it's best if this flavor of tm does *not* try to
239.326 -# second-guess timezones or DST. Instead fold whatever adjustments you want
239.327 -# into the minutes argument (and the constructor will normalize).
239.328 -
239.329 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
239.330 -
239.331 -class tmxxx:
239.332 -
239.333 - ordinal = None
239.334 -
239.335 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|, |>PARAMETER:hour<|=0, |>PARAMETER:minute<|=0, |>PARAMETER:second<|=0,
239.336 - |>PARAMETER:microsecond<|=0):
239.337 - # Normalize all the inputs, and store the normalized values.
239.338 - if not 0 <= |>PARAMETER:microsecond<| <= 999999:
239.339 - carry, |>PARAMETER:microsecond<| = divmod(|>PARAMETER:microsecond<|, 1000000)
239.340 - |>PARAMETER:second<| += carry
239.341 - if not 0 <= |>PARAMETER:second<| <= 59:
239.342 - carry, |>PARAMETER:second<| = divmod(|>PARAMETER:second<|, 60)
239.343 - |>PARAMETER:minute<| += carry
239.344 - if not 0 <= |>PARAMETER:minute<| <= 59:
239.345 - carry, |>PARAMETER:minute<| = divmod(|>PARAMETER:minute<|, 60)
239.346 - |>PARAMETER:hour<| += carry
239.347 - if not 0 <= |>PARAMETER:hour<| <= 23:
239.348 - carry, |>PARAMETER:hour<| = divmod(|>PARAMETER:hour<|, 24)
239.349 - |>PARAMETER:day<| += carry
239.350 -
239.351 - # That was easy. Now it gets muddy: the proper range for day
239.352 - # can't be determined without knowing the correct month and year,
239.353 - # but if day is, e.g., plus or minus a million, the current month
239.354 - # and year values make no sense (and may also be out of bounds
239.355 - # themselves).
239.356 - # Saying 12 months == 1 year should be non-controversial.
239.357 - if not 1 <= |>PARAMETER:month<| <= 12:
239.358 - carry, |>PARAMETER:month<| = divmod(|>PARAMETER:month<|-1, 12)
239.359 - |>PARAMETER:year<| += carry
239.360 - |>PARAMETER:month<| += 1
239.361 - assert 1 <= |>PARAMETER:month<| <= 12
239.362 -
239.363 - # Now only day can be out of bounds (year may also be out of bounds
239.364 - # for a datetime object, but we don't care about that here).
239.365 - # If day is out of bounds, what to do is arguable, but at least the
239.366 - # method here is principled and explainable.
239.367 - dim = _days_in_month(|>PARAMETER:year<|, |>PARAMETER:month<|)
239.368 - if not 1 <= |>PARAMETER:day<| <= dim:
239.369 - # Move day-1 days from the first of the month. First try to
239.370 - # get off cheap if we're only one day out of range (adjustments
239.371 - # for timezone alone can't be worse than that).
239.372 - if |>PARAMETER:day<| == 0: # move back a day
239.373 - |>PARAMETER:month<| -= 1
239.374 - if |>PARAMETER:month<| > 0:
239.375 - |>PARAMETER:day<| = _days_in_month(|>PARAMETER:year<|, |>PARAMETER:month<|)
239.376 - else:
239.377 - |>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<| = |>PARAMETER:year<|-1, 12, 31
239.378 - elif |>PARAMETER:day<| == dim + 1: # move forward a day
239.379 - |>PARAMETER:month<| += 1
239.380 - |>PARAMETER:day<| = 1
239.381 - if |>PARAMETER:month<| > 12:
239.382 - |>PARAMETER:month<| = 1
239.383 - |>PARAMETER:year<| += 1
239.384 - else:
239.385 - |>PARAMETER:self<|.ordinal = _ymd2ord(|>PARAMETER:year<|, |>PARAMETER:month<|, 1) + (|>PARAMETER:day<| - 1)
239.386 - |>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<| = _ord2ymd(|>PARAMETER:self<|.ordinal)
239.387 -
239.388 - |>PARAMETER:self<|.year, |>PARAMETER:self<|.month, |>PARAMETER:self<|.day = |>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|
239.389 - |>PARAMETER:self<|.hour, |>PARAMETER:self<|.minute, |>PARAMETER:self<|.second = |>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|
239.390 - |>PARAMETER:self<|.microsecond = |>PARAMETER:microsecond<|
239.391 -
239.392 - def |>METHOD:toordinal<|(|>PARAMETER:self<|):
239.393 - """Return proleptic Gregorian ordinal for the year, month and day.
239.394 -
239.395 - January 1 of year 1 is day 1. Only the year, month and day values
239.396 - contribute to the result.
239.397 - """
239.398 - if |>PARAMETER:self<|.ordinal is None:
239.399 - |>PARAMETER:self<|.ordinal = _ymd2ord(|>PARAMETER:self<|.year, |>PARAMETER:self<|.month, |>PARAMETER:self<|.day)
239.400 - return |>PARAMETER:self<|.ordinal
239.401 -
239.402 - def |>METHOD:time<|(|>PARAMETER:self<|):
239.403 - "Return Unixish timestamp, as a float (assuming UTC)."
239.404 - days = |>PARAMETER:self<|.toordinal() - _ORD1970 # convert to UNIX epoch
239.405 - seconds = ((days * 24. + |>PARAMETER:self<|.hour)*60. + |>PARAMETER:self<|.minute)*60.
239.406 - return seconds + |>PARAMETER:self<|.second + |>PARAMETER:self<|.microsecond / 1e6
239.407 -
239.408 - def |>METHOD:ctime<|(|>PARAMETER:self<|):
239.409 - "Return ctime() style string."
239.410 - weekday = |>PARAMETER:self<|.toordinal() % 7 or 7
239.411 - return "%s %s %2d %02d:%02d:%02d %04d" % (
239.412 - _DAYNAMES[weekday],
239.413 - _MONTHNAMES[|>PARAMETER:self<|.month],
239.414 - |>PARAMETER:self<|.day,
239.415 - |>PARAMETER:self<|.hour, |>PARAMETER:self<|.minute, |>PARAMETER:self<|.second,
239.416 - |>PARAMETER:self<|.year)
239.417 -
239.418 -class timedelta(object):
239.419 - """Represent the difference between two datetime objects.
239.420 -
239.421 - Supported operators:
239.422 -
239.423 - - add, subtract timedelta
239.424 - - unary plus, minus, abs
239.425 - - compare to timedelta
239.426 - - multiply, divide by int/long
239.427 -
239.428 - In addition, datetime supports subtraction of two datetime objects
239.429 - returning a timedelta, and addition or subtraction of a datetime
239.430 - and a timedelta giving a datetime.
239.431 -
239.432 - Representation: (days, seconds, microseconds). Why? Because I
239.433 - felt like it.
239.434 - """
239.435 -
239.436 - def |>METHOD:__new__<|(|>PARAMETER:cls<|, |>PARAMETER:days<|=0, |>PARAMETER:seconds<|=0, |>PARAMETER:microseconds<|=0,
239.437 - # XXX The following should only be used as keyword args:
239.438 - |>PARAMETER:milliseconds<|=0, |>PARAMETER:minutes<|=0, |>PARAMETER:hours<|=0, |>PARAMETER:weeks<|=0):
239.439 - # Doing this efficiently and accurately in C is going to be difficult
239.440 - # and error-prone, due to ubiquitous overflow possibilities, and that
239.441 - # C double doesn't have enough bits of precision to represent
239.442 - # microseconds over 10K years faithfully. The code here tries to make
239.443 - # explicit where go-fast assumptions can be relied on, in order to
239.444 - # guide the C implementation; it's way more convoluted than speed-
239.445 - # ignoring auto-overflow-to-long idiomatic Python could be.
239.446 -
239.447 - # XXX Check that all inputs are ints, longs or floats.
239.448 -
239.449 - # Final values, all integer.
239.450 - # s and us fit in 32-bit signed ints; d isn't bounded.
239.451 - d = s = us = 0
239.452 -
239.453 - # Normalize everything to days, seconds, microseconds.
239.454 - |>PARAMETER:days<| += |>PARAMETER:weeks<|*7
239.455 - |>PARAMETER:seconds<| += |>PARAMETER:minutes<|*60 + |>PARAMETER:hours<|*3600
239.456 - |>PARAMETER:microseconds<| += |>PARAMETER:milliseconds<|*1000
239.457 -
239.458 - # Get rid of all fractions, and normalize s and us.
239.459 - # Take a deep breath <wink>.
239.460 - if isinstance(|>PARAMETER:days<|, float):
239.461 - dayfrac, |>PARAMETER:days<| = _math.modf(|>PARAMETER:days<|)
239.462 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
239.463 - assert daysecondswhole == int(daysecondswhole) # can't overflow
239.464 - s = int(daysecondswhole)
239.465 - assert |>PARAMETER:days<| == long(|>PARAMETER:days<|)
239.466 - d = long(|>PARAMETER:days<|)
239.467 - else:
239.468 - daysecondsfrac = 0.0
239.469 - d = |>PARAMETER:days<|
239.470 - assert isinstance(daysecondsfrac, float)
239.471 - assert abs(daysecondsfrac) <= 1.0
239.472 - assert isinstance(d, (int, long))
239.473 - assert abs(s) <= 24 * 3600
239.474 - # days isn't referenced again before redefinition
239.475 -
239.476 - if isinstance(|>PARAMETER:seconds<|, float):
239.477 - secondsfrac, |>PARAMETER:seconds<| = _math.modf(|>PARAMETER:seconds<|)
239.478 - assert |>PARAMETER:seconds<| == long(|>PARAMETER:seconds<|)
239.479 - |>PARAMETER:seconds<| = long(|>PARAMETER:seconds<|)
239.480 - secondsfrac += daysecondsfrac
239.481 - assert abs(secondsfrac) <= 2.0
239.482 - else:
239.483 - secondsfrac = daysecondsfrac
239.484 - # daysecondsfrac isn't referenced again
239.485 - assert isinstance(secondsfrac, float)
239.486 - assert abs(secondsfrac) <= 2.0
239.487 -
239.488 - assert isinstance(|>PARAMETER:seconds<|, (int, long))
239.489 - |>PARAMETER:days<|, |>PARAMETER:seconds<| = divmod(|>PARAMETER:seconds<|, 24*3600)
239.490 - d += |>PARAMETER:days<|
239.491 - s += int(|>PARAMETER:seconds<|) # can't overflow
239.492 - assert isinstance(s, int)
239.493 - assert abs(s) <= 2 * 24 * 3600
239.494 - # seconds isn't referenced again before redefinition
239.495 -
239.496 - usdouble = secondsfrac * 1e6
239.497 - assert abs(usdouble) < 2.1e6 # exact value not critical
239.498 - # secondsfrac isn't referenced again
239.499 -
239.500 - if isinstance(|>PARAMETER:microseconds<|, float):
239.501 - |>PARAMETER:microseconds<| += usdouble
239.502 - |>PARAMETER:microseconds<| = round(|>PARAMETER:microseconds<|)
239.503 - |>PARAMETER:seconds<|, |>PARAMETER:microseconds<| = divmod(|>PARAMETER:microseconds<|, 1e6)
239.504 - assert |>PARAMETER:microseconds<| == int(|>PARAMETER:microseconds<|)
239.505 - assert |>PARAMETER:seconds<| == long(|>PARAMETER:seconds<|)
239.506 - |>PARAMETER:days<|, |>PARAMETER:seconds<| = divmod(|>PARAMETER:seconds<|, 24.*3600.)
239.507 - assert |>PARAMETER:days<| == long(|>PARAMETER:days<|)
239.508 - assert |>PARAMETER:seconds<| == int(|>PARAMETER:seconds<|)
239.509 - d += long(|>PARAMETER:days<|)
239.510 - s += int(|>PARAMETER:seconds<|) # can't overflow
239.511 - assert isinstance(s, int)
239.512 - assert abs(s) <= 3 * 24 * 3600
239.513 - else:
239.514 - |>PARAMETER:seconds<|, |>PARAMETER:microseconds<| = divmod(|>PARAMETER:microseconds<|, 1000000)
239.515 - |>PARAMETER:days<|, |>PARAMETER:seconds<| = divmod(|>PARAMETER:seconds<|, 24*3600)
239.516 - d += |>PARAMETER:days<|
239.517 - s += int(|>PARAMETER:seconds<|) # can't overflow
239.518 - assert isinstance(s, int)
239.519 - assert abs(s) <= 3 * 24 * 3600
239.520 - |>PARAMETER:microseconds<| = float(|>PARAMETER:microseconds<|)
239.521 - |>PARAMETER:microseconds<| += usdouble
239.522 - |>PARAMETER:microseconds<| = round(|>PARAMETER:microseconds<|)
239.523 - assert abs(s) <= 3 * 24 * 3600
239.524 - assert abs(|>PARAMETER:microseconds<|) < 3.1e6
239.525 -
239.526 - # Just a little bit of carrying possible for microseconds and seconds.
239.527 - assert isinstance(|>PARAMETER:microseconds<|, float)
239.528 - assert int(|>PARAMETER:microseconds<|) == |>PARAMETER:microseconds<|
239.529 - us = int(|>PARAMETER:microseconds<|)
239.530 - |>PARAMETER:seconds<|, us = divmod(us, 1000000)
239.531 - s += |>PARAMETER:seconds<| # cant't overflow
239.532 - assert isinstance(s, int)
239.533 - |>PARAMETER:days<|, s = divmod(s, 24*3600)
239.534 - d += |>PARAMETER:days<|
239.535 -
239.536 - assert isinstance(d, (int, long))
239.537 - assert isinstance(s, int) and 0 <= s < 24*3600
239.538 - assert isinstance(us, int) and 0 <= us < 1000000
239.539 -
239.540 - self = object.__new__(|>PARAMETER:cls<|)
239.541 -
239.542 - self.__days = d
239.543 - self.__seconds = s
239.544 - self.__microseconds = us
239.545 - if abs(d) > 999999999:
239.546 - raise OverflowError("timedelta # of days is too large: %d" % d)
239.547 -
239.548 - return self
239.549 -
239.550 - def |>METHOD:__repr__<|(|>PARAMETER:self<|):
239.551 - if |>PARAMETER:self<|.__microseconds:
239.552 - return "%s(%d, %d, %d)" % ('datetime.' + |>PARAMETER:self<|.__class__.__name__,
239.553 - |>PARAMETER:self<|.__days,
239.554 - |>PARAMETER:self<|.__seconds,
239.555 - |>PARAMETER:self<|.__microseconds)
239.556 - if |>PARAMETER:self<|.__seconds:
239.557 - return "%s(%d, %d)" % ('datetime.' + |>PARAMETER:self<|.__class__.__name__,
239.558 - |>PARAMETER:self<|.__days,
239.559 - |>PARAMETER:self<|.__seconds)
239.560 - return "%s(%d)" % ('datetime.' + |>PARAMETER:self<|.__class__.__name__, |>PARAMETER:self<|.__days)
239.561 -
239.562 - def |>METHOD:__str__<|(|>PARAMETER:self<|):
239.563 - mm, ss = divmod(|>PARAMETER:self<|.__seconds, 60)
239.564 - hh, mm = divmod(mm, 60)
239.565 - s = "%d:%02d:%02d" % (hh, mm, ss)
239.566 - if |>PARAMETER:self<|.__days:
239.567 - def |>METHOD:plural<|(|>PARAMETER:n<|):
239.568 - return |>PARAMETER:n<|, abs(|>PARAMETER:n<|) != 1 and "s" or ""
239.569 - s = ("%d day%s, " % plural(|>PARAMETER:self<|.__days)) + s
239.570 - if |>PARAMETER:self<|.__microseconds:
239.571 - s = s + ".%06d" % |>PARAMETER:self<|.__microseconds
239.572 - return s
239.573 -
239.574 - days = property(lambda self: self.__days, doc="days")
239.575 - seconds = property(lambda self: self.__seconds, doc="seconds")
239.576 - microseconds = property(lambda self: self.__microseconds,
239.577 - doc="microseconds")
239.578 -
239.579 - def |>METHOD:__add__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.580 - if isinstance(|>PARAMETER:other<|, timedelta):
239.581 - return timedelta(|>PARAMETER:self<|.__days + |>PARAMETER:other<|.__days,
239.582 - |>PARAMETER:self<|.__seconds + |>PARAMETER:other<|.__seconds,
239.583 - |>PARAMETER:self<|.__microseconds + |>PARAMETER:other<|.__microseconds)
239.584 - return NotImplemented
239.585 -
239.586 - __radd__ = __add__
239.587 -
239.588 - def |>METHOD:__sub__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.589 - if isinstance(|>PARAMETER:other<|, timedelta):
239.590 - return |>PARAMETER:self<| + -|>PARAMETER:other<|
239.591 - return NotImplemented
239.592 -
239.593 - def |>METHOD:__rsub__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.594 - if isinstance(|>PARAMETER:other<|, timedelta):
239.595 - return -|>PARAMETER:self<| + |>PARAMETER:other<|
239.596 - return NotImplemented
239.597 -
239.598 - def |>METHOD:__neg__<|(|>PARAMETER:self<|):
239.599 - return |>PARAMETER:self<|.__class__(-|>PARAMETER:self<|.__days,
239.600 - -|>PARAMETER:self<|.__seconds,
239.601 - -|>PARAMETER:self<|.__microseconds)
239.602 -
239.603 - def |>METHOD:__pos__<|(|>PARAMETER:self<|):
239.604 - return |>PARAMETER:self<|
239.605 -
239.606 - def |>METHOD:__abs__<|(|>PARAMETER:self<|):
239.607 - if |>PARAMETER:self<|.__days < 0:
239.608 - return -|>PARAMETER:self<|
239.609 - else:
239.610 - return |>PARAMETER:self<|
239.611 -
239.612 - def |>METHOD:__mul__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.613 - if isinstance(|>PARAMETER:other<|, (int, long)):
239.614 - return |>PARAMETER:self<|.__class__(|>PARAMETER:self<|.__days * |>PARAMETER:other<|,
239.615 - |>PARAMETER:self<|.__seconds * |>PARAMETER:other<|,
239.616 - |>PARAMETER:self<|.__microseconds * |>PARAMETER:other<|)
239.617 - return NotImplemented
239.618 -
239.619 - __rmul__ = __mul__
239.620 -
239.621 - def |>METHOD:__div__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.622 - if isinstance(|>PARAMETER:other<|, (int, long)):
239.623 - usec = ((|>PARAMETER:self<|.__days * (24*3600L) + |>PARAMETER:self<|.__seconds) * 1000000 +
239.624 - |>PARAMETER:self<|.__microseconds)
239.625 - return |>PARAMETER:self<|.__class__(0, 0, usec // |>PARAMETER:other<|)
239.626 - return NotImplemented
239.627 -
239.628 - __floordiv__ = __div__
239.629 -
239.630 - # Comparisons.
239.631 -
239.632 - def |>METHOD:__eq__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.633 - if isinstance(|>PARAMETER:other<|, timedelta):
239.634 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) == 0
239.635 - else:
239.636 - return False
239.637 -
239.638 - def |>METHOD:__ne__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.639 - if isinstance(|>PARAMETER:other<|, timedelta):
239.640 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) != 0
239.641 - else:
239.642 - return True
239.643 -
239.644 - def |>METHOD:__le__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.645 - if isinstance(|>PARAMETER:other<|, timedelta):
239.646 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) <= 0
239.647 - else:
239.648 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.649 -
239.650 - def |>METHOD:__lt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.651 - if isinstance(|>PARAMETER:other<|, timedelta):
239.652 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) < 0
239.653 - else:
239.654 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.655 -
239.656 - def |>METHOD:__ge__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.657 - if isinstance(|>PARAMETER:other<|, timedelta):
239.658 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) >= 0
239.659 - else:
239.660 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.661 -
239.662 - def |>METHOD:__gt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.663 - if isinstance(|>PARAMETER:other<|, timedelta):
239.664 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) > 0
239.665 - else:
239.666 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.667 -
239.668 - def |>METHOD:__cmp<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.669 - assert isinstance(|>PARAMETER:other<|, timedelta)
239.670 - return cmp(|>PARAMETER:self<|.__getstate(), |>PARAMETER:other<|.__getstate())
239.671 -
239.672 - def |>METHOD:__hash__<|(|>PARAMETER:self<|):
239.673 - return hash(|>PARAMETER:self<|.__getstate())
239.674 -
239.675 - def |>METHOD:__nonzero__<|(|>PARAMETER:self<|):
239.676 - return (|>PARAMETER:self<|.__days != 0 or
239.677 - |>PARAMETER:self<|.__seconds != 0 or
239.678 - |>PARAMETER:self<|.__microseconds != 0)
239.679 -
239.680 - # Pickle support.
239.681 -
239.682 - __safe_for_unpickling__ = True # For Python 2.2
239.683 -
239.684 - def |>METHOD:__getstate<|(|>PARAMETER:self<|):
239.685 - return (|>PARAMETER:self<|.__days, |>PARAMETER:self<|.__seconds, |>PARAMETER:self<|.__microseconds)
239.686 -
239.687 - def |>METHOD:__reduce__<|(|>PARAMETER:self<|):
239.688 - return (|>PARAMETER:self<|.__class__, |>PARAMETER:self<|.__getstate())
239.689 -
239.690 -timedelta.min = timedelta(-999999999)
239.691 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
239.692 - microseconds=999999)
239.693 -timedelta.resolution = timedelta(microseconds=1)
239.694 -
239.695 -class date(object):
239.696 - """Concrete date type.
239.697 -
239.698 - Constructors:
239.699 -
239.700 - __new__()
239.701 - fromtimestamp()
239.702 - today()
239.703 - fromordinal()
239.704 -
239.705 - Operators:
239.706 -
239.707 - __repr__, __str__
239.708 - __cmp__, __hash__
239.709 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
239.710 -
239.711 - Methods:
239.712 -
239.713 - timetuple()
239.714 - toordinal()
239.715 - weekday()
239.716 - isoweekday(), isocalendar(), isoformat()
239.717 - ctime()
239.718 - strftime()
239.719 -
239.720 - Properties (readonly):
239.721 - year, month, day
239.722 - """
239.723 -
239.724 - def |>METHOD:__new__<|(|>PARAMETER:cls<|, |>PARAMETER:year<|, |>PARAMETER:month<|=None, |>PARAMETER:day<|=None):
239.725 - """Constructor.
239.726 -
239.727 - Arguments:
239.728 -
239.729 - year, month, day (required, base 1)
239.730 - """
239.731 - if isinstance(|>PARAMETER:year<|, str):
239.732 - # Pickle support
239.733 - self = object.__new__(|>PARAMETER:cls<|)
239.734 - self.__setstate((|>PARAMETER:year<|,))
239.735 - return self
239.736 - _check_date_fields(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|)
239.737 - self = object.__new__(|>PARAMETER:cls<|)
239.738 - self.__year = |>PARAMETER:year<|
239.739 - self.__month = |>PARAMETER:month<|
239.740 - self.__day = |>PARAMETER:day<|
239.741 - return self
239.742 -
239.743 - # Additional constructors
239.744 -
239.745 - def |>METHOD:fromtimestamp<|(|>PARAMETER:cls<|, |>PARAMETER:t<|):
239.746 - "Construct a date from a POSIX timestamp (like time.time())."
239.747 - y, m, d, |>UNUSED:hh<|, |>UNUSED:mm<|, |>UNUSED:ss<|, |>UNUSED:weekday<|, |>UNUSED:jday<|, |>UNUSED:dst<| = _time.localtime(|>PARAMETER:t<|)
239.748 - return |>PARAMETER:cls<|(y, m, d)
239.749 - fromtimestamp = classmethod(fromtimestamp)
239.750 -
239.751 - def |>METHOD:today<|(|>PARAMETER:cls<|):
239.752 - "Construct a date from time.time()."
239.753 - t = _time.time()
239.754 - return |>PARAMETER:cls<|.fromtimestamp(t)
239.755 - today = classmethod(today)
239.756 -
239.757 - def |>METHOD:fromordinal<|(|>PARAMETER:cls<|, |>PARAMETER:n<|):
239.758 - """Contruct a date from a proleptic Gregorian ordinal.
239.759 -
239.760 - January 1 of year 1 is day 1. Only the year, month and day are
239.761 - non-zero in the result.
239.762 - """
239.763 - y, m, d = _ord2ymd(|>PARAMETER:n<|)
239.764 - return |>PARAMETER:cls<|(y, m, d)
239.765 - fromordinal = classmethod(fromordinal)
239.766 -
239.767 - # Conversions to string
239.768 -
239.769 - def |>METHOD:__repr__<|(|>PARAMETER:self<|):
239.770 - "Convert to formal string, for repr()."
239.771 - return "%s(%d, %d, %d)" % ('datetime.' + |>PARAMETER:self<|.__class__.__name__,
239.772 - |>PARAMETER:self<|.__year,
239.773 - |>PARAMETER:self<|.__month,
239.774 - |>PARAMETER:self<|.__day)
239.775 - # XXX These shouldn't depend on time.localtime(), because that
239.776 - # clips the usable dates to [1970 .. 2038). At least ctime() is
239.777 - # easily done without using strftime() -- that's better too because
239.778 - # strftime("%c", ...) is locale specific.
239.779 -
239.780 - def |>METHOD:ctime<|(|>PARAMETER:self<|):
239.781 - "Format a la ctime()."
239.782 - return tmxxx(|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day).ctime()
239.783 -
239.784 - def |>METHOD:strftime<|(|>PARAMETER:self<|, |>PARAMETER:fmt<|):
239.785 - "Format using strftime()."
239.786 - return _wrap_strftime(|>PARAMETER:self<|, |>PARAMETER:fmt<|, |>PARAMETER:self<|.timetuple())
239.787 -
239.788 - def |>METHOD:isoformat<|(|>PARAMETER:self<|):
239.789 - """Return the date formatted according to ISO.
239.790 -
239.791 - This is 'YYYY-MM-DD'.
239.792 -
239.793 - References:
239.794 - - http://www.w3.org/TR/NOTE-datetime
239.795 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
239.796 - """
239.797 - return "%04d-%02d-%02d" % (|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day)
239.798 -
239.799 - __str__ = isoformat
239.800 -
239.801 - # Read-only field accessors
239.802 - year = property(lambda self: self.__year,
239.803 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
239.804 - month = property(lambda self: self.__month, doc="month (1-12)")
239.805 - day = property(lambda self: self.__day, doc="day (1-31)")
239.806 -
239.807 - # Standard conversions, __cmp__, __hash__ (and helpers)
239.808 -
239.809 - def |>METHOD:timetuple<|(|>PARAMETER:self<|):
239.810 - "Return local time tuple compatible with time.localtime()."
239.811 - return _build_struct_time(|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day,
239.812 - 0, 0, 0, -1)
239.813 -
239.814 - def |>METHOD:toordinal<|(|>PARAMETER:self<|):
239.815 - """Return proleptic Gregorian ordinal for the year, month and day.
239.816 -
239.817 - January 1 of year 1 is day 1. Only the year, month and day values
239.818 - contribute to the result.
239.819 - """
239.820 - return _ymd2ord(|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day)
239.821 -
239.822 - def |>METHOD:replace<|(|>PARAMETER:self<|, |>PARAMETER:year<|=None, |>PARAMETER:month<|=None, |>PARAMETER:day<|=None):
239.823 - """Return a new date with new values for the specified fields."""
239.824 - if |>PARAMETER:year<| is None:
239.825 - |>PARAMETER:year<| = |>PARAMETER:self<|.__year
239.826 - if |>PARAMETER:month<| is None:
239.827 - |>PARAMETER:month<| = |>PARAMETER:self<|.__month
239.828 - if |>PARAMETER:day<| is None:
239.829 - |>PARAMETER:day<| = |>PARAMETER:self<|.__day
239.830 - _check_date_fields(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|)
239.831 - return date(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|)
239.832 -
239.833 - # Comparisons.
239.834 -
239.835 - def |>METHOD:__eq__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.836 - if isinstance(|>PARAMETER:other<|, date):
239.837 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) == 0
239.838 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
239.839 - return NotImplemented
239.840 - else:
239.841 - return False
239.842 -
239.843 - def |>METHOD:__ne__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.844 - if isinstance(|>PARAMETER:other<|, date):
239.845 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) != 0
239.846 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
239.847 - return NotImplemented
239.848 - else:
239.849 - return True
239.850 -
239.851 - def |>METHOD:__le__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.852 - if isinstance(|>PARAMETER:other<|, date):
239.853 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) <= 0
239.854 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
239.855 - return NotImplemented
239.856 - else:
239.857 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.858 -
239.859 - def |>METHOD:__lt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.860 - if isinstance(|>PARAMETER:other<|, date):
239.861 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) < 0
239.862 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
239.863 - return NotImplemented
239.864 - else:
239.865 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.866 -
239.867 - def |>METHOD:__ge__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.868 - if isinstance(|>PARAMETER:other<|, date):
239.869 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) >= 0
239.870 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
239.871 - return NotImplemented
239.872 - else:
239.873 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.874 -
239.875 - def |>METHOD:__gt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.876 - if isinstance(|>PARAMETER:other<|, date):
239.877 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) > 0
239.878 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
239.879 - return NotImplemented
239.880 - else:
239.881 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.882 -
239.883 - def |>METHOD:__cmp<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.884 - assert isinstance(|>PARAMETER:other<|, date)
239.885 - y, m, d = |>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day
239.886 - y2, m2, d2 = |>PARAMETER:other<|.__year, |>PARAMETER:other<|.__month, |>PARAMETER:other<|.__day
239.887 - return cmp((y, m, d), (y2, m2, d2))
239.888 -
239.889 - def |>METHOD:__hash__<|(|>PARAMETER:self<|):
239.890 - "Hash."
239.891 - return hash(|>PARAMETER:self<|.__getstate())
239.892 -
239.893 - # Computations
239.894 -
239.895 - def |>METHOD:_checkOverflow<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER:year<|):
239.896 - if not MINYEAR <= |>PARAMETER:year<| <= MAXYEAR:
239.897 - raise OverflowError("date +/-: result year %d not in %d..%d" %
239.898 - (|>PARAMETER:year<|, MINYEAR, MAXYEAR))
239.899 -
239.900 - def |>METHOD:__add__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.901 - "Add a date to a timedelta."
239.902 - if isinstance(|>PARAMETER:other<|, timedelta):
239.903 - t = tmxxx(|>PARAMETER:self<|.__year,
239.904 - |>PARAMETER:self<|.__month,
239.905 - |>PARAMETER:self<|.__day + |>PARAMETER:other<|.days)
239.906 - |>PARAMETER:self<|._checkOverflow(t.year)
239.907 - result = |>PARAMETER:self<|.__class__(t.year, t.month, t.day)
239.908 - return result
239.909 - return NotImplemented
239.910 -
239.911 - __radd__ = __add__
239.912 -
239.913 - def |>METHOD:__sub__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.914 - """Subtract two dates, or a date and a timedelta."""
239.915 - if isinstance(|>PARAMETER:other<|, timedelta):
239.916 - return |>PARAMETER:self<| + timedelta(-|>PARAMETER:other<|.days)
239.917 - if isinstance(|>PARAMETER:other<|, date):
239.918 - days1 = |>PARAMETER:self<|.toordinal()
239.919 - days2 = |>PARAMETER:other<|.toordinal()
239.920 - return timedelta(days1 - days2)
239.921 - return NotImplemented
239.922 -
239.923 - def |>METHOD:weekday<|(|>PARAMETER:self<|):
239.924 - "Return day of the week, where Monday == 0 ... Sunday == 6."
239.925 - return (|>PARAMETER:self<|.toordinal() + 6) % 7
239.926 -
239.927 - # Day-of-the-week and week-of-the-year, according to ISO
239.928 -
239.929 - def |>METHOD:isoweekday<|(|>PARAMETER:self<|):
239.930 - "Return day of the week, where Monday == 1 ... Sunday == 7."
239.931 - # 1-Jan-0001 is a Monday
239.932 - return |>PARAMETER:self<|.toordinal() % 7 or 7
239.933 -
239.934 - def |>METHOD:isocalendar<|(|>PARAMETER:self<|):
239.935 - """Return a 3-tuple containing ISO year, week number, and weekday.
239.936 -
239.937 - The first ISO week of the year is the (Mon-Sun) week
239.938 - containing the year's first Thursday; everything else derives
239.939 - from that.
239.940 -
239.941 - The first week is 1; Monday is 1 ... Sunday is 7.
239.942 -
239.943 - ISO calendar algorithm taken from
239.944 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
239.945 - """
239.946 - year = |>PARAMETER:self<|.__year
239.947 - week1monday = _isoweek1monday(year)
239.948 - today = _ymd2ord(|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day)
239.949 - # Internally, week and day have origin 0
239.950 - week, day = divmod(today - week1monday, 7)
239.951 - if week < 0:
239.952 - year -= 1
239.953 - week1monday = _isoweek1monday(year)
239.954 - week, day = divmod(today - week1monday, 7)
239.955 - elif week >= 52:
239.956 - if today >= _isoweek1monday(year+1):
239.957 - year += 1
239.958 - week = 0
239.959 - return year, week+1, day+1
239.960 -
239.961 - # Pickle support.
239.962 -
239.963 - __safe_for_unpickling__ = True # For Python 2.2
239.964 -
239.965 - def |>METHOD:__getstate<|(|>PARAMETER:self<|):
239.966 - yhi, ylo = divmod(|>PARAMETER:self<|.__year, 256)
239.967 - return ("%c%c%c%c" % (yhi, ylo, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day), )
239.968 -
239.969 - def |>METHOD:__setstate<|(|>PARAMETER:self<|, |>PARAMETER:t<|):
239.970 - assert isinstance(|>PARAMETER:t<|, tuple) and len(|>PARAMETER:t<|) == 1, `|>PARAMETER:t<|`
239.971 - string = |>PARAMETER:t<|[0]
239.972 - assert len(string) == 4
239.973 - yhi, ylo, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day = map(ord, string)
239.974 - |>PARAMETER:self<|.__year = yhi * 256 + ylo
239.975 -
239.976 - def |>METHOD:__reduce__<|(|>PARAMETER:self<|):
239.977 - return (|>PARAMETER:self<|.__class__, |>PARAMETER:self<|.__getstate())
239.978 -
239.979 -_date_class = date # so functions w/ args named "date" can get at the class
239.980 -
239.981 -date.min = date(1, 1, 1)
239.982 -date.max = date(9999, 12, 31)
239.983 -date.resolution = timedelta(days=1)
239.984 -
239.985 -class tzinfo(object):
239.986 - """Abstract base class for time zone info classes.
239.987 -
239.988 - Subclasses must override the name(), utcoffset() and dst() methods.
239.989 - """
239.990 -
239.991 - def |>METHOD:tzname<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER,UNUSED:dt<|):
239.992 - "datetime -> string name of time zone."
239.993 - raise NotImplementedError("tzinfo subclass must override tzname()")
239.994 -
239.995 - def |>METHOD:utcoffset<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER,UNUSED:dt<|):
239.996 - "datetime -> minutes east of UTC (negative for west of UTC)"
239.997 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
239.998 -
239.999 - def |>METHOD:dst<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER,UNUSED:dt<|):
239.1000 - """datetime -> DST offset in minutes east of UTC.
239.1001 -
239.1002 - Return 0 if DST not in effect. utcoffset() must include the DST
239.1003 - offset.
239.1004 - """
239.1005 - raise NotImplementedError("tzinfo subclass must override dst()")
239.1006 -
239.1007 - def |>METHOD:fromutc<|(|>PARAMETER:self<|, |>PARAMETER:dt<|):
239.1008 - "datetime in UTC -> datetime in local time."
239.1009 -
239.1010 - if not isinstance(|>PARAMETER:dt<|, datetime):
239.1011 - raise TypeError("fromutc() requires a datetime argument")
239.1012 - if |>PARAMETER:dt<|.tzinfo is not |>PARAMETER:self<|:
239.1013 - raise ValueError("dt.tzinfo is not self")
239.1014 -
239.1015 - dtoff = |>PARAMETER:dt<|.utcoffset()
239.1016 - if dtoff is None:
239.1017 - raise ValueError("fromutc() requires a non-None utcoffset() "
239.1018 - "result")
239.1019 -
239.1020 - # See the long comment block at the end of this file for an
239.1021 - # explanation of this algorithm.
239.1022 - dtdst = |>PARAMETER:dt<|.dst()
239.1023 - if dtdst is None:
239.1024 - raise ValueError("fromutc() requires a non-None dst() result")
239.1025 - delta = dtoff - dtdst
239.1026 - if delta:
239.1027 - |>PARAMETER:dt<| += delta
239.1028 - dtdst = |>PARAMETER:dt<|.dst()
239.1029 - if dtdst is None:
239.1030 - raise ValueError("fromutc(): dt.dst gave inconsistent "
239.1031 - "results; cannot convert")
239.1032 - if dtdst:
239.1033 - return |>PARAMETER:dt<| + dtdst
239.1034 - else:
239.1035 - return |>PARAMETER:dt<|
239.1036 -
239.1037 - # Pickle support.
239.1038 -
239.1039 - __safe_for_unpickling__ = True # For Python 2.2
239.1040 -
239.1041 - def |>METHOD:__reduce__<|(|>PARAMETER:self<|):
239.1042 - getinitargs = getattr(|>PARAMETER:self<|, "__getinitargs__", None)
239.1043 - if getinitargs:
239.1044 - args = getinitargs()
239.1045 - else:
239.1046 - args = ()
239.1047 - getstate = getattr(|>PARAMETER:self<|, "__getstate__", None)
239.1048 - if getstate:
239.1049 - state = getstate()
239.1050 - else:
239.1051 - state = getattr(|>PARAMETER:self<|, "__dict__", None) or None
239.1052 - if state is None:
239.1053 - return (|>PARAMETER:self<|.__class__, args)
239.1054 - else:
239.1055 - return (|>PARAMETER:self<|.__class__, args, state)
239.1056 -
239.1057 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
239.1058 -
239.1059 -class time(object):
239.1060 - """Time with time zone.
239.1061 -
239.1062 - Constructors:
239.1063 -
239.1064 - __new__()
239.1065 -
239.1066 - Operators:
239.1067 -
239.1068 - __repr__, __str__
239.1069 - __cmp__, __hash__
239.1070 -
239.1071 - Methods:
239.1072 -
239.1073 - strftime()
239.1074 - isoformat()
239.1075 - utcoffset()
239.1076 - tzname()
239.1077 - dst()
239.1078 -
239.1079 - Properties (readonly):
239.1080 - hour, minute, second, microsecond, tzinfo
239.1081 - """
239.1082 -
239.1083 - def |>METHOD:__new__<|(|>PARAMETER:cls<|, |>PARAMETER:hour<|=0, |>PARAMETER:minute<|=0, |>PARAMETER:second<|=0, |>PARAMETER:microsecond<|=0, |>PARAMETER:tzinfo<|=None):
239.1084 - """Constructor.
239.1085 -
239.1086 - Arguments:
239.1087 -
239.1088 - hour, minute (required)
239.1089 - second, microsecond (default to zero)
239.1090 - tzinfo (default to None)
239.1091 - """
239.1092 - self = object.__new__(|>PARAMETER:cls<|)
239.1093 - if isinstance(|>PARAMETER:hour<|, str):
239.1094 - # Pickle support
239.1095 - self.__setstate((|>PARAMETER:hour<|, |>PARAMETER:minute<| or None))
239.1096 - return self
239.1097 - _check_tzinfo_arg(|>PARAMETER:tzinfo<|)
239.1098 - _check_time_fields(|>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|, |>PARAMETER:microsecond<|)
239.1099 - self.__hour = |>PARAMETER:hour<|
239.1100 - self.__minute = |>PARAMETER:minute<|
239.1101 - self.__second = |>PARAMETER:second<|
239.1102 - self.__microsecond = |>PARAMETER:microsecond<|
239.1103 - self._tzinfo = |>PARAMETER:tzinfo<|
239.1104 - return self
239.1105 -
239.1106 - # Read-only field accessors
239.1107 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
239.1108 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
239.1109 - second = property(lambda self: self.__second, doc="second (0-59)")
239.1110 - microsecond = property(lambda self: self.__microsecond,
239.1111 - doc="microsecond (0-999999)")
239.1112 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
239.1113 -
239.1114 - # Standard conversions, __hash__ (and helpers)
239.1115 -
239.1116 - # Comparisons.
239.1117 -
239.1118 - def |>METHOD:__eq__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1119 - if isinstance(|>PARAMETER:other<|, time):
239.1120 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) == 0
239.1121 - else:
239.1122 - return False
239.1123 -
239.1124 - def |>METHOD:__ne__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1125 - if isinstance(|>PARAMETER:other<|, time):
239.1126 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) != 0
239.1127 - else:
239.1128 - return True
239.1129 -
239.1130 - def |>METHOD:__le__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1131 - if isinstance(|>PARAMETER:other<|, time):
239.1132 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) <= 0
239.1133 - else:
239.1134 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.1135 -
239.1136 - def |>METHOD:__lt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1137 - if isinstance(|>PARAMETER:other<|, time):
239.1138 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) < 0
239.1139 - else:
239.1140 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.1141 -
239.1142 - def |>METHOD:__ge__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1143 - if isinstance(|>PARAMETER:other<|, time):
239.1144 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) >= 0
239.1145 - else:
239.1146 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.1147 -
239.1148 - def |>METHOD:__gt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1149 - if isinstance(|>PARAMETER:other<|, time):
239.1150 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) > 0
239.1151 - else:
239.1152 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.1153 -
239.1154 - def |>METHOD:__cmp<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1155 - assert isinstance(|>PARAMETER:other<|, time)
239.1156 - mytz = |>PARAMETER:self<|._tzinfo
239.1157 - ottz = |>PARAMETER:other<|._tzinfo
239.1158 - myoff = otoff = None
239.1159 -
239.1160 - if mytz is ottz:
239.1161 - base_compare = True
239.1162 - else:
239.1163 - myoff = |>PARAMETER:self<|._utcoffset()
239.1164 - otoff = |>PARAMETER:other<|._utcoffset()
239.1165 - base_compare = myoff == otoff
239.1166 -
239.1167 - if base_compare:
239.1168 - return cmp((|>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
239.1169 - |>PARAMETER:self<|.__microsecond),
239.1170 - (|>PARAMETER:other<|.__hour, |>PARAMETER:other<|.__minute, |>PARAMETER:other<|.__second,
239.1171 - |>PARAMETER:other<|.__microsecond))
239.1172 - if myoff is None or otoff is None:
239.1173 - # XXX Buggy in 2.2.2.
239.1174 - raise TypeError("cannot compare naive and aware times")
239.1175 - myhhmm = |>PARAMETER:self<|.__hour * 60 + |>PARAMETER:self<|.__minute - myoff
239.1176 - othhmm = |>PARAMETER:other<|.__hour * 60 + |>PARAMETER:other<|.__minute - otoff
239.1177 - return cmp((myhhmm, |>PARAMETER:self<|.__second, |>PARAMETER:self<|.__microsecond),
239.1178 - (othhmm, |>PARAMETER:other<|.__second, |>PARAMETER:other<|.__microsecond))
239.1179 -
239.1180 - def |>METHOD:__hash__<|(|>PARAMETER:self<|):
239.1181 - """Hash."""
239.1182 - tzoff = |>PARAMETER:self<|._utcoffset()
239.1183 - if not tzoff: # zero or None
239.1184 - return hash(|>PARAMETER:self<|.__getstate()[0])
239.1185 - h, m = divmod(|>PARAMETER:self<|.hour * 60 + |>PARAMETER:self<|.minute - tzoff, 60)
239.1186 - if 0 <= h < 24:
239.1187 - return hash(time(h, m, |>PARAMETER:self<|.second, |>PARAMETER:self<|.microsecond))
239.1188 - return hash((h, m, |>PARAMETER:self<|.second, |>PARAMETER:self<|.microsecond))
239.1189 -
239.1190 - # Conversion to string
239.1191 -
239.1192 - def |>METHOD:_tzstr<|(|>PARAMETER:self<|, |>PARAMETER:sep<|=":"):
239.1193 - """Return formatted timezone offset (+xx:xx) or None."""
239.1194 - off = |>PARAMETER:self<|._utcoffset()
239.1195 - if off is not None:
239.1196 - if off < 0:
239.1197 - sign = "-"
239.1198 - off = -off
239.1199 - else:
239.1200 - sign = "+"
239.1201 - hh, mm = divmod(off, 60)
239.1202 - assert 0 <= hh < 24
239.1203 - off = "%s%02d%s%02d" % (sign, hh, |>PARAMETER:sep<|, mm)
239.1204 - return off
239.1205 -
239.1206 - def |>METHOD:__repr__<|(|>PARAMETER:self<|):
239.1207 - """Convert to formal string, for repr()."""
239.1208 - if |>PARAMETER:self<|.__microsecond != 0:
239.1209 - s = ", %d, %d" % (|>PARAMETER:self<|.__second, |>PARAMETER:self<|.__microsecond)
239.1210 - elif |>PARAMETER:self<|.__second != 0:
239.1211 - s = ", %d" % |>PARAMETER:self<|.__second
239.1212 - else:
239.1213 - s = ""
239.1214 - s= "%s(%d, %d%s)" % ('datetime.' + |>PARAMETER:self<|.__class__.__name__,
239.1215 - |>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, s)
239.1216 - if |>PARAMETER:self<|._tzinfo is not None:
239.1217 - assert s[-1:] == ")"
239.1218 - s = s[:-1] + ", tzinfo=%r" % |>PARAMETER:self<|._tzinfo + ")"
239.1219 - return s
239.1220 -
239.1221 - def |>METHOD:isoformat<|(|>PARAMETER:self<|):
239.1222 - """Return the time formatted according to ISO.
239.1223 -
239.1224 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
239.1225 - self.microsecond == 0.
239.1226 - """
239.1227 - s = _format_time(|>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
239.1228 - |>PARAMETER:self<|.__microsecond)
239.1229 - tz = |>PARAMETER:self<|._tzstr()
239.1230 - if tz:
239.1231 - s += tz
239.1232 - return s
239.1233 -
239.1234 - __str__ = isoformat
239.1235 -
239.1236 - def |>METHOD:strftime<|(|>PARAMETER:self<|, |>PARAMETER:fmt<|):
239.1237 - """Format using strftime(). The date part of the timestamp passed
239.1238 - to underlying strftime should not be used.
239.1239 - """
239.1240 - # The year must be >= 1900 else Python's strftime implementation
239.1241 - # can raise a bogus exception.
239.1242 - timetuple = (1900, 1, 1,
239.1243 - |>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
239.1244 - 0, 1, -1)
239.1245 - return _wrap_strftime(|>PARAMETER:self<|, |>PARAMETER:fmt<|, timetuple)
239.1246 -
239.1247 - # Timezone functions
239.1248 -
239.1249 - def |>METHOD:utcoffset<|(|>PARAMETER:self<|):
239.1250 - """Return the timezone offset in minutes east of UTC (negative west of
239.1251 - UTC)."""
239.1252 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "utcoffset", None)
239.1253 - offset = _check_utc_offset("utcoffset", offset)
239.1254 - if offset is not None:
239.1255 - offset = timedelta(minutes=offset)
239.1256 - return offset
239.1257 -
239.1258 - # Return an integer (or None) instead of a timedelta (or None).
239.1259 - def |>METHOD:_utcoffset<|(|>PARAMETER:self<|):
239.1260 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "utcoffset", None)
239.1261 - offset = _check_utc_offset("utcoffset", offset)
239.1262 - return offset
239.1263 -
239.1264 - def |>METHOD:tzname<|(|>PARAMETER:self<|):
239.1265 - """Return the timezone name.
239.1266 -
239.1267 - Note that the name is 100% informational -- there's no requirement that
239.1268 - it mean anything in particular. For example, "GMT", "UTC", "-500",
239.1269 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
239.1270 - """
239.1271 - name = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "tzname", None)
239.1272 - _check_tzname(name)
239.1273 - return name
239.1274 -
239.1275 - def |>METHOD:dst<|(|>PARAMETER:self<|):
239.1276 - """Return 0 if DST is not in effect, or the DST offset (in minutes
239.1277 - eastward) if DST is in effect.
239.1278 -
239.1279 - This is purely informational; the DST offset has already been added to
239.1280 - the UTC offset returned by utcoffset() if applicable, so there's no
239.1281 - need to consult dst() unless you're interested in displaying the DST
239.1282 - info.
239.1283 - """
239.1284 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "dst", None)
239.1285 - offset = _check_utc_offset("dst", offset)
239.1286 - if offset is not None:
239.1287 - offset = timedelta(minutes=offset)
239.1288 - return offset
239.1289 -
239.1290 - def |>METHOD:replace<|(|>PARAMETER:self<|, |>PARAMETER:hour<|=None, |>PARAMETER:minute<|=None, |>PARAMETER:second<|=None, |>PARAMETER:microsecond<|=None,
239.1291 - |>PARAMETER:tzinfo<|=True):
239.1292 - """Return a new time with new values for the specified fields."""
239.1293 - if |>PARAMETER:hour<| is None:
239.1294 - |>PARAMETER:hour<| = |>PARAMETER:self<|.hour
239.1295 - if |>PARAMETER:minute<| is None:
239.1296 - |>PARAMETER:minute<| = |>PARAMETER:self<|.minute
239.1297 - if |>PARAMETER:second<| is None:
239.1298 - |>PARAMETER:second<| = |>PARAMETER:self<|.second
239.1299 - if |>PARAMETER:microsecond<| is None:
239.1300 - |>PARAMETER:microsecond<| = |>PARAMETER:self<|.microsecond
239.1301 - if |>PARAMETER:tzinfo<| is True:
239.1302 - |>PARAMETER:tzinfo<| = |>PARAMETER:self<|.tzinfo
239.1303 - _check_time_fields(|>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|, |>PARAMETER:microsecond<|)
239.1304 - _check_tzinfo_arg(|>PARAMETER:tzinfo<|)
239.1305 - return time(|>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|, |>PARAMETER:microsecond<|, |>PARAMETER:tzinfo<|)
239.1306 -
239.1307 - # Return an integer (or None) instead of a timedelta (or None).
239.1308 - def |>METHOD:_dst<|(|>PARAMETER:self<|):
239.1309 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "dst", None)
239.1310 - offset = _check_utc_offset("dst", offset)
239.1311 - return offset
239.1312 -
239.1313 - def |>METHOD:__nonzero__<|(|>PARAMETER:self<|):
239.1314 - if |>PARAMETER:self<|.second or |>PARAMETER:self<|.microsecond:
239.1315 - return 1
239.1316 - offset = |>PARAMETER:self<|._utcoffset() or 0
239.1317 - return |>PARAMETER:self<|.hour * 60 + |>PARAMETER:self<|.minute - offset != 0
239.1318 -
239.1319 - # Pickle support.
239.1320 -
239.1321 - __safe_for_unpickling__ = True # For Python 2.2
239.1322 -
239.1323 - def |>METHOD:__getstate<|(|>PARAMETER:self<|):
239.1324 - us2, us3 = divmod(|>PARAMETER:self<|.__microsecond, 256)
239.1325 - us1, us2 = divmod(us2, 256)
239.1326 - basestate = ("%c" * 6) % (|>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
239.1327 - us1, us2, us3)
239.1328 - if |>PARAMETER:self<|._tzinfo is None:
239.1329 - return (basestate,)
239.1330 - else:
239.1331 - return (basestate, |>PARAMETER:self<|._tzinfo)
239.1332 -
239.1333 - def |>METHOD:__setstate<|(|>PARAMETER:self<|, |>PARAMETER:state<|):
239.1334 - assert isinstance(|>PARAMETER:state<|, tuple)
239.1335 - assert 1 <= len(|>PARAMETER:state<|) <= 2
239.1336 - string = |>PARAMETER:state<|[0]
239.1337 - assert len(string) == 6
239.1338 - |>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second, us1, us2, us3 = \
239.1339 - map(ord, string)
239.1340 - |>PARAMETER:self<|.__microsecond = (((us1 << 8) | us2) << 8) | us3
239.1341 - if len(|>PARAMETER:state<|) == 1:
239.1342 - |>PARAMETER:self<|._tzinfo = None
239.1343 - else:
239.1344 - |>PARAMETER:self<|._tzinfo = |>PARAMETER:state<|[1]
239.1345 -
239.1346 - def |>METHOD:__reduce__<|(|>PARAMETER:self<|):
239.1347 - return (|>PARAMETER:self<|.__class__, |>PARAMETER:self<|.__getstate())
239.1348 -
239.1349 -_time_class = time # so functions w/ args named "time" can get at the class
239.1350 -
239.1351 -time.min = time(0, 0, 0)
239.1352 -time.max = time(23, 59, 59, 999999)
239.1353 -time.resolution = timedelta(microseconds=1)
239.1354 -
239.1355 -class datetime(date):
239.1356 -
239.1357 - # XXX needs docstrings
239.1358 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
239.1359 -
239.1360 - def |>METHOD:__new__<|(|>PARAMETER:cls<|, |>PARAMETER:year<|, |>PARAMETER:month<|=None, |>PARAMETER:day<|=None, |>PARAMETER:hour<|=0, |>PARAMETER:minute<|=0, |>PARAMETER:second<|=0,
239.1361 - |>PARAMETER:microsecond<|=0, |>PARAMETER:tzinfo<|=None):
239.1362 - if isinstance(|>PARAMETER:year<|, str):
239.1363 - # Pickle support
239.1364 - self = date.__new__(|>PARAMETER:cls<|, |>PARAMETER:year<|[:4])
239.1365 - self.__setstate((|>PARAMETER:year<|, |>PARAMETER:month<|))
239.1366 - return self
239.1367 - _check_tzinfo_arg(|>PARAMETER:tzinfo<|)
239.1368 - _check_time_fields(|>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|, |>PARAMETER:microsecond<|)
239.1369 - self = date.__new__(|>PARAMETER:cls<|, |>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|)
239.1370 - # XXX This duplicates __year, __month, __day for convenience :-(
239.1371 - self.__year = |>PARAMETER:year<|
239.1372 - self.__month = |>PARAMETER:month<|
239.1373 - self.__day = |>PARAMETER:day<|
239.1374 - self.__hour = |>PARAMETER:hour<|
239.1375 - self.__minute = |>PARAMETER:minute<|
239.1376 - self.__second = |>PARAMETER:second<|
239.1377 - self.__microsecond = |>PARAMETER:microsecond<|
239.1378 - self._tzinfo = |>PARAMETER:tzinfo<|
239.1379 - return self
239.1380 -
239.1381 - # Read-only field accessors
239.1382 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
239.1383 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
239.1384 - second = property(lambda self: self.__second, doc="second (0-59)")
239.1385 - microsecond = property(lambda self: self.__microsecond,
239.1386 - doc="microsecond (0-999999)")
239.1387 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
239.1388 -
239.1389 - def |>METHOD:fromtimestamp<|(|>PARAMETER:cls<|, |>PARAMETER:t<|, |>PARAMETER:tz<|=None):
239.1390 - """Construct a datetime from a POSIX timestamp (like time.time()).
239.1391 -
239.1392 - A timezone info object may be passed in as well.
239.1393 - """
239.1394 -
239.1395 - _check_tzinfo_arg(|>PARAMETER:tz<|)
239.1396 - if |>PARAMETER:tz<| is None:
239.1397 - converter = _time.localtime
239.1398 - else:
239.1399 - converter = _time.gmtime
239.1400 - y, m, d, hh, mm, ss, |>UNUSED:weekday<|, |>UNUSED:jday<|, |>UNUSED:dst<| = converter(|>PARAMETER:t<|)
239.1401 - us = int((|>PARAMETER:t<| % 1.0) * 1000000)
239.1402 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
239.1403 - result = |>PARAMETER:cls<|(y, m, d, hh, mm, ss, us, |>PARAMETER:tz<|)
239.1404 - if |>PARAMETER:tz<| is not None:
239.1405 - result = |>PARAMETER:tz<|.fromutc(result)
239.1406 - return result
239.1407 - fromtimestamp = classmethod(fromtimestamp)
239.1408 -
239.1409 - def |>METHOD:utcfromtimestamp<|(|>PARAMETER:cls<|, |>PARAMETER:t<|):
239.1410 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
239.1411 - y, m, d, hh, mm, ss, |>UNUSED:weekday<|, |>UNUSED:jday<|, |>UNUSED:dst<| = _time.gmtime(|>PARAMETER:t<|)
239.1412 - us = int((|>PARAMETER:t<| % 1.0) * 1000000)
239.1413 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
239.1414 - return |>PARAMETER:cls<|(y, m, d, hh, mm, ss, us)
239.1415 - utcfromtimestamp = classmethod(utcfromtimestamp)
239.1416 -
239.1417 - # XXX This is supposed to do better than we *can* do by using time.time(),
239.1418 - # XXX if the platform supports a more accurate way. The C implementation
239.1419 - # XXX uses gettimeofday on platforms that have it, but that isn't
239.1420 - # XXX available from Python. So now() may return different results
239.1421 - # XXX across the implementations.
239.1422 - def |>METHOD:now<|(|>PARAMETER:cls<|, |>PARAMETER:tz<|=None):
239.1423 - "Construct a datetime from time.time() and optional time zone info."
239.1424 - t = _time.time()
239.1425 - return |>PARAMETER:cls<|.fromtimestamp(t, |>PARAMETER:tz<|)
239.1426 - now = classmethod(now)
239.1427 -
239.1428 - def |>METHOD:utcnow<|(|>PARAMETER:cls<|):
239.1429 - "Construct a UTC datetime from time.time()."
239.1430 - t = _time.time()
239.1431 - return |>PARAMETER:cls<|.utcfromtimestamp(t)
239.1432 - utcnow = classmethod(utcnow)
239.1433 -
239.1434 - def |>METHOD:combine<|(|>PARAMETER:cls<|, |>PARAMETER:date<|, |>PARAMETER:time<|):
239.1435 - "Construct a datetime from a given date and a given time."
239.1436 - if not isinstance(|>PARAMETER:date<|, _date_class):
239.1437 - raise TypeError("date argument must be a date instance")
239.1438 - if not isinstance(|>PARAMETER:time<|, _time_class):
239.1439 - raise TypeError("time argument must be a time instance")
239.1440 - return |>PARAMETER:cls<|(|>PARAMETER:date<|.year, |>PARAMETER:date<|.month, |>PARAMETER:date<|.day,
239.1441 - |>PARAMETER:time<|.hour, |>PARAMETER:time<|.minute, |>PARAMETER:time<|.second, |>PARAMETER:time<|.microsecond,
239.1442 - |>PARAMETER:time<|.tzinfo)
239.1443 - combine = classmethod(combine)
239.1444 -
239.1445 - def |>METHOD:timetuple<|(|>PARAMETER:self<|):
239.1446 - "Return local time tuple compatible with time.localtime()."
239.1447 - dst = |>PARAMETER:self<|._dst()
239.1448 - if dst is None:
239.1449 - dst = -1
239.1450 - elif dst:
239.1451 - dst = 1
239.1452 - return _build_struct_time(|>PARAMETER:self<|.year, |>PARAMETER:self<|.month, |>PARAMETER:self<|.day,
239.1453 - |>PARAMETER:self<|.hour, |>PARAMETER:self<|.minute, |>PARAMETER:self<|.second,
239.1454 - dst)
239.1455 -
239.1456 - def |>METHOD:utctimetuple<|(|>PARAMETER:self<|):
239.1457 - "Return UTC time tuple compatible with time.gmtime()."
239.1458 - y, m, d = |>PARAMETER:self<|.year, |>PARAMETER:self<|.month, |>PARAMETER:self<|.day
239.1459 - hh, mm, ss = |>PARAMETER:self<|.hour, |>PARAMETER:self<|.minute, |>PARAMETER:self<|.second
239.1460 - offset = |>PARAMETER:self<|._utcoffset()
239.1461 - if offset: # neither None nor 0
239.1462 - tm = tmxxx(y, m, d, hh, mm - offset)
239.1463 - y, m, d = tm.year, tm.month, tm.day
239.1464 - hh, mm = tm.hour, tm.minute
239.1465 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
239.1466 -
239.1467 - def |>METHOD:date<|(|>PARAMETER:self<|):
239.1468 - "Return the date part."
239.1469 - return date(|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day)
239.1470 -
239.1471 - def |>METHOD:time<|(|>PARAMETER:self<|):
239.1472 - "Return the time part, with tzinfo None."
239.1473 - return time(|>PARAMETER:self<|.hour, |>PARAMETER:self<|.minute, |>PARAMETER:self<|.second, |>PARAMETER:self<|.microsecond)
239.1474 -
239.1475 - def |>METHOD:timetz<|(|>PARAMETER:self<|):
239.1476 - "Return the time part, with same tzinfo."
239.1477 - return time(|>PARAMETER:self<|.hour, |>PARAMETER:self<|.minute, |>PARAMETER:self<|.second, |>PARAMETER:self<|.microsecond,
239.1478 - |>PARAMETER:self<|._tzinfo)
239.1479 -
239.1480 - def |>METHOD:replace<|(|>PARAMETER:self<|, |>PARAMETER:year<|=None, |>PARAMETER:month<|=None, |>PARAMETER:day<|=None, |>PARAMETER:hour<|=None,
239.1481 - |>PARAMETER:minute<|=None, |>PARAMETER:second<|=None, |>PARAMETER:microsecond<|=None, |>PARAMETER:tzinfo<|=True):
239.1482 - """Return a new datetime with new values for the specified fields."""
239.1483 - if |>PARAMETER:year<| is None:
239.1484 - |>PARAMETER:year<| = |>PARAMETER:self<|.year
239.1485 - if |>PARAMETER:month<| is None:
239.1486 - |>PARAMETER:month<| = |>PARAMETER:self<|.month
239.1487 - if |>PARAMETER:day<| is None:
239.1488 - |>PARAMETER:day<| = |>PARAMETER:self<|.day
239.1489 - if |>PARAMETER:hour<| is None:
239.1490 - |>PARAMETER:hour<| = |>PARAMETER:self<|.hour
239.1491 - if |>PARAMETER:minute<| is None:
239.1492 - |>PARAMETER:minute<| = |>PARAMETER:self<|.minute
239.1493 - if |>PARAMETER:second<| is None:
239.1494 - |>PARAMETER:second<| = |>PARAMETER:self<|.second
239.1495 - if |>PARAMETER:microsecond<| is None:
239.1496 - |>PARAMETER:microsecond<| = |>PARAMETER:self<|.microsecond
239.1497 - if |>PARAMETER:tzinfo<| is True:
239.1498 - |>PARAMETER:tzinfo<| = |>PARAMETER:self<|.tzinfo
239.1499 - _check_date_fields(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|)
239.1500 - _check_time_fields(|>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|, |>PARAMETER:microsecond<|)
239.1501 - _check_tzinfo_arg(|>PARAMETER:tzinfo<|)
239.1502 - return datetime(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|, |>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|,
239.1503 - |>PARAMETER:microsecond<|, |>PARAMETER:tzinfo<|)
239.1504 -
239.1505 - def |>METHOD:astimezone<|(|>PARAMETER:self<|, |>PARAMETER:tz<|):
239.1506 - if not isinstance(|>PARAMETER:tz<|, tzinfo):
239.1507 - raise TypeError("tz argument must be an instance of tzinfo")
239.1508 -
239.1509 - mytz = |>PARAMETER:self<|.tzinfo
239.1510 - if mytz is None:
239.1511 - raise ValueError("astimezone() requires an aware datetime")
239.1512 -
239.1513 - if |>PARAMETER:tz<| is mytz:
239.1514 - return |>PARAMETER:self<|
239.1515 -
239.1516 - # Convert self to UTC, and attach the new time zone object.
239.1517 - myoffset = |>PARAMETER:self<|.utcoffset()
239.1518 - if myoffset is None:
239.1519 - raise ValuError("astimezone() requires an aware datetime")
239.1520 - utc = (|>PARAMETER:self<| - myoffset).replace(tzinfo=|>PARAMETER:tz<|)
239.1521 -
239.1522 - # Convert from UTC to tz's local time.
239.1523 - return |>PARAMETER:tz<|.fromutc(utc)
239.1524 -
239.1525 - # Ways to produce a string.
239.1526 -
239.1527 - def |>METHOD:ctime<|(|>PARAMETER:self<|):
239.1528 - "Format a la ctime()."
239.1529 - t = tmxxx(|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day, |>PARAMETER:self<|.__hour,
239.1530 - |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second)
239.1531 - return t.ctime()
239.1532 -
239.1533 - def |>METHOD:isoformat<|(|>PARAMETER:self<|, |>PARAMETER:sep<|='T'):
239.1534 - """Return the time formatted according to ISO.
239.1535 -
239.1536 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
239.1537 - self.microsecond == 0.
239.1538 -
239.1539 - If self.tzinfo is not None, the UTC offset is also attached, giving
239.1540 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
239.1541 -
239.1542 - Optional argument sep specifies the separator between date and
239.1543 - time, default 'T'.
239.1544 - """
239.1545 - s = ("%04d-%02d-%02d%c" % (|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day,
239.1546 - |>PARAMETER:sep<|) +
239.1547 - _format_time(|>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
239.1548 - |>PARAMETER:self<|.__microsecond))
239.1549 - off = |>PARAMETER:self<|._utcoffset()
239.1550 - if off is not None:
239.1551 - if off < 0:
239.1552 - sign = "-"
239.1553 - off = -off
239.1554 - else:
239.1555 - sign = "+"
239.1556 - hh, mm = divmod(off, 60)
239.1557 - s += "%s%02d:%02d" % (sign, hh, mm)
239.1558 - return s
239.1559 -
239.1560 - def |>METHOD:__repr__<|(|>PARAMETER:self<|):
239.1561 - "Convert to formal string, for repr()."
239.1562 - L = [|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day, # These are never zero
239.1563 - |>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second, |>PARAMETER:self<|.__microsecond]
239.1564 - if L[-1] == 0:
239.1565 - del L[-1]
239.1566 - if L[-1] == 0:
239.1567 - del L[-1]
239.1568 - s = ", ".join(map(str, L))
239.1569 - s = "%s(%s)" % ('datetime.' + |>PARAMETER:self<|.__class__.__name__, s)
239.1570 - if |>PARAMETER:self<|._tzinfo is not None:
239.1571 - assert s[-1:] == ")"
239.1572 - s = s[:-1] + ", tzinfo=%r" % |>PARAMETER:self<|._tzinfo + ")"
239.1573 - return s
239.1574 -
239.1575 - def |>METHOD:__str__<|(|>PARAMETER:self<|):
239.1576 - "Convert to string, for str()."
239.1577 - return |>PARAMETER:self<|.isoformat(sep=' ')
239.1578 -
239.1579 - def |>METHOD:utcoffset<|(|>PARAMETER:self<|):
239.1580 - """Return the timezone offset in minutes east of UTC (negative west of
239.1581 - UTC)."""
239.1582 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "utcoffset", |>PARAMETER:self<|)
239.1583 - offset = _check_utc_offset("utcoffset", offset)
239.1584 - if offset is not None:
239.1585 - offset = timedelta(minutes=offset)
239.1586 - return offset
239.1587 -
239.1588 - # Return an integer (or None) instead of a timedelta (or None).
239.1589 - def |>METHOD:_utcoffset<|(|>PARAMETER:self<|):
239.1590 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "utcoffset", |>PARAMETER:self<|)
239.1591 - offset = _check_utc_offset("utcoffset", offset)
239.1592 - return offset
239.1593 -
239.1594 - def |>METHOD:tzname<|(|>PARAMETER:self<|):
239.1595 - """Return the timezone name.
239.1596 -
239.1597 - Note that the name is 100% informational -- there's no requirement that
239.1598 - it mean anything in particular. For example, "GMT", "UTC", "-500",
239.1599 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
239.1600 - """
239.1601 - name = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "tzname", |>PARAMETER:self<|)
239.1602 - _check_tzname(name)
239.1603 - return name
239.1604 -
239.1605 - def |>METHOD:dst<|(|>PARAMETER:self<|):
239.1606 - """Return 0 if DST is not in effect, or the DST offset (in minutes
239.1607 - eastward) if DST is in effect.
239.1608 -
239.1609 - This is purely informational; the DST offset has already been added to
239.1610 - the UTC offset returned by utcoffset() if applicable, so there's no
239.1611 - need to consult dst() unless you're interested in displaying the DST
239.1612 - info.
239.1613 - """
239.1614 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "dst", |>PARAMETER:self<|)
239.1615 - offset = _check_utc_offset("dst", offset)
239.1616 - if offset is not None:
239.1617 - offset = timedelta(minutes=offset)
239.1618 - return offset
239.1619 -
239.1620 - # Return an integer (or None) instead of a timedelta (or None).1573
239.1621 - def |>METHOD:_dst<|(|>PARAMETER:self<|):
239.1622 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "dst", |>PARAMETER:self<|)
239.1623 - offset = _check_utc_offset("dst", offset)
239.1624 - return offset
239.1625 -
239.1626 - # Comparisons.
239.1627 -
239.1628 - def |>METHOD:__eq__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1629 - if isinstance(|>PARAMETER:other<|, datetime):
239.1630 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) == 0
239.1631 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
239.1632 - return NotImplemented
239.1633 - else:
239.1634 - return False
239.1635 -
239.1636 - def |>METHOD:__ne__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1637 - if isinstance(|>PARAMETER:other<|, datetime):
239.1638 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) != 0
239.1639 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
239.1640 - return NotImplemented
239.1641 - else:
239.1642 - return True
239.1643 -
239.1644 - def |>METHOD:__le__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1645 - if isinstance(|>PARAMETER:other<|, datetime):
239.1646 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) <= 0
239.1647 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
239.1648 - return NotImplemented
239.1649 - else:
239.1650 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.1651 -
239.1652 - def |>METHOD:__lt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1653 - if isinstance(|>PARAMETER:other<|, datetime):
239.1654 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) < 0
239.1655 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
239.1656 - return NotImplemented
239.1657 - else:
239.1658 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.1659 -
239.1660 - def |>METHOD:__ge__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1661 - if isinstance(|>PARAMETER:other<|, datetime):
239.1662 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) >= 0
239.1663 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
239.1664 - return NotImplemented
239.1665 - else:
239.1666 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.1667 -
239.1668 - def |>METHOD:__gt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1669 - if isinstance(|>PARAMETER:other<|, datetime):
239.1670 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) > 0
239.1671 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
239.1672 - return NotImplemented
239.1673 - else:
239.1674 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
239.1675 -
239.1676 - def |>METHOD:__cmp<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1677 - assert isinstance(|>PARAMETER:other<|, datetime)
239.1678 - mytz = |>PARAMETER:self<|._tzinfo
239.1679 - ottz = |>PARAMETER:other<|._tzinfo
239.1680 - myoff = otoff = None
239.1681 -
239.1682 - if mytz is ottz:
239.1683 - base_compare = True
239.1684 - else:
239.1685 - if mytz is not None:
239.1686 - myoff = |>PARAMETER:self<|._utcoffset()
239.1687 - if ottz is not None:
239.1688 - otoff = |>PARAMETER:other<|._utcoffset()
239.1689 - base_compare = myoff == otoff
239.1690 -
239.1691 - if base_compare:
239.1692 - return cmp((|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day,
239.1693 - |>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
239.1694 - |>PARAMETER:self<|.__microsecond),
239.1695 - (|>PARAMETER:other<|.__year, |>PARAMETER:other<|.__month, |>PARAMETER:other<|.__day,
239.1696 - |>PARAMETER:other<|.__hour, |>PARAMETER:other<|.__minute, |>PARAMETER:other<|.__second,
239.1697 - |>PARAMETER:other<|.__microsecond))
239.1698 - if myoff is None or otoff is None:
239.1699 - # XXX Buggy in 2.2.2.
239.1700 - raise TypeError("cannot compare naive and aware datetimes")
239.1701 - # XXX What follows could be done more efficiently...
239.1702 - diff = |>PARAMETER:self<| - |>PARAMETER:other<| # this will take offsets into account
239.1703 - if diff.days < 0:
239.1704 - return -1
239.1705 - return diff and 1 or 0
239.1706 -
239.1707 - def |>METHOD:__add__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1708 - "Add a datetime and a timedelta."
239.1709 - if not isinstance(|>PARAMETER:other<|, timedelta):
239.1710 - return NotImplemented
239.1711 - t = tmxxx(|>PARAMETER:self<|.__year,
239.1712 - |>PARAMETER:self<|.__month,
239.1713 - |>PARAMETER:self<|.__day + |>PARAMETER:other<|.days,
239.1714 - |>PARAMETER:self<|.__hour,
239.1715 - |>PARAMETER:self<|.__minute,
239.1716 - |>PARAMETER:self<|.__second + |>PARAMETER:other<|.seconds,
239.1717 - |>PARAMETER:self<|.__microsecond + |>PARAMETER:other<|.microseconds)
239.1718 - |>PARAMETER:self<|._checkOverflow(t.year)
239.1719 - result = |>PARAMETER:self<|.__class__(t.year, t.month, t.day,
239.1720 - t.hour, t.minute, t.second,
239.1721 - t.microsecond, tzinfo=|>PARAMETER:self<|._tzinfo)
239.1722 - return result
239.1723 -
239.1724 - __radd__ = __add__
239.1725 -
239.1726 - def |>METHOD:__sub__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
239.1727 - "Subtract two datetimes, or a datetime and a timedelta."
239.1728 - if not isinstance(|>PARAMETER:other<|, datetime):
239.1729 - if isinstance(|>PARAMETER:other<|, timedelta):
239.1730 - return |>PARAMETER:self<| + -|>PARAMETER:other<|
239.1731 - return NotImplemented
239.1732 -
239.1733 - days1 = |>PARAMETER:self<|.toordinal()
239.1734 - days2 = |>PARAMETER:other<|.toordinal()
239.1735 - secs1 = |>PARAMETER:self<|.__second + |>PARAMETER:self<|.__minute * 60 + |>PARAMETER:self<|.__hour * 3600
239.1736 - secs2 = |>PARAMETER:other<|.__second + |>PARAMETER:other<|.__minute * 60 + |>PARAMETER:other<|.__hour * 3600
239.1737 - base = timedelta(days1 - days2,
239.1738 - secs1 - secs2,
239.1739 - |>PARAMETER:self<|.__microsecond - |>PARAMETER:other<|.__microsecond)
239.1740 - if |>PARAMETER:self<|._tzinfo is |>PARAMETER:other<|._tzinfo:
239.1741 - return base
239.1742 - myoff = |>PARAMETER:self<|._utcoffset()
239.1743 - otoff = |>PARAMETER:other<|._utcoffset()
239.1744 - if myoff == otoff:
239.1745 - return base
239.1746 - if myoff is None or otoff is None:
239.1747 - raise TypeError, "cannot mix naive and timezone-aware time"
239.1748 - return base + timedelta(minutes = otoff-myoff)
239.1749 -
239.1750 - def |>METHOD:__hash__<|(|>PARAMETER:self<|):
239.1751 - tzoff = |>PARAMETER:self<|._utcoffset()
239.1752 - if tzoff is None:
239.1753 - return hash(|>PARAMETER:self<|.__getstate()[0])
239.1754 - days = _ymd2ord(|>PARAMETER:self<|.year, |>PARAMETER:self<|.month, |>PARAMETER:self<|.day)
239.1755 - seconds = |>PARAMETER:self<|.hour * 3600 + (|>PARAMETER:self<|.minute - tzoff) * 60 + |>PARAMETER:self<|.second
239.1756 - return hash(timedelta(days, seconds, |>PARAMETER:self<|.microsecond))
239.1757 -
239.1758 - # Pickle support.
239.1759 -
239.1760 - __safe_for_unpickling__ = True # For Python 2.2
239.1761 -
239.1762 - def |>METHOD:__getstate<|(|>PARAMETER:self<|):
239.1763 - yhi, ylo = divmod(|>PARAMETER:self<|.__year, 256)
239.1764 - us2, us3 = divmod(|>PARAMETER:self<|.__microsecond, 256)
239.1765 - us1, us2 = divmod(us2, 256)
239.1766 - basestate = ("%c" * 10) % (yhi, ylo, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day,
239.1767 - |>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
239.1768 - us1, us2, us3)
239.1769 - if |>PARAMETER:self<|._tzinfo is None:
239.1770 - return (basestate,)
239.1771 - else:
239.1772 - return (basestate, |>PARAMETER:self<|._tzinfo)
239.1773 -
239.1774 - def |>METHOD:__setstate<|(|>PARAMETER:self<|, |>PARAMETER:state<|):
239.1775 - assert isinstance(|>PARAMETER:state<|, tuple)
239.1776 - assert 1 <= len(|>PARAMETER:state<|) <= 2
239.1777 - string = |>PARAMETER:state<|[0]
239.1778 - assert len(string) == 10
239.1779 - (yhi, ylo, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day, |>PARAMETER:self<|.__hour,
239.1780 - |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second, us1, us2, us3) = map(ord, string)
239.1781 - |>PARAMETER:self<|.__year = yhi * 256 + ylo
239.1782 - |>PARAMETER:self<|.__microsecond = (((us1 << 8) | us2) << 8) | us3
239.1783 - if len(|>PARAMETER:state<|) == 1:
239.1784 - |>PARAMETER:self<|._tzinfo = None
239.1785 - else:
239.1786 - |>PARAMETER:self<|._tzinfo = |>PARAMETER:state<|[1]
239.1787 -
239.1788 - def |>METHOD:__reduce__<|(|>PARAMETER:self<|):
239.1789 - return (|>PARAMETER:self<|.__class__, |>PARAMETER:self<|.__getstate())
239.1790 -
239.1791 -
239.1792 -datetime.min = datetime(1, 1, 1)
239.1793 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
239.1794 -datetime.resolution = timedelta(microseconds=1)
239.1795 -
239.1796 -
239.1797 -def |>METHOD:_isoweek1monday<|(|>PARAMETER:year<|):
239.1798 - # Helper to calculate the day number of the Monday starting week 1
239.1799 - # XXX This could be done more efficiently
239.1800 - THURSDAY = 3
239.1801 - firstday = _ymd2ord(|>PARAMETER:year<|, 1, 1)
239.1802 - firstweekday = (firstday + 6) % 7 # See weekday() above
239.1803 - week1monday = firstday - firstweekday
239.1804 - if firstweekday > THURSDAY:
239.1805 - week1monday += 7
239.1806 - return week1monday
239.1807 -
239.1808 -"""
239.1809 -Some time zone algebra. For a datetime x, let
239.1810 - x.n = x stripped of its timezone -- its naive time.
239.1811 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
239.1812 - return None
239.1813 - x.d = x.dst(), and assuming that doesn't raise an exception or
239.1814 - return None
239.1815 - x.s = x's standard offset, x.o - x.d
239.1816 -
239.1817 -Now some derived rules, where k is a duration (timedelta).
239.1818 -
239.1819 -1. x.o = x.s + x.d
239.1820 - This follows from the definition of x.s.
239.1821 -
239.1822 -2. If x and y have the same tzinfo member, x.s = y.s.
239.1823 - This is actually a requirement, an assumption we need to make about
239.1824 - sane tzinfo classes.
239.1825 -
239.1826 -3. The naive UTC time corresponding to x is x.n - x.o.
239.1827 - This is again a requirement for a sane tzinfo class.
239.1828 -
239.1829 -4. (x+k).s = x.s
239.1830 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
239.1831 -
239.1832 -5. (x+k).n = x.n + k
239.1833 - Again follows from how arithmetic is defined.
239.1834 -
239.1835 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
239.1836 -(meaning that the various tzinfo methods exist, and don't blow up or return
239.1837 -None when called).
239.1838 -
239.1839 -The function wants to return a datetime y with timezone tz, equivalent to x.
239.1840 -x is already in UTC.
239.1841 -
239.1842 -By #3, we want
239.1843 -
239.1844 - y.n - y.o = x.n [1]
239.1845 -
239.1846 -The algorithm starts by attaching tz to x.n, and calling that y. So
239.1847 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
239.1848 -becomes true; in effect, we want to solve [2] for k:
239.1849 -
239.1850 - (y+k).n - (y+k).o = x.n [2]
239.1851 -
239.1852 -By #1, this is the same as
239.1853 -
239.1854 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
239.1855 -
239.1856 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
239.1857 -Substituting that into [3],
239.1858 -
239.1859 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
239.1860 - k - (y+k).s - (y+k).d = 0; rearranging,
239.1861 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
239.1862 - k = y.s - (y+k).d
239.1863 -
239.1864 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
239.1865 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
239.1866 -very large, since all offset-returning methods return a duration of magnitude
239.1867 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
239.1868 -be 0, so ignoring it has no consequence then.
239.1869 -
239.1870 -In any case, the new value is
239.1871 -
239.1872 - z = y + y.s [4]
239.1873 -
239.1874 -It's helpful to step back at look at [4] from a higher level: it's simply
239.1875 -mapping from UTC to tz's standard time.
239.1876 -
239.1877 -At this point, if
239.1878 -
239.1879 - z.n - z.o = x.n [5]
239.1880 -
239.1881 -we have an equivalent time, and are almost done. The insecurity here is
239.1882 -at the start of daylight time. Picture US Eastern for concreteness. The wall
239.1883 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
239.1884 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
239.1885 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
239.1886 -on the day DST starts. We want to return the 1:MM EST spelling because that's
239.1887 -the only spelling that makes sense on the local wall clock.
239.1888 -
239.1889 -In fact, if [5] holds at this point, we do have the standard-time spelling,
239.1890 -but that takes a bit of proof. We first prove a stronger result. What's the
239.1891 -difference between the LHS and RHS of [5]? Let
239.1892 -
239.1893 - diff = x.n - (z.n - z.o) [6]
239.1894 -
239.1895 -Now
239.1896 - z.n = by [4]
239.1897 - (y + y.s).n = by #5
239.1898 - y.n + y.s = since y.n = x.n
239.1899 - x.n + y.s = since z and y are have the same tzinfo member,
239.1900 - y.s = z.s by #2
239.1901 - x.n + z.s
239.1902 -
239.1903 -Plugging that back into [6] gives
239.1904 -
239.1905 - diff =
239.1906 - x.n - ((x.n + z.s) - z.o) = expanding
239.1907 - x.n - x.n - z.s + z.o = cancelling
239.1908 - - z.s + z.o = by #2
239.1909 - z.d
239.1910 -
239.1911 -So diff = z.d.
239.1912 -
239.1913 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
239.1914 -spelling we wanted in the endcase described above. We're done. Contrarily,
239.1915 -if z.d = 0, then we have a UTC equivalent, and are also done.
239.1916 -
239.1917 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
239.1918 -add to z (in effect, z is in tz's standard time, and we need to shift the
239.1919 -local clock into tz's daylight time).
239.1920 -
239.1921 -Let
239.1922 -
239.1923 - z' = z + z.d = z + diff [7]
239.1924 -
239.1925 -and we can again ask whether
239.1926 -
239.1927 - z'.n - z'.o = x.n [8]
239.1928 -
239.1929 -If so, we're done. If not, the tzinfo class is insane, according to the
239.1930 -assumptions we've made. This also requires a bit of proof. As before, let's
239.1931 -compute the difference between the LHS and RHS of [8] (and skipping some of
239.1932 -the justifications for the kinds of substitutions we've done several times
239.1933 -already):
239.1934 -
239.1935 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
239.1936 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
239.1937 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
239.1938 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
239.1939 - - z.n + z.n - z.o + z'.o = cancel z.n
239.1940 - - z.o + z'.o = #1 twice
239.1941 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
239.1942 - z'.d - z.d
239.1943 -
239.1944 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
239.1945 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
239.1946 -return z', not bothering to compute z'.d.
239.1947 -
239.1948 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
239.1949 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
239.1950 -would have to change the result dst() returns: we start in DST, and moving
239.1951 -a little further into it takes us out of DST.
239.1952 -
239.1953 -There isn't a sane case where this can happen. The closest it gets is at
239.1954 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
239.1955 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
239.1956 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
239.1957 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
239.1958 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
239.1959 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
239.1960 -standard time. Since that's what the local clock *does*, we want to map both
239.1961 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
239.1962 -in local time, but so it goes -- it's the way the local clock works.
239.1963 -
239.1964 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
239.1965 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
239.1966 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
239.1967 -(correctly) concludes that z' is not UTC-equivalent to x.
239.1968 -
239.1969 -Because we know z.d said z was in daylight time (else [5] would have held and
239.1970 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
239.1971 -and we we have stopped then), and there are only 2 possible values dst() can
239.1972 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
239.1973 -but the reasoning doesn't depend on the example -- it depends on there being
239.1974 -two possible dst() outcomes, one zero and the other non-zero). Therefore
239.1975 -z' must be in standard time, and is the spelling we want in this case.
239.1976 -
239.1977 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
239.1978 -concerned (because it takes z' as being in standard time rather than the
239.1979 -daylight time we intend here), but returning it gives the real-life "local
239.1980 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
239.1981 -tz.
239.1982 -
239.1983 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
239.1984 -the 1:MM standard time spelling we want.
239.1985 -
239.1986 -So how can this break? One of the assumptions must be violated. Two
239.1987 -possibilities:
239.1988 -
239.1989 -1) [2] effectively says that y.s is invariant across all y belong to a given
239.1990 - time zone. This isn't true if, for political reasons or continental drift,
239.1991 - a region decides to change its base offset from UTC.
239.1992 -
239.1993 -2) There may be versions of "double daylight" time where the tail end of
239.1994 - the analysis gives up a step too early. I haven't thought about that
239.1995 - enough to say.
239.1996 -
239.1997 -In any case, it's clear that the default fromutc() is strong enough to handle
239.1998 -"almost all" time zones: so long as the standard offset is invariant, it
239.1999 -doesn't matter if daylight time transition points change from year to year, or
239.2000 -if daylight time is skipped in some years; it doesn't matter how large or
239.2001 -small dst() may get within its bounds; and it doesn't even matter if some
239.2002 -perverse time zone returns a negative dst()). So a breaking case must be
239.2003 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
239.2004 -"""
239.2005 -
239.2006 -def |>METHOD:_test<|():
239.2007 - import test_datetime
239.2008 - test_datetime.test_main()
239.2009 -
239.2010 -if __name__ == "__main__":
239.2011 - _test()
240.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.structure Sun Jan 04 13:11:53 2015 -0600
240.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
240.3 @@ -1,170 +0,0 @@
240.4 -_is_leap:METHOD:[PRIVATE]:ESCAPED{_is_leap}(PARAMETERS{ESCAPED{year}}):
240.5 -_days_in_year:METHOD:[PRIVATE]:ESCAPED{_days_in_year}(PARAMETERS{ESCAPED{year}}):
240.6 -_days_before_year:METHOD:[PRIVATE]:ESCAPED{_days_before_year}(PARAMETERS{ESCAPED{year}}):
240.7 -_days_in_month:METHOD:[PRIVATE]:ESCAPED{_days_in_month}(PARAMETERS{ESCAPED{year}ESCAPED{,}ESCAPED{month}}):
240.8 -_days_before_month:METHOD:[PRIVATE]:ESCAPED{_days_before_month}(PARAMETERS{ESCAPED{year}ESCAPED{,}ESCAPED{month}}):
240.9 -_ymd2ord:METHOD:[PRIVATE]:ESCAPED{_ymd2ord}(PARAMETERS{ESCAPED{year}ESCAPED{,}ESCAPED{month}ESCAPED{,}ESCAPED{day}}):
240.10 -_ord2ymd:METHOD:[PRIVATE]:ESCAPED{_ord2ymd}(PARAMETERS{ESCAPED{n}}):
240.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}}):
240.12 -_format_time:METHOD:[PRIVATE]:ESCAPED{_format_time}(PARAMETERS{ESCAPED{hh}ESCAPED{,}ESCAPED{mm}ESCAPED{,}ESCAPED{ss}ESCAPED{,}ESCAPED{us}}):
240.13 -_wrap_strftime:METHOD:[PRIVATE]:ESCAPED{_wrap_strftime}(PARAMETERS{ESCAPED{object}ESCAPED{,}ESCAPED{format}ESCAPED{,}ESCAPED{timetuple}}):
240.14 -_call_tzinfo_method:METHOD:[PRIVATE]:ESCAPED{_call_tzinfo_method}(PARAMETERS{ESCAPED{tzinfo}ESCAPED{,}ESCAPED{methname}ESCAPED{,}ESCAPED{tzinfoarg}}):
240.15 -_check_tzname:METHOD:[PRIVATE]:ESCAPED{_check_tzname}(PARAMETERS{ESCAPED{name}}):
240.16 -_check_utc_offset:METHOD:[PRIVATE]:ESCAPED{_check_utc_offset}(PARAMETERS{ESCAPED{name}ESCAPED{,}ESCAPED{offset}}):
240.17 -_check_date_fields:METHOD:[PRIVATE]:ESCAPED{_check_date_fields}(PARAMETERS{ESCAPED{year}ESCAPED{,}ESCAPED{month}ESCAPED{,}ESCAPED{day}}):
240.18 -_check_time_fields:METHOD:[PRIVATE]:ESCAPED{_check_time_fields}(PARAMETERS{ESCAPED{hour}ESCAPED{,}ESCAPED{minute}ESCAPED{,}ESCAPED{second}ESCAPED{,}ESCAPED{microsecond}}):
240.19 -_check_tzinfo_arg:METHOD:[PRIVATE]:ESCAPED{_check_tzinfo_arg}(PARAMETERS{ESCAPED{tz}}):
240.20 -_cmperror:METHOD:[PRIVATE]:ESCAPED{_cmperror}(PARAMETERS{ESCAPED{x}ESCAPED{,}ESCAPED{y}}):
240.21 -tmxxx:CLASS:[]:ESCAPED{tmxxx}:
240.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}}):
240.23 - ctime:METHOD:[]:ESCAPED{ctime}(PARAMETERS{ESCAPED{self}}):
240.24 - day:ATTRIBUTE:[]:ESCAPED{day}:
240.25 - hour:ATTRIBUTE:[]:ESCAPED{hour}:
240.26 - microsecond:ATTRIBUTE:[]:ESCAPED{microsecond}:
240.27 - minute:ATTRIBUTE:[]:ESCAPED{minute}:
240.28 - month:ATTRIBUTE:[]:ESCAPED{month}:
240.29 - ordinal:ATTRIBUTE:[]:ESCAPED{ordinal}:
240.30 - second:ATTRIBUTE:[]:ESCAPED{second}:
240.31 - time:METHOD:[]:ESCAPED{time}(PARAMETERS{ESCAPED{self}}):
240.32 - toordinal:METHOD:[]:ESCAPED{toordinal}(PARAMETERS{ESCAPED{self}}):
240.33 - year:ATTRIBUTE:[]:ESCAPED{year}:
240.34 -timedelta:CLASS:[]:ESCAPED{timedelta}:
240.35 - __abs__:METHOD:[]:ESCAPED{__abs__}(PARAMETERS{ESCAPED{self}}):
240.36 - __add__:METHOD:[]:ESCAPED{__add__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.37 - __cmp:METHOD:[PRIVATE]:ESCAPED{__cmp}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.38 - __days:ATTRIBUTE:[]:ESCAPED{__days}:
240.39 - __div__:METHOD:[]:ESCAPED{__div__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.40 - __eq__:METHOD:[]:ESCAPED{__eq__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.41 - __ge__:METHOD:[]:ESCAPED{__ge__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.42 - __getstate:METHOD:[PRIVATE]:ESCAPED{__getstate}(PARAMETERS{ESCAPED{self}}):
240.43 - __gt__:METHOD:[]:ESCAPED{__gt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.44 - __hash__:METHOD:[]:ESCAPED{__hash__}(PARAMETERS{ESCAPED{self}}):
240.45 - __le__:METHOD:[]:ESCAPED{__le__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.46 - __lt__:METHOD:[]:ESCAPED{__lt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.47 - __microseconds:ATTRIBUTE:[]:ESCAPED{__microseconds}:
240.48 - __mul__:METHOD:[]:ESCAPED{__mul__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.49 - __ne__:METHOD:[]:ESCAPED{__ne__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.50 - __neg__:METHOD:[]:ESCAPED{__neg__}(PARAMETERS{ESCAPED{self}}):
240.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}}):
240.52 - __nonzero__:METHOD:[]:ESCAPED{__nonzero__}(PARAMETERS{ESCAPED{self}}):
240.53 - __pos__:METHOD:[]:ESCAPED{__pos__}(PARAMETERS{ESCAPED{self}}):
240.54 - __reduce__:METHOD:[]:ESCAPED{__reduce__}(PARAMETERS{ESCAPED{self}}):
240.55 - __repr__:METHOD:[]:ESCAPED{__repr__}(PARAMETERS{ESCAPED{self}}):
240.56 - __rsub__:METHOD:[]:ESCAPED{__rsub__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.57 - __seconds:ATTRIBUTE:[]:ESCAPED{__seconds}:
240.58 - __str__:METHOD:[]:ESCAPED{__str__}(PARAMETERS{ESCAPED{self}}):
240.59 - plural:METHOD:[]:ESCAPED{plural}(PARAMETERS{ESCAPED{n}}):
240.60 - __sub__:METHOD:[]:ESCAPED{__sub__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.61 -date:CLASS:[]:ESCAPED{date}:
240.62 - __add__:METHOD:[]:ESCAPED{__add__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.63 - __cmp:METHOD:[PRIVATE]:ESCAPED{__cmp}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.64 - __day:ATTRIBUTE:[]:ESCAPED{__day}:
240.65 - __eq__:METHOD:[]:ESCAPED{__eq__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.66 - __ge__:METHOD:[]:ESCAPED{__ge__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.67 - __getstate:METHOD:[PRIVATE]:ESCAPED{__getstate}(PARAMETERS{ESCAPED{self}}):
240.68 - __gt__:METHOD:[]:ESCAPED{__gt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.69 - __hash__:METHOD:[]:ESCAPED{__hash__}(PARAMETERS{ESCAPED{self}}):
240.70 - __le__:METHOD:[]:ESCAPED{__le__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.71 - __lt__:METHOD:[]:ESCAPED{__lt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.72 - __month:ATTRIBUTE:[]:ESCAPED{__month}:
240.73 - __ne__:METHOD:[]:ESCAPED{__ne__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.74 - __new__:METHOD:[]:ESCAPED{__new__}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{year}ESCAPED{,}ESCAPED{month}ESCAPED{,}ESCAPED{day}}):
240.75 - __reduce__:METHOD:[]:ESCAPED{__reduce__}(PARAMETERS{ESCAPED{self}}):
240.76 - __repr__:METHOD:[]:ESCAPED{__repr__}(PARAMETERS{ESCAPED{self}}):
240.77 - __setstate:METHOD:[PRIVATE]:ESCAPED{__setstate}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{t}}):
240.78 - __sub__:METHOD:[]:ESCAPED{__sub__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.79 - __year:ATTRIBUTE:[]:ESCAPED{__year}:
240.80 - _checkOverflow:METHOD:[PRIVATE]:ESCAPED{_checkOverflow}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{year}}):
240.81 - ctime:METHOD:[]:ESCAPED{ctime}(PARAMETERS{ESCAPED{self}}):
240.82 - fromordinal:METHOD:[]:ESCAPED{fromordinal}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{n}}):
240.83 - fromtimestamp:METHOD:[]:ESCAPED{fromtimestamp}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{t}}):
240.84 - isocalendar:METHOD:[]:ESCAPED{isocalendar}(PARAMETERS{ESCAPED{self}}):
240.85 - isoformat:METHOD:[]:ESCAPED{isoformat}(PARAMETERS{ESCAPED{self}}):
240.86 - isoweekday:METHOD:[]:ESCAPED{isoweekday}(PARAMETERS{ESCAPED{self}}):
240.87 - replace:METHOD:[]:ESCAPED{replace}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{year}ESCAPED{,}ESCAPED{month}ESCAPED{,}ESCAPED{day}}):
240.88 - strftime:METHOD:[]:ESCAPED{strftime}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{fmt}}):
240.89 - timetuple:METHOD:[]:ESCAPED{timetuple}(PARAMETERS{ESCAPED{self}}):
240.90 - today:METHOD:[]:ESCAPED{today}(PARAMETERS{ESCAPED{cls}}):
240.91 - toordinal:METHOD:[]:ESCAPED{toordinal}(PARAMETERS{ESCAPED{self}}):
240.92 - weekday:METHOD:[]:ESCAPED{weekday}(PARAMETERS{ESCAPED{self}}):
240.93 -tzinfo:CLASS:[]:ESCAPED{tzinfo}:
240.94 - __reduce__:METHOD:[]:ESCAPED{__reduce__}(PARAMETERS{ESCAPED{self}}):
240.95 - dst:METHOD:[]:ESCAPED{dst}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{dt}}):
240.96 - fromutc:METHOD:[]:ESCAPED{fromutc}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{dt}}):
240.97 - tzname:METHOD:[]:ESCAPED{tzname}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{dt}}):
240.98 - utcoffset:METHOD:[]:ESCAPED{utcoffset}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{dt}}):
240.99 -time:CLASS:[]:ESCAPED{time}:
240.100 - __cmp:METHOD:[PRIVATE]:ESCAPED{__cmp}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.101 - __eq__:METHOD:[]:ESCAPED{__eq__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.102 - __ge__:METHOD:[]:ESCAPED{__ge__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.103 - __getstate:METHOD:[PRIVATE]:ESCAPED{__getstate}(PARAMETERS{ESCAPED{self}}):
240.104 - __gt__:METHOD:[]:ESCAPED{__gt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.105 - __hash__:METHOD:[]:ESCAPED{__hash__}(PARAMETERS{ESCAPED{self}}):
240.106 - __hour:ATTRIBUTE:[]:ESCAPED{__hour}:
240.107 - __le__:METHOD:[]:ESCAPED{__le__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.108 - __lt__:METHOD:[]:ESCAPED{__lt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.109 - __microsecond:ATTRIBUTE:[]:ESCAPED{__microsecond}:
240.110 - __minute:ATTRIBUTE:[]:ESCAPED{__minute}:
240.111 - __ne__:METHOD:[]:ESCAPED{__ne__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.112 - __new__:METHOD:[]:ESCAPED{__new__}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{hour}ESCAPED{,}ESCAPED{minute}ESCAPED{,}ESCAPED{second}ESCAPED{,}ESCAPED{microsecond}ESCAPED{,}ESCAPED{tzinfo}}):
240.113 - __nonzero__:METHOD:[]:ESCAPED{__nonzero__}(PARAMETERS{ESCAPED{self}}):
240.114 - __reduce__:METHOD:[]:ESCAPED{__reduce__}(PARAMETERS{ESCAPED{self}}):
240.115 - __repr__:METHOD:[]:ESCAPED{__repr__}(PARAMETERS{ESCAPED{self}}):
240.116 - __second:ATTRIBUTE:[]:ESCAPED{__second}:
240.117 - __setstate:METHOD:[PRIVATE]:ESCAPED{__setstate}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{state}}):
240.118 - _dst:METHOD:[PRIVATE]:ESCAPED{_dst}(PARAMETERS{ESCAPED{self}}):
240.119 - _tzinfo:ATTRIBUTE:[]:ESCAPED{_tzinfo}:
240.120 - _tzstr:METHOD:[PRIVATE]:ESCAPED{_tzstr}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{sep}}):
240.121 - _utcoffset:METHOD:[PRIVATE]:ESCAPED{_utcoffset}(PARAMETERS{ESCAPED{self}}):
240.122 - dst:METHOD:[]:ESCAPED{dst}(PARAMETERS{ESCAPED{self}}):
240.123 - isoformat:METHOD:[]:ESCAPED{isoformat}(PARAMETERS{ESCAPED{self}}):
240.124 - replace:METHOD:[]:ESCAPED{replace}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{hour}ESCAPED{,}ESCAPED{minute}ESCAPED{,}ESCAPED{second}ESCAPED{,}ESCAPED{microsecond}ESCAPED{,}ESCAPED{tzinfo}}):
240.125 - strftime:METHOD:[]:ESCAPED{strftime}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{fmt}}):
240.126 - tzname:METHOD:[]:ESCAPED{tzname}(PARAMETERS{ESCAPED{self}}):
240.127 - utcoffset:METHOD:[]:ESCAPED{utcoffset}(PARAMETERS{ESCAPED{self}}):
240.128 -datetime:CLASS:[]:ESCAPED{datetime}:
240.129 - __add__:METHOD:[]:ESCAPED{__add__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.130 - __cmp:METHOD:[PRIVATE]:ESCAPED{__cmp}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.131 - __day:ATTRIBUTE:[]:ESCAPED{__day}:
240.132 - __eq__:METHOD:[]:ESCAPED{__eq__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.133 - __ge__:METHOD:[]:ESCAPED{__ge__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.134 - __getstate:METHOD:[PRIVATE]:ESCAPED{__getstate}(PARAMETERS{ESCAPED{self}}):
240.135 - __gt__:METHOD:[]:ESCAPED{__gt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.136 - __hash__:METHOD:[]:ESCAPED{__hash__}(PARAMETERS{ESCAPED{self}}):
240.137 - __hour:ATTRIBUTE:[]:ESCAPED{__hour}:
240.138 - __le__:METHOD:[]:ESCAPED{__le__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.139 - __lt__:METHOD:[]:ESCAPED{__lt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.140 - __microsecond:ATTRIBUTE:[]:ESCAPED{__microsecond}:
240.141 - __minute:ATTRIBUTE:[]:ESCAPED{__minute}:
240.142 - __month:ATTRIBUTE:[]:ESCAPED{__month}:
240.143 - __ne__:METHOD:[]:ESCAPED{__ne__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.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}}):
240.145 - __reduce__:METHOD:[]:ESCAPED{__reduce__}(PARAMETERS{ESCAPED{self}}):
240.146 - __repr__:METHOD:[]:ESCAPED{__repr__}(PARAMETERS{ESCAPED{self}}):
240.147 - __second:ATTRIBUTE:[]:ESCAPED{__second}:
240.148 - __setstate:METHOD:[PRIVATE]:ESCAPED{__setstate}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{state}}):
240.149 - __str__:METHOD:[]:ESCAPED{__str__}(PARAMETERS{ESCAPED{self}}):
240.150 - __sub__:METHOD:[]:ESCAPED{__sub__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
240.151 - __year:ATTRIBUTE:[]:ESCAPED{__year}:
240.152 - _dst:METHOD:[PRIVATE]:ESCAPED{_dst}(PARAMETERS{ESCAPED{self}}):
240.153 - _tzinfo:ATTRIBUTE:[]:ESCAPED{_tzinfo}:
240.154 - _utcoffset:METHOD:[PRIVATE]:ESCAPED{_utcoffset}(PARAMETERS{ESCAPED{self}}):
240.155 - astimezone:METHOD:[]:ESCAPED{astimezone}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{tz}}):
240.156 - combine:METHOD:[]:ESCAPED{combine}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{date}ESCAPED{,}ESCAPED{time}}):
240.157 - ctime:METHOD:[]:ESCAPED{ctime}(PARAMETERS{ESCAPED{self}}):
240.158 - date:METHOD:[]:ESCAPED{date}(PARAMETERS{ESCAPED{self}}):
240.159 - dst:METHOD:[]:ESCAPED{dst}(PARAMETERS{ESCAPED{self}}):
240.160 - fromtimestamp:METHOD:[]:ESCAPED{fromtimestamp}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{t}ESCAPED{,}ESCAPED{tz}}):
240.161 - isoformat:METHOD:[]:ESCAPED{isoformat}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{sep}}):
240.162 - now:METHOD:[]:ESCAPED{now}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{tz}}):
240.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}}):
240.164 - time:METHOD:[]:ESCAPED{time}(PARAMETERS{ESCAPED{self}}):
240.165 - timetuple:METHOD:[]:ESCAPED{timetuple}(PARAMETERS{ESCAPED{self}}):
240.166 - timetz:METHOD:[]:ESCAPED{timetz}(PARAMETERS{ESCAPED{self}}):
240.167 - tzname:METHOD:[]:ESCAPED{tzname}(PARAMETERS{ESCAPED{self}}):
240.168 - utcfromtimestamp:METHOD:[]:ESCAPED{utcfromtimestamp}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{t}}):
240.169 - utcnow:METHOD:[]:ESCAPED{utcnow}(PARAMETERS{ESCAPED{cls}}):
240.170 - utcoffset:METHOD:[]:ESCAPED{utcoffset}(PARAMETERS{ESCAPED{self}}):
240.171 - utctimetuple:METHOD:[]:ESCAPED{utctimetuple}(PARAMETERS{ESCAPED{self}}):
240.172 -_isoweek1monday:METHOD:[PRIVATE]:ESCAPED{_isoweek1monday}(PARAMETERS{ESCAPED{year}}):
240.173 -_test:METHOD:[PRIVATE]:ESCAPED{_test}:
241.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
241.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
241.3 @@ -1,2011 +0,0 @@
241.4 -"""Concrete date/time and related types -- prototype implemented in Python.
241.5 -
241.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
241.7 -
241.8 -See also http://dir.yahoo.com/Reference/calendars/
241.9 -
241.10 -For a primer on DST, including many current DST rules, see
241.11 -http://webexhibits.org/daylightsaving/
241.12 -
241.13 -For more about DST than you ever wanted to know, see
241.14 -ftp://elsie.nci.nih.gov/pub/
241.15 -
241.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
241.17 -
241.18 -"""
241.19 -
241.20 -import time as _time
241.21 -import math as _math
241.22 -
241.23 -MINYEAR = 1
241.24 -MAXYEAR = 9999
241.25 -
241.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
241.27 -# also assumes the current Gregorian calendar indefinitely extended in
241.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
241.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
241.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
241.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
241.32 -# for all computations. See the book for algorithms for converting between
241.33 -# proleptic Gregorian ordinals and many other calendar systems.
241.34 -
241.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
241.36 -
241.37 -_DAYS_BEFORE_MONTH = [None]
241.38 -dbm = 0
241.39 -for dim in _DAYS_IN_MONTH[1:]:
241.40 - _DAYS_BEFORE_MONTH.append(dbm)
241.41 - dbm += dim
241.42 -del dbm, dim
241.43 -
241.44 -def _is_leap(year):
241.45 - "year -> 1 if leap year, else 0."
241.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
241.47 -
241.48 -def _days_in_year(year):
241.49 - "year -> number of days in year (366 if a leap year, else 365)."
241.50 - return 365 + _is_leap(year)
241.51 -
241.52 -def _days_before_year(year):
241.53 - "year -> number of days before January 1st of year."
241.54 - y = year - 1
241.55 - return y*365 + y//4 - y//100 + y//400
241.56 -
241.57 -def _days_in_month(year, month):
241.58 - "year, month -> number of days in that month in that year."
241.59 - try:
241.60 - assert 1 <= month <= 12, month
241.61 - if month == 2 and _is_leap(year):
241.62 - return 29
241.63 - except Exception, e:
241.64 - print "Exception: ", e
241.65 - return _DAYS_IN_MONTH[month]
241.66 -
241.67 -def _days_before_month(year, month):
241.68 - "year, month -> number of days in year preceeding first day of month."
241.69 - if not 1 <= month <= 12:
241.70 - raise ValueError('month must be in 1..12', month)
241.71 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
241.72 -
241.73 -def _ymd2ord(year, month, day):
241.74 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
241.75 - if not 1 <= month <= 12:
241.76 - raise ValueError('month must be in 1..12', month)
241.77 - dim = _days_in_month(year, month)
241.78 - if not 1 <= day <= dim:
241.79 - raise ValueError('day must be in 1..%d' % dim, day)
241.80 - return (_days_before_year(year) +
241.81 - _days_before_month(year, month) +
241.82 - day)
241.83 -
241.84 -_DI400Y = _days_before_year(401) # number of days in 400 years
241.85 -_DI100Y = _days_before_year(101) # " " " " 100 "
241.86 -_DI4Y = _days_before_year(5) # " " " " 4 "
241.87 -
241.88 -# A 4-year cycle has an extra leap day over what we'd get from pasting
241.89 -# together 4 single years.
241.90 -assert _DI4Y == 4 * 365 + 1
241.91 -
241.92 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
241.93 -# pasting together 4 100-year cycles.
241.94 -assert _DI400Y == 4 * _DI100Y + 1
241.95 -
241.96 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
241.97 -# pasting together 25 4-year cycles.
241.98 -assert _DI100Y == 25 * _DI4Y - 1
241.99 -
241.100 -def _ord2ymd(n):
241.101 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
241.102 -
241.103 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
241.104 - # repeats exactly every 400 years. The basic strategy is to find the
241.105 - # closest 400-year boundary at or before n, then work with the offset
241.106 - # from that boundary to n. Life is much clearer if we subtract 1 from
241.107 - # n first -- then the values of n at 400-year boundaries are exactly
241.108 - # those divisible by _DI400Y:
241.109 - #
241.110 - # D M Y n n-1
241.111 - # -- --- ---- ---------- ----------------
241.112 - # 31 Dec -400 -_DI400Y -_DI400Y -1
241.113 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
241.114 - # ...
241.115 - # 30 Dec 000 -1 -2
241.116 - # 31 Dec 000 0 -1
241.117 - # 1 Jan 001 1 0 400-year boundary
241.118 - # 2 Jan 001 2 1
241.119 - # 3 Jan 001 3 2
241.120 - # ...
241.121 - # 31 Dec 400 _DI400Y _DI400Y -1
241.122 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
241.123 - n -= 1
241.124 - n400, n = divmod(n, _DI400Y)
241.125 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
241.126 -
241.127 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
241.128 - # the desired date. Now compute how many 100-year cycles precede n.
241.129 - # Note that it's possible for n100 to equal 4! In that case 4 full
241.130 - # 100-year cycles precede the desired day, which implies the desired
241.131 - # day is December 31 at the end of a 400-year cycle.
241.132 - n100, n = divmod(n, _DI100Y)
241.133 -
241.134 - # Now compute how many 4-year cycles precede it.
241.135 - n4, n = divmod(n, _DI4Y)
241.136 -
241.137 - # And now how many single years. Again n1 can be 4, and again meaning
241.138 - # that the desired day is December 31 at the end of the 4-year cycle.
241.139 - n1, n = divmod(n, 365)
241.140 -
241.141 - year += n100 * 100 + n4 * 4 + n1
241.142 - if n1 == 4 or n100 == 4:
241.143 - assert n == 0
241.144 - return year-1, 12, 31
241.145 -
241.146 - # Now the year is correct, and n is the offset from January 1. We find
241.147 - # the month via an estimate that's either exact or one too large.
241.148 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
241.149 - assert leapyear == _is_leap(year)
241.150 - month = (n + 50) >> 5
241.151 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
241.152 - if preceding > n: # estimate is too large
241.153 - month -= 1
241.154 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
241.155 - n -= preceding
241.156 - assert 0 <= n < _days_in_month(year, month)
241.157 -
241.158 - # Now the year and month are correct, and n is the offset from the
241.159 - # start of that month: we're done!
241.160 - return year, month, n+1
241.161 -
241.162 -# Month and day names. For localized versions, see the calendar module.
241.163 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
241.164 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
241.165 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
241.166 -
241.167 -
241.168 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
241.169 - wday = (_ymd2ord(y, m, d) + 6) % 7
241.170 - dnum = _days_before_month(y, m) + d
241.171 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
241.172 -
241.173 -def _format_time(hh, mm, ss, us):
241.174 - # Skip trailing microseconds when us==0.
241.175 - result = "%02d:%02d:%02d" % (hh, mm, ss)
241.176 - if us:
241.177 - result += ".%06d" % us
241.178 - return result
241.179 -
241.180 -# Correctly substitute for %z and %Z escapes in strftime formats.
241.181 -def _wrap_strftime(object, format, timetuple):
241.182 - year = timetuple[0]
241.183 - if year < 1900:
241.184 - raise ValueError("year=%d is before 1900; the datetime strftime() "
241.185 - "methods require year >= 1900" % year)
241.186 - # Don't call _utcoffset() or tzname() unless actually needed.
241.187 - zreplace = None # the string to use for %z
241.188 - Zreplace = None # the string to use for %Z
241.189 -
241.190 - # Scan format for %z and %Z escapes, replacing as needed.
241.191 - newformat = []
241.192 - push = newformat.append
241.193 - i, n = 0, len(format)
241.194 - while i < n:
241.195 - ch = format[i]
241.196 - i += 1
241.197 - if ch == '%':
241.198 - if i < n:
241.199 - ch = format[i]
241.200 - i += 1
241.201 - if ch == 'z':
241.202 - if zreplace is None:
241.203 - zreplace = ""
241.204 - if hasattr(object, "_utcoffset"):
241.205 - offset = object._utcoffset()
241.206 - if offset is not None:
241.207 - sign = '+'
241.208 - if offset < 0:
241.209 - offset = -offset
241.210 - sign = '-'
241.211 - h, m = divmod(offset, 60)
241.212 - zreplace = '%c%02d%02d' % (sign, h, m)
241.213 - assert '%' not in zreplace
241.214 - newformat.append(zreplace)
241.215 - elif ch == 'Z':
241.216 - if Zreplace is None:
241.217 - Zreplace = ""
241.218 - if hasattr(object, "tzname"):
241.219 - s = object.tzname()
241.220 - if s is not None:
241.221 - # strftime is going to have at this: escape %
241.222 - Zreplace = s.replace('%', '%%')
241.223 - newformat.append(Zreplace)
241.224 - else:
241.225 - push('%')
241.226 - push(ch)
241.227 - else:
241.228 - push('%')
241.229 - else:
241.230 - push(ch)
241.231 - newformat = "".join(newformat)
241.232 - return _time.strftime(newformat, timetuple)
241.233 -
241.234 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
241.235 - if tzinfo is None:
241.236 - return None
241.237 - return getattr(tzinfo, methname)(tzinfoarg)
241.238 -
241.239 -# Just raise TypeError if the arg isn't None or a string.
241.240 -def _check_tzname(name):
241.241 - if name is not None and not isinstance(name, str):
241.242 - raise TypeError("tzinfo.tzname() must return None or string, "
241.243 - "not '%s'" % type(name))
241.244 -
241.245 -# name is the offset-producing method, "utcoffset" or "dst".
241.246 -# offset is what it returned.
241.247 -# If offset isn't None or timedelta, raises TypeError.
241.248 -# If offset is None, returns None.
241.249 -# Else offset is checked for being in range, and a whole # of minutes.
241.250 -# If it is, its integer value is returned. Else ValueError is raised.
241.251 -def _check_utc_offset(name, offset):
241.252 - assert name in ("utcoffset", "dst")
241.253 - if offset is None:
241.254 - return None
241.255 - if not isinstance(offset, timedelta):
241.256 - raise TypeError("tzinfo.%s() must return None "
241.257 - "or timedelta, not '%s'" % (name, type(offset)))
241.258 - days = offset.days
241.259 - if days < -1 or days > 0:
241.260 - offset = 1440 # trigger out-of-range
241.261 - else:
241.262 - seconds = days * 86400 + offset.seconds
241.263 - minutes, seconds = divmod(seconds, 60)
241.264 - if seconds or offset.microseconds:
241.265 - raise ValueError("tzinfo.%s() must return a whole number "
241.266 - "of minutes" % name)
241.267 - offset = minutes
241.268 - if -1440 < offset < 1440:
241.269 - return offset
241.270 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
241.271 -
241.272 -def _check_date_fields(year, month, day):
241.273 - if not MINYEAR <= year <= MAXYEAR:
241.274 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
241.275 - if not 1 <= month <= 12:
241.276 - raise ValueError('month must be in 1..12', month)
241.277 - dim = _days_in_month(year, month)
241.278 - if not 1 <= day <= dim:
241.279 - raise ValueError('day must be in 1..%d' % dim, day)
241.280 -
241.281 -def _check_time_fields(hour, minute, second, microsecond):
241.282 - if not 0 <= hour <= 23:
241.283 - raise ValueError('hour must be in 0..23', hour)
241.284 - if not 0 <= minute <= 59:
241.285 - raise ValueError('minute must be in 0..59', minute)
241.286 - if not 0 <= second <= 59:
241.287 - raise ValueError('second must be in 0..59', second)
241.288 - if not 0 <= microsecond <= 999999:
241.289 - raise ValueError('microsecond must be in 0..999999', microsecond)
241.290 -
241.291 -def _check_tzinfo_arg(tz):
241.292 - if tz is not None and not isinstance(tz, tzinfo):
241.293 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
241.294 -
241.295 -
241.296 -# Notes on comparison: In general, datetime module comparison operators raise
241.297 -# TypeError when they don't know how to do a comparison themself. If they
241.298 -# returned NotImplemented instead, comparison could (silently) fall back to
241.299 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
241.300 -# and that's not helpful. There are two exceptions:
241.301 -#
241.302 -# 1. For date and datetime, if the other object has a "timetuple" attr,
241.303 -# NotImplemented is returned. This is a hook to allow other kinds of
241.304 -# datetime-like objects a chance to intercept the comparison.
241.305 -#
241.306 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
241.307 -# so opertaions like
241.308 -#
241.309 -# x == y
241.310 -# x != y
241.311 -# x in sequence
241.312 -# x not in sequence
241.313 -# dict[x] = y
241.314 -#
241.315 -# don't raise annoying TypeErrors just because a datetime object
241.316 -# is part of a heterogeneous collection. If there's no known way to
241.317 -# compare X to a datetime, saying they're not equal is reasonable.
241.318 -
241.319 -def _cmperror(x, y):
241.320 - raise TypeError("can't compare '%s' to '%s'" % (
241.321 - type(x).__name__, type(y).__name__))
241.322 -
241.323 -# This is a start at a struct tm workalike. Goals:
241.324 -#
241.325 -# + Works the same way across platforms.
241.326 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
241.327 -#
241.328 -# Note: I suspect it's best if this flavor of tm does *not* try to
241.329 -# second-guess timezones or DST. Instead fold whatever adjustments you want
241.330 -# into the minutes argument (and the constructor will normalize).
241.331 -
241.332 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
241.333 -
241.334 -class tmxxx:
241.335 -
241.336 - ordinal = None
241.337 -
241.338 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
241.339 - microsecond=0):
241.340 - # Normalize all the inputs, and store the normalized values.
241.341 - if not 0 <= microsecond <= 999999:
241.342 - carry, microsecond = divmod(microsecond, 1000000)
241.343 - second += carry
241.344 - if not 0 <= second <= 59:
241.345 - carry, second = divmod(second, 60)
241.346 - minute += carry
241.347 - if not 0 <= minute <= 59:
241.348 - carry, minute = divmod(minute, 60)
241.349 - hour += carry
241.350 - if not 0 <= hour <= 23:
241.351 - carry, hour = divmod(hour, 24)
241.352 - day += carry
241.353 -
241.354 - # That was easy. Now it gets muddy: the proper range for day
241.355 - # can't be determined without knowing the correct month and year,
241.356 - # but if day is, e.g., plus or minus a million, the current month
241.357 - # and year values make no sense (and may also be out of bounds
241.358 - # themselves).
241.359 - # Saying 12 months == 1 year should be non-controversial.
241.360 - if not 1 <= month <= 12:
241.361 - carry, month = divmod(month-1, 12)
241.362 - year += carry
241.363 - month += 1
241.364 - assert 1 <= month <= 12
241.365 -
241.366 - # Now only day can be out of bounds (year may also be out of bounds
241.367 - # for a datetime object, but we don't care about that here).
241.368 - # If day is out of bounds, what to do is arguable, but at least the
241.369 - # method here is principled and explainable.
241.370 - dim = _days_in_month(year, month)
241.371 - if not 1 <= day <= dim:
241.372 - # Move day-1 days from the first of the month. First try to
241.373 - # get off cheap if we're only one day out of range (adjustments
241.374 - # for timezone alone can't be worse than that).
241.375 - if day == 0: # move back a day
241.376 - month -= 1
241.377 - if month > 0:
241.378 - day = _days_in_month(year, month)
241.379 - else:
241.380 - year, month, day = year-1, 12, 31
241.381 - elif day == dim + 1: # move forward a day
241.382 - month += 1
241.383 - day = 1
241.384 - if month > 12:
241.385 - month = 1
241.386 - year += 1
241.387 - else:
241.388 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
241.389 - year, month, day = _ord2ymd(self.ordinal)
241.390 -
241.391 - self.year, self.month, self.day = year, month, day
241.392 - self.hour, self.minute, self.second = hour, minute, second
241.393 - self.microsecond = microsecond
241.394 -
241.395 - def toordinal(self):
241.396 - """Return proleptic Gregorian ordinal for the year, month and day.
241.397 -
241.398 - January 1 of year 1 is day 1. Only the year, month and day values
241.399 - contribute to the result.
241.400 - """
241.401 - if self.ordinal is None:
241.402 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
241.403 - return self.ordinal
241.404 -
241.405 - def time(self):
241.406 - "Return Unixish timestamp, as a float (assuming UTC)."
241.407 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
241.408 - seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
241.409 - return seconds + self.second + self.microsecond / 1e6
241.410 -
241.411 - def ctime(self):
241.412 - "Return ctime() style string."
241.413 - weekday = self.toordinal() % 7 or 7
241.414 - return "%s %s %2d %02d:%02d:%02d %04d" % (
241.415 - _DAYNAMES[weekday],
241.416 - _MONTHNAMES[self.month],
241.417 - self.day,
241.418 - self.hour, self.minute, self.second,
241.419 - self.year)
241.420 -
241.421 -class timedelta(object):
241.422 - """Represent the difference between two datetime objects.
241.423 -
241.424 - Supported operators:
241.425 -
241.426 - - add, subtract timedelta
241.427 - - unary plus, minus, abs
241.428 - - compare to timedelta
241.429 - - multiply, divide by int/long
241.430 -
241.431 - In addition, datetime supports subtraction of two datetime objects
241.432 - returning a timedelta, and addition or subtraction of a datetime
241.433 - and a timedelta giving a datetime.
241.434 -
241.435 - Representation: (days, seconds, microseconds). Why? Because I
241.436 - felt like it.
241.437 - """
241.438 -
241.439 - def __new__(cls, days=0, seconds=0, microseconds=0,
241.440 - # XXX The following should only be used as keyword args:
241.441 - milliseconds=0, minutes=0, hours=0, weeks=0):
241.442 - # Doing this efficiently and accurately in C is going to be difficult
241.443 - # and error-prone, due to ubiquitous overflow possibilities, and that
241.444 - # C double doesn't have enough bits of precision to represent
241.445 - # microseconds over 10K years faithfully. The code here tries to make
241.446 - # explicit where go-fast assumptions can be relied on, in order to
241.447 - # guide the C implementation; it's way more convoluted than speed-
241.448 - # ignoring auto-overflow-to-long idiomatic Python could be.
241.449 -
241.450 - # XXX Check that all inputs are ints, longs or floats.
241.451 -
241.452 - # Final values, all integer.
241.453 - # s and us fit in 32-bit signed ints; d isn't bounded.
241.454 - d = s = us = 0
241.455 -
241.456 - # Normalize everything to days, seconds, microseconds.
241.457 - days += weeks*7
241.458 - seconds += minutes*60 + hours*3600
241.459 - microseconds += milliseconds*1000
241.460 -
241.461 - # Get rid of all fractions, and normalize s and us.
241.462 - # Take a deep breath <wink>.
241.463 - if isinstance(days, float):
241.464 - dayfrac, days = _math.modf(days)
241.465 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
241.466 - assert daysecondswhole == int(daysecondswhole) # can't overflow
241.467 - s = int(daysecondswhole)
241.468 - assert days == long(days)
241.469 - d = long(days)
241.470 - else:
241.471 - daysecondsfrac = 0.0
241.472 - d = days
241.473 - assert isinstance(daysecondsfrac, float)
241.474 - assert abs(daysecondsfrac) <= 1.0
241.475 - assert isinstance(d, (int, long))
241.476 - assert abs(s) <= 24 * 3600
241.477 - # days isn't referenced again before redefinition
241.478 -
241.479 - if isinstance(seconds, float):
241.480 - secondsfrac, seconds = _math.modf(seconds)
241.481 - assert seconds == long(seconds)
241.482 - seconds = long(seconds)
241.483 - secondsfrac += daysecondsfrac
241.484 - assert abs(secondsfrac) <= 2.0
241.485 - else:
241.486 - secondsfrac = daysecondsfrac
241.487 - # daysecondsfrac isn't referenced again
241.488 - assert isinstance(secondsfrac, float)
241.489 - assert abs(secondsfrac) <= 2.0
241.490 -
241.491 - assert isinstance(seconds, (int, long))
241.492 - days, seconds = divmod(seconds, 24*3600)
241.493 - d += days
241.494 - s += int(seconds) # can't overflow
241.495 - assert isinstance(s, int)
241.496 - assert abs(s) <= 2 * 24 * 3600
241.497 - # seconds isn't referenced again before redefinition
241.498 -
241.499 - usdouble = secondsfrac * 1e6
241.500 - assert abs(usdouble) < 2.1e6 # exact value not critical
241.501 - # secondsfrac isn't referenced again
241.502 -
241.503 - if isinstance(microseconds, float):
241.504 - microseconds += usdouble
241.505 - microseconds = round(microseconds)
241.506 - seconds, microseconds = divmod(microseconds, 1e6)
241.507 - assert microseconds == int(microseconds)
241.508 - assert seconds == long(seconds)
241.509 - days, seconds = divmod(seconds, 24.*3600.)
241.510 - assert days == long(days)
241.511 - assert seconds == int(seconds)
241.512 - d += long(days)
241.513 - s += int(seconds) # can't overflow
241.514 - assert isinstance(s, int)
241.515 - assert abs(s) <= 3 * 24 * 3600
241.516 - else:
241.517 - seconds, microseconds = divmod(microseconds, 1000000)
241.518 - days, seconds = divmod(seconds, 24*3600)
241.519 - d += days
241.520 - s += int(seconds) # can't overflow
241.521 - assert isinstance(s, int)
241.522 - assert abs(s) <= 3 * 24 * 3600
241.523 - microseconds = float(microseconds)
241.524 - microseconds += usdouble
241.525 - microseconds = round(microseconds)
241.526 - assert abs(s) <= 3 * 24 * 3600
241.527 - assert abs(microseconds) < 3.1e6
241.528 -
241.529 - # Just a little bit of carrying possible for microseconds and seconds.
241.530 - assert isinstance(microseconds, float)
241.531 - assert int(microseconds) == microseconds
241.532 - us = int(microseconds)
241.533 - seconds, us = divmod(us, 1000000)
241.534 - s += seconds # cant't overflow
241.535 - assert isinstance(s, int)
241.536 - days, s = divmod(s, 24*3600)
241.537 - d += days
241.538 -
241.539 - assert isinstance(d, (int, long))
241.540 - assert isinstance(s, int) and 0 <= s < 24*3600
241.541 - assert isinstance(us, int) and 0 <= us < 1000000
241.542 -
241.543 - self = object.__new__(cls)
241.544 -
241.545 - self.__days = d
241.546 - self.__seconds = s
241.547 - self.__microseconds = us
241.548 - if abs(d) > 999999999:
241.549 - raise OverflowError("timedelta # of days is too large: %d" % d)
241.550 -
241.551 - return self
241.552 -
241.553 - def __repr__(self):
241.554 - if self.__microseconds:
241.555 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
241.556 - self.__days,
241.557 - self.__seconds,
241.558 - self.__microseconds)
241.559 - if self.__seconds:
241.560 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
241.561 - self.__days,
241.562 - self.__seconds)
241.563 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
241.564 -
241.565 - def __str__(self):
241.566 - mm, ss = divmod(self.__seconds, 60)
241.567 - hh, mm = divmod(mm, 60)
241.568 - s = "%d:%02d:%02d" % (hh, mm, ss)
241.569 - if self.__days:
241.570 - def plural(n):
241.571 - return n, abs(n) != 1 and "s" or ""
241.572 - s = ("%d day%s, " % plural(self.__days)) + s
241.573 - if self.__microseconds:
241.574 - s = s + ".%06d" % self.__microseconds
241.575 - return s
241.576 -
241.577 - days = property(lambda self: self.__days, doc="days")
241.578 - seconds = property(lambda self: self.__seconds, doc="seconds")
241.579 - microseconds = property(lambda self: self.__microseconds,
241.580 - doc="microseconds")
241.581 -
241.582 - def __add__(self, other):
241.583 - if isinstance(other, timedelta):
241.584 - return timedelta(self.__days + other.__days,
241.585 - self.__seconds + other.__seconds,
241.586 - self.__microseconds + other.__microseconds)
241.587 - return NotImplemented
241.588 -
241.589 - __radd__ = __add__
241.590 -
241.591 - def __sub__(self, other):
241.592 - if isinstance(other, timedelta):
241.593 - return self + -other
241.594 - return NotImplemented
241.595 -
241.596 - def __rsub__(self, other):
241.597 - if isinstance(other, timedelta):
241.598 - return -self + other
241.599 - return NotImplemented
241.600 -
241.601 - def __neg__(self):
241.602 - return self.__class__(-self.__days,
241.603 - -self.__seconds,
241.604 - -self.__microseconds)
241.605 -
241.606 - def __pos__(self):
241.607 - return self
241.608 -
241.609 - def __abs__(self):
241.610 - if self.__days < 0:
241.611 - return -self
241.612 - else:
241.613 - return self
241.614 -
241.615 - def __mul__(self, other):
241.616 - if isinstance(other, (int, long)):
241.617 - return self.__class__(self.__days * other,
241.618 - self.__seconds * other,
241.619 - self.__microseconds * other)
241.620 - return NotImplemented
241.621 -
241.622 - __rmul__ = __mul__
241.623 -
241.624 - def __div__(self, other):
241.625 - if isinstance(other, (int, long)):
241.626 - usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
241.627 - self.__microseconds)
241.628 - return self.__class__(0, 0, usec // other)
241.629 - return NotImplemented
241.630 -
241.631 - __floordiv__ = __div__
241.632 -
241.633 - # Comparisons.
241.634 -
241.635 - def __eq__(self, other):
241.636 - if isinstance(other, timedelta):
241.637 - return self.__cmp(other) == 0
241.638 - else:
241.639 - return False
241.640 -
241.641 - def __ne__(self, other):
241.642 - if isinstance(other, timedelta):
241.643 - return self.__cmp(other) != 0
241.644 - else:
241.645 - return True
241.646 -
241.647 - def __le__(self, other):
241.648 - if isinstance(other, timedelta):
241.649 - return self.__cmp(other) <= 0
241.650 - else:
241.651 - _cmperror(self, other)
241.652 -
241.653 - def __lt__(self, other):
241.654 - if isinstance(other, timedelta):
241.655 - return self.__cmp(other) < 0
241.656 - else:
241.657 - _cmperror(self, other)
241.658 -
241.659 - def __ge__(self, other):
241.660 - if isinstance(other, timedelta):
241.661 - return self.__cmp(other) >= 0
241.662 - else:
241.663 - _cmperror(self, other)
241.664 -
241.665 - def __gt__(self, other):
241.666 - if isinstance(other, timedelta):
241.667 - return self.__cmp(other) > 0
241.668 - else:
241.669 - _cmperror(self, other)
241.670 -
241.671 - def __cmp(self, other):
241.672 - assert isinstance(other, timedelta)
241.673 - return cmp(self.__getstate(), other.__getstate())
241.674 -
241.675 - def __hash__(self):
241.676 - return hash(self.__getstate())
241.677 -
241.678 - def __nonzero__(self):
241.679 - return (self.__days != 0 or
241.680 - self.__seconds != 0 or
241.681 - self.__microseconds != 0)
241.682 -
241.683 - # Pickle support.
241.684 -
241.685 - __safe_for_unpickling__ = True # For Python 2.2
241.686 -
241.687 - def __getstate(self):
241.688 - return (self.__days, self.__seconds, self.__microseconds)
241.689 -
241.690 - def __reduce__(self):
241.691 - return (self.__class__, self.__getstate())
241.692 -
241.693 -timedelta.min = timedelta(-999999999)
241.694 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
241.695 - microseconds=999999)
241.696 -timedelta.resolution = timedelta(microseconds=1)
241.697 -
241.698 -class date(object):
241.699 - """Concrete date type.
241.700 -
241.701 - Constructors:
241.702 -
241.703 - __new__()
241.704 - fromtimestamp()
241.705 - today()
241.706 - fromordinal()
241.707 -
241.708 - Operators:
241.709 -
241.710 - __repr__, __str__
241.711 - __cmp__, __hash__
241.712 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
241.713 -
241.714 - Methods:
241.715 -
241.716 - timetuple()
241.717 - toordinal()
241.718 - weekday()
241.719 - isoweekday(), isocalendar(), isoformat()
241.720 - ctime()
241.721 - strftime()
241.722 -
241.723 - Properties (readonly):
241.724 - year, month, day
241.725 - """
241.726 -
241.727 - def __new__(cls, year, month=None, day=None):
241.728 - """Constructor.
241.729 -
241.730 - Arguments:
241.731 -
241.732 - year, month, day (required, base 1)
241.733 - """
241.734 - if isinstance(year, str):
241.735 - # Pickle support
241.736 - self = object.__new__(cls)
241.737 - self.__setstate((year,))
241.738 - return self
241.739 - _check_date_fields(year, month, day)
241.740 - self = object.__new__(cls)
241.741 - self.__year = year
241.742 - self.__month = month
241.743 - self.__day = day
241.744 - return self
241.745 -
241.746 - # Additional constructors
241.747 -
241.748 - def fromtimestamp(cls, t):
241.749 - "Construct a date from a POSIX timestamp (like time.time())."
241.750 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
241.751 - return cls(y, m, d)
241.752 - fromtimestamp = classmethod(fromtimestamp)
241.753 -
241.754 - def today(cls):
241.755 - "Construct a date from time.time()."
241.756 - t = _time.time()
241.757 - return cls.fromtimestamp(t)
241.758 - today = classmethod(today)
241.759 -
241.760 - def fromordinal(cls, n):
241.761 - """Contruct a date from a proleptic Gregorian ordinal.
241.762 -
241.763 - January 1 of year 1 is day 1. Only the year, month and day are
241.764 - non-zero in the result.
241.765 - """
241.766 - y, m, d = _ord2ymd(n)
241.767 - return cls(y, m, d)
241.768 - fromordinal = classmethod(fromordinal)
241.769 -
241.770 - # Conversions to string
241.771 -
241.772 - def __repr__(self):
241.773 - "Convert to formal string, for repr()."
241.774 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
241.775 - self.__year,
241.776 - self.__month,
241.777 - self.__day)
241.778 - # XXX These shouldn't depend on time.localtime(), because that
241.779 - # clips the usable dates to [1970 .. 2038). At least ctime() is
241.780 - # easily done without using strftime() -- that's better too because
241.781 - # strftime("%c", ...) is locale specific.
241.782 -
241.783 - def ctime(self):
241.784 - "Format a la ctime()."
241.785 - return tmxxx(self.__year, self.__month, self.__day).ctime()
241.786 -
241.787 - def strftime(self, fmt):
241.788 - "Format using strftime()."
241.789 - return _wrap_strftime(self, fmt, self.timetuple())
241.790 -
241.791 - def isoformat(self):
241.792 - """Return the date formatted according to ISO.
241.793 -
241.794 - This is 'YYYY-MM-DD'.
241.795 -
241.796 - References:
241.797 - - http://www.w3.org/TR/NOTE-datetime
241.798 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
241.799 - """
241.800 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
241.801 -
241.802 - __str__ = isoformat
241.803 -
241.804 - # Read-only field accessors
241.805 - year = property(lambda self: self.__year,
241.806 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
241.807 - month = property(lambda self: self.__month, doc="month (1-12)")
241.808 - day = property(lambda self: self.__day, doc="day (1-31)")
241.809 -
241.810 - # Standard conversions, __cmp__, __hash__ (and helpers)
241.811 -
241.812 - def timetuple(self):
241.813 - "Return local time tuple compatible with time.localtime()."
241.814 - return _build_struct_time(self.__year, self.__month, self.__day,
241.815 - 0, 0, 0, -1)
241.816 -
241.817 - def toordinal(self):
241.818 - """Return proleptic Gregorian ordinal for the year, month and day.
241.819 -
241.820 - January 1 of year 1 is day 1. Only the year, month and day values
241.821 - contribute to the result.
241.822 - """
241.823 - return _ymd2ord(self.__year, self.__month, self.__day)
241.824 -
241.825 - def replace(self, year=None, month=None, day=None):
241.826 - """Return a new date with new values for the specified fields."""
241.827 - if year is None:
241.828 - year = self.__year
241.829 - if month is None:
241.830 - month = self.__month
241.831 - if day is None:
241.832 - day = self.__day
241.833 - _check_date_fields(year, month, day)
241.834 - return date(year, month, day)
241.835 -
241.836 - # Comparisons.
241.837 -
241.838 - def __eq__(self, other):
241.839 - if isinstance(other, date):
241.840 - return self.__cmp(other) == 0
241.841 - elif hasattr(other, "timetuple"):
241.842 - return NotImplemented
241.843 - else:
241.844 - return False
241.845 -
241.846 - def __ne__(self, other):
241.847 - if isinstance(other, date):
241.848 - return self.__cmp(other) != 0
241.849 - elif hasattr(other, "timetuple"):
241.850 - return NotImplemented
241.851 - else:
241.852 - return True
241.853 -
241.854 - def __le__(self, other):
241.855 - if isinstance(other, date):
241.856 - return self.__cmp(other) <= 0
241.857 - elif hasattr(other, "timetuple"):
241.858 - return NotImplemented
241.859 - else:
241.860 - _cmperror(self, other)
241.861 -
241.862 - def __lt__(self, other):
241.863 - if isinstance(other, date):
241.864 - return self.__cmp(other) < 0
241.865 - elif hasattr(other, "timetuple"):
241.866 - return NotImplemented
241.867 - else:
241.868 - _cmperror(self, other)
241.869 -
241.870 - def __ge__(self, other):
241.871 - if isinstance(other, date):
241.872 - return self.__cmp(other) >= 0
241.873 - elif hasattr(other, "timetuple"):
241.874 - return NotImplemented
241.875 - else:
241.876 - _cmperror(self, other)
241.877 -
241.878 - def __gt__(self, other):
241.879 - if isinstance(other, date):
241.880 - return self.__cmp(other) > 0
241.881 - elif hasattr(other, "timetuple"):
241.882 - return NotImplemented
241.883 - else:
241.884 - _cmperror(self, other)
241.885 -
241.886 - def __cmp(self, other):
241.887 - assert isinstance(other, date)
241.888 - y, m, d = self.__year, self.__month, self.__day
241.889 - y2, m2, d2 = other.__year, other.__month, other.__day
241.890 - return cmp((y, m, d), (y2, m2, d2))
241.891 -
241.892 - def __hash__(self):
241.893 - "Hash."
241.894 - return hash(self.__getstate())
241.895 -
241.896 - # Computations
241.897 -
241.898 - def _checkOverflow(self, year):
241.899 - if not MINYEAR <= year <= MAXYEAR:
241.900 - raise OverflowError("date +/-: result year %d not in %d..%d" %
241.901 - (year, MINYEAR, MAXYEAR))
241.902 -
241.903 - def __add__(self, other):
241.904 - "Add a date to a timedelta."
241.905 - if isinstance(other, timedelta):
241.906 - t = tmxxx(self.__year,
241.907 - self.__month,
241.908 - self.__day + other.days)
241.909 - self._checkOverflow(t.year)
241.910 - result = self.__class__(t.year, t.month, t.day)
241.911 - return result
241.912 - return NotImplemented
241.913 -
241.914 - __radd__ = __add__
241.915 -
241.916 - def __sub__(self, other):
241.917 - """Subtract two dates, or a date and a timedelta."""
241.918 - if isinstance(other, timedelta):
241.919 - return self + timedelta(-other.days)
241.920 - if isinstance(other, date):
241.921 - days1 = self.toordinal()
241.922 - days2 = other.toordinal()
241.923 - return timedelta(days1 - days2)
241.924 - return NotImplemented
241.925 -
241.926 - def weekday(self):
241.927 - "Return day of the week, where Monday == 0 ... Sunday == 6."
241.928 - return (self.toordinal() + 6) % 7
241.929 -
241.930 - # Day-of-the-week and week-of-the-year, according to ISO
241.931 -
241.932 - def isoweekday(self):
241.933 - "Return day of the week, where Monday == 1 ... Sunday == 7."
241.934 - # 1-Jan-0001 is a Monday
241.935 - return self.toordinal() % 7 or 7
241.936 -
241.937 - def isocalendar(self):
241.938 - """Return a 3-tuple containing ISO year, week number, and weekday.
241.939 -
241.940 - The first ISO week of the year is the (Mon-Sun) week
241.941 - containing the year's first Thursday; everything else derives
241.942 - from that.
241.943 -
241.944 - The first week is 1; Monday is 1 ... Sunday is 7.
241.945 -
241.946 - ISO calendar algorithm taken from
241.947 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
241.948 - """
241.949 - year = self.__year
241.950 - week1monday = _isoweek1monday(year)
241.951 - today = _ymd2ord(self.__year, self.__month, self.__day)
241.952 - # Internally, week and day have origin 0
241.953 - week, day = divmod(today - week1monday, 7)
241.954 - if week < 0:
241.955 - year -= 1
241.956 - week1monday = _isoweek1monday(year)
241.957 - week, day = divmod(today - week1monday, 7)
241.958 - elif week >= 52:
241.959 - if today >= _isoweek1monday(year+1):
241.960 - year += 1
241.961 - week = 0
241.962 - return year, week+1, day+1
241.963 -
241.964 - # Pickle support.
241.965 -
241.966 - __safe_for_unpickling__ = True # For Python 2.2
241.967 -
241.968 - def __getstate(self):
241.969 - yhi, ylo = divmod(self.__year, 256)
241.970 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
241.971 -
241.972 - def __setstate(self, t):
241.973 - assert isinstance(t, tuple) and len(t) == 1, `t`
241.974 - string = t[0]
241.975 - assert len(string) == 4
241.976 - yhi, ylo, self.__month, self.__day = map(ord, string)
241.977 - self.__year = yhi * 256 + ylo
241.978 -
241.979 - def __reduce__(self):
241.980 - return (self.__class__, self.__getstate())
241.981 -
241.982 -_date_class = date # so functions w/ args named "date" can get at the class
241.983 -
241.984 -date.min = date(1, 1, 1)
241.985 -date.max = date(9999, 12, 31)
241.986 -date.resolution = timedelta(days=1)
241.987 -
241.988 -class tzinfo(object):
241.989 - """Abstract base class for time zone info classes.
241.990 -
241.991 - Subclasses must override the name(), utcoffset() and dst() methods.
241.992 - """
241.993 -
241.994 - def tzname(self, dt):
241.995 - "datetime -> string name of time zone."
241.996 - raise NotImplementedError("tzinfo subclass must override tzname()")
241.997 -
241.998 - def utcoffset(self, dt):
241.999 - "datetime -> minutes east of UTC (negative for west of UTC)"
241.1000 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
241.1001 -
241.1002 - def dst(self, dt):
241.1003 - """datetime -> DST offset in minutes east of UTC.
241.1004 -
241.1005 - Return 0 if DST not in effect. utcoffset() must include the DST
241.1006 - offset.
241.1007 - """
241.1008 - raise NotImplementedError("tzinfo subclass must override dst()")
241.1009 -
241.1010 - def fromutc(self, dt):
241.1011 - "datetime in UTC -> datetime in local time."
241.1012 -
241.1013 - if not isinstance(dt, datetime):
241.1014 - raise TypeError("fromutc() requires a datetime argument")
241.1015 - if dt.tzinfo is not self:
241.1016 - raise ValueError("dt.tzinfo is not self")
241.1017 -
241.1018 - dtoff = dt.utcoffset()
241.1019 - if dtoff is None:
241.1020 - raise ValueError("fromutc() requires a non-None utcoffset() "
241.1021 - "result")
241.1022 -
241.1023 - # See the long comment block at the end of this file for an
241.1024 - # explanation of this algorithm.
241.1025 - dtdst = dt.dst()
241.1026 - if dtdst is None:
241.1027 - raise ValueError("fromutc() requires a non-None dst() result")
241.1028 - delta = dtoff - dtdst
241.1029 - if delta:
241.1030 - dt += delta
241.1031 - dtdst = dt.dst()
241.1032 - if dtdst is None:
241.1033 - raise ValueError("fromutc(): dt.dst gave inconsistent "
241.1034 - "results; cannot convert")
241.1035 - if dtdst:
241.1036 - return dt + dtdst
241.1037 - else:
241.1038 - return dt
241.1039 -
241.1040 - # Pickle support.
241.1041 -
241.1042 - __safe_for_unpickling__ = True # For Python 2.2
241.1043 -
241.1044 - def __reduce__(self):
241.1045 - getinitargs = getattr(self, "__getinitargs__", None)
241.1046 - if getinitargs:
241.1047 - args = getinitargs()
241.1048 - else:
241.1049 - args = ()
241.1050 - getstate = getattr(self, "__getstate__", None)
241.1051 - if getstate:
241.1052 - state = getstate()
241.1053 - else:
241.1054 - state = getattr(self, "__dict__", None) or None
241.1055 - if state is None:
241.1056 - return (self.__class__, args)
241.1057 - else:
241.1058 - return (self.__class__, args, state)
241.1059 -
241.1060 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
241.1061 -
241.1062 -class time(object):
241.1063 - """Time with time zone.
241.1064 -
241.1065 - Constructors:
241.1066 -
241.1067 - __new__()
241.1068 -
241.1069 - Operators:
241.1070 -
241.1071 - __repr__, __str__
241.1072 - __cmp__, __hash__
241.1073 -
241.1074 - Methods:
241.1075 -
241.1076 - strftime()
241.1077 - isoformat()
241.1078 - utcoffset()
241.1079 - tzname()
241.1080 - dst()
241.1081 -
241.1082 - Properties (readonly):
241.1083 - hour, minute, second, microsecond, tzinfo
241.1084 - """
241.1085 -
241.1086 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
241.1087 - """Constructor.
241.1088 -
241.1089 - Arguments:
241.1090 -
241.1091 - hour, minute (required)
241.1092 - second, microsecond (default to zero)
241.1093 - tzinfo (default to None)
241.1094 - """
241.1095 - self = object.__new__(cls)
241.1096 - if isinstance(hour, str):
241.1097 - # Pickle support
241.1098 - self.__setstate((hour, minute or None))
241.1099 - return self
241.1100 - _check_tzinfo_arg(tzinfo)
241.1101 - _check_time_fields(hour, minute, second, microsecond)
241.1102 - self.__hour = hour
241.1103 - self.__minute = minute
241.1104 - self.__second = second
241.1105 - self.__microsecond = microsecond
241.1106 - self._tzinfo = tzinfo
241.1107 - return self
241.1108 -
241.1109 - # Read-only field accessors
241.1110 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
241.1111 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
241.1112 - second = property(lambda self: self.__second, doc="second (0-59)")
241.1113 - microsecond = property(lambda self: self.__microsecond,
241.1114 - doc="microsecond (0-999999)")
241.1115 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
241.1116 -
241.1117 - # Standard conversions, __hash__ (and helpers)
241.1118 -
241.1119 - # Comparisons.
241.1120 -
241.1121 - def __eq__(self, other):
241.1122 - if isinstance(other, time):
241.1123 - return self.__cmp(other) == 0
241.1124 - else:
241.1125 - return False
241.1126 -
241.1127 - def __ne__(self, other):
241.1128 - if isinstance(other, time):
241.1129 - return self.__cmp(other) != 0
241.1130 - else:
241.1131 - return True
241.1132 -
241.1133 - def __le__(self, other):
241.1134 - if isinstance(other, time):
241.1135 - return self.__cmp(other) <= 0
241.1136 - else:
241.1137 - _cmperror(self, other)
241.1138 -
241.1139 - def __lt__(self, other):
241.1140 - if isinstance(other, time):
241.1141 - return self.__cmp(other) < 0
241.1142 - else:
241.1143 - _cmperror(self, other)
241.1144 -
241.1145 - def __ge__(self, other):
241.1146 - if isinstance(other, time):
241.1147 - return self.__cmp(other) >= 0
241.1148 - else:
241.1149 - _cmperror(self, other)
241.1150 -
241.1151 - def __gt__(self, other):
241.1152 - if isinstance(other, time):
241.1153 - return self.__cmp(other) > 0
241.1154 - else:
241.1155 - _cmperror(self, other)
241.1156 -
241.1157 - def __cmp(self, other):
241.1158 - assert isinstance(other, time)
241.1159 - mytz = self._tzinfo
241.1160 - ottz = other._tzinfo
241.1161 - myoff = otoff = None
241.1162 -
241.1163 - if mytz is ottz:
241.1164 - base_compare = True
241.1165 - else:
241.1166 - myoff = self._utcoffset()
241.1167 - otoff = other._utcoffset()
241.1168 - base_compare = myoff == otoff
241.1169 -
241.1170 - if base_compare:
241.1171 - return cmp((self.__hour, self.__minute, self.__second,
241.1172 - self.__microsecond),
241.1173 - (other.__hour, other.__minute, other.__second,
241.1174 - other.__microsecond))
241.1175 - if myoff is None or otoff is None:
241.1176 - # XXX Buggy in 2.2.2.
241.1177 - raise TypeError("cannot compare naive and aware times")
241.1178 - myhhmm = self.__hour * 60 + self.__minute - myoff
241.1179 - othhmm = other.__hour * 60 + other.__minute - otoff
241.1180 - return cmp((myhhmm, self.__second, self.__microsecond),
241.1181 - (othhmm, other.__second, other.__microsecond))
241.1182 -
241.1183 - def __hash__(self):
241.1184 - """Hash."""
241.1185 - tzoff = self._utcoffset()
241.1186 - if not tzoff: # zero or None
241.1187 - return hash(self.__getstate()[0])
241.1188 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
241.1189 - if 0 <= h < 24:
241.1190 - return hash(time(h, m, self.second, self.microsecond))
241.1191 - return hash((h, m, self.second, self.microsecond))
241.1192 -
241.1193 - # Conversion to string
241.1194 -
241.1195 - def _tzstr(self, sep=":"):
241.1196 - """Return formatted timezone offset (+xx:xx) or None."""
241.1197 - off = self._utcoffset()
241.1198 - if off is not None:
241.1199 - if off < 0:
241.1200 - sign = "-"
241.1201 - off = -off
241.1202 - else:
241.1203 - sign = "+"
241.1204 - hh, mm = divmod(off, 60)
241.1205 - assert 0 <= hh < 24
241.1206 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
241.1207 - return off
241.1208 -
241.1209 - def __repr__(self):
241.1210 - """Convert to formal string, for repr()."""
241.1211 - if self.__microsecond != 0:
241.1212 - s = ", %d, %d" % (self.__second, self.__microsecond)
241.1213 - elif self.__second != 0:
241.1214 - s = ", %d" % self.__second
241.1215 - else:
241.1216 - s = ""
241.1217 - s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
241.1218 - self.__hour, self.__minute, s)
241.1219 - if self._tzinfo is not None:
241.1220 - assert s[-1:] == ")"
241.1221 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
241.1222 - return s
241.1223 -
241.1224 - def isoformat(self):
241.1225 - """Return the time formatted according to ISO.
241.1226 -
241.1227 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
241.1228 - self.microsecond == 0.
241.1229 - """
241.1230 - s = _format_time(self.__hour, self.__minute, self.__second,
241.1231 - self.__microsecond)
241.1232 - tz = self._tzstr()
241.1233 - if tz:
241.1234 - s += tz
241.1235 - return s
241.1236 -
241.1237 - __str__ = isoformat
241.1238 -
241.1239 - def strftime(self, fmt):
241.1240 - """Format using strftime(). The date part of the timestamp passed
241.1241 - to underlying strftime should not be used.
241.1242 - """
241.1243 - # The year must be >= 1900 else Python's strftime implementation
241.1244 - # can raise a bogus exception.
241.1245 - timetuple = (1900, 1, 1,
241.1246 - self.__hour, self.__minute, self.__second,
241.1247 - 0, 1, -1)
241.1248 - return _wrap_strftime(self, fmt, timetuple)
241.1249 -
241.1250 - # Timezone functions
241.1251 -
241.1252 - def utcoffset(self):
241.1253 - """Return the timezone offset in minutes east of UTC (negative west of
241.1254 - UTC)."""
241.1255 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
241.1256 - offset = _check_utc_offset("utcoffset", offset)
241.1257 - if offset is not None:
241.1258 - offset = timedelta(minutes=offset)
241.1259 - return offset
241.1260 -
241.1261 - # Return an integer (or None) instead of a timedelta (or None).
241.1262 - def _utcoffset(self):
241.1263 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
241.1264 - offset = _check_utc_offset("utcoffset", offset)
241.1265 - return offset
241.1266 -
241.1267 - def tzname(self):
241.1268 - """Return the timezone name.
241.1269 -
241.1270 - Note that the name is 100% informational -- there's no requirement that
241.1271 - it mean anything in particular. For example, "GMT", "UTC", "-500",
241.1272 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
241.1273 - """
241.1274 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
241.1275 - _check_tzname(name)
241.1276 - return name
241.1277 -
241.1278 - def dst(self):
241.1279 - """Return 0 if DST is not in effect, or the DST offset (in minutes
241.1280 - eastward) if DST is in effect.
241.1281 -
241.1282 - This is purely informational; the DST offset has already been added to
241.1283 - the UTC offset returned by utcoffset() if applicable, so there's no
241.1284 - need to consult dst() unless you're interested in displaying the DST
241.1285 - info.
241.1286 - """
241.1287 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
241.1288 - offset = _check_utc_offset("dst", offset)
241.1289 - if offset is not None:
241.1290 - offset = timedelta(minutes=offset)
241.1291 - return offset
241.1292 -
241.1293 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
241.1294 - tzinfo=True):
241.1295 - """Return a new time with new values for the specified fields."""
241.1296 - if hour is None:
241.1297 - hour = self.hour
241.1298 - if minute is None:
241.1299 - minute = self.minute
241.1300 - if second is None:
241.1301 - second = self.second
241.1302 - if microsecond is None:
241.1303 - microsecond = self.microsecond
241.1304 - if tzinfo is True:
241.1305 - tzinfo = self.tzinfo
241.1306 - _check_time_fields(hour, minute, second, microsecond)
241.1307 - _check_tzinfo_arg(tzinfo)
241.1308 - return time(hour, minute, second, microsecond, tzinfo)
241.1309 -
241.1310 - # Return an integer (or None) instead of a timedelta (or None).
241.1311 - def _dst(self):
241.1312 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
241.1313 - offset = _check_utc_offset("dst", offset)
241.1314 - return offset
241.1315 -
241.1316 - def __nonzero__(self):
241.1317 - if self.second or self.microsecond:
241.1318 - return 1
241.1319 - offset = self._utcoffset() or 0
241.1320 - return self.hour * 60 + self.minute - offset != 0
241.1321 -
241.1322 - # Pickle support.
241.1323 -
241.1324 - __safe_for_unpickling__ = True # For Python 2.2
241.1325 -
241.1326 - def __getstate(self):
241.1327 - us2, us3 = divmod(self.__microsecond, 256)
241.1328 - us1, us2 = divmod(us2, 256)
241.1329 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
241.1330 - us1, us2, us3)
241.1331 - if self._tzinfo is None:
241.1332 - return (basestate,)
241.1333 - else:
241.1334 - return (basestate, self._tzinfo)
241.1335 -
241.1336 - def __setstate(self, state):
241.1337 - assert isinstance(state, tuple)
241.1338 - assert 1 <= len(state) <= 2
241.1339 - string = state[0]
241.1340 - assert len(string) == 6
241.1341 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
241.1342 - map(ord, string)
241.1343 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
241.1344 - if len(state) == 1:
241.1345 - self._tzinfo = None
241.1346 - else:
241.1347 - self._tzinfo = state[1]
241.1348 -
241.1349 - def __reduce__(self):
241.1350 - return (self.__class__, self.__getstate())
241.1351 -
241.1352 -_time_class = time # so functions w/ args named "time" can get at the class
241.1353 -
241.1354 -time.min = time(0, 0, 0)
241.1355 -time.max = time(23, 59, 59, 999999)
241.1356 -time.resolution = timedelta(microseconds=1)
241.1357 -
241.1358 -class datetime(date):
241.1359 -
241.1360 - # XXX needs docstrings
241.1361 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
241.1362 -
241.1363 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
241.1364 - microsecond=0, tzinfo=None):
241.1365 - if isinstance(year, str):
241.1366 - # Pickle support
241.1367 - self = date.__new__(cls, year[:4])
241.1368 - self.__setstate((year, month))
241.1369 - return self
241.1370 - _check_tzinfo_arg(tzinfo)
241.1371 - _check_time_fields(hour, minute, second, microsecond)
241.1372 - self = date.__new__(cls, year, month, day)
241.1373 - # XXX This duplicates __year, __month, __day for convenience :-(
241.1374 - self.__year = year
241.1375 - self.__month = month
241.1376 - self.__day = day
241.1377 - self.__hour = hour
241.1378 - self.__minute = minute
241.1379 - self.__second = second
241.1380 - self.__microsecond = microsecond
241.1381 - self._tzinfo = tzinfo
241.1382 - return self
241.1383 -
241.1384 - # Read-only field accessors
241.1385 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
241.1386 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
241.1387 - second = property(lambda self: self.__second, doc="second (0-59)")
241.1388 - microsecond = property(lambda self: self.__microsecond,
241.1389 - doc="microsecond (0-999999)")
241.1390 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
241.1391 -
241.1392 - def fromtimestamp(cls, t, tz=None):
241.1393 - """Construct a datetime from a POSIX timestamp (like time.time()).
241.1394 -
241.1395 - A timezone info object may be passed in as well.
241.1396 - """
241.1397 -
241.1398 - _check_tzinfo_arg(tz)
241.1399 - if tz is None:
241.1400 - converter = _time.localtime
241.1401 - else:
241.1402 - converter = _time.gmtime
241.1403 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
241.1404 - us = int((t % 1.0) * 1000000)
241.1405 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
241.1406 - result = cls(y, m, d, hh, mm, ss, us, tz)
241.1407 - if tz is not None:
241.1408 - result = tz.fromutc(result)
241.1409 - return result
241.1410 - fromtimestamp = classmethod(fromtimestamp)
241.1411 -
241.1412 - def utcfromtimestamp(cls, t):
241.1413 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
241.1414 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
241.1415 - us = int((t % 1.0) * 1000000)
241.1416 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
241.1417 - return cls(y, m, d, hh, mm, ss, us)
241.1418 - utcfromtimestamp = classmethod(utcfromtimestamp)
241.1419 -
241.1420 - # XXX This is supposed to do better than we *can* do by using time.time(),
241.1421 - # XXX if the platform supports a more accurate way. The C implementation
241.1422 - # XXX uses gettimeofday on platforms that have it, but that isn't
241.1423 - # XXX available from Python. So now() may return different results
241.1424 - # XXX across the implementations.
241.1425 - def now(cls, tz=None):
241.1426 - "Construct a datetime from time.time() and optional time zone info."
241.1427 - t = _time.time()
241.1428 - return cls.fromtimestamp(t, tz)
241.1429 - now = classmethod(now)
241.1430 -
241.1431 - def utcnow(cls):
241.1432 - "Construct a UTC datetime from time.time()."
241.1433 - t = _time.time()
241.1434 - return cls.utcfromtimestamp(t)
241.1435 - utcnow = classmethod(utcnow)
241.1436 -
241.1437 - def combine(cls, date, time):
241.1438 - "Construct a datetime from a given date and a given time."
241.1439 - if not isinstance(date, _date_class):
241.1440 - raise TypeError("date argument must be a date instance")
241.1441 - if not isinstance(time, _time_class):
241.1442 - raise TypeError("time argument must be a time instance")
241.1443 - return cls(date.year, date.month, date.day,
241.1444 - time.hour, time.minute, time.second, time.microsecond,
241.1445 - time.tzinfo)
241.1446 - combine = classmethod(combine)
241.1447 -
241.1448 - def timetuple(self):
241.1449 - "Return local time tuple compatible with time.localtime()."
241.1450 - dst = self._dst()
241.1451 - if dst is None:
241.1452 - dst = -1
241.1453 - elif dst:
241.1454 - dst = 1
241.1455 - return _build_struct_time(self.year, self.month, self.day,
241.1456 - self.hour, self.minute, self.second,
241.1457 - dst)
241.1458 -
241.1459 - def utctimetuple(self):
241.1460 - "Return UTC time tuple compatible with time.gmtime()."
241.1461 - y, m, d = self.year, self.month, self.day
241.1462 - hh, mm, ss = self.hour, self.minute, self.second
241.1463 - offset = self._utcoffset()
241.1464 - if offset: # neither None nor 0
241.1465 - tm = tmxxx(y, m, d, hh, mm - offset)
241.1466 - y, m, d = tm.year, tm.month, tm.day
241.1467 - hh, mm = tm.hour, tm.minute
241.1468 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
241.1469 -
241.1470 - def date(self):
241.1471 - "Return the date part."
241.1472 - return date(self.__year, self.__month, self.__day)
241.1473 -
241.1474 - def time(self):
241.1475 - "Return the time part, with tzinfo None."
241.1476 - return time(self.hour, self.minute, self.second, self.microsecond)
241.1477 -
241.1478 - def timetz(self):
241.1479 - "Return the time part, with same tzinfo."
241.1480 - return time(self.hour, self.minute, self.second, self.microsecond,
241.1481 - self._tzinfo)
241.1482 -
241.1483 - def replace(self, year=None, month=None, day=None, hour=None,
241.1484 - minute=None, second=None, microsecond=None, tzinfo=True):
241.1485 - """Return a new datetime with new values for the specified fields."""
241.1486 - if year is None:
241.1487 - year = self.year
241.1488 - if month is None:
241.1489 - month = self.month
241.1490 - if day is None:
241.1491 - day = self.day
241.1492 - if hour is None:
241.1493 - hour = self.hour
241.1494 - if minute is None:
241.1495 - minute = self.minute
241.1496 - if second is None:
241.1497 - second = self.second
241.1498 - if microsecond is None:
241.1499 - microsecond = self.microsecond
241.1500 - if tzinfo is True:
241.1501 - tzinfo = self.tzinfo
241.1502 - _check_date_fields(year, month, day)
241.1503 - _check_time_fields(hour, minute, second, microsecond)
241.1504 - _check_tzinfo_arg(tzinfo)
241.1505 - return datetime(year, month, day, hour, minute, second,
241.1506 - microsecond, tzinfo)
241.1507 -
241.1508 - def astimezone(self, tz):
241.1509 - if not isinstance(tz, tzinfo):
241.1510 - raise TypeError("tz argument must be an instance of tzinfo")
241.1511 -
241.1512 - mytz = self.tzinfo
241.1513 - if mytz is None:
241.1514 - raise ValueError("astimezone() requires an aware datetime")
241.1515 -
241.1516 - if tz is mytz:
241.1517 - return self
241.1518 -
241.1519 - # Convert self to UTC, and attach the new time zone object.
241.1520 - myoffset = self.utcoffset()
241.1521 - if myoffset is None:
241.1522 - raise ValuError("astimezone() requires an aware datetime")
241.1523 - utc = (self - myoffset).replace(tzinfo=tz)
241.1524 -
241.1525 - # Convert from UTC to tz's local time.
241.1526 - return tz.fromutc(utc)
241.1527 -
241.1528 - # Ways to produce a string.
241.1529 -
241.1530 - def ctime(self):
241.1531 - "Format a la ctime()."
241.1532 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
241.1533 - self.__minute, self.__second)
241.1534 - return t.ctime()
241.1535 -
241.1536 - def isoformat(self, sep='T'):
241.1537 - """Return the time formatted according to ISO.
241.1538 -
241.1539 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
241.1540 - self.microsecond == 0.
241.1541 -
241.1542 - If self.tzinfo is not None, the UTC offset is also attached, giving
241.1543 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
241.1544 -
241.1545 - Optional argument sep specifies the separator between date and
241.1546 - time, default 'T'.
241.1547 - """
241.1548 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
241.1549 - sep) +
241.1550 - _format_time(self.__hour, self.__minute, self.__second,
241.1551 - self.__microsecond))
241.1552 - off = self._utcoffset()
241.1553 - if off is not None:
241.1554 - if off < 0:
241.1555 - sign = "-"
241.1556 - off = -off
241.1557 - else:
241.1558 - sign = "+"
241.1559 - hh, mm = divmod(off, 60)
241.1560 - s += "%s%02d:%02d" % (sign, hh, mm)
241.1561 - return s
241.1562 -
241.1563 - def __repr__(self):
241.1564 - "Convert to formal string, for repr()."
241.1565 - L = [self.__year, self.__month, self.__day, # These are never zero
241.1566 - self.__hour, self.__minute, self.__second, self.__microsecond]
241.1567 - if L[-1] == 0:
241.1568 - del L[-1]
241.1569 - if L[-1] == 0:
241.1570 - del L[-1]
241.1571 - s = ", ".join(map(str, L))
241.1572 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
241.1573 - if self._tzinfo is not None:
241.1574 - assert s[-1:] == ")"
241.1575 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
241.1576 - return s
241.1577 -
241.1578 - def __str__(self):
241.1579 - "Convert to string, for str()."
241.1580 - return self.isoformat(sep=' ')
241.1581 -
241.1582 - def utcoffset(self):
241.1583 - """Return the timezone offset in minutes east of UTC (negative west of
241.1584 - UTC)."""
241.1585 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
241.1586 - offset = _check_utc_offset("utcoffset", offset)
241.1587 - if offset is not None:
241.1588 - offset = timedelta(minutes=offset)
241.1589 - return offset
241.1590 -
241.1591 - # Return an integer (or None) instead of a timedelta (or None).
241.1592 - def _utcoffset(self):
241.1593 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
241.1594 - offset = _check_utc_offset("utcoffset", offset)
241.1595 - return offset
241.1596 -
241.1597 - def tzname(self):
241.1598 - """Return the timezone name.
241.1599 -
241.1600 - Note that the name is 100% informational -- there's no requirement that
241.1601 - it mean anything in particular. For example, "GMT", "UTC", "-500",
241.1602 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
241.1603 - """
241.1604 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
241.1605 - _check_tzname(name)
241.1606 - return name
241.1607 -
241.1608 - def dst(self):
241.1609 - """Return 0 if DST is not in effect, or the DST offset (in minutes
241.1610 - eastward) if DST is in effect.
241.1611 -
241.1612 - This is purely informational; the DST offset has already been added to
241.1613 - the UTC offset returned by utcoffset() if applicable, so there's no
241.1614 - need to consult dst() unless you're interested in displaying the DST
241.1615 - info.
241.1616 - """
241.1617 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
241.1618 - offset = _check_utc_offset("dst", offset)
241.1619 - if offset is not None:
241.1620 - offset = timedelta(minutes=offset)
241.1621 - return offset
241.1622 -
241.1623 - # Return an integer (or None) instead of a timedelta (or None).1573
241.1624 - def _dst(self):
241.1625 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
241.1626 - offset = _check_utc_offset("dst", offset)
241.1627 - return offset
241.1628 -
241.1629 - # Comparisons.
241.1630 -
241.1631 - def __eq__(self, other):
241.1632 - if isinstance(other, datetime):
241.1633 - return self.__cmp(other) == 0
241.1634 - elif hasattr(other, "timetuple"):
241.1635 - return NotImplemented
241.1636 - else:
241.1637 - return False
241.1638 -
241.1639 - def __ne__(self, other):
241.1640 - if isinstance(other, datetime):
241.1641 - return self.__cmp(other) != 0
241.1642 - elif hasattr(other, "timetuple"):
241.1643 - return NotImplemented
241.1644 - else:
241.1645 - return True
241.1646 -
241.1647 - def __le__(self, other):
241.1648 - if isinstance(other, datetime):
241.1649 - return self.__cmp(other) <= 0
241.1650 - elif hasattr(other, "timetuple"):
241.1651 - return NotImplemented
241.1652 - else:
241.1653 - _cmperror(self, other)
241.1654 -
241.1655 - def __lt__(self, other):
241.1656 - if isinstance(other, datetime):
241.1657 - return self.__cmp(other) < 0
241.1658 - elif hasattr(other, "timetuple"):
241.1659 - return NotImplemented
241.1660 - else:
241.1661 - _cmperror(self, other)
241.1662 -
241.1663 - def __ge__(self, other):
241.1664 - if isinstance(other, datetime):
241.1665 - return self.__cmp(other) >= 0
241.1666 - elif hasattr(other, "timetuple"):
241.1667 - return NotImplemented
241.1668 - else:
241.1669 - _cmperror(self, other)
241.1670 -
241.1671 - def __gt__(self, other):
241.1672 - if isinstance(other, datetime):
241.1673 - return self.__cmp(other) > 0
241.1674 - elif hasattr(other, "timetuple"):
241.1675 - return NotImplemented
241.1676 - else:
241.1677 - _cmperror(self, other)
241.1678 -
241.1679 - def __cmp(self, other):
241.1680 - assert isinstance(other, datetime)
241.1681 - mytz = self._tzinfo
241.1682 - ottz = other._tzinfo
241.1683 - myoff = otoff = None
241.1684 -
241.1685 - if mytz is ottz:
241.1686 - base_compare = True
241.1687 - else:
241.1688 - if mytz is not None:
241.1689 - myoff = self._utcoffset()
241.1690 - if ottz is not None:
241.1691 - otoff = other._utcoffset()
241.1692 - base_compare = myoff == otoff
241.1693 -
241.1694 - if base_compare:
241.1695 - return cmp((self.__year, self.__month, self.__day,
241.1696 - self.__hour, self.__minute, self.__second,
241.1697 - self.__microsecond),
241.1698 - (other.__year, other.__month, other.__day,
241.1699 - other.__hour, other.__minute, other.__second,
241.1700 - other.__microsecond))
241.1701 - if myoff is None or otoff is None:
241.1702 - # XXX Buggy in 2.2.2.
241.1703 - raise TypeError("cannot compare naive and aware datetimes")
241.1704 - # XXX What follows could be done more efficiently...
241.1705 - diff = self - other # this will take offsets into account
241.1706 - if diff.days < 0:
241.1707 - return -1
241.1708 - return diff and 1 or 0
241.1709 -
241.1710 - def __add__(self, other):
241.1711 - "Add a datetime and a timedelta."
241.1712 - if not isinstance(other, timedelta):
241.1713 - return NotImplemented
241.1714 - t = tmxxx(self.__year,
241.1715 - self.__month,
241.1716 - self.__day + other.days,
241.1717 - self.__hour,
241.1718 - self.__minute,
241.1719 - self.__second + other.seconds,
241.1720 - self.__microsecond + other.microseconds)
241.1721 - self._checkOverflow(t.year)
241.1722 - result = self.__class__(t.year, t.month, t.day,
241.1723 - t.hour, t.minute, t.second,
241.1724 - t.microsecond, tzinfo=self._tzinfo)
241.1725 - return result
241.1726 -
241.1727 - __radd__ = __add__
241.1728 -
241.1729 - def __sub__(self, other):
241.1730 - "Subtract two datetimes, or a datetime and a timedelta."
241.1731 - if not isinstance(other, datetime):
241.1732 - if isinstance(other, timedelta):
241.1733 - return self + -other
241.1734 - return NotImplemented
241.1735 -
241.1736 - days1 = self.toordinal()
241.1737 - days2 = other.toordinal()
241.1738 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
241.1739 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
241.1740 - base = timedelta(days1 - days2,
241.1741 - secs1 - secs2,
241.1742 - self.__microsecond - other.__microsecond)
241.1743 - if self._tzinfo is other._tzinfo:
241.1744 - return base
241.1745 - myoff = self._utcoffset()
241.1746 - otoff = other._utcoffset()
241.1747 - if myoff == otoff:
241.1748 - return base
241.1749 - if myoff is None or otoff is None:
241.1750 - raise TypeError, "cannot mix naive and timezone-aware time"
241.1751 - return base + timedelta(minutes = otoff-myoff)
241.1752 -
241.1753 - def __hash__(self):
241.1754 - tzoff = self._utcoffset()
241.1755 - if tzoff is None:
241.1756 - return hash(self.__getstate()[0])
241.1757 - days = _ymd2ord(self.year, self.month, self.day)
241.1758 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
241.1759 - return hash(timedelta(days, seconds, self.microsecond))
241.1760 -
241.1761 - # Pickle support.
241.1762 -
241.1763 - __safe_for_unpickling__ = True # For Python 2.2
241.1764 -
241.1765 - def __getstate(self):
241.1766 - yhi, ylo = divmod(self.__year, 256)
241.1767 - us2, us3 = divmod(self.__microsecond, 256)
241.1768 - us1, us2 = divmod(us2, 256)
241.1769 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
241.1770 - self.__hour, self.__minute, self.__second,
241.1771 - us1, us2, us3)
241.1772 - if self._tzinfo is None:
241.1773 - return (basestate,)
241.1774 - else:
241.1775 - return (basestate, self._tzinfo)
241.1776 -
241.1777 - def __setstate(self, state):
241.1778 - assert isinstance(state, tuple)
241.1779 - assert 1 <= len(state) <= 2
241.1780 - string = state[0]
241.1781 - assert len(string) == 10
241.1782 - (yhi, ylo, self.__month, self.__day, self.__hour,
241.1783 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
241.1784 - self.__year = yhi * 256 + ylo
241.1785 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
241.1786 - if len(state) == 1:
241.1787 - self._tzinfo = None
241.1788 - else:
241.1789 - self._tzinfo = state[1]
241.1790 -
241.1791 - def __reduce__(self):
241.1792 - return (self.__class__, self.__getstate())
241.1793 -
241.1794 -
241.1795 -datetime.min = datetime(1, 1, 1)
241.1796 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
241.1797 -datetime.resolution = timedelta(microseconds=1)
241.1798 -
241.1799 -
241.1800 -def _isoweek1monday(year):
241.1801 - # Helper to calculate the day number of the Monday starting week 1
241.1802 - # XXX This could be done more efficiently
241.1803 - THURSDAY = 3
241.1804 - firstday = _ymd2ord(year, 1, 1)
241.1805 - firstweekday = (firstday + 6) % 7 # See weekday() above
241.1806 - week1monday = firstday - firstweekday
241.1807 - if firstweekday > THURSDAY:
241.1808 - week1monday += 7
241.1809 - return week1monday
241.1810 -
241.1811 -"""
241.1812 -Some time zone algebra. For a datetime x, let
241.1813 - x.n = x stripped of its timezone -- its naive time.
241.1814 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
241.1815 - return None
241.1816 - x.d = x.dst(), and assuming that doesn't raise an exception or
241.1817 - return None
241.1818 - x.s = x's standard offset, x.o - x.d
241.1819 -
241.1820 -Now some derived rules, where k is a duration (timedelta).
241.1821 -
241.1822 -1. x.o = x.s + x.d
241.1823 - This follows from the definition of x.s.
241.1824 -
241.1825 -2. If x and y have the same tzinfo member, x.s = y.s.
241.1826 - This is actually a requirement, an assumption we need to make about
241.1827 - sane tzinfo classes.
241.1828 -
241.1829 -3. The naive UTC time corresponding to x is x.n - x.o.
241.1830 - This is again a requirement for a sane tzinfo class.
241.1831 -
241.1832 -4. (x+k).s = x.s
241.1833 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
241.1834 -
241.1835 -5. (x+k).n = x.n + k
241.1836 - Again follows from how arithmetic is defined.
241.1837 -
241.1838 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
241.1839 -(meaning that the various tzinfo methods exist, and don't blow up or return
241.1840 -None when called).
241.1841 -
241.1842 -The function wants to return a datetime y with timezone tz, equivalent to x.
241.1843 -x is already in UTC.
241.1844 -
241.1845 -By #3, we want
241.1846 -
241.1847 - y.n - y.o = x.n [1]
241.1848 -
241.1849 -The algorithm starts by attaching tz to x.n, and calling that y. So
241.1850 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
241.1851 -becomes true; in effect, we want to solve [2] for k:
241.1852 -
241.1853 - (y+k).n - (y+k).o = x.n [2]
241.1854 -
241.1855 -By #1, this is the same as
241.1856 -
241.1857 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
241.1858 -
241.1859 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
241.1860 -Substituting that into [3],
241.1861 -
241.1862 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
241.1863 - k - (y+k).s - (y+k).d = 0; rearranging,
241.1864 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
241.1865 - k = y.s - (y+k).d
241.1866 -
241.1867 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
241.1868 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
241.1869 -very large, since all offset-returning methods return a duration of magnitude
241.1870 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
241.1871 -be 0, so ignoring it has no consequence then.
241.1872 -
241.1873 -In any case, the new value is
241.1874 -
241.1875 - z = y + y.s [4]
241.1876 -
241.1877 -It's helpful to step back at look at [4] from a higher level: it's simply
241.1878 -mapping from UTC to tz's standard time.
241.1879 -
241.1880 -At this point, if
241.1881 -
241.1882 - z.n - z.o = x.n [5]
241.1883 -
241.1884 -we have an equivalent time, and are almost done. The insecurity here is
241.1885 -at the start of daylight time. Picture US Eastern for concreteness. The wall
241.1886 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
241.1887 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
241.1888 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
241.1889 -on the day DST starts. We want to return the 1:MM EST spelling because that's
241.1890 -the only spelling that makes sense on the local wall clock.
241.1891 -
241.1892 -In fact, if [5] holds at this point, we do have the standard-time spelling,
241.1893 -but that takes a bit of proof. We first prove a stronger result. What's the
241.1894 -difference between the LHS and RHS of [5]? Let
241.1895 -
241.1896 - diff = x.n - (z.n - z.o) [6]
241.1897 -
241.1898 -Now
241.1899 - z.n = by [4]
241.1900 - (y + y.s).n = by #5
241.1901 - y.n + y.s = since y.n = x.n
241.1902 - x.n + y.s = since z and y are have the same tzinfo member,
241.1903 - y.s = z.s by #2
241.1904 - x.n + z.s
241.1905 -
241.1906 -Plugging that back into [6] gives
241.1907 -
241.1908 - diff =
241.1909 - x.n - ((x.n + z.s) - z.o) = expanding
241.1910 - x.n - x.n - z.s + z.o = cancelling
241.1911 - - z.s + z.o = by #2
241.1912 - z.d
241.1913 -
241.1914 -So diff = z.d.
241.1915 -
241.1916 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
241.1917 -spelling we wanted in the endcase described above. We're done. Contrarily,
241.1918 -if z.d = 0, then we have a UTC equivalent, and are also done.
241.1919 -
241.1920 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
241.1921 -add to z (in effect, z is in tz's standard time, and we need to shift the
241.1922 -local clock into tz's daylight time).
241.1923 -
241.1924 -Let
241.1925 -
241.1926 - z' = z + z.d = z + diff [7]
241.1927 -
241.1928 -and we can again ask whether
241.1929 -
241.1930 - z'.n - z'.o = x.n [8]
241.1931 -
241.1932 -If so, we're done. If not, the tzinfo class is insane, according to the
241.1933 -assumptions we've made. This also requires a bit of proof. As before, let's
241.1934 -compute the difference between the LHS and RHS of [8] (and skipping some of
241.1935 -the justifications for the kinds of substitutions we've done several times
241.1936 -already):
241.1937 -
241.1938 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
241.1939 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
241.1940 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
241.1941 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
241.1942 - - z.n + z.n - z.o + z'.o = cancel z.n
241.1943 - - z.o + z'.o = #1 twice
241.1944 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
241.1945 - z'.d - z.d
241.1946 -
241.1947 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
241.1948 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
241.1949 -return z', not bothering to compute z'.d.
241.1950 -
241.1951 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
241.1952 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
241.1953 -would have to change the result dst() returns: we start in DST, and moving
241.1954 -a little further into it takes us out of DST.
241.1955 -
241.1956 -There isn't a sane case where this can happen. The closest it gets is at
241.1957 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
241.1958 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
241.1959 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
241.1960 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
241.1961 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
241.1962 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
241.1963 -standard time. Since that's what the local clock *does*, we want to map both
241.1964 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
241.1965 -in local time, but so it goes -- it's the way the local clock works.
241.1966 -
241.1967 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
241.1968 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
241.1969 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
241.1970 -(correctly) concludes that z' is not UTC-equivalent to x.
241.1971 -
241.1972 -Because we know z.d said z was in daylight time (else [5] would have held and
241.1973 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
241.1974 -and we we have stopped then), and there are only 2 possible values dst() can
241.1975 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
241.1976 -but the reasoning doesn't depend on the example -- it depends on there being
241.1977 -two possible dst() outcomes, one zero and the other non-zero). Therefore
241.1978 -z' must be in standard time, and is the spelling we want in this case.
241.1979 -
241.1980 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
241.1981 -concerned (because it takes z' as being in standard time rather than the
241.1982 -daylight time we intend here), but returning it gives the real-life "local
241.1983 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
241.1984 -tz.
241.1985 -
241.1986 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
241.1987 -the 1:MM standard time spelling we want.
241.1988 -
241.1989 -So how can this break? One of the assumptions must be violated. Two
241.1990 -possibilities:
241.1991 -
241.1992 -1) [2] effectively says that y.s is invariant across all y belong to a given
241.1993 - time zone. This isn't true if, for political reasons or continental drift,
241.1994 - a region decides to change its base offset from UTC.
241.1995 -
241.1996 -2) There may be versions of "double daylight" time where the tail end of
241.1997 - the analysis gives up a step too early. I haven't thought about that
241.1998 - enough to say.
241.1999 -
241.2000 -In any case, it's clear that the default fromutc() is strong enough to handle
241.2001 -"almost all" time zones: so long as the standard offset is invariant, it
241.2002 -doesn't matter if daylight time transition points change from year to year, or
241.2003 -if daylight time is skipped in some years; it doesn't matter how large or
241.2004 -small dst() may get within its bounds; and it doesn't even matter if some
241.2005 -perverse time zone returns a negative dst()). So a breaking case must be
241.2006 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
241.2007 -"""
241.2008 -
241.2009 -def _test():
241.2010 - import test_datetime
241.2011 - test_datetime.test_main()
241.2012 -
241.2013 -if __name__ == "__main__":
241.2014 - _test()
242.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
242.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
242.3 @@ -1,2013 +0,0 @@
242.4 -"""Concrete date/time and related types -- prototype implemented in Python.
242.5 -
242.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
242.7 -
242.8 -See also http://dir.yahoo.com/Reference/calendars/
242.9 -
242.10 -For a primer on DST, including many current DST rules, see
242.11 -http://webexhibits.org/daylightsaving/
242.12 -
242.13 -For more about DST than you ever wanted to know, see
242.14 -ftp://elsie.nci.nih.gov/pub/
242.15 -
242.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
242.17 -
242.18 -"""
242.19 -
242.20 -import time as _time
242.21 -import math as _math
242.22 -
242.23 -MINYEAR = 1
242.24 -MAXYEAR = 9999
242.25 -
242.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
242.27 -# also assumes the current Gregorian calendar indefinitely extended in
242.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
242.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
242.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
242.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
242.32 -# for all computations. See the book for algorithms for converting between
242.33 -# proleptic Gregorian ordinals and many other calendar systems.
242.34 -
242.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
242.36 -
242.37 -_DAYS_BEFORE_MONTH = [None]
242.38 -dbm = 0
242.39 -for dim in _DAYS_IN_MONTH[1:]:
242.40 - _DAYS_BEFORE_MONTH.append(dbm)
242.41 - dbm += dim
242.42 -del dbm, dim
242.43 -
242.44 -def _is_leap(year):
242.45 - "year -> 1 if leap year, else 0."
242.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
242.47 -
242.48 -def _days_in_year(year):
242.49 - "year -> number of days in year (366 if a leap year, else 365)."
242.50 - return 365 + _is_leap(year)
242.51 -
242.52 -def _days_before_year(year):
242.53 - "year -> number of days before January 1st of year."
242.54 - y = year - 1
242.55 - return y*365 + y//4 - y//100 + y//400
242.56 -
242.57 -def _days_in_month(year, month):
242.58 - "year, month -> number of days in that month in that year."
242.59 - try:
242.60 - assert 1 <= month <= 12, month
242.61 - if month == 2 and _is_leap(year):
242.62 - return 29
242.63 - except Exception, e:
242.64 - print "Exception: ", e
242.65 - finally:
242.66 -
242.67 - return _DAYS_IN_MONTH[month]
242.68 -
242.69 -def _days_before_month(year, month):
242.70 - "year, month -> number of days in year preceeding first day of month."
242.71 - if not 1 <= month <= 12:
242.72 - raise ValueError('month must be in 1..12', month)
242.73 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
242.74 -
242.75 -def _ymd2ord(year, month, day):
242.76 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
242.77 - if not 1 <= month <= 12:
242.78 - raise ValueError('month must be in 1..12', month)
242.79 - dim = _days_in_month(year, month)
242.80 - if not 1 <= day <= dim:
242.81 - raise ValueError('day must be in 1..%d' % dim, day)
242.82 - return (_days_before_year(year) +
242.83 - _days_before_month(year, month) +
242.84 - day)
242.85 -
242.86 -_DI400Y = _days_before_year(401) # number of days in 400 years
242.87 -_DI100Y = _days_before_year(101) # " " " " 100 "
242.88 -_DI4Y = _days_before_year(5) # " " " " 4 "
242.89 -
242.90 -# A 4-year cycle has an extra leap day over what we'd get from pasting
242.91 -# together 4 single years.
242.92 -assert _DI4Y == 4 * 365 + 1
242.93 -
242.94 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
242.95 -# pasting together 4 100-year cycles.
242.96 -assert _DI400Y == 4 * _DI100Y + 1
242.97 -
242.98 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
242.99 -# pasting together 25 4-year cycles.
242.100 -assert _DI100Y == 25 * _DI4Y - 1
242.101 -
242.102 -def _ord2ymd(n):
242.103 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
242.104 -
242.105 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
242.106 - # repeats exactly every 400 years. The basic strategy is to find the
242.107 - # closest 400-year boundary at or before n, then work with the offset
242.108 - # from that boundary to n. Life is much clearer if we subtract 1 from
242.109 - # n first -- then the values of n at 400-year boundaries are exactly
242.110 - # those divisible by _DI400Y:
242.111 - #
242.112 - # D M Y n n-1
242.113 - # -- --- ---- ---------- ----------------
242.114 - # 31 Dec -400 -_DI400Y -_DI400Y -1
242.115 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
242.116 - # ...
242.117 - # 30 Dec 000 -1 -2
242.118 - # 31 Dec 000 0 -1
242.119 - # 1 Jan 001 1 0 400-year boundary
242.120 - # 2 Jan 001 2 1
242.121 - # 3 Jan 001 3 2
242.122 - # ...
242.123 - # 31 Dec 400 _DI400Y _DI400Y -1
242.124 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
242.125 - n -= 1
242.126 - n400, n = divmod(n, _DI400Y)
242.127 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
242.128 -
242.129 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
242.130 - # the desired date. Now compute how many 100-year cycles precede n.
242.131 - # Note that it's possible for n100 to equal 4! In that case 4 full
242.132 - # 100-year cycles precede the desired day, which implies the desired
242.133 - # day is December 31 at the end of a 400-year cycle.
242.134 - n100, n = divmod(n, _DI100Y)
242.135 -
242.136 - # Now compute how many 4-year cycles precede it.
242.137 - n4, n = divmod(n, _DI4Y)
242.138 -
242.139 - # And now how many single years. Again n1 can be 4, and again meaning
242.140 - # that the desired day is December 31 at the end of the 4-year cycle.
242.141 - n1, n = divmod(n, 365)
242.142 -
242.143 - year += n100 * 100 + n4 * 4 + n1
242.144 - if n1 == 4 or n100 == 4:
242.145 - assert n == 0
242.146 - return year-1, 12, 31
242.147 -
242.148 - # Now the year is correct, and n is the offset from January 1. We find
242.149 - # the month via an estimate that's either exact or one too large.
242.150 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
242.151 - assert leapyear == _is_leap(year)
242.152 - month = (n + 50) >> 5
242.153 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
242.154 - if preceding > n: # estimate is too large
242.155 - month -= 1
242.156 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
242.157 - n -= preceding
242.158 - assert 0 <= n < _days_in_month(year, month)
242.159 -
242.160 - # Now the year and month are correct, and n is the offset from the
242.161 - # start of that month: we're done!
242.162 - return year, month, n+1
242.163 -
242.164 -# Month and day names. For localized versions, see the calendar module.
242.165 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
242.166 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
242.167 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
242.168 -
242.169 -
242.170 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
242.171 - wday = (_ymd2ord(y, m, d) + 6) % 7
242.172 - dnum = _days_before_month(y, m) + d
242.173 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
242.174 -
242.175 -def _format_time(hh, mm, ss, us):
242.176 - # Skip trailing microseconds when us==0.
242.177 - result = "%02d:%02d:%02d" % (hh, mm, ss)
242.178 - if us:
242.179 - result += ".%06d" % us
242.180 - return result
242.181 -
242.182 -# Correctly substitute for %z and %Z escapes in strftime formats.
242.183 -def _wrap_strftime(object, format, timetuple):
242.184 - year = timetuple[0]
242.185 - if year < 1900:
242.186 - raise ValueError("year=%d is before 1900; the datetime strftime() "
242.187 - "methods require year >= 1900" % year)
242.188 - # Don't call _utcoffset() or tzname() unless actually needed.
242.189 - zreplace = None # the string to use for %z
242.190 - Zreplace = None # the string to use for %Z
242.191 -
242.192 - # Scan format for %z and %Z escapes, replacing as needed.
242.193 - newformat = []
242.194 - push = newformat.append
242.195 - i, n = 0, len(format)
242.196 - while i < n:
242.197 - ch = format[i]
242.198 - i += 1
242.199 - if ch == '%':
242.200 - if i < n:
242.201 - ch = format[i]
242.202 - i += 1
242.203 - if ch == 'z':
242.204 - if zreplace is None:
242.205 - zreplace = ""
242.206 - if hasattr(object, "_utcoffset"):
242.207 - offset = object._utcoffset()
242.208 - if offset is not None:
242.209 - sign = '+'
242.210 - if offset < 0:
242.211 - offset = -offset
242.212 - sign = '-'
242.213 - h, m = divmod(offset, 60)
242.214 - zreplace = '%c%02d%02d' % (sign, h, m)
242.215 - assert '%' not in zreplace
242.216 - newformat.append(zreplace)
242.217 - elif ch == 'Z':
242.218 - if Zreplace is None:
242.219 - Zreplace = ""
242.220 - if hasattr(object, "tzname"):
242.221 - s = object.tzname()
242.222 - if s is not None:
242.223 - # strftime is going to have at this: escape %
242.224 - Zreplace = s.replace('%', '%%')
242.225 - newformat.append(Zreplace)
242.226 - else:
242.227 - push('%')
242.228 - push(ch)
242.229 - else:
242.230 - push('%')
242.231 - else:
242.232 - push(ch)
242.233 - newformat = "".join(newformat)
242.234 - return _time.strftime(newformat, timetuple)
242.235 -
242.236 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
242.237 - if tzinfo is None:
242.238 - return None
242.239 - return getattr(tzinfo, methname)(tzinfoarg)
242.240 -
242.241 -# Just raise TypeError if the arg isn't None or a string.
242.242 -def _check_tzname(name):
242.243 - if name is not None and not isinstance(name, str):
242.244 - raise TypeError("tzinfo.tzname() must return None or string, "
242.245 - "not '%s'" % type(name))
242.246 -
242.247 -# name is the offset-producing method, "utcoffset" or "dst".
242.248 -# offset is what it returned.
242.249 -# If offset isn't None or timedelta, raises TypeError.
242.250 -# If offset is None, returns None.
242.251 -# Else offset is checked for being in range, and a whole # of minutes.
242.252 -# If it is, its integer value is returned. Else ValueError is raised.
242.253 -def _check_utc_offset(name, offset):
242.254 - assert name in ("utcoffset", "dst")
242.255 - if offset is None:
242.256 - return None
242.257 - if not isinstance(offset, timedelta):
242.258 - raise TypeError("tzinfo.%s() must return None "
242.259 - "or timedelta, not '%s'" % (name, type(offset)))
242.260 - days = offset.days
242.261 - if days < -1 or days > 0:
242.262 - offset = 1440 # trigger out-of-range
242.263 - else:
242.264 - seconds = days * 86400 + offset.seconds
242.265 - minutes, seconds = divmod(seconds, 60)
242.266 - if seconds or offset.microseconds:
242.267 - raise ValueError("tzinfo.%s() must return a whole number "
242.268 - "of minutes" % name)
242.269 - offset = minutes
242.270 - if -1440 < offset < 1440:
242.271 - return offset
242.272 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
242.273 -
242.274 -def _check_date_fields(year, month, day):
242.275 - if not MINYEAR <= year <= MAXYEAR:
242.276 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
242.277 - if not 1 <= month <= 12:
242.278 - raise ValueError('month must be in 1..12', month)
242.279 - dim = _days_in_month(year, month)
242.280 - if not 1 <= day <= dim:
242.281 - raise ValueError('day must be in 1..%d' % dim, day)
242.282 -
242.283 -def _check_time_fields(hour, minute, second, microsecond):
242.284 - if not 0 <= hour <= 23:
242.285 - raise ValueError('hour must be in 0..23', hour)
242.286 - if not 0 <= minute <= 59:
242.287 - raise ValueError('minute must be in 0..59', minute)
242.288 - if not 0 <= second <= 59:
242.289 - raise ValueError('second must be in 0..59', second)
242.290 - if not 0 <= microsecond <= 999999:
242.291 - raise ValueError('microsecond must be in 0..999999', microsecond)
242.292 -
242.293 -def _check_tzinfo_arg(tz):
242.294 - if tz is not None and not isinstance(tz, tzinfo):
242.295 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
242.296 -
242.297 -
242.298 -# Notes on comparison: In general, datetime module comparison operators raise
242.299 -# TypeError when they don't know how to do a comparison themself. If they
242.300 -# returned NotImplemented instead, comparison could (silently) fall back to
242.301 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
242.302 -# and that's not helpful. There are two exceptions:
242.303 -#
242.304 -# 1. For date and datetime, if the other object has a "timetuple" attr,
242.305 -# NotImplemented is returned. This is a hook to allow other kinds of
242.306 -# datetime-like objects a chance to intercept the comparison.
242.307 -#
242.308 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
242.309 -# so opertaions like
242.310 -#
242.311 -# x == y
242.312 -# x != y
242.313 -# x in sequence
242.314 -# x not in sequence
242.315 -# dict[x] = y
242.316 -#
242.317 -# don't raise annoying TypeErrors just because a datetime object
242.318 -# is part of a heterogeneous collection. If there's no known way to
242.319 -# compare X to a datetime, saying they're not equal is reasonable.
242.320 -
242.321 -def _cmperror(x, y):
242.322 - raise TypeError("can't compare '%s' to '%s'" % (
242.323 - type(x).__name__, type(y).__name__))
242.324 -
242.325 -# This is a start at a struct tm workalike. Goals:
242.326 -#
242.327 -# + Works the same way across platforms.
242.328 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
242.329 -#
242.330 -# Note: I suspect it's best if this flavor of tm does *not* try to
242.331 -# second-guess timezones or DST. Instead fold whatever adjustments you want
242.332 -# into the minutes argument (and the constructor will normalize).
242.333 -
242.334 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
242.335 -
242.336 -class tmxxx:
242.337 -
242.338 - ordinal = None
242.339 -
242.340 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
242.341 - microsecond=0):
242.342 - # Normalize all the inputs, and store the normalized values.
242.343 - if not 0 <= microsecond <= 999999:
242.344 - carry, microsecond = divmod(microsecond, 1000000)
242.345 - second += carry
242.346 - if not 0 <= second <= 59:
242.347 - carry, second = divmod(second, 60)
242.348 - minute += carry
242.349 - if not 0 <= minute <= 59:
242.350 - carry, minute = divmod(minute, 60)
242.351 - hour += carry
242.352 - if not 0 <= hour <= 23:
242.353 - carry, hour = divmod(hour, 24)
242.354 - day += carry
242.355 -
242.356 - # That was easy. Now it gets muddy: the proper range for day
242.357 - # can't be determined without knowing the correct month and year,
242.358 - # but if day is, e.g., plus or minus a million, the current month
242.359 - # and year values make no sense (and may also be out of bounds
242.360 - # themselves).
242.361 - # Saying 12 months == 1 year should be non-controversial.
242.362 - if not 1 <= month <= 12:
242.363 - carry, month = divmod(month-1, 12)
242.364 - year += carry
242.365 - month += 1
242.366 - assert 1 <= month <= 12
242.367 -
242.368 - # Now only day can be out of bounds (year may also be out of bounds
242.369 - # for a datetime object, but we don't care about that here).
242.370 - # If day is out of bounds, what to do is arguable, but at least the
242.371 - # method here is principled and explainable.
242.372 - dim = _days_in_month(year, month)
242.373 - if not 1 <= day <= dim:
242.374 - # Move day-1 days from the first of the month. First try to
242.375 - # get off cheap if we're only one day out of range (adjustments
242.376 - # for timezone alone can't be worse than that).
242.377 - if day == 0: # move back a day
242.378 - month -= 1
242.379 - if month > 0:
242.380 - day = _days_in_month(year, month)
242.381 - else:
242.382 - year, month, day = year-1, 12, 31
242.383 - elif day == dim + 1: # move forward a day
242.384 - month += 1
242.385 - day = 1
242.386 - if month > 12:
242.387 - month = 1
242.388 - year += 1
242.389 - else:
242.390 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
242.391 - year, month, day = _ord2ymd(self.ordinal)
242.392 -
242.393 - self.year, self.month, self.day = year, month, day
242.394 - self.hour, self.minute, self.second = hour, minute, second
242.395 - self.microsecond = microsecond
242.396 -
242.397 - def toordinal(self):
242.398 - """Return proleptic Gregorian ordinal for the year, month and day.
242.399 -
242.400 - January 1 of year 1 is day 1. Only the year, month and day values
242.401 - contribute to the result.
242.402 - """
242.403 - if self.ordinal is None:
242.404 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
242.405 - return self.ordinal
242.406 -
242.407 - def time(self):
242.408 - "Return Unixish timestamp, as a float (assuming UTC)."
242.409 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
242.410 - seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
242.411 - return seconds + self.second + self.microsecond / 1e6
242.412 -
242.413 - def ctime(self):
242.414 - "Return ctime() style string."
242.415 - weekday = self.toordinal() % 7 or 7
242.416 - return "%s %s %2d %02d:%02d:%02d %04d" % (
242.417 - _DAYNAMES[weekday],
242.418 - _MONTHNAMES[self.month],
242.419 - self.day,
242.420 - self.hour, self.minute, self.second,
242.421 - self.year)
242.422 -
242.423 -class timedelta(object):
242.424 - """Represent the difference between two datetime objects.
242.425 -
242.426 - Supported operators:
242.427 -
242.428 - - add, subtract timedelta
242.429 - - unary plus, minus, abs
242.430 - - compare to timedelta
242.431 - - multiply, divide by int/long
242.432 -
242.433 - In addition, datetime supports subtraction of two datetime objects
242.434 - returning a timedelta, and addition or subtraction of a datetime
242.435 - and a timedelta giving a datetime.
242.436 -
242.437 - Representation: (days, seconds, microseconds). Why? Because I
242.438 - felt like it.
242.439 - """
242.440 -
242.441 - def __new__(cls, days=0, seconds=0, microseconds=0,
242.442 - # XXX The following should only be used as keyword args:
242.443 - milliseconds=0, minutes=0, hours=0, weeks=0):
242.444 - # Doing this efficiently and accurately in C is going to be difficult
242.445 - # and error-prone, due to ubiquitous overflow possibilities, and that
242.446 - # C double doesn't have enough bits of precision to represent
242.447 - # microseconds over 10K years faithfully. The code here tries to make
242.448 - # explicit where go-fast assumptions can be relied on, in order to
242.449 - # guide the C implementation; it's way more convoluted than speed-
242.450 - # ignoring auto-overflow-to-long idiomatic Python could be.
242.451 -
242.452 - # XXX Check that all inputs are ints, longs or floats.
242.453 -
242.454 - # Final values, all integer.
242.455 - # s and us fit in 32-bit signed ints; d isn't bounded.
242.456 - d = s = us = 0
242.457 -
242.458 - # Normalize everything to days, seconds, microseconds.
242.459 - days += weeks*7
242.460 - seconds += minutes*60 + hours*3600
242.461 - microseconds += milliseconds*1000
242.462 -
242.463 - # Get rid of all fractions, and normalize s and us.
242.464 - # Take a deep breath <wink>.
242.465 - if isinstance(days, float):
242.466 - dayfrac, days = _math.modf(days)
242.467 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
242.468 - assert daysecondswhole == int(daysecondswhole) # can't overflow
242.469 - s = int(daysecondswhole)
242.470 - assert days == long(days)
242.471 - d = long(days)
242.472 - else:
242.473 - daysecondsfrac = 0.0
242.474 - d = days
242.475 - assert isinstance(daysecondsfrac, float)
242.476 - assert abs(daysecondsfrac) <= 1.0
242.477 - assert isinstance(d, (int, long))
242.478 - assert abs(s) <= 24 * 3600
242.479 - # days isn't referenced again before redefinition
242.480 -
242.481 - if isinstance(seconds, float):
242.482 - secondsfrac, seconds = _math.modf(seconds)
242.483 - assert seconds == long(seconds)
242.484 - seconds = long(seconds)
242.485 - secondsfrac += daysecondsfrac
242.486 - assert abs(secondsfrac) <= 2.0
242.487 - else:
242.488 - secondsfrac = daysecondsfrac
242.489 - # daysecondsfrac isn't referenced again
242.490 - assert isinstance(secondsfrac, float)
242.491 - assert abs(secondsfrac) <= 2.0
242.492 -
242.493 - assert isinstance(seconds, (int, long))
242.494 - days, seconds = divmod(seconds, 24*3600)
242.495 - d += days
242.496 - s += int(seconds) # can't overflow
242.497 - assert isinstance(s, int)
242.498 - assert abs(s) <= 2 * 24 * 3600
242.499 - # seconds isn't referenced again before redefinition
242.500 -
242.501 - usdouble = secondsfrac * 1e6
242.502 - assert abs(usdouble) < 2.1e6 # exact value not critical
242.503 - # secondsfrac isn't referenced again
242.504 -
242.505 - if isinstance(microseconds, float):
242.506 - microseconds += usdouble
242.507 - microseconds = round(microseconds)
242.508 - seconds, microseconds = divmod(microseconds, 1e6)
242.509 - assert microseconds == int(microseconds)
242.510 - assert seconds == long(seconds)
242.511 - days, seconds = divmod(seconds, 24.*3600.)
242.512 - assert days == long(days)
242.513 - assert seconds == int(seconds)
242.514 - d += long(days)
242.515 - s += int(seconds) # can't overflow
242.516 - assert isinstance(s, int)
242.517 - assert abs(s) <= 3 * 24 * 3600
242.518 - else:
242.519 - seconds, microseconds = divmod(microseconds, 1000000)
242.520 - days, seconds = divmod(seconds, 24*3600)
242.521 - d += days
242.522 - s += int(seconds) # can't overflow
242.523 - assert isinstance(s, int)
242.524 - assert abs(s) <= 3 * 24 * 3600
242.525 - microseconds = float(microseconds)
242.526 - microseconds += usdouble
242.527 - microseconds = round(microseconds)
242.528 - assert abs(s) <= 3 * 24 * 3600
242.529 - assert abs(microseconds) < 3.1e6
242.530 -
242.531 - # Just a little bit of carrying possible for microseconds and seconds.
242.532 - assert isinstance(microseconds, float)
242.533 - assert int(microseconds) == microseconds
242.534 - us = int(microseconds)
242.535 - seconds, us = divmod(us, 1000000)
242.536 - s += seconds # cant't overflow
242.537 - assert isinstance(s, int)
242.538 - days, s = divmod(s, 24*3600)
242.539 - d += days
242.540 -
242.541 - assert isinstance(d, (int, long))
242.542 - assert isinstance(s, int) and 0 <= s < 24*3600
242.543 - assert isinstance(us, int) and 0 <= us < 1000000
242.544 -
242.545 - self = object.__new__(cls)
242.546 -
242.547 - self.__days = d
242.548 - self.__seconds = s
242.549 - self.__microseconds = us
242.550 - if abs(d) > 999999999:
242.551 - raise OverflowError("timedelta # of days is too large: %d" % d)
242.552 -
242.553 - return self
242.554 -
242.555 - def __repr__(self):
242.556 - if self.__microseconds:
242.557 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
242.558 - self.__days,
242.559 - self.__seconds,
242.560 - self.__microseconds)
242.561 - if self.__seconds:
242.562 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
242.563 - self.__days,
242.564 - self.__seconds)
242.565 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
242.566 -
242.567 - def __str__(self):
242.568 - mm, ss = divmod(self.__seconds, 60)
242.569 - hh, mm = divmod(mm, 60)
242.570 - s = "%d:%02d:%02d" % (hh, mm, ss)
242.571 - if self.__days:
242.572 - def plural(n):
242.573 - return n, abs(n) != 1 and "s" or ""
242.574 - s = ("%d day%s, " % plural(self.__days)) + s
242.575 - if self.__microseconds:
242.576 - s = s + ".%06d" % self.__microseconds
242.577 - return s
242.578 -
242.579 - days = property(lambda self: self.__days, doc="days")
242.580 - seconds = property(lambda self: self.__seconds, doc="seconds")
242.581 - microseconds = property(lambda self: self.__microseconds,
242.582 - doc="microseconds")
242.583 -
242.584 - def __add__(self, other):
242.585 - if isinstance(other, timedelta):
242.586 - return timedelta(self.__days + other.__days,
242.587 - self.__seconds + other.__seconds,
242.588 - self.__microseconds + other.__microseconds)
242.589 - return NotImplemented
242.590 -
242.591 - __radd__ = __add__
242.592 -
242.593 - def __sub__(self, other):
242.594 - if isinstance(other, timedelta):
242.595 - return self + -other
242.596 - return NotImplemented
242.597 -
242.598 - def __rsub__(self, other):
242.599 - if isinstance(other, timedelta):
242.600 - return -self + other
242.601 - return NotImplemented
242.602 -
242.603 - def __neg__(self):
242.604 - return self.__class__(-self.__days,
242.605 - -self.__seconds,
242.606 - -self.__microseconds)
242.607 -
242.608 - def __pos__(self):
242.609 - return self
242.610 -
242.611 - def __abs__(self):
242.612 - if self.__days < 0:
242.613 - return -self
242.614 - else:
242.615 - return self
242.616 -
242.617 - def __mul__(self, other):
242.618 - if isinstance(other, (int, long)):
242.619 - return self.__class__(self.__days * other,
242.620 - self.__seconds * other,
242.621 - self.__microseconds * other)
242.622 - return NotImplemented
242.623 -
242.624 - __rmul__ = __mul__
242.625 -
242.626 - def __div__(self, other):
242.627 - if isinstance(other, (int, long)):
242.628 - usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
242.629 - self.__microseconds)
242.630 - return self.__class__(0, 0, usec // other)
242.631 - return NotImplemented
242.632 -
242.633 - __floordiv__ = __div__
242.634 -
242.635 - # Comparisons.
242.636 -
242.637 - def __eq__(self, other):
242.638 - if isinstance(other, timedelta):
242.639 - return self.__cmp(other) == 0
242.640 - else:
242.641 - return False
242.642 -
242.643 - def __ne__(self, other):
242.644 - if isinstance(other, timedelta):
242.645 - return self.__cmp(other) != 0
242.646 - else:
242.647 - return True
242.648 -
242.649 - def __le__(self, other):
242.650 - if isinstance(other, timedelta):
242.651 - return self.__cmp(other) <= 0
242.652 - else:
242.653 - _cmperror(self, other)
242.654 -
242.655 - def __lt__(self, other):
242.656 - if isinstance(other, timedelta):
242.657 - return self.__cmp(other) < 0
242.658 - else:
242.659 - _cmperror(self, other)
242.660 -
242.661 - def __ge__(self, other):
242.662 - if isinstance(other, timedelta):
242.663 - return self.__cmp(other) >= 0
242.664 - else:
242.665 - _cmperror(self, other)
242.666 -
242.667 - def __gt__(self, other):
242.668 - if isinstance(other, timedelta):
242.669 - return self.__cmp(other) > 0
242.670 - else:
242.671 - _cmperror(self, other)
242.672 -
242.673 - def __cmp(self, other):
242.674 - assert isinstance(other, timedelta)
242.675 - return cmp(self.__getstate(), other.__getstate())
242.676 -
242.677 - def __hash__(self):
242.678 - return hash(self.__getstate())
242.679 -
242.680 - def __nonzero__(self):
242.681 - return (self.__days != 0 or
242.682 - self.__seconds != 0 or
242.683 - self.__microseconds != 0)
242.684 -
242.685 - # Pickle support.
242.686 -
242.687 - __safe_for_unpickling__ = True # For Python 2.2
242.688 -
242.689 - def __getstate(self):
242.690 - return (self.__days, self.__seconds, self.__microseconds)
242.691 -
242.692 - def __reduce__(self):
242.693 - return (self.__class__, self.__getstate())
242.694 -
242.695 -timedelta.min = timedelta(-999999999)
242.696 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
242.697 - microseconds=999999)
242.698 -timedelta.resolution = timedelta(microseconds=1)
242.699 -
242.700 -class date(object):
242.701 - """Concrete date type.
242.702 -
242.703 - Constructors:
242.704 -
242.705 - __new__()
242.706 - fromtimestamp()
242.707 - today()
242.708 - fromordinal()
242.709 -
242.710 - Operators:
242.711 -
242.712 - __repr__, __str__
242.713 - __cmp__, __hash__
242.714 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
242.715 -
242.716 - Methods:
242.717 -
242.718 - timetuple()
242.719 - toordinal()
242.720 - weekday()
242.721 - isoweekday(), isocalendar(), isoformat()
242.722 - ctime()
242.723 - strftime()
242.724 -
242.725 - Properties (readonly):
242.726 - year, month, day
242.727 - """
242.728 -
242.729 - def __new__(cls, year, month=None, day=None):
242.730 - """Constructor.
242.731 -
242.732 - Arguments:
242.733 -
242.734 - year, month, day (required, base 1)
242.735 - """
242.736 - if isinstance(year, str):
242.737 - # Pickle support
242.738 - self = object.__new__(cls)
242.739 - self.__setstate((year,))
242.740 - return self
242.741 - _check_date_fields(year, month, day)
242.742 - self = object.__new__(cls)
242.743 - self.__year = year
242.744 - self.__month = month
242.745 - self.__day = day
242.746 - return self
242.747 -
242.748 - # Additional constructors
242.749 -
242.750 - def fromtimestamp(cls, t):
242.751 - "Construct a date from a POSIX timestamp (like time.time())."
242.752 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
242.753 - return cls(y, m, d)
242.754 - fromtimestamp = classmethod(fromtimestamp)
242.755 -
242.756 - def today(cls):
242.757 - "Construct a date from time.time()."
242.758 - t = _time.time()
242.759 - return cls.fromtimestamp(t)
242.760 - today = classmethod(today)
242.761 -
242.762 - def fromordinal(cls, n):
242.763 - """Contruct a date from a proleptic Gregorian ordinal.
242.764 -
242.765 - January 1 of year 1 is day 1. Only the year, month and day are
242.766 - non-zero in the result.
242.767 - """
242.768 - y, m, d = _ord2ymd(n)
242.769 - return cls(y, m, d)
242.770 - fromordinal = classmethod(fromordinal)
242.771 -
242.772 - # Conversions to string
242.773 -
242.774 - def __repr__(self):
242.775 - "Convert to formal string, for repr()."
242.776 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
242.777 - self.__year,
242.778 - self.__month,
242.779 - self.__day)
242.780 - # XXX These shouldn't depend on time.localtime(), because that
242.781 - # clips the usable dates to [1970 .. 2038). At least ctime() is
242.782 - # easily done without using strftime() -- that's better too because
242.783 - # strftime("%c", ...) is locale specific.
242.784 -
242.785 - def ctime(self):
242.786 - "Format a la ctime()."
242.787 - return tmxxx(self.__year, self.__month, self.__day).ctime()
242.788 -
242.789 - def strftime(self, fmt):
242.790 - "Format using strftime()."
242.791 - return _wrap_strftime(self, fmt, self.timetuple())
242.792 -
242.793 - def isoformat(self):
242.794 - """Return the date formatted according to ISO.
242.795 -
242.796 - This is 'YYYY-MM-DD'.
242.797 -
242.798 - References:
242.799 - - http://www.w3.org/TR/NOTE-datetime
242.800 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
242.801 - """
242.802 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
242.803 -
242.804 - __str__ = isoformat
242.805 -
242.806 - # Read-only field accessors
242.807 - year = property(lambda self: self.__year,
242.808 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
242.809 - month = property(lambda self: self.__month, doc="month (1-12)")
242.810 - day = property(lambda self: self.__day, doc="day (1-31)")
242.811 -
242.812 - # Standard conversions, __cmp__, __hash__ (and helpers)
242.813 -
242.814 - def timetuple(self):
242.815 - "Return local time tuple compatible with time.localtime()."
242.816 - return _build_struct_time(self.__year, self.__month, self.__day,
242.817 - 0, 0, 0, -1)
242.818 -
242.819 - def toordinal(self):
242.820 - """Return proleptic Gregorian ordinal for the year, month and day.
242.821 -
242.822 - January 1 of year 1 is day 1. Only the year, month and day values
242.823 - contribute to the result.
242.824 - """
242.825 - return _ymd2ord(self.__year, self.__month, self.__day)
242.826 -
242.827 - def replace(self, year=None, month=None, day=None):
242.828 - """Return a new date with new values for the specified fields."""
242.829 - if year is None:
242.830 - year = self.__year
242.831 - if month is None:
242.832 - month = self.__month
242.833 - if day is None:
242.834 - day = self.__day
242.835 - _check_date_fields(year, month, day)
242.836 - return date(year, month, day)
242.837 -
242.838 - # Comparisons.
242.839 -
242.840 - def __eq__(self, other):
242.841 - if isinstance(other, date):
242.842 - return self.__cmp(other) == 0
242.843 - elif hasattr(other, "timetuple"):
242.844 - return NotImplemented
242.845 - else:
242.846 - return False
242.847 -
242.848 - def __ne__(self, other):
242.849 - if isinstance(other, date):
242.850 - return self.__cmp(other) != 0
242.851 - elif hasattr(other, "timetuple"):
242.852 - return NotImplemented
242.853 - else:
242.854 - return True
242.855 -
242.856 - def __le__(self, other):
242.857 - if isinstance(other, date):
242.858 - return self.__cmp(other) <= 0
242.859 - elif hasattr(other, "timetuple"):
242.860 - return NotImplemented
242.861 - else:
242.862 - _cmperror(self, other)
242.863 -
242.864 - def __lt__(self, other):
242.865 - if isinstance(other, date):
242.866 - return self.__cmp(other) < 0
242.867 - elif hasattr(other, "timetuple"):
242.868 - return NotImplemented
242.869 - else:
242.870 - _cmperror(self, other)
242.871 -
242.872 - def __ge__(self, other):
242.873 - if isinstance(other, date):
242.874 - return self.__cmp(other) >= 0
242.875 - elif hasattr(other, "timetuple"):
242.876 - return NotImplemented
242.877 - else:
242.878 - _cmperror(self, other)
242.879 -
242.880 - def __gt__(self, other):
242.881 - if isinstance(other, date):
242.882 - return self.__cmp(other) > 0
242.883 - elif hasattr(other, "timetuple"):
242.884 - return NotImplemented
242.885 - else:
242.886 - _cmperror(self, other)
242.887 -
242.888 - def __cmp(self, other):
242.889 - assert isinstance(other, date)
242.890 - y, m, d = self.__year, self.__month, self.__day
242.891 - y2, m2, d2 = other.__year, other.__month, other.__day
242.892 - return cmp((y, m, d), (y2, m2, d2))
242.893 -
242.894 - def __hash__(self):
242.895 - "Hash."
242.896 - return hash(self.__getstate())
242.897 -
242.898 - # Computations
242.899 -
242.900 - def _checkOverflow(self, year):
242.901 - if not MINYEAR <= year <= MAXYEAR:
242.902 - raise OverflowError("date +/-: result year %d not in %d..%d" %
242.903 - (year, MINYEAR, MAXYEAR))
242.904 -
242.905 - def __add__(self, other):
242.906 - "Add a date to a timedelta."
242.907 - if isinstance(other, timedelta):
242.908 - t = tmxxx(self.__year,
242.909 - self.__month,
242.910 - self.__day + other.days)
242.911 - self._checkOverflow(t.year)
242.912 - result = self.__class__(t.year, t.month, t.day)
242.913 - return result
242.914 - return NotImplemented
242.915 -
242.916 - __radd__ = __add__
242.917 -
242.918 - def __sub__(self, other):
242.919 - """Subtract two dates, or a date and a timedelta."""
242.920 - if isinstance(other, timedelta):
242.921 - return self + timedelta(-other.days)
242.922 - if isinstance(other, date):
242.923 - days1 = self.toordinal()
242.924 - days2 = other.toordinal()
242.925 - return timedelta(days1 - days2)
242.926 - return NotImplemented
242.927 -
242.928 - def weekday(self):
242.929 - "Return day of the week, where Monday == 0 ... Sunday == 6."
242.930 - return (self.toordinal() + 6) % 7
242.931 -
242.932 - # Day-of-the-week and week-of-the-year, according to ISO
242.933 -
242.934 - def isoweekday(self):
242.935 - "Return day of the week, where Monday == 1 ... Sunday == 7."
242.936 - # 1-Jan-0001 is a Monday
242.937 - return self.toordinal() % 7 or 7
242.938 -
242.939 - def isocalendar(self):
242.940 - """Return a 3-tuple containing ISO year, week number, and weekday.
242.941 -
242.942 - The first ISO week of the year is the (Mon-Sun) week
242.943 - containing the year's first Thursday; everything else derives
242.944 - from that.
242.945 -
242.946 - The first week is 1; Monday is 1 ... Sunday is 7.
242.947 -
242.948 - ISO calendar algorithm taken from
242.949 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
242.950 - """
242.951 - year = self.__year
242.952 - week1monday = _isoweek1monday(year)
242.953 - today = _ymd2ord(self.__year, self.__month, self.__day)
242.954 - # Internally, week and day have origin 0
242.955 - week, day = divmod(today - week1monday, 7)
242.956 - if week < 0:
242.957 - year -= 1
242.958 - week1monday = _isoweek1monday(year)
242.959 - week, day = divmod(today - week1monday, 7)
242.960 - elif week >= 52:
242.961 - if today >= _isoweek1monday(year+1):
242.962 - year += 1
242.963 - week = 0
242.964 - return year, week+1, day+1
242.965 -
242.966 - # Pickle support.
242.967 -
242.968 - __safe_for_unpickling__ = True # For Python 2.2
242.969 -
242.970 - def __getstate(self):
242.971 - yhi, ylo = divmod(self.__year, 256)
242.972 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
242.973 -
242.974 - def __setstate(self, t):
242.975 - assert isinstance(t, tuple) and len(t) == 1, `t`
242.976 - string = t[0]
242.977 - assert len(string) == 4
242.978 - yhi, ylo, self.__month, self.__day = map(ord, string)
242.979 - self.__year = yhi * 256 + ylo
242.980 -
242.981 - def __reduce__(self):
242.982 - return (self.__class__, self.__getstate())
242.983 -
242.984 -_date_class = date # so functions w/ args named "date" can get at the class
242.985 -
242.986 -date.min = date(1, 1, 1)
242.987 -date.max = date(9999, 12, 31)
242.988 -date.resolution = timedelta(days=1)
242.989 -
242.990 -class tzinfo(object):
242.991 - """Abstract base class for time zone info classes.
242.992 -
242.993 - Subclasses must override the name(), utcoffset() and dst() methods.
242.994 - """
242.995 -
242.996 - def tzname(self, dt):
242.997 - "datetime -> string name of time zone."
242.998 - raise NotImplementedError("tzinfo subclass must override tzname()")
242.999 -
242.1000 - def utcoffset(self, dt):
242.1001 - "datetime -> minutes east of UTC (negative for west of UTC)"
242.1002 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
242.1003 -
242.1004 - def dst(self, dt):
242.1005 - """datetime -> DST offset in minutes east of UTC.
242.1006 -
242.1007 - Return 0 if DST not in effect. utcoffset() must include the DST
242.1008 - offset.
242.1009 - """
242.1010 - raise NotImplementedError("tzinfo subclass must override dst()")
242.1011 -
242.1012 - def fromutc(self, dt):
242.1013 - "datetime in UTC -> datetime in local time."
242.1014 -
242.1015 - if not isinstance(dt, datetime):
242.1016 - raise TypeError("fromutc() requires a datetime argument")
242.1017 - if dt.tzinfo is not self:
242.1018 - raise ValueError("dt.tzinfo is not self")
242.1019 -
242.1020 - dtoff = dt.utcoffset()
242.1021 - if dtoff is None:
242.1022 - raise ValueError("fromutc() requires a non-None utcoffset() "
242.1023 - "result")
242.1024 -
242.1025 - # See the long comment block at the end of this file for an
242.1026 - # explanation of this algorithm.
242.1027 - dtdst = dt.dst()
242.1028 - if dtdst is None:
242.1029 - raise ValueError("fromutc() requires a non-None dst() result")
242.1030 - delta = dtoff - dtdst
242.1031 - if delta:
242.1032 - dt += delta
242.1033 - dtdst = dt.dst()
242.1034 - if dtdst is None:
242.1035 - raise ValueError("fromutc(): dt.dst gave inconsistent "
242.1036 - "results; cannot convert")
242.1037 - if dtdst:
242.1038 - return dt + dtdst
242.1039 - else:
242.1040 - return dt
242.1041 -
242.1042 - # Pickle support.
242.1043 -
242.1044 - __safe_for_unpickling__ = True # For Python 2.2
242.1045 -
242.1046 - def __reduce__(self):
242.1047 - getinitargs = getattr(self, "__getinitargs__", None)
242.1048 - if getinitargs:
242.1049 - args = getinitargs()
242.1050 - else:
242.1051 - args = ()
242.1052 - getstate = getattr(self, "__getstate__", None)
242.1053 - if getstate:
242.1054 - state = getstate()
242.1055 - else:
242.1056 - state = getattr(self, "__dict__", None) or None
242.1057 - if state is None:
242.1058 - return (self.__class__, args)
242.1059 - else:
242.1060 - return (self.__class__, args, state)
242.1061 -
242.1062 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
242.1063 -
242.1064 -class time(object):
242.1065 - """Time with time zone.
242.1066 -
242.1067 - Constructors:
242.1068 -
242.1069 - __new__()
242.1070 -
242.1071 - Operators:
242.1072 -
242.1073 - __repr__, __str__
242.1074 - __cmp__, __hash__
242.1075 -
242.1076 - Methods:
242.1077 -
242.1078 - strftime()
242.1079 - isoformat()
242.1080 - utcoffset()
242.1081 - tzname()
242.1082 - dst()
242.1083 -
242.1084 - Properties (readonly):
242.1085 - hour, minute, second, microsecond, tzinfo
242.1086 - """
242.1087 -
242.1088 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
242.1089 - """Constructor.
242.1090 -
242.1091 - Arguments:
242.1092 -
242.1093 - hour, minute (required)
242.1094 - second, microsecond (default to zero)
242.1095 - tzinfo (default to None)
242.1096 - """
242.1097 - self = object.__new__(cls)
242.1098 - if isinstance(hour, str):
242.1099 - # Pickle support
242.1100 - self.__setstate((hour, minute or None))
242.1101 - return self
242.1102 - _check_tzinfo_arg(tzinfo)
242.1103 - _check_time_fields(hour, minute, second, microsecond)
242.1104 - self.__hour = hour
242.1105 - self.__minute = minute
242.1106 - self.__second = second
242.1107 - self.__microsecond = microsecond
242.1108 - self._tzinfo = tzinfo
242.1109 - return self
242.1110 -
242.1111 - # Read-only field accessors
242.1112 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
242.1113 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
242.1114 - second = property(lambda self: self.__second, doc="second (0-59)")
242.1115 - microsecond = property(lambda self: self.__microsecond,
242.1116 - doc="microsecond (0-999999)")
242.1117 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
242.1118 -
242.1119 - # Standard conversions, __hash__ (and helpers)
242.1120 -
242.1121 - # Comparisons.
242.1122 -
242.1123 - def __eq__(self, other):
242.1124 - if isinstance(other, time):
242.1125 - return self.__cmp(other) == 0
242.1126 - else:
242.1127 - return False
242.1128 -
242.1129 - def __ne__(self, other):
242.1130 - if isinstance(other, time):
242.1131 - return self.__cmp(other) != 0
242.1132 - else:
242.1133 - return True
242.1134 -
242.1135 - def __le__(self, other):
242.1136 - if isinstance(other, time):
242.1137 - return self.__cmp(other) <= 0
242.1138 - else:
242.1139 - _cmperror(self, other)
242.1140 -
242.1141 - def __lt__(self, other):
242.1142 - if isinstance(other, time):
242.1143 - return self.__cmp(other) < 0
242.1144 - else:
242.1145 - _cmperror(self, other)
242.1146 -
242.1147 - def __ge__(self, other):
242.1148 - if isinstance(other, time):
242.1149 - return self.__cmp(other) >= 0
242.1150 - else:
242.1151 - _cmperror(self, other)
242.1152 -
242.1153 - def __gt__(self, other):
242.1154 - if isinstance(other, time):
242.1155 - return self.__cmp(other) > 0
242.1156 - else:
242.1157 - _cmperror(self, other)
242.1158 -
242.1159 - def __cmp(self, other):
242.1160 - assert isinstance(other, time)
242.1161 - mytz = self._tzinfo
242.1162 - ottz = other._tzinfo
242.1163 - myoff = otoff = None
242.1164 -
242.1165 - if mytz is ottz:
242.1166 - base_compare = True
242.1167 - else:
242.1168 - myoff = self._utcoffset()
242.1169 - otoff = other._utcoffset()
242.1170 - base_compare = myoff == otoff
242.1171 -
242.1172 - if base_compare:
242.1173 - return cmp((self.__hour, self.__minute, self.__second,
242.1174 - self.__microsecond),
242.1175 - (other.__hour, other.__minute, other.__second,
242.1176 - other.__microsecond))
242.1177 - if myoff is None or otoff is None:
242.1178 - # XXX Buggy in 2.2.2.
242.1179 - raise TypeError("cannot compare naive and aware times")
242.1180 - myhhmm = self.__hour * 60 + self.__minute - myoff
242.1181 - othhmm = other.__hour * 60 + other.__minute - otoff
242.1182 - return cmp((myhhmm, self.__second, self.__microsecond),
242.1183 - (othhmm, other.__second, other.__microsecond))
242.1184 -
242.1185 - def __hash__(self):
242.1186 - """Hash."""
242.1187 - tzoff = self._utcoffset()
242.1188 - if not tzoff: # zero or None
242.1189 - return hash(self.__getstate()[0])
242.1190 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
242.1191 - if 0 <= h < 24:
242.1192 - return hash(time(h, m, self.second, self.microsecond))
242.1193 - return hash((h, m, self.second, self.microsecond))
242.1194 -
242.1195 - # Conversion to string
242.1196 -
242.1197 - def _tzstr(self, sep=":"):
242.1198 - """Return formatted timezone offset (+xx:xx) or None."""
242.1199 - off = self._utcoffset()
242.1200 - if off is not None:
242.1201 - if off < 0:
242.1202 - sign = "-"
242.1203 - off = -off
242.1204 - else:
242.1205 - sign = "+"
242.1206 - hh, mm = divmod(off, 60)
242.1207 - assert 0 <= hh < 24
242.1208 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
242.1209 - return off
242.1210 -
242.1211 - def __repr__(self):
242.1212 - """Convert to formal string, for repr()."""
242.1213 - if self.__microsecond != 0:
242.1214 - s = ", %d, %d" % (self.__second, self.__microsecond)
242.1215 - elif self.__second != 0:
242.1216 - s = ", %d" % self.__second
242.1217 - else:
242.1218 - s = ""
242.1219 - s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
242.1220 - self.__hour, self.__minute, s)
242.1221 - if self._tzinfo is not None:
242.1222 - assert s[-1:] == ")"
242.1223 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
242.1224 - return s
242.1225 -
242.1226 - def isoformat(self):
242.1227 - """Return the time formatted according to ISO.
242.1228 -
242.1229 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
242.1230 - self.microsecond == 0.
242.1231 - """
242.1232 - s = _format_time(self.__hour, self.__minute, self.__second,
242.1233 - self.__microsecond)
242.1234 - tz = self._tzstr()
242.1235 - if tz:
242.1236 - s += tz
242.1237 - return s
242.1238 -
242.1239 - __str__ = isoformat
242.1240 -
242.1241 - def strftime(self, fmt):
242.1242 - """Format using strftime(). The date part of the timestamp passed
242.1243 - to underlying strftime should not be used.
242.1244 - """
242.1245 - # The year must be >= 1900 else Python's strftime implementation
242.1246 - # can raise a bogus exception.
242.1247 - timetuple = (1900, 1, 1,
242.1248 - self.__hour, self.__minute, self.__second,
242.1249 - 0, 1, -1)
242.1250 - return _wrap_strftime(self, fmt, timetuple)
242.1251 -
242.1252 - # Timezone functions
242.1253 -
242.1254 - def utcoffset(self):
242.1255 - """Return the timezone offset in minutes east of UTC (negative west of
242.1256 - UTC)."""
242.1257 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
242.1258 - offset = _check_utc_offset("utcoffset", offset)
242.1259 - if offset is not None:
242.1260 - offset = timedelta(minutes=offset)
242.1261 - return offset
242.1262 -
242.1263 - # Return an integer (or None) instead of a timedelta (or None).
242.1264 - def _utcoffset(self):
242.1265 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
242.1266 - offset = _check_utc_offset("utcoffset", offset)
242.1267 - return offset
242.1268 -
242.1269 - def tzname(self):
242.1270 - """Return the timezone name.
242.1271 -
242.1272 - Note that the name is 100% informational -- there's no requirement that
242.1273 - it mean anything in particular. For example, "GMT", "UTC", "-500",
242.1274 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
242.1275 - """
242.1276 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
242.1277 - _check_tzname(name)
242.1278 - return name
242.1279 -
242.1280 - def dst(self):
242.1281 - """Return 0 if DST is not in effect, or the DST offset (in minutes
242.1282 - eastward) if DST is in effect.
242.1283 -
242.1284 - This is purely informational; the DST offset has already been added to
242.1285 - the UTC offset returned by utcoffset() if applicable, so there's no
242.1286 - need to consult dst() unless you're interested in displaying the DST
242.1287 - info.
242.1288 - """
242.1289 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
242.1290 - offset = _check_utc_offset("dst", offset)
242.1291 - if offset is not None:
242.1292 - offset = timedelta(minutes=offset)
242.1293 - return offset
242.1294 -
242.1295 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
242.1296 - tzinfo=True):
242.1297 - """Return a new time with new values for the specified fields."""
242.1298 - if hour is None:
242.1299 - hour = self.hour
242.1300 - if minute is None:
242.1301 - minute = self.minute
242.1302 - if second is None:
242.1303 - second = self.second
242.1304 - if microsecond is None:
242.1305 - microsecond = self.microsecond
242.1306 - if tzinfo is True:
242.1307 - tzinfo = self.tzinfo
242.1308 - _check_time_fields(hour, minute, second, microsecond)
242.1309 - _check_tzinfo_arg(tzinfo)
242.1310 - return time(hour, minute, second, microsecond, tzinfo)
242.1311 -
242.1312 - # Return an integer (or None) instead of a timedelta (or None).
242.1313 - def _dst(self):
242.1314 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
242.1315 - offset = _check_utc_offset("dst", offset)
242.1316 - return offset
242.1317 -
242.1318 - def __nonzero__(self):
242.1319 - if self.second or self.microsecond:
242.1320 - return 1
242.1321 - offset = self._utcoffset() or 0
242.1322 - return self.hour * 60 + self.minute - offset != 0
242.1323 -
242.1324 - # Pickle support.
242.1325 -
242.1326 - __safe_for_unpickling__ = True # For Python 2.2
242.1327 -
242.1328 - def __getstate(self):
242.1329 - us2, us3 = divmod(self.__microsecond, 256)
242.1330 - us1, us2 = divmod(us2, 256)
242.1331 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
242.1332 - us1, us2, us3)
242.1333 - if self._tzinfo is None:
242.1334 - return (basestate,)
242.1335 - else:
242.1336 - return (basestate, self._tzinfo)
242.1337 -
242.1338 - def __setstate(self, state):
242.1339 - assert isinstance(state, tuple)
242.1340 - assert 1 <= len(state) <= 2
242.1341 - string = state[0]
242.1342 - assert len(string) == 6
242.1343 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
242.1344 - map(ord, string)
242.1345 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
242.1346 - if len(state) == 1:
242.1347 - self._tzinfo = None
242.1348 - else:
242.1349 - self._tzinfo = state[1]
242.1350 -
242.1351 - def __reduce__(self):
242.1352 - return (self.__class__, self.__getstate())
242.1353 -
242.1354 -_time_class = time # so functions w/ args named "time" can get at the class
242.1355 -
242.1356 -time.min = time(0, 0, 0)
242.1357 -time.max = time(23, 59, 59, 999999)
242.1358 -time.resolution = timedelta(microseconds=1)
242.1359 -
242.1360 -class datetime(date):
242.1361 -
242.1362 - # XXX needs docstrings
242.1363 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
242.1364 -
242.1365 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
242.1366 - microsecond=0, tzinfo=None):
242.1367 - if isinstance(year, str):
242.1368 - # Pickle support
242.1369 - self = date.__new__(cls, year[:4])
242.1370 - self.__setstate((year, month))
242.1371 - return self
242.1372 - _check_tzinfo_arg(tzinfo)
242.1373 - _check_time_fields(hour, minute, second, microsecond)
242.1374 - self = date.__new__(cls, year, month, day)
242.1375 - # XXX This duplicates __year, __month, __day for convenience :-(
242.1376 - self.__year = year
242.1377 - self.__month = month
242.1378 - self.__day = day
242.1379 - self.__hour = hour
242.1380 - self.__minute = minute
242.1381 - self.__second = second
242.1382 - self.__microsecond = microsecond
242.1383 - self._tzinfo = tzinfo
242.1384 - return self
242.1385 -
242.1386 - # Read-only field accessors
242.1387 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
242.1388 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
242.1389 - second = property(lambda self: self.__second, doc="second (0-59)")
242.1390 - microsecond = property(lambda self: self.__microsecond,
242.1391 - doc="microsecond (0-999999)")
242.1392 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
242.1393 -
242.1394 - def fromtimestamp(cls, t, tz=None):
242.1395 - """Construct a datetime from a POSIX timestamp (like time.time()).
242.1396 -
242.1397 - A timezone info object may be passed in as well.
242.1398 - """
242.1399 -
242.1400 - _check_tzinfo_arg(tz)
242.1401 - if tz is None:
242.1402 - converter = _time.localtime
242.1403 - else:
242.1404 - converter = _time.gmtime
242.1405 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
242.1406 - us = int((t % 1.0) * 1000000)
242.1407 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
242.1408 - result = cls(y, m, d, hh, mm, ss, us, tz)
242.1409 - if tz is not None:
242.1410 - result = tz.fromutc(result)
242.1411 - return result
242.1412 - fromtimestamp = classmethod(fromtimestamp)
242.1413 -
242.1414 - def utcfromtimestamp(cls, t):
242.1415 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
242.1416 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
242.1417 - us = int((t % 1.0) * 1000000)
242.1418 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
242.1419 - return cls(y, m, d, hh, mm, ss, us)
242.1420 - utcfromtimestamp = classmethod(utcfromtimestamp)
242.1421 -
242.1422 - # XXX This is supposed to do better than we *can* do by using time.time(),
242.1423 - # XXX if the platform supports a more accurate way. The C implementation
242.1424 - # XXX uses gettimeofday on platforms that have it, but that isn't
242.1425 - # XXX available from Python. So now() may return different results
242.1426 - # XXX across the implementations.
242.1427 - def now(cls, tz=None):
242.1428 - "Construct a datetime from time.time() and optional time zone info."
242.1429 - t = _time.time()
242.1430 - return cls.fromtimestamp(t, tz)
242.1431 - now = classmethod(now)
242.1432 -
242.1433 - def utcnow(cls):
242.1434 - "Construct a UTC datetime from time.time()."
242.1435 - t = _time.time()
242.1436 - return cls.utcfromtimestamp(t)
242.1437 - utcnow = classmethod(utcnow)
242.1438 -
242.1439 - def combine(cls, date, time):
242.1440 - "Construct a datetime from a given date and a given time."
242.1441 - if not isinstance(date, _date_class):
242.1442 - raise TypeError("date argument must be a date instance")
242.1443 - if not isinstance(time, _time_class):
242.1444 - raise TypeError("time argument must be a time instance")
242.1445 - return cls(date.year, date.month, date.day,
242.1446 - time.hour, time.minute, time.second, time.microsecond,
242.1447 - time.tzinfo)
242.1448 - combine = classmethod(combine)
242.1449 -
242.1450 - def timetuple(self):
242.1451 - "Return local time tuple compatible with time.localtime()."
242.1452 - dst = self._dst()
242.1453 - if dst is None:
242.1454 - dst = -1
242.1455 - elif dst:
242.1456 - dst = 1
242.1457 - return _build_struct_time(self.year, self.month, self.day,
242.1458 - self.hour, self.minute, self.second,
242.1459 - dst)
242.1460 -
242.1461 - def utctimetuple(self):
242.1462 - "Return UTC time tuple compatible with time.gmtime()."
242.1463 - y, m, d = self.year, self.month, self.day
242.1464 - hh, mm, ss = self.hour, self.minute, self.second
242.1465 - offset = self._utcoffset()
242.1466 - if offset: # neither None nor 0
242.1467 - tm = tmxxx(y, m, d, hh, mm - offset)
242.1468 - y, m, d = tm.year, tm.month, tm.day
242.1469 - hh, mm = tm.hour, tm.minute
242.1470 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
242.1471 -
242.1472 - def date(self):
242.1473 - "Return the date part."
242.1474 - return date(self.__year, self.__month, self.__day)
242.1475 -
242.1476 - def time(self):
242.1477 - "Return the time part, with tzinfo None."
242.1478 - return time(self.hour, self.minute, self.second, self.microsecond)
242.1479 -
242.1480 - def timetz(self):
242.1481 - "Return the time part, with same tzinfo."
242.1482 - return time(self.hour, self.minute, self.second, self.microsecond,
242.1483 - self._tzinfo)
242.1484 -
242.1485 - def replace(self, year=None, month=None, day=None, hour=None,
242.1486 - minute=None, second=None, microsecond=None, tzinfo=True):
242.1487 - """Return a new datetime with new values for the specified fields."""
242.1488 - if year is None:
242.1489 - year = self.year
242.1490 - if month is None:
242.1491 - month = self.month
242.1492 - if day is None:
242.1493 - day = self.day
242.1494 - if hour is None:
242.1495 - hour = self.hour
242.1496 - if minute is None:
242.1497 - minute = self.minute
242.1498 - if second is None:
242.1499 - second = self.second
242.1500 - if microsecond is None:
242.1501 - microsecond = self.microsecond
242.1502 - if tzinfo is True:
242.1503 - tzinfo = self.tzinfo
242.1504 - _check_date_fields(year, month, day)
242.1505 - _check_time_fields(hour, minute, second, microsecond)
242.1506 - _check_tzinfo_arg(tzinfo)
242.1507 - return datetime(year, month, day, hour, minute, second,
242.1508 - microsecond, tzinfo)
242.1509 -
242.1510 - def astimezone(self, tz):
242.1511 - if not isinstance(tz, tzinfo):
242.1512 - raise TypeError("tz argument must be an instance of tzinfo")
242.1513 -
242.1514 - mytz = self.tzinfo
242.1515 - if mytz is None:
242.1516 - raise ValueError("astimezone() requires an aware datetime")
242.1517 -
242.1518 - if tz is mytz:
242.1519 - return self
242.1520 -
242.1521 - # Convert self to UTC, and attach the new time zone object.
242.1522 - myoffset = self.utcoffset()
242.1523 - if myoffset is None:
242.1524 - raise ValuError("astimezone() requires an aware datetime")
242.1525 - utc = (self - myoffset).replace(tzinfo=tz)
242.1526 -
242.1527 - # Convert from UTC to tz's local time.
242.1528 - return tz.fromutc(utc)
242.1529 -
242.1530 - # Ways to produce a string.
242.1531 -
242.1532 - def ctime(self):
242.1533 - "Format a la ctime()."
242.1534 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
242.1535 - self.__minute, self.__second)
242.1536 - return t.ctime()
242.1537 -
242.1538 - def isoformat(self, sep='T'):
242.1539 - """Return the time formatted according to ISO.
242.1540 -
242.1541 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
242.1542 - self.microsecond == 0.
242.1543 -
242.1544 - If self.tzinfo is not None, the UTC offset is also attached, giving
242.1545 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
242.1546 -
242.1547 - Optional argument sep specifies the separator between date and
242.1548 - time, default 'T'.
242.1549 - """
242.1550 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
242.1551 - sep) +
242.1552 - _format_time(self.__hour, self.__minute, self.__second,
242.1553 - self.__microsecond))
242.1554 - off = self._utcoffset()
242.1555 - if off is not None:
242.1556 - if off < 0:
242.1557 - sign = "-"
242.1558 - off = -off
242.1559 - else:
242.1560 - sign = "+"
242.1561 - hh, mm = divmod(off, 60)
242.1562 - s += "%s%02d:%02d" % (sign, hh, mm)
242.1563 - return s
242.1564 -
242.1565 - def __repr__(self):
242.1566 - "Convert to formal string, for repr()."
242.1567 - L = [self.__year, self.__month, self.__day, # These are never zero
242.1568 - self.__hour, self.__minute, self.__second, self.__microsecond]
242.1569 - if L[-1] == 0:
242.1570 - del L[-1]
242.1571 - if L[-1] == 0:
242.1572 - del L[-1]
242.1573 - s = ", ".join(map(str, L))
242.1574 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
242.1575 - if self._tzinfo is not None:
242.1576 - assert s[-1:] == ")"
242.1577 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
242.1578 - return s
242.1579 -
242.1580 - def __str__(self):
242.1581 - "Convert to string, for str()."
242.1582 - return self.isoformat(sep=' ')
242.1583 -
242.1584 - def utcoffset(self):
242.1585 - """Return the timezone offset in minutes east of UTC (negative west of
242.1586 - UTC)."""
242.1587 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
242.1588 - offset = _check_utc_offset("utcoffset", offset)
242.1589 - if offset is not None:
242.1590 - offset = timedelta(minutes=offset)
242.1591 - return offset
242.1592 -
242.1593 - # Return an integer (or None) instead of a timedelta (or None).
242.1594 - def _utcoffset(self):
242.1595 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
242.1596 - offset = _check_utc_offset("utcoffset", offset)
242.1597 - return offset
242.1598 -
242.1599 - def tzname(self):
242.1600 - """Return the timezone name.
242.1601 -
242.1602 - Note that the name is 100% informational -- there's no requirement that
242.1603 - it mean anything in particular. For example, "GMT", "UTC", "-500",
242.1604 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
242.1605 - """
242.1606 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
242.1607 - _check_tzname(name)
242.1608 - return name
242.1609 -
242.1610 - def dst(self):
242.1611 - """Return 0 if DST is not in effect, or the DST offset (in minutes
242.1612 - eastward) if DST is in effect.
242.1613 -
242.1614 - This is purely informational; the DST offset has already been added to
242.1615 - the UTC offset returned by utcoffset() if applicable, so there's no
242.1616 - need to consult dst() unless you're interested in displaying the DST
242.1617 - info.
242.1618 - """
242.1619 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
242.1620 - offset = _check_utc_offset("dst", offset)
242.1621 - if offset is not None:
242.1622 - offset = timedelta(minutes=offset)
242.1623 - return offset
242.1624 -
242.1625 - # Return an integer (or None) instead of a timedelta (or None).1573
242.1626 - def _dst(self):
242.1627 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
242.1628 - offset = _check_utc_offset("dst", offset)
242.1629 - return offset
242.1630 -
242.1631 - # Comparisons.
242.1632 -
242.1633 - def __eq__(self, other):
242.1634 - if isinstance(other, datetime):
242.1635 - return self.__cmp(other) == 0
242.1636 - elif hasattr(other, "timetuple"):
242.1637 - return NotImplemented
242.1638 - else:
242.1639 - return False
242.1640 -
242.1641 - def __ne__(self, other):
242.1642 - if isinstance(other, datetime):
242.1643 - return self.__cmp(other) != 0
242.1644 - elif hasattr(other, "timetuple"):
242.1645 - return NotImplemented
242.1646 - else:
242.1647 - return True
242.1648 -
242.1649 - def __le__(self, other):
242.1650 - if isinstance(other, datetime):
242.1651 - return self.__cmp(other) <= 0
242.1652 - elif hasattr(other, "timetuple"):
242.1653 - return NotImplemented
242.1654 - else:
242.1655 - _cmperror(self, other)
242.1656 -
242.1657 - def __lt__(self, other):
242.1658 - if isinstance(other, datetime):
242.1659 - return self.__cmp(other) < 0
242.1660 - elif hasattr(other, "timetuple"):
242.1661 - return NotImplemented
242.1662 - else:
242.1663 - _cmperror(self, other)
242.1664 -
242.1665 - def __ge__(self, other):
242.1666 - if isinstance(other, datetime):
242.1667 - return self.__cmp(other) >= 0
242.1668 - elif hasattr(other, "timetuple"):
242.1669 - return NotImplemented
242.1670 - else:
242.1671 - _cmperror(self, other)
242.1672 -
242.1673 - def __gt__(self, other):
242.1674 - if isinstance(other, datetime):
242.1675 - return self.__cmp(other) > 0
242.1676 - elif hasattr(other, "timetuple"):
242.1677 - return NotImplemented
242.1678 - else:
242.1679 - _cmperror(self, other)
242.1680 -
242.1681 - def __cmp(self, other):
242.1682 - assert isinstance(other, datetime)
242.1683 - mytz = self._tzinfo
242.1684 - ottz = other._tzinfo
242.1685 - myoff = otoff = None
242.1686 -
242.1687 - if mytz is ottz:
242.1688 - base_compare = True
242.1689 - else:
242.1690 - if mytz is not None:
242.1691 - myoff = self._utcoffset()
242.1692 - if ottz is not None:
242.1693 - otoff = other._utcoffset()
242.1694 - base_compare = myoff == otoff
242.1695 -
242.1696 - if base_compare:
242.1697 - return cmp((self.__year, self.__month, self.__day,
242.1698 - self.__hour, self.__minute, self.__second,
242.1699 - self.__microsecond),
242.1700 - (other.__year, other.__month, other.__day,
242.1701 - other.__hour, other.__minute, other.__second,
242.1702 - other.__microsecond))
242.1703 - if myoff is None or otoff is None:
242.1704 - # XXX Buggy in 2.2.2.
242.1705 - raise TypeError("cannot compare naive and aware datetimes")
242.1706 - # XXX What follows could be done more efficiently...
242.1707 - diff = self - other # this will take offsets into account
242.1708 - if diff.days < 0:
242.1709 - return -1
242.1710 - return diff and 1 or 0
242.1711 -
242.1712 - def __add__(self, other):
242.1713 - "Add a datetime and a timedelta."
242.1714 - if not isinstance(other, timedelta):
242.1715 - return NotImplemented
242.1716 - t = tmxxx(self.__year,
242.1717 - self.__month,
242.1718 - self.__day + other.days,
242.1719 - self.__hour,
242.1720 - self.__minute,
242.1721 - self.__second + other.seconds,
242.1722 - self.__microsecond + other.microseconds)
242.1723 - self._checkOverflow(t.year)
242.1724 - result = self.__class__(t.year, t.month, t.day,
242.1725 - t.hour, t.minute, t.second,
242.1726 - t.microsecond, tzinfo=self._tzinfo)
242.1727 - return result
242.1728 -
242.1729 - __radd__ = __add__
242.1730 -
242.1731 - def __sub__(self, other):
242.1732 - "Subtract two datetimes, or a datetime and a timedelta."
242.1733 - if not isinstance(other, datetime):
242.1734 - if isinstance(other, timedelta):
242.1735 - return self + -other
242.1736 - return NotImplemented
242.1737 -
242.1738 - days1 = self.toordinal()
242.1739 - days2 = other.toordinal()
242.1740 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
242.1741 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
242.1742 - base = timedelta(days1 - days2,
242.1743 - secs1 - secs2,
242.1744 - self.__microsecond - other.__microsecond)
242.1745 - if self._tzinfo is other._tzinfo:
242.1746 - return base
242.1747 - myoff = self._utcoffset()
242.1748 - otoff = other._utcoffset()
242.1749 - if myoff == otoff:
242.1750 - return base
242.1751 - if myoff is None or otoff is None:
242.1752 - raise TypeError, "cannot mix naive and timezone-aware time"
242.1753 - return base + timedelta(minutes = otoff-myoff)
242.1754 -
242.1755 - def __hash__(self):
242.1756 - tzoff = self._utcoffset()
242.1757 - if tzoff is None:
242.1758 - return hash(self.__getstate()[0])
242.1759 - days = _ymd2ord(self.year, self.month, self.day)
242.1760 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
242.1761 - return hash(timedelta(days, seconds, self.microsecond))
242.1762 -
242.1763 - # Pickle support.
242.1764 -
242.1765 - __safe_for_unpickling__ = True # For Python 2.2
242.1766 -
242.1767 - def __getstate(self):
242.1768 - yhi, ylo = divmod(self.__year, 256)
242.1769 - us2, us3 = divmod(self.__microsecond, 256)
242.1770 - us1, us2 = divmod(us2, 256)
242.1771 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
242.1772 - self.__hour, self.__minute, self.__second,
242.1773 - us1, us2, us3)
242.1774 - if self._tzinfo is None:
242.1775 - return (basestate,)
242.1776 - else:
242.1777 - return (basestate, self._tzinfo)
242.1778 -
242.1779 - def __setstate(self, state):
242.1780 - assert isinstance(state, tuple)
242.1781 - assert 1 <= len(state) <= 2
242.1782 - string = state[0]
242.1783 - assert len(string) == 10
242.1784 - (yhi, ylo, self.__month, self.__day, self.__hour,
242.1785 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
242.1786 - self.__year = yhi * 256 + ylo
242.1787 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
242.1788 - if len(state) == 1:
242.1789 - self._tzinfo = None
242.1790 - else:
242.1791 - self._tzinfo = state[1]
242.1792 -
242.1793 - def __reduce__(self):
242.1794 - return (self.__class__, self.__getstate())
242.1795 -
242.1796 -
242.1797 -datetime.min = datetime(1, 1, 1)
242.1798 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
242.1799 -datetime.resolution = timedelta(microseconds=1)
242.1800 -
242.1801 -
242.1802 -def _isoweek1monday(year):
242.1803 - # Helper to calculate the day number of the Monday starting week 1
242.1804 - # XXX This could be done more efficiently
242.1805 - THURSDAY = 3
242.1806 - firstday = _ymd2ord(year, 1, 1)
242.1807 - firstweekday = (firstday + 6) % 7 # See weekday() above
242.1808 - week1monday = firstday - firstweekday
242.1809 - if firstweekday > THURSDAY:
242.1810 - week1monday += 7
242.1811 - return week1monday
242.1812 -
242.1813 -"""
242.1814 -Some time zone algebra. For a datetime x, let
242.1815 - x.n = x stripped of its timezone -- its naive time.
242.1816 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
242.1817 - return None
242.1818 - x.d = x.dst(), and assuming that doesn't raise an exception or
242.1819 - return None
242.1820 - x.s = x's standard offset, x.o - x.d
242.1821 -
242.1822 -Now some derived rules, where k is a duration (timedelta).
242.1823 -
242.1824 -1. x.o = x.s + x.d
242.1825 - This follows from the definition of x.s.
242.1826 -
242.1827 -2. If x and y have the same tzinfo member, x.s = y.s.
242.1828 - This is actually a requirement, an assumption we need to make about
242.1829 - sane tzinfo classes.
242.1830 -
242.1831 -3. The naive UTC time corresponding to x is x.n - x.o.
242.1832 - This is again a requirement for a sane tzinfo class.
242.1833 -
242.1834 -4. (x+k).s = x.s
242.1835 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
242.1836 -
242.1837 -5. (x+k).n = x.n + k
242.1838 - Again follows from how arithmetic is defined.
242.1839 -
242.1840 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
242.1841 -(meaning that the various tzinfo methods exist, and don't blow up or return
242.1842 -None when called).
242.1843 -
242.1844 -The function wants to return a datetime y with timezone tz, equivalent to x.
242.1845 -x is already in UTC.
242.1846 -
242.1847 -By #3, we want
242.1848 -
242.1849 - y.n - y.o = x.n [1]
242.1850 -
242.1851 -The algorithm starts by attaching tz to x.n, and calling that y. So
242.1852 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
242.1853 -becomes true; in effect, we want to solve [2] for k:
242.1854 -
242.1855 - (y+k).n - (y+k).o = x.n [2]
242.1856 -
242.1857 -By #1, this is the same as
242.1858 -
242.1859 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
242.1860 -
242.1861 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
242.1862 -Substituting that into [3],
242.1863 -
242.1864 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
242.1865 - k - (y+k).s - (y+k).d = 0; rearranging,
242.1866 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
242.1867 - k = y.s - (y+k).d
242.1868 -
242.1869 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
242.1870 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
242.1871 -very large, since all offset-returning methods return a duration of magnitude
242.1872 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
242.1873 -be 0, so ignoring it has no consequence then.
242.1874 -
242.1875 -In any case, the new value is
242.1876 -
242.1877 - z = y + y.s [4]
242.1878 -
242.1879 -It's helpful to step back at look at [4] from a higher level: it's simply
242.1880 -mapping from UTC to tz's standard time.
242.1881 -
242.1882 -At this point, if
242.1883 -
242.1884 - z.n - z.o = x.n [5]
242.1885 -
242.1886 -we have an equivalent time, and are almost done. The insecurity here is
242.1887 -at the start of daylight time. Picture US Eastern for concreteness. The wall
242.1888 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
242.1889 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
242.1890 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
242.1891 -on the day DST starts. We want to return the 1:MM EST spelling because that's
242.1892 -the only spelling that makes sense on the local wall clock.
242.1893 -
242.1894 -In fact, if [5] holds at this point, we do have the standard-time spelling,
242.1895 -but that takes a bit of proof. We first prove a stronger result. What's the
242.1896 -difference between the LHS and RHS of [5]? Let
242.1897 -
242.1898 - diff = x.n - (z.n - z.o) [6]
242.1899 -
242.1900 -Now
242.1901 - z.n = by [4]
242.1902 - (y + y.s).n = by #5
242.1903 - y.n + y.s = since y.n = x.n
242.1904 - x.n + y.s = since z and y are have the same tzinfo member,
242.1905 - y.s = z.s by #2
242.1906 - x.n + z.s
242.1907 -
242.1908 -Plugging that back into [6] gives
242.1909 -
242.1910 - diff =
242.1911 - x.n - ((x.n + z.s) - z.o) = expanding
242.1912 - x.n - x.n - z.s + z.o = cancelling
242.1913 - - z.s + z.o = by #2
242.1914 - z.d
242.1915 -
242.1916 -So diff = z.d.
242.1917 -
242.1918 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
242.1919 -spelling we wanted in the endcase described above. We're done. Contrarily,
242.1920 -if z.d = 0, then we have a UTC equivalent, and are also done.
242.1921 -
242.1922 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
242.1923 -add to z (in effect, z is in tz's standard time, and we need to shift the
242.1924 -local clock into tz's daylight time).
242.1925 -
242.1926 -Let
242.1927 -
242.1928 - z' = z + z.d = z + diff [7]
242.1929 -
242.1930 -and we can again ask whether
242.1931 -
242.1932 - z'.n - z'.o = x.n [8]
242.1933 -
242.1934 -If so, we're done. If not, the tzinfo class is insane, according to the
242.1935 -assumptions we've made. This also requires a bit of proof. As before, let's
242.1936 -compute the difference between the LHS and RHS of [8] (and skipping some of
242.1937 -the justifications for the kinds of substitutions we've done several times
242.1938 -already):
242.1939 -
242.1940 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
242.1941 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
242.1942 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
242.1943 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
242.1944 - - z.n + z.n - z.o + z'.o = cancel z.n
242.1945 - - z.o + z'.o = #1 twice
242.1946 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
242.1947 - z'.d - z.d
242.1948 -
242.1949 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
242.1950 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
242.1951 -return z', not bothering to compute z'.d.
242.1952 -
242.1953 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
242.1954 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
242.1955 -would have to change the result dst() returns: we start in DST, and moving
242.1956 -a little further into it takes us out of DST.
242.1957 -
242.1958 -There isn't a sane case where this can happen. The closest it gets is at
242.1959 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
242.1960 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
242.1961 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
242.1962 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
242.1963 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
242.1964 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
242.1965 -standard time. Since that's what the local clock *does*, we want to map both
242.1966 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
242.1967 -in local time, but so it goes -- it's the way the local clock works.
242.1968 -
242.1969 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
242.1970 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
242.1971 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
242.1972 -(correctly) concludes that z' is not UTC-equivalent to x.
242.1973 -
242.1974 -Because we know z.d said z was in daylight time (else [5] would have held and
242.1975 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
242.1976 -and we we have stopped then), and there are only 2 possible values dst() can
242.1977 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
242.1978 -but the reasoning doesn't depend on the example -- it depends on there being
242.1979 -two possible dst() outcomes, one zero and the other non-zero). Therefore
242.1980 -z' must be in standard time, and is the spelling we want in this case.
242.1981 -
242.1982 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
242.1983 -concerned (because it takes z' as being in standard time rather than the
242.1984 -daylight time we intend here), but returning it gives the real-life "local
242.1985 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
242.1986 -tz.
242.1987 -
242.1988 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
242.1989 -the 1:MM standard time spelling we want.
242.1990 -
242.1991 -So how can this break? One of the assumptions must be violated. Two
242.1992 -possibilities:
242.1993 -
242.1994 -1) [2] effectively says that y.s is invariant across all y belong to a given
242.1995 - time zone. This isn't true if, for political reasons or continental drift,
242.1996 - a region decides to change its base offset from UTC.
242.1997 -
242.1998 -2) There may be versions of "double daylight" time where the tail end of
242.1999 - the analysis gives up a step too early. I haven't thought about that
242.2000 - enough to say.
242.2001 -
242.2002 -In any case, it's clear that the default fromutc() is strong enough to handle
242.2003 -"almost all" time zones: so long as the standard offset is invariant, it
242.2004 -doesn't matter if daylight time transition points change from year to year, or
242.2005 -if daylight time is skipped in some years; it doesn't matter how large or
242.2006 -small dst() may get within its bounds; and it doesn't even matter if some
242.2007 -perverse time zone returns a negative dst()). So a breaking case must be
242.2008 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
242.2009 -"""
242.2010 -
242.2011 -def _test():
242.2012 - import test_datetime
242.2013 - test_datetime.test_main()
242.2014 -
242.2015 -if __name__ == "__main__":
242.2016 - _test()
243.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testFix3.fixed Sun Jan 04 13:11:53 2015 -0600
243.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
243.3 @@ -1,2011 +0,0 @@
243.4 -"""Concrete date/time and related types -- prototype implemented in Python.
243.5 -
243.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
243.7 -
243.8 -See also http://dir.yahoo.com/Reference/calendars/
243.9 -
243.10 -For a primer on DST, including many current DST rules, see
243.11 -http://webexhibits.org/daylightsaving/
243.12 -
243.13 -For more about DST than you ever wanted to know, see
243.14 -ftp://elsie.nci.nih.gov/pub/
243.15 -
243.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
243.17 -
243.18 -"""
243.19 -
243.20 -import time as _time
243.21 -import math as _math
243.22 -
243.23 -MINYEAR = 1
243.24 -MAXYEAR = 9999
243.25 -
243.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
243.27 -# also assumes the current Gregorian calendar indefinitely extended in
243.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
243.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
243.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
243.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
243.32 -# for all computations. See the book for algorithms for converting between
243.33 -# proleptic Gregorian ordinals and many other calendar systems.
243.34 -
243.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
243.36 -
243.37 -_DAYS_BEFORE_MONTH = [None]
243.38 -dbm = 0
243.39 -for dim in _DAYS_IN_MONTH[1:]:
243.40 - _DAYS_BEFORE_MONTH.append(dbm)
243.41 - dbm += dim
243.42 -del dbm, dim
243.43 -
243.44 -def _is_leap(year):
243.45 - "year -> 1 if leap year, else 0."
243.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
243.47 -
243.48 -def _days_in_year(year):
243.49 - "year -> number of days in year (366 if a leap year, else 365)."
243.50 - return 365 + _is_leap(year)
243.51 -
243.52 -def _days_before_year(year):
243.53 - "year -> number of days before January 1st of year."
243.54 - y = year - 1
243.55 - return y*365 + y//4 - y//100 + y//400
243.56 -
243.57 -def _days_in_month(year, month):
243.58 - "year, month -> number of days in that month in that year."
243.59 - try:
243.60 - assert 1 <= month <= 12, month
243.61 - if month == 2 and _is_leap(year):
243.62 - return 29
243.63 - finally:
243.64 -
243.65 - return _DAYS_IN_MONTH[month]
243.66 -
243.67 -def _days_before_month(year, month):
243.68 - "year, month -> number of days in year preceeding first day of month."
243.69 - if not 1 <= month <= 12:
243.70 - raise ValueError('month must be in 1..12', month)
243.71 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
243.72 -
243.73 -def _ymd2ord(year, month, day):
243.74 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
243.75 - if not 1 <= month <= 12:
243.76 - raise ValueError('month must be in 1..12', month)
243.77 - dim = _days_in_month(year, month)
243.78 - if not 1 <= day <= dim:
243.79 - raise ValueError('day must be in 1..%d' % dim, day)
243.80 - return (_days_before_year(year) +
243.81 - _days_before_month(year, month) +
243.82 - day)
243.83 -
243.84 -_DI400Y = _days_before_year(401) # number of days in 400 years
243.85 -_DI100Y = _days_before_year(101) # " " " " 100 "
243.86 -_DI4Y = _days_before_year(5) # " " " " 4 "
243.87 -
243.88 -# A 4-year cycle has an extra leap day over what we'd get from pasting
243.89 -# together 4 single years.
243.90 -assert _DI4Y == 4 * 365 + 1
243.91 -
243.92 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
243.93 -# pasting together 4 100-year cycles.
243.94 -assert _DI400Y == 4 * _DI100Y + 1
243.95 -
243.96 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
243.97 -# pasting together 25 4-year cycles.
243.98 -assert _DI100Y == 25 * _DI4Y - 1
243.99 -
243.100 -def _ord2ymd(n):
243.101 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
243.102 -
243.103 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
243.104 - # repeats exactly every 400 years. The basic strategy is to find the
243.105 - # closest 400-year boundary at or before n, then work with the offset
243.106 - # from that boundary to n. Life is much clearer if we subtract 1 from
243.107 - # n first -- then the values of n at 400-year boundaries are exactly
243.108 - # those divisible by _DI400Y:
243.109 - #
243.110 - # D M Y n n-1
243.111 - # -- --- ---- ---------- ----------------
243.112 - # 31 Dec -400 -_DI400Y -_DI400Y -1
243.113 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
243.114 - # ...
243.115 - # 30 Dec 000 -1 -2
243.116 - # 31 Dec 000 0 -1
243.117 - # 1 Jan 001 1 0 400-year boundary
243.118 - # 2 Jan 001 2 1
243.119 - # 3 Jan 001 3 2
243.120 - # ...
243.121 - # 31 Dec 400 _DI400Y _DI400Y -1
243.122 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
243.123 - n -= 1
243.124 - n400, n = divmod(n, _DI400Y)
243.125 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
243.126 -
243.127 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
243.128 - # the desired date. Now compute how many 100-year cycles precede n.
243.129 - # Note that it's possible for n100 to equal 4! In that case 4 full
243.130 - # 100-year cycles precede the desired day, which implies the desired
243.131 - # day is December 31 at the end of a 400-year cycle.
243.132 - n100, n = divmod(n, _DI100Y)
243.133 -
243.134 - # Now compute how many 4-year cycles precede it.
243.135 - n4, n = divmod(n, _DI4Y)
243.136 -
243.137 - # And now how many single years. Again n1 can be 4, and again meaning
243.138 - # that the desired day is December 31 at the end of the 4-year cycle.
243.139 - n1, n = divmod(n, 365)
243.140 -
243.141 - year += n100 * 100 + n4 * 4 + n1
243.142 - if n1 == 4 or n100 == 4:
243.143 - assert n == 0
243.144 - return year-1, 12, 31
243.145 -
243.146 - # Now the year is correct, and n is the offset from January 1. We find
243.147 - # the month via an estimate that's either exact or one too large.
243.148 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
243.149 - assert leapyear == _is_leap(year)
243.150 - month = (n + 50) >> 5
243.151 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
243.152 - if preceding > n: # estimate is too large
243.153 - month -= 1
243.154 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
243.155 - n -= preceding
243.156 - assert 0 <= n < _days_in_month(year, month)
243.157 -
243.158 - # Now the year and month are correct, and n is the offset from the
243.159 - # start of that month: we're done!
243.160 - return year, month, n+1
243.161 -
243.162 -# Month and day names. For localized versions, see the calendar module.
243.163 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
243.164 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
243.165 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
243.166 -
243.167 -
243.168 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
243.169 - wday = (_ymd2ord(y, m, d) + 6) % 7
243.170 - dnum = _days_before_month(y, m) + d
243.171 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
243.172 -
243.173 -def _format_time(hh, mm, ss, us):
243.174 - # Skip trailing microseconds when us==0.
243.175 - result = "%02d:%02d:%02d" % (hh, mm, ss)
243.176 - if us:
243.177 - result += ".%06d" % us
243.178 - return result
243.179 -
243.180 -# Correctly substitute for %z and %Z escapes in strftime formats.
243.181 -def _wrap_strftime(object, format, timetuple):
243.182 - year = timetuple[0]
243.183 - if year < 1900:
243.184 - raise ValueError("year=%d is before 1900; the datetime strftime() "
243.185 - "methods require year >= 1900" % year)
243.186 - # Don't call _utcoffset() or tzname() unless actually needed.
243.187 - zreplace = None # the string to use for %z
243.188 - Zreplace = None # the string to use for %Z
243.189 -
243.190 - # Scan format for %z and %Z escapes, replacing as needed.
243.191 - newformat = []
243.192 - push = newformat.append
243.193 - i, n = 0, len(format)
243.194 - while i < n:
243.195 - ch = format[i]
243.196 - i += 1
243.197 - if ch == '%':
243.198 - if i < n:
243.199 - ch = format[i]
243.200 - i += 1
243.201 - if ch == 'z':
243.202 - if zreplace is None:
243.203 - zreplace = ""
243.204 - if hasattr(object, "_utcoffset"):
243.205 - offset = object._utcoffset()
243.206 - if offset is not None:
243.207 - sign = '+'
243.208 - if offset < 0:
243.209 - offset = -offset
243.210 - sign = '-'
243.211 - h, m = divmod(offset, 60)
243.212 - zreplace = '%c%02d%02d' % (sign, h, m)
243.213 - assert '%' not in zreplace
243.214 - newformat.append(zreplace)
243.215 - elif ch == 'Z':
243.216 - if Zreplace is None:
243.217 - Zreplace = ""
243.218 - if hasattr(object, "tzname"):
243.219 - s = object.tzname()
243.220 - if s is not None:
243.221 - # strftime is going to have at this: escape %
243.222 - Zreplace = s.replace('%', '%%')
243.223 - newformat.append(Zreplace)
243.224 - else:
243.225 - push('%')
243.226 - push(ch)
243.227 - else:
243.228 - push('%')
243.229 - else:
243.230 - push(ch)
243.231 - newformat = "".join(newformat)
243.232 - return _time.strftime(newformat, timetuple)
243.233 -
243.234 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
243.235 - if tzinfo is None:
243.236 - return None
243.237 - return getattr(tzinfo, methname)(tzinfoarg)
243.238 -
243.239 -# Just raise TypeError if the arg isn't None or a string.
243.240 -def _check_tzname(name):
243.241 - if name is not None and not isinstance(name, str):
243.242 - raise TypeError("tzinfo.tzname() must return None or string, "
243.243 - "not '%s'" % type(name))
243.244 -
243.245 -# name is the offset-producing method, "utcoffset" or "dst".
243.246 -# offset is what it returned.
243.247 -# If offset isn't None or timedelta, raises TypeError.
243.248 -# If offset is None, returns None.
243.249 -# Else offset is checked for being in range, and a whole # of minutes.
243.250 -# If it is, its integer value is returned. Else ValueError is raised.
243.251 -def _check_utc_offset(name, offset):
243.252 - assert name in ("utcoffset", "dst")
243.253 - if offset is None:
243.254 - return None
243.255 - if not isinstance(offset, timedelta):
243.256 - raise TypeError("tzinfo.%s() must return None "
243.257 - "or timedelta, not '%s'" % (name, type(offset)))
243.258 - days = offset.days
243.259 - if days < -1 or days > 0:
243.260 - offset = 1440 # trigger out-of-range
243.261 - else:
243.262 - seconds = days * 86400 + offset.seconds
243.263 - minutes, seconds = divmod(seconds, 60)
243.264 - if seconds or offset.microseconds:
243.265 - raise ValueError("tzinfo.%s() must return a whole number "
243.266 - "of minutes" % name)
243.267 - offset = minutes
243.268 - if -1440 < offset < 1440:
243.269 - return offset
243.270 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
243.271 -
243.272 -def _check_date_fields(year, month, day):
243.273 - if not MINYEAR <= year <= MAXYEAR:
243.274 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
243.275 - if not 1 <= month <= 12:
243.276 - raise ValueError('month must be in 1..12', month)
243.277 - dim = _days_in_month(year, month)
243.278 - if not 1 <= day <= dim:
243.279 - raise ValueError('day must be in 1..%d' % dim, day)
243.280 -
243.281 -def _check_time_fields(hour, minute, second, microsecond):
243.282 - if not 0 <= hour <= 23:
243.283 - raise ValueError('hour must be in 0..23', hour)
243.284 - if not 0 <= minute <= 59:
243.285 - raise ValueError('minute must be in 0..59', minute)
243.286 - if not 0 <= second <= 59:
243.287 - raise ValueError('second must be in 0..59', second)
243.288 - if not 0 <= microsecond <= 999999:
243.289 - raise ValueError('microsecond must be in 0..999999', microsecond)
243.290 -
243.291 -def _check_tzinfo_arg(tz):
243.292 - if tz is not None and not isinstance(tz, tzinfo):
243.293 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
243.294 -
243.295 -
243.296 -# Notes on comparison: In general, datetime module comparison operators raise
243.297 -# TypeError when they don't know how to do a comparison themself. If they
243.298 -# returned NotImplemented instead, comparison could (silently) fall back to
243.299 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
243.300 -# and that's not helpful. There are two exceptions:
243.301 -#
243.302 -# 1. For date and datetime, if the other object has a "timetuple" attr,
243.303 -# NotImplemented is returned. This is a hook to allow other kinds of
243.304 -# datetime-like objects a chance to intercept the comparison.
243.305 -#
243.306 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
243.307 -# so opertaions like
243.308 -#
243.309 -# x == y
243.310 -# x != y
243.311 -# x in sequence
243.312 -# x not in sequence
243.313 -# dict[x] = y
243.314 -#
243.315 -# don't raise annoying TypeErrors just because a datetime object
243.316 -# is part of a heterogeneous collection. If there's no known way to
243.317 -# compare X to a datetime, saying they're not equal is reasonable.
243.318 -
243.319 -def _cmperror(x, y):
243.320 - raise TypeError("can't compare '%s' to '%s'" % (
243.321 - type(x).__name__, type(y).__name__))
243.322 -
243.323 -# This is a start at a struct tm workalike. Goals:
243.324 -#
243.325 -# + Works the same way across platforms.
243.326 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
243.327 -#
243.328 -# Note: I suspect it's best if this flavor of tm does *not* try to
243.329 -# second-guess timezones or DST. Instead fold whatever adjustments you want
243.330 -# into the minutes argument (and the constructor will normalize).
243.331 -
243.332 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
243.333 -
243.334 -class tmxxx:
243.335 -
243.336 - ordinal = None
243.337 -
243.338 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
243.339 - microsecond=0):
243.340 - # Normalize all the inputs, and store the normalized values.
243.341 - if not 0 <= microsecond <= 999999:
243.342 - carry, microsecond = divmod(microsecond, 1000000)
243.343 - second += carry
243.344 - if not 0 <= second <= 59:
243.345 - carry, second = divmod(second, 60)
243.346 - minute += carry
243.347 - if not 0 <= minute <= 59:
243.348 - carry, minute = divmod(minute, 60)
243.349 - hour += carry
243.350 - if not 0 <= hour <= 23:
243.351 - carry, hour = divmod(hour, 24)
243.352 - day += carry
243.353 -
243.354 - # That was easy. Now it gets muddy: the proper range for day
243.355 - # can't be determined without knowing the correct month and year,
243.356 - # but if day is, e.g., plus or minus a million, the current month
243.357 - # and year values make no sense (and may also be out of bounds
243.358 - # themselves).
243.359 - # Saying 12 months == 1 year should be non-controversial.
243.360 - if not 1 <= month <= 12:
243.361 - carry, month = divmod(month-1, 12)
243.362 - year += carry
243.363 - month += 1
243.364 - assert 1 <= month <= 12
243.365 -
243.366 - # Now only day can be out of bounds (year may also be out of bounds
243.367 - # for a datetime object, but we don't care about that here).
243.368 - # If day is out of bounds, what to do is arguable, but at least the
243.369 - # method here is principled and explainable.
243.370 - dim = _days_in_month(year, month)
243.371 - if not 1 <= day <= dim:
243.372 - # Move day-1 days from the first of the month. First try to
243.373 - # get off cheap if we're only one day out of range (adjustments
243.374 - # for timezone alone can't be worse than that).
243.375 - if day == 0: # move back a day
243.376 - month -= 1
243.377 - if month > 0:
243.378 - day = _days_in_month(year, month)
243.379 - else:
243.380 - year, month, day = year-1, 12, 31
243.381 - elif day == dim + 1: # move forward a day
243.382 - month += 1
243.383 - day = 1
243.384 - if month > 12:
243.385 - month = 1
243.386 - year += 1
243.387 - else:
243.388 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
243.389 - year, month, day = _ord2ymd(self.ordinal)
243.390 -
243.391 - self.year, self.month, self.day = year, month, day
243.392 - self.hour, self.minute, self.second = hour, minute, second
243.393 - self.microsecond = microsecond
243.394 -
243.395 - def toordinal(self):
243.396 - """Return proleptic Gregorian ordinal for the year, month and day.
243.397 -
243.398 - January 1 of year 1 is day 1. Only the year, month and day values
243.399 - contribute to the result.
243.400 - """
243.401 - if self.ordinal is None:
243.402 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
243.403 - return self.ordinal
243.404 -
243.405 - def time(self):
243.406 - "Return Unixish timestamp, as a float (assuming UTC)."
243.407 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
243.408 - seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
243.409 - return seconds + self.second + self.microsecond / 1e6
243.410 -
243.411 - def ctime(self):
243.412 - "Return ctime() style string."
243.413 - weekday = self.toordinal() % 7 or 7
243.414 - return "%s %s %2d %02d:%02d:%02d %04d" % (
243.415 - _DAYNAMES[weekday],
243.416 - _MONTHNAMES[self.month],
243.417 - self.day,
243.418 - self.hour, self.minute, self.second,
243.419 - self.year)
243.420 -
243.421 -class timedelta(object):
243.422 - """Represent the difference between two datetime objects.
243.423 -
243.424 - Supported operators:
243.425 -
243.426 - - add, subtract timedelta
243.427 - - unary plus, minus, abs
243.428 - - compare to timedelta
243.429 - - multiply, divide by int/long
243.430 -
243.431 - In addition, datetime supports subtraction of two datetime objects
243.432 - returning a timedelta, and addition or subtraction of a datetime
243.433 - and a timedelta giving a datetime.
243.434 -
243.435 - Representation: (days, seconds, microseconds). Why? Because I
243.436 - felt like it.
243.437 - """
243.438 -
243.439 - def __new__(cls, days=0, seconds=0, microseconds=0,
243.440 - # XXX The following should only be used as keyword args:
243.441 - milliseconds=0, minutes=0, hours=0, weeks=0):
243.442 - # Doing this efficiently and accurately in C is going to be difficult
243.443 - # and error-prone, due to ubiquitous overflow possibilities, and that
243.444 - # C double doesn't have enough bits of precision to represent
243.445 - # microseconds over 10K years faithfully. The code here tries to make
243.446 - # explicit where go-fast assumptions can be relied on, in order to
243.447 - # guide the C implementation; it's way more convoluted than speed-
243.448 - # ignoring auto-overflow-to-long idiomatic Python could be.
243.449 -
243.450 - # XXX Check that all inputs are ints, longs or floats.
243.451 -
243.452 - # Final values, all integer.
243.453 - # s and us fit in 32-bit signed ints; d isn't bounded.
243.454 - d = s = us = 0
243.455 -
243.456 - # Normalize everything to days, seconds, microseconds.
243.457 - days += weeks*7
243.458 - seconds += minutes*60 + hours*3600
243.459 - microseconds += milliseconds*1000
243.460 -
243.461 - # Get rid of all fractions, and normalize s and us.
243.462 - # Take a deep breath <wink>.
243.463 - if isinstance(days, float):
243.464 - dayfrac, days = _math.modf(days)
243.465 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
243.466 - assert daysecondswhole == int(daysecondswhole) # can't overflow
243.467 - s = int(daysecondswhole)
243.468 - assert days == long(days)
243.469 - d = long(days)
243.470 - else:
243.471 - daysecondsfrac = 0.0
243.472 - d = days
243.473 - assert isinstance(daysecondsfrac, float)
243.474 - assert abs(daysecondsfrac) <= 1.0
243.475 - assert isinstance(d, (int, long))
243.476 - assert abs(s) <= 24 * 3600
243.477 - # days isn't referenced again before redefinition
243.478 -
243.479 - if isinstance(seconds, float):
243.480 - secondsfrac, seconds = _math.modf(seconds)
243.481 - assert seconds == long(seconds)
243.482 - seconds = long(seconds)
243.483 - secondsfrac += daysecondsfrac
243.484 - assert abs(secondsfrac) <= 2.0
243.485 - else:
243.486 - secondsfrac = daysecondsfrac
243.487 - # daysecondsfrac isn't referenced again
243.488 - assert isinstance(secondsfrac, float)
243.489 - assert abs(secondsfrac) <= 2.0
243.490 -
243.491 - assert isinstance(seconds, (int, long))
243.492 - days, seconds = divmod(seconds, 24*3600)
243.493 - d += days
243.494 - s += int(seconds) # can't overflow
243.495 - assert isinstance(s, int)
243.496 - assert abs(s) <= 2 * 24 * 3600
243.497 - # seconds isn't referenced again before redefinition
243.498 -
243.499 - usdouble = secondsfrac * 1e6
243.500 - assert abs(usdouble) < 2.1e6 # exact value not critical
243.501 - # secondsfrac isn't referenced again
243.502 -
243.503 - if isinstance(microseconds, float):
243.504 - microseconds += usdouble
243.505 - microseconds = round(microseconds)
243.506 - seconds, microseconds = divmod(microseconds, 1e6)
243.507 - assert microseconds == int(microseconds)
243.508 - assert seconds == long(seconds)
243.509 - days, seconds = divmod(seconds, 24.*3600.)
243.510 - assert days == long(days)
243.511 - assert seconds == int(seconds)
243.512 - d += long(days)
243.513 - s += int(seconds) # can't overflow
243.514 - assert isinstance(s, int)
243.515 - assert abs(s) <= 3 * 24 * 3600
243.516 - else:
243.517 - seconds, microseconds = divmod(microseconds, 1000000)
243.518 - days, seconds = divmod(seconds, 24*3600)
243.519 - d += days
243.520 - s += int(seconds) # can't overflow
243.521 - assert isinstance(s, int)
243.522 - assert abs(s) <= 3 * 24 * 3600
243.523 - microseconds = float(microseconds)
243.524 - microseconds += usdouble
243.525 - microseconds = round(microseconds)
243.526 - assert abs(s) <= 3 * 24 * 3600
243.527 - assert abs(microseconds) < 3.1e6
243.528 -
243.529 - # Just a little bit of carrying possible for microseconds and seconds.
243.530 - assert isinstance(microseconds, float)
243.531 - assert int(microseconds) == microseconds
243.532 - us = int(microseconds)
243.533 - seconds, us = divmod(us, 1000000)
243.534 - s += seconds # cant't overflow
243.535 - assert isinstance(s, int)
243.536 - days, s = divmod(s, 24*3600)
243.537 - d += days
243.538 -
243.539 - assert isinstance(d, (int, long))
243.540 - assert isinstance(s, int) and 0 <= s < 24*3600
243.541 - assert isinstance(us, int) and 0 <= us < 1000000
243.542 -
243.543 - self = object.__new__(cls)
243.544 -
243.545 - self.__days = d
243.546 - self.__seconds = s
243.547 - self.__microseconds = us
243.548 - if abs(d) > 999999999:
243.549 - raise OverflowError("timedelta # of days is too large: %d" % d)
243.550 -
243.551 - return self
243.552 -
243.553 - def __repr__(self):
243.554 - if self.__microseconds:
243.555 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
243.556 - self.__days,
243.557 - self.__seconds,
243.558 - self.__microseconds)
243.559 - if self.__seconds:
243.560 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
243.561 - self.__days,
243.562 - self.__seconds)
243.563 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
243.564 -
243.565 - def __str__(self):
243.566 - mm, ss = divmod(self.__seconds, 60)
243.567 - hh, mm = divmod(mm, 60)
243.568 - s = "%d:%02d:%02d" % (hh, mm, ss)
243.569 - if self.__days:
243.570 - def plural(n):
243.571 - return n, abs(n) != 1 and "s" or ""
243.572 - s = ("%d day%s, " % plural(self.__days)) + s
243.573 - if self.__microseconds:
243.574 - s = s + ".%06d" % self.__microseconds
243.575 - return s
243.576 -
243.577 - days = property(lambda self: self.__days, doc="days")
243.578 - seconds = property(lambda self: self.__seconds, doc="seconds")
243.579 - microseconds = property(lambda self: self.__microseconds,
243.580 - doc="microseconds")
243.581 -
243.582 - def __add__(self, other):
243.583 - if isinstance(other, timedelta):
243.584 - return timedelta(self.__days + other.__days,
243.585 - self.__seconds + other.__seconds,
243.586 - self.__microseconds + other.__microseconds)
243.587 - return NotImplemented
243.588 -
243.589 - __radd__ = __add__
243.590 -
243.591 - def __sub__(self, other):
243.592 - if isinstance(other, timedelta):
243.593 - return self + -other
243.594 - return NotImplemented
243.595 -
243.596 - def __rsub__(self, other):
243.597 - if isinstance(other, timedelta):
243.598 - return -self + other
243.599 - return NotImplemented
243.600 -
243.601 - def __neg__(self):
243.602 - return self.__class__(-self.__days,
243.603 - -self.__seconds,
243.604 - -self.__microseconds)
243.605 -
243.606 - def __pos__(self):
243.607 - return self
243.608 -
243.609 - def __abs__(self):
243.610 - if self.__days < 0:
243.611 - return -self
243.612 - else:
243.613 - return self
243.614 -
243.615 - def __mul__(self, other):
243.616 - if isinstance(other, (int, long)):
243.617 - return self.__class__(self.__days * other,
243.618 - self.__seconds * other,
243.619 - self.__microseconds * other)
243.620 - return NotImplemented
243.621 -
243.622 - __rmul__ = __mul__
243.623 -
243.624 - def __div__(self, other):
243.625 - if isinstance(other, (int, long)):
243.626 - usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
243.627 - self.__microseconds)
243.628 - return self.__class__(0, 0, usec // other)
243.629 - return NotImplemented
243.630 -
243.631 - __floordiv__ = __div__
243.632 -
243.633 - # Comparisons.
243.634 -
243.635 - def __eq__(self, other):
243.636 - if isinstance(other, timedelta):
243.637 - return self.__cmp(other) == 0
243.638 - else:
243.639 - return False
243.640 -
243.641 - def __ne__(self, other):
243.642 - if isinstance(other, timedelta):
243.643 - return self.__cmp(other) != 0
243.644 - else:
243.645 - return True
243.646 -
243.647 - def __le__(self, other):
243.648 - if isinstance(other, timedelta):
243.649 - return self.__cmp(other) <= 0
243.650 - else:
243.651 - _cmperror(self, other)
243.652 -
243.653 - def __lt__(self, other):
243.654 - if isinstance(other, timedelta):
243.655 - return self.__cmp(other) < 0
243.656 - else:
243.657 - _cmperror(self, other)
243.658 -
243.659 - def __ge__(self, other):
243.660 - if isinstance(other, timedelta):
243.661 - return self.__cmp(other) >= 0
243.662 - else:
243.663 - _cmperror(self, other)
243.664 -
243.665 - def __gt__(self, other):
243.666 - if isinstance(other, timedelta):
243.667 - return self.__cmp(other) > 0
243.668 - else:
243.669 - _cmperror(self, other)
243.670 -
243.671 - def __cmp(self, other):
243.672 - assert isinstance(other, timedelta)
243.673 - return cmp(self.__getstate(), other.__getstate())
243.674 -
243.675 - def __hash__(self):
243.676 - return hash(self.__getstate())
243.677 -
243.678 - def __nonzero__(self):
243.679 - return (self.__days != 0 or
243.680 - self.__seconds != 0 or
243.681 - self.__microseconds != 0)
243.682 -
243.683 - # Pickle support.
243.684 -
243.685 - __safe_for_unpickling__ = True # For Python 2.2
243.686 -
243.687 - def __getstate(self):
243.688 - return (self.__days, self.__seconds, self.__microseconds)
243.689 -
243.690 - def __reduce__(self):
243.691 - return (self.__class__, self.__getstate())
243.692 -
243.693 -timedelta.min = timedelta(-999999999)
243.694 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
243.695 - microseconds=999999)
243.696 -timedelta.resolution = timedelta(microseconds=1)
243.697 -
243.698 -class date(object):
243.699 - """Concrete date type.
243.700 -
243.701 - Constructors:
243.702 -
243.703 - __new__()
243.704 - fromtimestamp()
243.705 - today()
243.706 - fromordinal()
243.707 -
243.708 - Operators:
243.709 -
243.710 - __repr__, __str__
243.711 - __cmp__, __hash__
243.712 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
243.713 -
243.714 - Methods:
243.715 -
243.716 - timetuple()
243.717 - toordinal()
243.718 - weekday()
243.719 - isoweekday(), isocalendar(), isoformat()
243.720 - ctime()
243.721 - strftime()
243.722 -
243.723 - Properties (readonly):
243.724 - year, month, day
243.725 - """
243.726 -
243.727 - def __new__(cls, year, month=None, day=None):
243.728 - """Constructor.
243.729 -
243.730 - Arguments:
243.731 -
243.732 - year, month, day (required, base 1)
243.733 - """
243.734 - if isinstance(year, str):
243.735 - # Pickle support
243.736 - self = object.__new__(cls)
243.737 - self.__setstate((year,))
243.738 - return self
243.739 - _check_date_fields(year, month, day)
243.740 - self = object.__new__(cls)
243.741 - self.__year = year
243.742 - self.__month = month
243.743 - self.__day = day
243.744 - return self
243.745 -
243.746 - # Additional constructors
243.747 -
243.748 - def fromtimestamp(cls, t):
243.749 - "Construct a date from a POSIX timestamp (like time.time())."
243.750 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
243.751 - return cls(y, m, d)
243.752 - fromtimestamp = classmethod(fromtimestamp)
243.753 -
243.754 - def today(cls):
243.755 - "Construct a date from time.time()."
243.756 - t = _time.time()
243.757 - return cls.fromtimestamp(t)
243.758 - today = classmethod(today)
243.759 -
243.760 - def fromordinal(cls, n):
243.761 - """Contruct a date from a proleptic Gregorian ordinal.
243.762 -
243.763 - January 1 of year 1 is day 1. Only the year, month and day are
243.764 - non-zero in the result.
243.765 - """
243.766 - y, m, d = _ord2ymd(n)
243.767 - return cls(y, m, d)
243.768 - fromordinal = classmethod(fromordinal)
243.769 -
243.770 - # Conversions to string
243.771 -
243.772 - def __repr__(self):
243.773 - "Convert to formal string, for repr()."
243.774 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
243.775 - self.__year,
243.776 - self.__month,
243.777 - self.__day)
243.778 - # XXX These shouldn't depend on time.localtime(), because that
243.779 - # clips the usable dates to [1970 .. 2038). At least ctime() is
243.780 - # easily done without using strftime() -- that's better too because
243.781 - # strftime("%c", ...) is locale specific.
243.782 -
243.783 - def ctime(self):
243.784 - "Format a la ctime()."
243.785 - return tmxxx(self.__year, self.__month, self.__day).ctime()
243.786 -
243.787 - def strftime(self, fmt):
243.788 - "Format using strftime()."
243.789 - return _wrap_strftime(self, fmt, self.timetuple())
243.790 -
243.791 - def isoformat(self):
243.792 - """Return the date formatted according to ISO.
243.793 -
243.794 - This is 'YYYY-MM-DD'.
243.795 -
243.796 - References:
243.797 - - http://www.w3.org/TR/NOTE-datetime
243.798 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
243.799 - """
243.800 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
243.801 -
243.802 - __str__ = isoformat
243.803 -
243.804 - # Read-only field accessors
243.805 - year = property(lambda self: self.__year,
243.806 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
243.807 - month = property(lambda self: self.__month, doc="month (1-12)")
243.808 - day = property(lambda self: self.__day, doc="day (1-31)")
243.809 -
243.810 - # Standard conversions, __cmp__, __hash__ (and helpers)
243.811 -
243.812 - def timetuple(self):
243.813 - "Return local time tuple compatible with time.localtime()."
243.814 - return _build_struct_time(self.__year, self.__month, self.__day,
243.815 - 0, 0, 0, -1)
243.816 -
243.817 - def toordinal(self):
243.818 - """Return proleptic Gregorian ordinal for the year, month and day.
243.819 -
243.820 - January 1 of year 1 is day 1. Only the year, month and day values
243.821 - contribute to the result.
243.822 - """
243.823 - return _ymd2ord(self.__year, self.__month, self.__day)
243.824 -
243.825 - def replace(self, year=None, month=None, day=None):
243.826 - """Return a new date with new values for the specified fields."""
243.827 - if year is None:
243.828 - year = self.__year
243.829 - if month is None:
243.830 - month = self.__month
243.831 - if day is None:
243.832 - day = self.__day
243.833 - _check_date_fields(year, month, day)
243.834 - return date(year, month, day)
243.835 -
243.836 - # Comparisons.
243.837 -
243.838 - def __eq__(self, other):
243.839 - if isinstance(other, date):
243.840 - return self.__cmp(other) == 0
243.841 - elif hasattr(other, "timetuple"):
243.842 - return NotImplemented
243.843 - else:
243.844 - return False
243.845 -
243.846 - def __ne__(self, other):
243.847 - if isinstance(other, date):
243.848 - return self.__cmp(other) != 0
243.849 - elif hasattr(other, "timetuple"):
243.850 - return NotImplemented
243.851 - else:
243.852 - return True
243.853 -
243.854 - def __le__(self, other):
243.855 - if isinstance(other, date):
243.856 - return self.__cmp(other) <= 0
243.857 - elif hasattr(other, "timetuple"):
243.858 - return NotImplemented
243.859 - else:
243.860 - _cmperror(self, other)
243.861 -
243.862 - def __lt__(self, other):
243.863 - if isinstance(other, date):
243.864 - return self.__cmp(other) < 0
243.865 - elif hasattr(other, "timetuple"):
243.866 - return NotImplemented
243.867 - else:
243.868 - _cmperror(self, other)
243.869 -
243.870 - def __ge__(self, other):
243.871 - if isinstance(other, date):
243.872 - return self.__cmp(other) >= 0
243.873 - elif hasattr(other, "timetuple"):
243.874 - return NotImplemented
243.875 - else:
243.876 - _cmperror(self, other)
243.877 -
243.878 - def __gt__(self, other):
243.879 - if isinstance(other, date):
243.880 - return self.__cmp(other) > 0
243.881 - elif hasattr(other, "timetuple"):
243.882 - return NotImplemented
243.883 - else:
243.884 - _cmperror(self, other)
243.885 -
243.886 - def __cmp(self, other):
243.887 - assert isinstance(other, date)
243.888 - y, m, d = self.__year, self.__month, self.__day
243.889 - y2, m2, d2 = other.__year, other.__month, other.__day
243.890 - return cmp((y, m, d), (y2, m2, d2))
243.891 -
243.892 - def __hash__(self):
243.893 - "Hash."
243.894 - return hash(self.__getstate())
243.895 -
243.896 - # Computations
243.897 -
243.898 - def _checkOverflow(self, year):
243.899 - if not MINYEAR <= year <= MAXYEAR:
243.900 - raise OverflowError("date +/-: result year %d not in %d..%d" %
243.901 - (year, MINYEAR, MAXYEAR))
243.902 -
243.903 - def __add__(self, other):
243.904 - "Add a date to a timedelta."
243.905 - if isinstance(other, timedelta):
243.906 - t = tmxxx(self.__year,
243.907 - self.__month,
243.908 - self.__day + other.days)
243.909 - self._checkOverflow(t.year)
243.910 - result = self.__class__(t.year, t.month, t.day)
243.911 - return result
243.912 - return NotImplemented
243.913 -
243.914 - __radd__ = __add__
243.915 -
243.916 - def __sub__(self, other):
243.917 - """Subtract two dates, or a date and a timedelta."""
243.918 - if isinstance(other, timedelta):
243.919 - return self + timedelta(-other.days)
243.920 - if isinstance(other, date):
243.921 - days1 = self.toordinal()
243.922 - days2 = other.toordinal()
243.923 - return timedelta(days1 - days2)
243.924 - return NotImplemented
243.925 -
243.926 - def weekday(self):
243.927 - "Return day of the week, where Monday == 0 ... Sunday == 6."
243.928 - return (self.toordinal() + 6) % 7
243.929 -
243.930 - # Day-of-the-week and week-of-the-year, according to ISO
243.931 -
243.932 - def isoweekday(self):
243.933 - "Return day of the week, where Monday == 1 ... Sunday == 7."
243.934 - # 1-Jan-0001 is a Monday
243.935 - return self.toordinal() % 7 or 7
243.936 -
243.937 - def isocalendar(self):
243.938 - """Return a 3-tuple containing ISO year, week number, and weekday.
243.939 -
243.940 - The first ISO week of the year is the (Mon-Sun) week
243.941 - containing the year's first Thursday; everything else derives
243.942 - from that.
243.943 -
243.944 - The first week is 1; Monday is 1 ... Sunday is 7.
243.945 -
243.946 - ISO calendar algorithm taken from
243.947 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
243.948 - """
243.949 - year = self.__year
243.950 - week1monday = _isoweek1monday(year)
243.951 - today = _ymd2ord(self.__year, self.__month, self.__day)
243.952 - # Internally, week and day have origin 0
243.953 - week, day = divmod(today - week1monday, 7)
243.954 - if week < 0:
243.955 - year -= 1
243.956 - week1monday = _isoweek1monday(year)
243.957 - week, day = divmod(today - week1monday, 7)
243.958 - elif week >= 52:
243.959 - if today >= _isoweek1monday(year+1):
243.960 - year += 1
243.961 - week = 0
243.962 - return year, week+1, day+1
243.963 -
243.964 - # Pickle support.
243.965 -
243.966 - __safe_for_unpickling__ = True # For Python 2.2
243.967 -
243.968 - def __getstate(self):
243.969 - yhi, ylo = divmod(self.__year, 256)
243.970 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
243.971 -
243.972 - def __setstate(self, t):
243.973 - assert isinstance(t, tuple) and len(t) == 1, `t`
243.974 - string = t[0]
243.975 - assert len(string) == 4
243.976 - yhi, ylo, self.__month, self.__day = map(ord, string)
243.977 - self.__year = yhi * 256 + ylo
243.978 -
243.979 - def __reduce__(self):
243.980 - return (self.__class__, self.__getstate())
243.981 -
243.982 -_date_class = date # so functions w/ args named "date" can get at the class
243.983 -
243.984 -date.min = date(1, 1, 1)
243.985 -date.max = date(9999, 12, 31)
243.986 -date.resolution = timedelta(days=1)
243.987 -
243.988 -class tzinfo(object):
243.989 - """Abstract base class for time zone info classes.
243.990 -
243.991 - Subclasses must override the name(), utcoffset() and dst() methods.
243.992 - """
243.993 -
243.994 - def tzname(self, dt):
243.995 - "datetime -> string name of time zone."
243.996 - raise NotImplementedError("tzinfo subclass must override tzname()")
243.997 -
243.998 - def utcoffset(self, dt):
243.999 - "datetime -> minutes east of UTC (negative for west of UTC)"
243.1000 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
243.1001 -
243.1002 - def dst(self, dt):
243.1003 - """datetime -> DST offset in minutes east of UTC.
243.1004 -
243.1005 - Return 0 if DST not in effect. utcoffset() must include the DST
243.1006 - offset.
243.1007 - """
243.1008 - raise NotImplementedError("tzinfo subclass must override dst()")
243.1009 -
243.1010 - def fromutc(self, dt):
243.1011 - "datetime in UTC -> datetime in local time."
243.1012 -
243.1013 - if not isinstance(dt, datetime):
243.1014 - raise TypeError("fromutc() requires a datetime argument")
243.1015 - if dt.tzinfo is not self:
243.1016 - raise ValueError("dt.tzinfo is not self")
243.1017 -
243.1018 - dtoff = dt.utcoffset()
243.1019 - if dtoff is None:
243.1020 - raise ValueError("fromutc() requires a non-None utcoffset() "
243.1021 - "result")
243.1022 -
243.1023 - # See the long comment block at the end of this file for an
243.1024 - # explanation of this algorithm.
243.1025 - dtdst = dt.dst()
243.1026 - if dtdst is None:
243.1027 - raise ValueError("fromutc() requires a non-None dst() result")
243.1028 - delta = dtoff - dtdst
243.1029 - if delta:
243.1030 - dt += delta
243.1031 - dtdst = dt.dst()
243.1032 - if dtdst is None:
243.1033 - raise ValueError("fromutc(): dt.dst gave inconsistent "
243.1034 - "results; cannot convert")
243.1035 - if dtdst:
243.1036 - return dt + dtdst
243.1037 - else:
243.1038 - return dt
243.1039 -
243.1040 - # Pickle support.
243.1041 -
243.1042 - __safe_for_unpickling__ = True # For Python 2.2
243.1043 -
243.1044 - def __reduce__(self):
243.1045 - getinitargs = getattr(self, "__getinitargs__", None)
243.1046 - if getinitargs:
243.1047 - args = getinitargs()
243.1048 - else:
243.1049 - args = ()
243.1050 - getstate = getattr(self, "__getstate__", None)
243.1051 - if getstate:
243.1052 - state = getstate()
243.1053 - else:
243.1054 - state = getattr(self, "__dict__", None) or None
243.1055 - if state is None:
243.1056 - return (self.__class__, args)
243.1057 - else:
243.1058 - return (self.__class__, args, state)
243.1059 -
243.1060 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
243.1061 -
243.1062 -class time(object):
243.1063 - """Time with time zone.
243.1064 -
243.1065 - Constructors:
243.1066 -
243.1067 - __new__()
243.1068 -
243.1069 - Operators:
243.1070 -
243.1071 - __repr__, __str__
243.1072 - __cmp__, __hash__
243.1073 -
243.1074 - Methods:
243.1075 -
243.1076 - strftime()
243.1077 - isoformat()
243.1078 - utcoffset()
243.1079 - tzname()
243.1080 - dst()
243.1081 -
243.1082 - Properties (readonly):
243.1083 - hour, minute, second, microsecond, tzinfo
243.1084 - """
243.1085 -
243.1086 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
243.1087 - """Constructor.
243.1088 -
243.1089 - Arguments:
243.1090 -
243.1091 - hour, minute (required)
243.1092 - second, microsecond (default to zero)
243.1093 - tzinfo (default to None)
243.1094 - """
243.1095 - self = object.__new__(cls)
243.1096 - if isinstance(hour, str):
243.1097 - # Pickle support
243.1098 - self.__setstate((hour, minute or None))
243.1099 - return self
243.1100 - _check_tzinfo_arg(tzinfo)
243.1101 - _check_time_fields(hour, minute, second, microsecond)
243.1102 - self.__hour = hour
243.1103 - self.__minute = minute
243.1104 - self.__second = second
243.1105 - self.__microsecond = microsecond
243.1106 - self._tzinfo = tzinfo
243.1107 - return self
243.1108 -
243.1109 - # Read-only field accessors
243.1110 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
243.1111 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
243.1112 - second = property(lambda self: self.__second, doc="second (0-59)")
243.1113 - microsecond = property(lambda self: self.__microsecond,
243.1114 - doc="microsecond (0-999999)")
243.1115 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
243.1116 -
243.1117 - # Standard conversions, __hash__ (and helpers)
243.1118 -
243.1119 - # Comparisons.
243.1120 -
243.1121 - def __eq__(self, other):
243.1122 - if isinstance(other, time):
243.1123 - return self.__cmp(other) == 0
243.1124 - else:
243.1125 - return False
243.1126 -
243.1127 - def __ne__(self, other):
243.1128 - if isinstance(other, time):
243.1129 - return self.__cmp(other) != 0
243.1130 - else:
243.1131 - return True
243.1132 -
243.1133 - def __le__(self, other):
243.1134 - if isinstance(other, time):
243.1135 - return self.__cmp(other) <= 0
243.1136 - else:
243.1137 - _cmperror(self, other)
243.1138 -
243.1139 - def __lt__(self, other):
243.1140 - if isinstance(other, time):
243.1141 - return self.__cmp(other) < 0
243.1142 - else:
243.1143 - _cmperror(self, other)
243.1144 -
243.1145 - def __ge__(self, other):
243.1146 - if isinstance(other, time):
243.1147 - return self.__cmp(other) >= 0
243.1148 - else:
243.1149 - _cmperror(self, other)
243.1150 -
243.1151 - def __gt__(self, other):
243.1152 - if isinstance(other, time):
243.1153 - return self.__cmp(other) > 0
243.1154 - else:
243.1155 - _cmperror(self, other)
243.1156 -
243.1157 - def __cmp(self, other):
243.1158 - assert isinstance(other, time)
243.1159 - mytz = self._tzinfo
243.1160 - ottz = other._tzinfo
243.1161 - myoff = otoff = None
243.1162 -
243.1163 - if mytz is ottz:
243.1164 - base_compare = True
243.1165 - else:
243.1166 - myoff = self._utcoffset()
243.1167 - otoff = other._utcoffset()
243.1168 - base_compare = myoff == otoff
243.1169 -
243.1170 - if base_compare:
243.1171 - return cmp((self.__hour, self.__minute, self.__second,
243.1172 - self.__microsecond),
243.1173 - (other.__hour, other.__minute, other.__second,
243.1174 - other.__microsecond))
243.1175 - if myoff is None or otoff is None:
243.1176 - # XXX Buggy in 2.2.2.
243.1177 - raise TypeError("cannot compare naive and aware times")
243.1178 - myhhmm = self.__hour * 60 + self.__minute - myoff
243.1179 - othhmm = other.__hour * 60 + other.__minute - otoff
243.1180 - return cmp((myhhmm, self.__second, self.__microsecond),
243.1181 - (othhmm, other.__second, other.__microsecond))
243.1182 -
243.1183 - def __hash__(self):
243.1184 - """Hash."""
243.1185 - tzoff = self._utcoffset()
243.1186 - if not tzoff: # zero or None
243.1187 - return hash(self.__getstate()[0])
243.1188 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
243.1189 - if 0 <= h < 24:
243.1190 - return hash(time(h, m, self.second, self.microsecond))
243.1191 - return hash((h, m, self.second, self.microsecond))
243.1192 -
243.1193 - # Conversion to string
243.1194 -
243.1195 - def _tzstr(self, sep=":"):
243.1196 - """Return formatted timezone offset (+xx:xx) or None."""
243.1197 - off = self._utcoffset()
243.1198 - if off is not None:
243.1199 - if off < 0:
243.1200 - sign = "-"
243.1201 - off = -off
243.1202 - else:
243.1203 - sign = "+"
243.1204 - hh, mm = divmod(off, 60)
243.1205 - assert 0 <= hh < 24
243.1206 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
243.1207 - return off
243.1208 -
243.1209 - def __repr__(self):
243.1210 - """Convert to formal string, for repr()."""
243.1211 - if self.__microsecond != 0:
243.1212 - s = ", %d, %d" % (self.__second, self.__microsecond)
243.1213 - elif self.__second != 0:
243.1214 - s = ", %d" % self.__second
243.1215 - else:
243.1216 - s = ""
243.1217 - s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
243.1218 - self.__hour, self.__minute, s)
243.1219 - if self._tzinfo is not None:
243.1220 - assert s[-1:] == ")"
243.1221 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
243.1222 - return s
243.1223 -
243.1224 - def isoformat(self):
243.1225 - """Return the time formatted according to ISO.
243.1226 -
243.1227 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
243.1228 - self.microsecond == 0.
243.1229 - """
243.1230 - s = _format_time(self.__hour, self.__minute, self.__second,
243.1231 - self.__microsecond)
243.1232 - tz = self._tzstr()
243.1233 - if tz:
243.1234 - s += tz
243.1235 - return s
243.1236 -
243.1237 - __str__ = isoformat
243.1238 -
243.1239 - def strftime(self, fmt):
243.1240 - """Format using strftime(). The date part of the timestamp passed
243.1241 - to underlying strftime should not be used.
243.1242 - """
243.1243 - # The year must be >= 1900 else Python's strftime implementation
243.1244 - # can raise a bogus exception.
243.1245 - timetuple = (1900, 1, 1,
243.1246 - self.__hour, self.__minute, self.__second,
243.1247 - 0, 1, -1)
243.1248 - return _wrap_strftime(self, fmt, timetuple)
243.1249 -
243.1250 - # Timezone functions
243.1251 -
243.1252 - def utcoffset(self):
243.1253 - """Return the timezone offset in minutes east of UTC (negative west of
243.1254 - UTC)."""
243.1255 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
243.1256 - offset = _check_utc_offset("utcoffset", offset)
243.1257 - if offset is not None:
243.1258 - offset = timedelta(minutes=offset)
243.1259 - return offset
243.1260 -
243.1261 - # Return an integer (or None) instead of a timedelta (or None).
243.1262 - def _utcoffset(self):
243.1263 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
243.1264 - offset = _check_utc_offset("utcoffset", offset)
243.1265 - return offset
243.1266 -
243.1267 - def tzname(self):
243.1268 - """Return the timezone name.
243.1269 -
243.1270 - Note that the name is 100% informational -- there's no requirement that
243.1271 - it mean anything in particular. For example, "GMT", "UTC", "-500",
243.1272 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
243.1273 - """
243.1274 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
243.1275 - _check_tzname(name)
243.1276 - return name
243.1277 -
243.1278 - def dst(self):
243.1279 - """Return 0 if DST is not in effect, or the DST offset (in minutes
243.1280 - eastward) if DST is in effect.
243.1281 -
243.1282 - This is purely informational; the DST offset has already been added to
243.1283 - the UTC offset returned by utcoffset() if applicable, so there's no
243.1284 - need to consult dst() unless you're interested in displaying the DST
243.1285 - info.
243.1286 - """
243.1287 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
243.1288 - offset = _check_utc_offset("dst", offset)
243.1289 - if offset is not None:
243.1290 - offset = timedelta(minutes=offset)
243.1291 - return offset
243.1292 -
243.1293 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
243.1294 - tzinfo=True):
243.1295 - """Return a new time with new values for the specified fields."""
243.1296 - if hour is None:
243.1297 - hour = self.hour
243.1298 - if minute is None:
243.1299 - minute = self.minute
243.1300 - if second is None:
243.1301 - second = self.second
243.1302 - if microsecond is None:
243.1303 - microsecond = self.microsecond
243.1304 - if tzinfo is True:
243.1305 - tzinfo = self.tzinfo
243.1306 - _check_time_fields(hour, minute, second, microsecond)
243.1307 - _check_tzinfo_arg(tzinfo)
243.1308 - return time(hour, minute, second, microsecond, tzinfo)
243.1309 -
243.1310 - # Return an integer (or None) instead of a timedelta (or None).
243.1311 - def _dst(self):
243.1312 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
243.1313 - offset = _check_utc_offset("dst", offset)
243.1314 - return offset
243.1315 -
243.1316 - def __nonzero__(self):
243.1317 - if self.second or self.microsecond:
243.1318 - return 1
243.1319 - offset = self._utcoffset() or 0
243.1320 - return self.hour * 60 + self.minute - offset != 0
243.1321 -
243.1322 - # Pickle support.
243.1323 -
243.1324 - __safe_for_unpickling__ = True # For Python 2.2
243.1325 -
243.1326 - def __getstate(self):
243.1327 - us2, us3 = divmod(self.__microsecond, 256)
243.1328 - us1, us2 = divmod(us2, 256)
243.1329 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
243.1330 - us1, us2, us3)
243.1331 - if self._tzinfo is None:
243.1332 - return (basestate,)
243.1333 - else:
243.1334 - return (basestate, self._tzinfo)
243.1335 -
243.1336 - def __setstate(self, state):
243.1337 - assert isinstance(state, tuple)
243.1338 - assert 1 <= len(state) <= 2
243.1339 - string = state[0]
243.1340 - assert len(string) == 6
243.1341 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
243.1342 - map(ord, string)
243.1343 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
243.1344 - if len(state) == 1:
243.1345 - self._tzinfo = None
243.1346 - else:
243.1347 - self._tzinfo = state[1]
243.1348 -
243.1349 - def __reduce__(self):
243.1350 - return (self.__class__, self.__getstate())
243.1351 -
243.1352 -_time_class = time # so functions w/ args named "time" can get at the class
243.1353 -
243.1354 -time.min = time(0, 0, 0)
243.1355 -time.max = time(23, 59, 59, 999999)
243.1356 -time.resolution = timedelta(microseconds=1)
243.1357 -
243.1358 -class datetime(date):
243.1359 -
243.1360 - # XXX needs docstrings
243.1361 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
243.1362 -
243.1363 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
243.1364 - microsecond=0, tzinfo=None):
243.1365 - if isinstance(year, str):
243.1366 - # Pickle support
243.1367 - self = date.__new__(cls, year[:4])
243.1368 - self.__setstate((year, month))
243.1369 - return self
243.1370 - _check_tzinfo_arg(tzinfo)
243.1371 - _check_time_fields(hour, minute, second, microsecond)
243.1372 - self = date.__new__(cls, year, month, day)
243.1373 - # XXX This duplicates __year, __month, __day for convenience :-(
243.1374 - self.__year = year
243.1375 - self.__month = month
243.1376 - self.__day = day
243.1377 - self.__hour = hour
243.1378 - self.__minute = minute
243.1379 - self.__second = second
243.1380 - self.__microsecond = microsecond
243.1381 - self._tzinfo = tzinfo
243.1382 - return self
243.1383 -
243.1384 - # Read-only field accessors
243.1385 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
243.1386 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
243.1387 - second = property(lambda self: self.__second, doc="second (0-59)")
243.1388 - microsecond = property(lambda self: self.__microsecond,
243.1389 - doc="microsecond (0-999999)")
243.1390 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
243.1391 -
243.1392 - def fromtimestamp(cls, t, tz=None):
243.1393 - """Construct a datetime from a POSIX timestamp (like time.time()).
243.1394 -
243.1395 - A timezone info object may be passed in as well.
243.1396 - """
243.1397 -
243.1398 - _check_tzinfo_arg(tz)
243.1399 - if tz is None:
243.1400 - converter = _time.localtime
243.1401 - else:
243.1402 - converter = _time.gmtime
243.1403 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
243.1404 - us = int((t % 1.0) * 1000000)
243.1405 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
243.1406 - result = cls(y, m, d, hh, mm, ss, us, tz)
243.1407 - if tz is not None:
243.1408 - result = tz.fromutc(result)
243.1409 - return result
243.1410 - fromtimestamp = classmethod(fromtimestamp)
243.1411 -
243.1412 - def utcfromtimestamp(cls, t):
243.1413 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
243.1414 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
243.1415 - us = int((t % 1.0) * 1000000)
243.1416 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
243.1417 - return cls(y, m, d, hh, mm, ss, us)
243.1418 - utcfromtimestamp = classmethod(utcfromtimestamp)
243.1419 -
243.1420 - # XXX This is supposed to do better than we *can* do by using time.time(),
243.1421 - # XXX if the platform supports a more accurate way. The C implementation
243.1422 - # XXX uses gettimeofday on platforms that have it, but that isn't
243.1423 - # XXX available from Python. So now() may return different results
243.1424 - # XXX across the implementations.
243.1425 - def now(cls, tz=None):
243.1426 - "Construct a datetime from time.time() and optional time zone info."
243.1427 - t = _time.time()
243.1428 - return cls.fromtimestamp(t, tz)
243.1429 - now = classmethod(now)
243.1430 -
243.1431 - def utcnow(cls):
243.1432 - "Construct a UTC datetime from time.time()."
243.1433 - t = _time.time()
243.1434 - return cls.utcfromtimestamp(t)
243.1435 - utcnow = classmethod(utcnow)
243.1436 -
243.1437 - def combine(cls, date, time):
243.1438 - "Construct a datetime from a given date and a given time."
243.1439 - if not isinstance(date, _date_class):
243.1440 - raise TypeError("date argument must be a date instance")
243.1441 - if not isinstance(time, _time_class):
243.1442 - raise TypeError("time argument must be a time instance")
243.1443 - return cls(date.year, date.month, date.day,
243.1444 - time.hour, time.minute, time.second, time.microsecond,
243.1445 - time.tzinfo)
243.1446 - combine = classmethod(combine)
243.1447 -
243.1448 - def timetuple(self):
243.1449 - "Return local time tuple compatible with time.localtime()."
243.1450 - dst = self._dst()
243.1451 - if dst is None:
243.1452 - dst = -1
243.1453 - elif dst:
243.1454 - dst = 1
243.1455 - return _build_struct_time(self.year, self.month, self.day,
243.1456 - self.hour, self.minute, self.second,
243.1457 - dst)
243.1458 -
243.1459 - def utctimetuple(self):
243.1460 - "Return UTC time tuple compatible with time.gmtime()."
243.1461 - y, m, d = self.year, self.month, self.day
243.1462 - hh, mm, ss = self.hour, self.minute, self.second
243.1463 - offset = self._utcoffset()
243.1464 - if offset: # neither None nor 0
243.1465 - tm = tmxxx(y, m, d, hh, mm - offset)
243.1466 - y, m, d = tm.year, tm.month, tm.day
243.1467 - hh, mm = tm.hour, tm.minute
243.1468 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
243.1469 -
243.1470 - def date(self):
243.1471 - "Return the date part."
243.1472 - return date(self.__year, self.__month, self.__day)
243.1473 -
243.1474 - def time(self):
243.1475 - "Return the time part, with tzinfo None."
243.1476 - return time(self.hour, self.minute, self.second, self.microsecond)
243.1477 -
243.1478 - def timetz(self):
243.1479 - "Return the time part, with same tzinfo."
243.1480 - return time(self.hour, self.minute, self.second, self.microsecond,
243.1481 - self._tzinfo)
243.1482 -
243.1483 - def replace(self, year=None, month=None, day=None, hour=None,
243.1484 - minute=None, second=None, microsecond=None, tzinfo=True):
243.1485 - """Return a new datetime with new values for the specified fields."""
243.1486 - if year is None:
243.1487 - year = self.year
243.1488 - if month is None:
243.1489 - month = self.month
243.1490 - if day is None:
243.1491 - day = self.day
243.1492 - if hour is None:
243.1493 - hour = self.hour
243.1494 - if minute is None:
243.1495 - minute = self.minute
243.1496 - if second is None:
243.1497 - second = self.second
243.1498 - if microsecond is None:
243.1499 - microsecond = self.microsecond
243.1500 - if tzinfo is True:
243.1501 - tzinfo = self.tzinfo
243.1502 - _check_date_fields(year, month, day)
243.1503 - _check_time_fields(hour, minute, second, microsecond)
243.1504 - _check_tzinfo_arg(tzinfo)
243.1505 - return datetime(year, month, day, hour, minute, second,
243.1506 - microsecond, tzinfo)
243.1507 -
243.1508 - def astimezone(self, tz):
243.1509 - if not isinstance(tz, tzinfo):
243.1510 - raise TypeError("tz argument must be an instance of tzinfo")
243.1511 -
243.1512 - mytz = self.tzinfo
243.1513 - if mytz is None:
243.1514 - raise ValueError("astimezone() requires an aware datetime")
243.1515 -
243.1516 - if tz is mytz:
243.1517 - return self
243.1518 -
243.1519 - # Convert self to UTC, and attach the new time zone object.
243.1520 - myoffset = self.utcoffset()
243.1521 - if myoffset is None:
243.1522 - raise ValuError("astimezone() requires an aware datetime")
243.1523 - utc = (self - myoffset).replace(tzinfo=tz)
243.1524 -
243.1525 - # Convert from UTC to tz's local time.
243.1526 - return tz.fromutc(utc)
243.1527 -
243.1528 - # Ways to produce a string.
243.1529 -
243.1530 - def ctime(self):
243.1531 - "Format a la ctime()."
243.1532 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
243.1533 - self.__minute, self.__second)
243.1534 - return t.ctime()
243.1535 -
243.1536 - def isoformat(self, sep='T'):
243.1537 - """Return the time formatted according to ISO.
243.1538 -
243.1539 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
243.1540 - self.microsecond == 0.
243.1541 -
243.1542 - If self.tzinfo is not None, the UTC offset is also attached, giving
243.1543 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
243.1544 -
243.1545 - Optional argument sep specifies the separator between date and
243.1546 - time, default 'T'.
243.1547 - """
243.1548 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
243.1549 - sep) +
243.1550 - _format_time(self.__hour, self.__minute, self.__second,
243.1551 - self.__microsecond))
243.1552 - off = self._utcoffset()
243.1553 - if off is not None:
243.1554 - if off < 0:
243.1555 - sign = "-"
243.1556 - off = -off
243.1557 - else:
243.1558 - sign = "+"
243.1559 - hh, mm = divmod(off, 60)
243.1560 - s += "%s%02d:%02d" % (sign, hh, mm)
243.1561 - return s
243.1562 -
243.1563 - def __repr__(self):
243.1564 - "Convert to formal string, for repr()."
243.1565 - L = [self.__year, self.__month, self.__day, # These are never zero
243.1566 - self.__hour, self.__minute, self.__second, self.__microsecond]
243.1567 - if L[-1] == 0:
243.1568 - del L[-1]
243.1569 - if L[-1] == 0:
243.1570 - del L[-1]
243.1571 - s = ", ".join(map(str, L))
243.1572 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
243.1573 - if self._tzinfo is not None:
243.1574 - assert s[-1:] == ")"
243.1575 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
243.1576 - return s
243.1577 -
243.1578 - def __str__(self):
243.1579 - "Convert to string, for str()."
243.1580 - return self.isoformat(sep=' ')
243.1581 -
243.1582 - def utcoffset(self):
243.1583 - """Return the timezone offset in minutes east of UTC (negative west of
243.1584 - UTC)."""
243.1585 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
243.1586 - offset = _check_utc_offset("utcoffset", offset)
243.1587 - if offset is not None:
243.1588 - offset = timedelta(minutes=offset)
243.1589 - return offset
243.1590 -
243.1591 - # Return an integer (or None) instead of a timedelta (or None).
243.1592 - def _utcoffset(self):
243.1593 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
243.1594 - offset = _check_utc_offset("utcoffset", offset)
243.1595 - return offset
243.1596 -
243.1597 - def tzname(self):
243.1598 - """Return the timezone name.
243.1599 -
243.1600 - Note that the name is 100% informational -- there's no requirement that
243.1601 - it mean anything in particular. For example, "GMT", "UTC", "-500",
243.1602 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
243.1603 - """
243.1604 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
243.1605 - _check_tzname(name)
243.1606 - return name
243.1607 -
243.1608 - def dst(self):
243.1609 - """Return 0 if DST is not in effect, or the DST offset (in minutes
243.1610 - eastward) if DST is in effect.
243.1611 -
243.1612 - This is purely informational; the DST offset has already been added to
243.1613 - the UTC offset returned by utcoffset() if applicable, so there's no
243.1614 - need to consult dst() unless you're interested in displaying the DST
243.1615 - info.
243.1616 - """
243.1617 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
243.1618 - offset = _check_utc_offset("dst", offset)
243.1619 - if offset is not None:
243.1620 - offset = timedelta(minutes=offset)
243.1621 - return offset
243.1622 -
243.1623 - # Return an integer (or None) instead of a timedelta (or None).1573
243.1624 - def _dst(self):
243.1625 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
243.1626 - offset = _check_utc_offset("dst", offset)
243.1627 - return offset
243.1628 -
243.1629 - # Comparisons.
243.1630 -
243.1631 - def __eq__(self, other):
243.1632 - if isinstance(other, datetime):
243.1633 - return self.__cmp(other) == 0
243.1634 - elif hasattr(other, "timetuple"):
243.1635 - return NotImplemented
243.1636 - else:
243.1637 - return False
243.1638 -
243.1639 - def __ne__(self, other):
243.1640 - if isinstance(other, datetime):
243.1641 - return self.__cmp(other) != 0
243.1642 - elif hasattr(other, "timetuple"):
243.1643 - return NotImplemented
243.1644 - else:
243.1645 - return True
243.1646 -
243.1647 - def __le__(self, other):
243.1648 - if isinstance(other, datetime):
243.1649 - return self.__cmp(other) <= 0
243.1650 - elif hasattr(other, "timetuple"):
243.1651 - return NotImplemented
243.1652 - else:
243.1653 - _cmperror(self, other)
243.1654 -
243.1655 - def __lt__(self, other):
243.1656 - if isinstance(other, datetime):
243.1657 - return self.__cmp(other) < 0
243.1658 - elif hasattr(other, "timetuple"):
243.1659 - return NotImplemented
243.1660 - else:
243.1661 - _cmperror(self, other)
243.1662 -
243.1663 - def __ge__(self, other):
243.1664 - if isinstance(other, datetime):
243.1665 - return self.__cmp(other) >= 0
243.1666 - elif hasattr(other, "timetuple"):
243.1667 - return NotImplemented
243.1668 - else:
243.1669 - _cmperror(self, other)
243.1670 -
243.1671 - def __gt__(self, other):
243.1672 - if isinstance(other, datetime):
243.1673 - return self.__cmp(other) > 0
243.1674 - elif hasattr(other, "timetuple"):
243.1675 - return NotImplemented
243.1676 - else:
243.1677 - _cmperror(self, other)
243.1678 -
243.1679 - def __cmp(self, other):
243.1680 - assert isinstance(other, datetime)
243.1681 - mytz = self._tzinfo
243.1682 - ottz = other._tzinfo
243.1683 - myoff = otoff = None
243.1684 -
243.1685 - if mytz is ottz:
243.1686 - base_compare = True
243.1687 - else:
243.1688 - if mytz is not None:
243.1689 - myoff = self._utcoffset()
243.1690 - if ottz is not None:
243.1691 - otoff = other._utcoffset()
243.1692 - base_compare = myoff == otoff
243.1693 -
243.1694 - if base_compare:
243.1695 - return cmp((self.__year, self.__month, self.__day,
243.1696 - self.__hour, self.__minute, self.__second,
243.1697 - self.__microsecond),
243.1698 - (other.__year, other.__month, other.__day,
243.1699 - other.__hour, other.__minute, other.__second,
243.1700 - other.__microsecond))
243.1701 - if myoff is None or otoff is None:
243.1702 - # XXX Buggy in 2.2.2.
243.1703 - raise TypeError("cannot compare naive and aware datetimes")
243.1704 - # XXX What follows could be done more efficiently...
243.1705 - diff = self - other # this will take offsets into account
243.1706 - if diff.days < 0:
243.1707 - return -1
243.1708 - return diff and 1 or 0
243.1709 -
243.1710 - def __add__(self, other):
243.1711 - "Add a datetime and a timedelta."
243.1712 - if not isinstance(other, timedelta):
243.1713 - return NotImplemented
243.1714 - t = tmxxx(self.__year,
243.1715 - self.__month,
243.1716 - self.__day + other.days,
243.1717 - self.__hour,
243.1718 - self.__minute,
243.1719 - self.__second + other.seconds,
243.1720 - self.__microsecond + other.microseconds)
243.1721 - self._checkOverflow(t.year)
243.1722 - result = self.__class__(t.year, t.month, t.day,
243.1723 - t.hour, t.minute, t.second,
243.1724 - t.microsecond, tzinfo=self._tzinfo)
243.1725 - return result
243.1726 -
243.1727 - __radd__ = __add__
243.1728 -
243.1729 - def __sub__(self, other):
243.1730 - "Subtract two datetimes, or a datetime and a timedelta."
243.1731 - if not isinstance(other, datetime):
243.1732 - if isinstance(other, timedelta):
243.1733 - return self + -other
243.1734 - return NotImplemented
243.1735 -
243.1736 - days1 = self.toordinal()
243.1737 - days2 = other.toordinal()
243.1738 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
243.1739 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
243.1740 - base = timedelta(days1 - days2,
243.1741 - secs1 - secs2,
243.1742 - self.__microsecond - other.__microsecond)
243.1743 - if self._tzinfo is other._tzinfo:
243.1744 - return base
243.1745 - myoff = self._utcoffset()
243.1746 - otoff = other._utcoffset()
243.1747 - if myoff == otoff:
243.1748 - return base
243.1749 - if myoff is None or otoff is None:
243.1750 - raise TypeError, "cannot mix naive and timezone-aware time"
243.1751 - return base + timedelta(minutes = otoff-myoff)
243.1752 -
243.1753 - def __hash__(self):
243.1754 - tzoff = self._utcoffset()
243.1755 - if tzoff is None:
243.1756 - return hash(self.__getstate()[0])
243.1757 - days = _ymd2ord(self.year, self.month, self.day)
243.1758 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
243.1759 - return hash(timedelta(days, seconds, self.microsecond))
243.1760 -
243.1761 - # Pickle support.
243.1762 -
243.1763 - __safe_for_unpickling__ = True # For Python 2.2
243.1764 -
243.1765 - def __getstate(self):
243.1766 - yhi, ylo = divmod(self.__year, 256)
243.1767 - us2, us3 = divmod(self.__microsecond, 256)
243.1768 - us1, us2 = divmod(us2, 256)
243.1769 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
243.1770 - self.__hour, self.__minute, self.__second,
243.1771 - us1, us2, us3)
243.1772 - if self._tzinfo is None:
243.1773 - return (basestate,)
243.1774 - else:
243.1775 - return (basestate, self._tzinfo)
243.1776 -
243.1777 - def __setstate(self, state):
243.1778 - assert isinstance(state, tuple)
243.1779 - assert 1 <= len(state) <= 2
243.1780 - string = state[0]
243.1781 - assert len(string) == 10
243.1782 - (yhi, ylo, self.__month, self.__day, self.__hour,
243.1783 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
243.1784 - self.__year = yhi * 256 + ylo
243.1785 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
243.1786 - if len(state) == 1:
243.1787 - self._tzinfo = None
243.1788 - else:
243.1789 - self._tzinfo = state[1]
243.1790 -
243.1791 - def __reduce__(self):
243.1792 - return (self.__class__, self.__getstate())
243.1793 -
243.1794 -
243.1795 -datetime.min = datetime(1, 1, 1)
243.1796 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
243.1797 -datetime.resolution = timedelta(microseconds=1)
243.1798 -
243.1799 -
243.1800 -def _isoweek1monday(year):
243.1801 - # Helper to calculate the day number of the Monday starting week 1
243.1802 - # XXX This could be done more efficiently
243.1803 - THURSDAY = 3
243.1804 - firstday = _ymd2ord(year, 1, 1)
243.1805 - firstweekday = (firstday + 6) % 7 # See weekday() above
243.1806 - week1monday = firstday - firstweekday
243.1807 - if firstweekday > THURSDAY:
243.1808 - week1monday += 7
243.1809 - return week1monday
243.1810 -
243.1811 -"""
243.1812 -Some time zone algebra. For a datetime x, let
243.1813 - x.n = x stripped of its timezone -- its naive time.
243.1814 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
243.1815 - return None
243.1816 - x.d = x.dst(), and assuming that doesn't raise an exception or
243.1817 - return None
243.1818 - x.s = x's standard offset, x.o - x.d
243.1819 -
243.1820 -Now some derived rules, where k is a duration (timedelta).
243.1821 -
243.1822 -1. x.o = x.s + x.d
243.1823 - This follows from the definition of x.s.
243.1824 -
243.1825 -2. If x and y have the same tzinfo member, x.s = y.s.
243.1826 - This is actually a requirement, an assumption we need to make about
243.1827 - sane tzinfo classes.
243.1828 -
243.1829 -3. The naive UTC time corresponding to x is x.n - x.o.
243.1830 - This is again a requirement for a sane tzinfo class.
243.1831 -
243.1832 -4. (x+k).s = x.s
243.1833 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
243.1834 -
243.1835 -5. (x+k).n = x.n + k
243.1836 - Again follows from how arithmetic is defined.
243.1837 -
243.1838 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
243.1839 -(meaning that the various tzinfo methods exist, and don't blow up or return
243.1840 -None when called).
243.1841 -
243.1842 -The function wants to return a datetime y with timezone tz, equivalent to x.
243.1843 -x is already in UTC.
243.1844 -
243.1845 -By #3, we want
243.1846 -
243.1847 - y.n - y.o = x.n [1]
243.1848 -
243.1849 -The algorithm starts by attaching tz to x.n, and calling that y. So
243.1850 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
243.1851 -becomes true; in effect, we want to solve [2] for k:
243.1852 -
243.1853 - (y+k).n - (y+k).o = x.n [2]
243.1854 -
243.1855 -By #1, this is the same as
243.1856 -
243.1857 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
243.1858 -
243.1859 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
243.1860 -Substituting that into [3],
243.1861 -
243.1862 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
243.1863 - k - (y+k).s - (y+k).d = 0; rearranging,
243.1864 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
243.1865 - k = y.s - (y+k).d
243.1866 -
243.1867 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
243.1868 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
243.1869 -very large, since all offset-returning methods return a duration of magnitude
243.1870 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
243.1871 -be 0, so ignoring it has no consequence then.
243.1872 -
243.1873 -In any case, the new value is
243.1874 -
243.1875 - z = y + y.s [4]
243.1876 -
243.1877 -It's helpful to step back at look at [4] from a higher level: it's simply
243.1878 -mapping from UTC to tz's standard time.
243.1879 -
243.1880 -At this point, if
243.1881 -
243.1882 - z.n - z.o = x.n [5]
243.1883 -
243.1884 -we have an equivalent time, and are almost done. The insecurity here is
243.1885 -at the start of daylight time. Picture US Eastern for concreteness. The wall
243.1886 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
243.1887 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
243.1888 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
243.1889 -on the day DST starts. We want to return the 1:MM EST spelling because that's
243.1890 -the only spelling that makes sense on the local wall clock.
243.1891 -
243.1892 -In fact, if [5] holds at this point, we do have the standard-time spelling,
243.1893 -but that takes a bit of proof. We first prove a stronger result. What's the
243.1894 -difference between the LHS and RHS of [5]? Let
243.1895 -
243.1896 - diff = x.n - (z.n - z.o) [6]
243.1897 -
243.1898 -Now
243.1899 - z.n = by [4]
243.1900 - (y + y.s).n = by #5
243.1901 - y.n + y.s = since y.n = x.n
243.1902 - x.n + y.s = since z and y are have the same tzinfo member,
243.1903 - y.s = z.s by #2
243.1904 - x.n + z.s
243.1905 -
243.1906 -Plugging that back into [6] gives
243.1907 -
243.1908 - diff =
243.1909 - x.n - ((x.n + z.s) - z.o) = expanding
243.1910 - x.n - x.n - z.s + z.o = cancelling
243.1911 - - z.s + z.o = by #2
243.1912 - z.d
243.1913 -
243.1914 -So diff = z.d.
243.1915 -
243.1916 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
243.1917 -spelling we wanted in the endcase described above. We're done. Contrarily,
243.1918 -if z.d = 0, then we have a UTC equivalent, and are also done.
243.1919 -
243.1920 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
243.1921 -add to z (in effect, z is in tz's standard time, and we need to shift the
243.1922 -local clock into tz's daylight time).
243.1923 -
243.1924 -Let
243.1925 -
243.1926 - z' = z + z.d = z + diff [7]
243.1927 -
243.1928 -and we can again ask whether
243.1929 -
243.1930 - z'.n - z'.o = x.n [8]
243.1931 -
243.1932 -If so, we're done. If not, the tzinfo class is insane, according to the
243.1933 -assumptions we've made. This also requires a bit of proof. As before, let's
243.1934 -compute the difference between the LHS and RHS of [8] (and skipping some of
243.1935 -the justifications for the kinds of substitutions we've done several times
243.1936 -already):
243.1937 -
243.1938 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
243.1939 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
243.1940 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
243.1941 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
243.1942 - - z.n + z.n - z.o + z'.o = cancel z.n
243.1943 - - z.o + z'.o = #1 twice
243.1944 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
243.1945 - z'.d - z.d
243.1946 -
243.1947 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
243.1948 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
243.1949 -return z', not bothering to compute z'.d.
243.1950 -
243.1951 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
243.1952 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
243.1953 -would have to change the result dst() returns: we start in DST, and moving
243.1954 -a little further into it takes us out of DST.
243.1955 -
243.1956 -There isn't a sane case where this can happen. The closest it gets is at
243.1957 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
243.1958 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
243.1959 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
243.1960 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
243.1961 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
243.1962 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
243.1963 -standard time. Since that's what the local clock *does*, we want to map both
243.1964 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
243.1965 -in local time, but so it goes -- it's the way the local clock works.
243.1966 -
243.1967 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
243.1968 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
243.1969 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
243.1970 -(correctly) concludes that z' is not UTC-equivalent to x.
243.1971 -
243.1972 -Because we know z.d said z was in daylight time (else [5] would have held and
243.1973 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
243.1974 -and we we have stopped then), and there are only 2 possible values dst() can
243.1975 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
243.1976 -but the reasoning doesn't depend on the example -- it depends on there being
243.1977 -two possible dst() outcomes, one zero and the other non-zero). Therefore
243.1978 -z' must be in standard time, and is the spelling we want in this case.
243.1979 -
243.1980 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
243.1981 -concerned (because it takes z' as being in standard time rather than the
243.1982 -daylight time we intend here), but returning it gives the real-life "local
243.1983 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
243.1984 -tz.
243.1985 -
243.1986 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
243.1987 -the 1:MM standard time spelling we want.
243.1988 -
243.1989 -So how can this break? One of the assumptions must be violated. Two
243.1990 -possibilities:
243.1991 -
243.1992 -1) [2] effectively says that y.s is invariant across all y belong to a given
243.1993 - time zone. This isn't true if, for political reasons or continental drift,
243.1994 - a region decides to change its base offset from UTC.
243.1995 -
243.1996 -2) There may be versions of "double daylight" time where the tail end of
243.1997 - the analysis gives up a step too early. I haven't thought about that
243.1998 - enough to say.
243.1999 -
243.2000 -In any case, it's clear that the default fromutc() is strong enough to handle
243.2001 -"almost all" time zones: so long as the standard offset is invariant, it
243.2002 -doesn't matter if daylight time transition points change from year to year, or
243.2003 -if daylight time is skipped in some years; it doesn't matter how large or
243.2004 -small dst() may get within its bounds; and it doesn't even matter if some
243.2005 -perverse time zone returns a negative dst()). So a breaking case must be
243.2006 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
243.2007 -"""
243.2008 -
243.2009 -def _test():
243.2010 - import test_datetime
243.2011 - test_datetime.test_main()
243.2012 -
243.2013 -if __name__ == "__main__":
243.2014 - _test()
244.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testFix4.fixed Sun Jan 04 13:11:53 2015 -0600
244.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
244.3 @@ -1,2012 +0,0 @@
244.4 -"""Concrete date/time and related types -- prototype implemented in Python.
244.5 -
244.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
244.7 -
244.8 -See also http://dir.yahoo.com/Reference/calendars/
244.9 -
244.10 -For a primer on DST, including many current DST rules, see
244.11 -http://webexhibits.org/daylightsaving/
244.12 -
244.13 -For more about DST than you ever wanted to know, see
244.14 -ftp://elsie.nci.nih.gov/pub/
244.15 -
244.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
244.17 -
244.18 -"""
244.19 -
244.20 -import time as _time
244.21 -import math as _math
244.22 -
244.23 -MINYEAR = 1
244.24 -MAXYEAR = 9999
244.25 -
244.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
244.27 -# also assumes the current Gregorian calendar indefinitely extended in
244.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
244.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
244.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
244.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
244.32 -# for all computations. See the book for algorithms for converting between
244.33 -# proleptic Gregorian ordinals and many other calendar systems.
244.34 -
244.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
244.36 -
244.37 -_DAYS_BEFORE_MONTH = [None]
244.38 -dbm = 0
244.39 -for dim in _DAYS_IN_MONTH[1:]:
244.40 - _DAYS_BEFORE_MONTH.append(dbm)
244.41 - dbm += dim
244.42 -del dbm, dim
244.43 -
244.44 -def _is_leap(year):
244.45 - "year -> 1 if leap year, else 0."
244.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
244.47 -
244.48 -def _days_in_year(year):
244.49 - "year -> number of days in year (366 if a leap year, else 365)."
244.50 - return 365 + _is_leap(year)
244.51 -
244.52 -def _days_before_year(year):
244.53 - "year -> number of days before January 1st of year."
244.54 - y = year - 1
244.55 - return y*365 + y//4 - y//100 + y//400
244.56 -
244.57 -def _days_in_month(year, month):
244.58 - "year, month -> number of days in that month in that year."
244.59 - |>new_name<|(month)
244.60 - if month == 2 and _is_leap(year):
244.61 - return 29
244.62 - return _DAYS_IN_MONTH[month]
244.63 -
244.64 -
244.65 -def |>^new_name<|(month):
244.66 - assert 1 <= month <= 12, month
244.67 -
244.68 -def _days_before_month(year, month):
244.69 - "year, month -> number of days in year preceeding first day of month."
244.70 - if not 1 <= month <= 12:
244.71 - raise ValueError('month must be in 1..12', month)
244.72 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
244.73 -
244.74 -def _ymd2ord(year, month, day):
244.75 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
244.76 - if not 1 <= month <= 12:
244.77 - raise ValueError('month must be in 1..12', month)
244.78 - dim = _days_in_month(year, month)
244.79 - if not 1 <= day <= dim:
244.80 - raise ValueError('day must be in 1..%d' % dim, day)
244.81 - return (_days_before_year(year) +
244.82 - _days_before_month(year, month) +
244.83 - day)
244.84 -
244.85 -_DI400Y = _days_before_year(401) # number of days in 400 years
244.86 -_DI100Y = _days_before_year(101) # " " " " 100 "
244.87 -_DI4Y = _days_before_year(5) # " " " " 4 "
244.88 -
244.89 -# A 4-year cycle has an extra leap day over what we'd get from pasting
244.90 -# together 4 single years.
244.91 -assert _DI4Y == 4 * 365 + 1
244.92 -
244.93 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
244.94 -# pasting together 4 100-year cycles.
244.95 -assert _DI400Y == 4 * _DI100Y + 1
244.96 -
244.97 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
244.98 -# pasting together 25 4-year cycles.
244.99 -assert _DI100Y == 25 * _DI4Y - 1
244.100 -
244.101 -def _ord2ymd(n):
244.102 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
244.103 -
244.104 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
244.105 - # repeats exactly every 400 years. The basic strategy is to find the
244.106 - # closest 400-year boundary at or before n, then work with the offset
244.107 - # from that boundary to n. Life is much clearer if we subtract 1 from
244.108 - # n first -- then the values of n at 400-year boundaries are exactly
244.109 - # those divisible by _DI400Y:
244.110 - #
244.111 - # D M Y n n-1
244.112 - # -- --- ---- ---------- ----------------
244.113 - # 31 Dec -400 -_DI400Y -_DI400Y -1
244.114 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
244.115 - # ...
244.116 - # 30 Dec 000 -1 -2
244.117 - # 31 Dec 000 0 -1
244.118 - # 1 Jan 001 1 0 400-year boundary
244.119 - # 2 Jan 001 2 1
244.120 - # 3 Jan 001 3 2
244.121 - # ...
244.122 - # 31 Dec 400 _DI400Y _DI400Y -1
244.123 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
244.124 - n -= 1
244.125 - n400, n = divmod(n, _DI400Y)
244.126 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
244.127 -
244.128 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
244.129 - # the desired date. Now compute how many 100-year cycles precede n.
244.130 - # Note that it's possible for n100 to equal 4! In that case 4 full
244.131 - # 100-year cycles precede the desired day, which implies the desired
244.132 - # day is December 31 at the end of a 400-year cycle.
244.133 - n100, n = divmod(n, _DI100Y)
244.134 -
244.135 - # Now compute how many 4-year cycles precede it.
244.136 - n4, n = divmod(n, _DI4Y)
244.137 -
244.138 - # And now how many single years. Again n1 can be 4, and again meaning
244.139 - # that the desired day is December 31 at the end of the 4-year cycle.
244.140 - n1, n = divmod(n, 365)
244.141 -
244.142 - year += n100 * 100 + n4 * 4 + n1
244.143 - if n1 == 4 or n100 == 4:
244.144 - assert n == 0
244.145 - return year-1, 12, 31
244.146 -
244.147 - # Now the year is correct, and n is the offset from January 1. We find
244.148 - # the month via an estimate that's either exact or one too large.
244.149 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
244.150 - assert leapyear == _is_leap(year)
244.151 - month = (n + 50) >> 5
244.152 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
244.153 - if preceding > n: # estimate is too large
244.154 - month -= 1
244.155 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
244.156 - n -= preceding
244.157 - assert 0 <= n < _days_in_month(year, month)
244.158 -
244.159 - # Now the year and month are correct, and n is the offset from the
244.160 - # start of that month: we're done!
244.161 - return year, month, n+1
244.162 -
244.163 -# Month and day names. For localized versions, see the calendar module.
244.164 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
244.165 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
244.166 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
244.167 -
244.168 -
244.169 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
244.170 - wday = (_ymd2ord(y, m, d) + 6) % 7
244.171 - dnum = _days_before_month(y, m) + d
244.172 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
244.173 -
244.174 -def _format_time(hh, mm, ss, us):
244.175 - # Skip trailing microseconds when us==0.
244.176 - result = "%02d:%02d:%02d" % (hh, mm, ss)
244.177 - if us:
244.178 - result += ".%06d" % us
244.179 - return result
244.180 -
244.181 -# Correctly substitute for %z and %Z escapes in strftime formats.
244.182 -def _wrap_strftime(object, format, timetuple):
244.183 - year = timetuple[0]
244.184 - if year < 1900:
244.185 - raise ValueError("year=%d is before 1900; the datetime strftime() "
244.186 - "methods require year >= 1900" % year)
244.187 - # Don't call _utcoffset() or tzname() unless actually needed.
244.188 - zreplace = None # the string to use for %z
244.189 - Zreplace = None # the string to use for %Z
244.190 -
244.191 - # Scan format for %z and %Z escapes, replacing as needed.
244.192 - newformat = []
244.193 - push = newformat.append
244.194 - i, n = 0, len(format)
244.195 - while i < n:
244.196 - ch = format[i]
244.197 - i += 1
244.198 - if ch == '%':
244.199 - if i < n:
244.200 - ch = format[i]
244.201 - i += 1
244.202 - if ch == 'z':
244.203 - if zreplace is None:
244.204 - zreplace = ""
244.205 - if hasattr(object, "_utcoffset"):
244.206 - offset = object._utcoffset()
244.207 - if offset is not None:
244.208 - sign = '+'
244.209 - if offset < 0:
244.210 - offset = -offset
244.211 - sign = '-'
244.212 - h, m = divmod(offset, 60)
244.213 - zreplace = '%c%02d%02d' % (sign, h, m)
244.214 - assert '%' not in zreplace
244.215 - newformat.append(zreplace)
244.216 - elif ch == 'Z':
244.217 - if Zreplace is None:
244.218 - Zreplace = ""
244.219 - if hasattr(object, "tzname"):
244.220 - s = object.tzname()
244.221 - if s is not None:
244.222 - # strftime is going to have at this: escape %
244.223 - Zreplace = s.replace('%', '%%')
244.224 - newformat.append(Zreplace)
244.225 - else:
244.226 - push('%')
244.227 - push(ch)
244.228 - else:
244.229 - push('%')
244.230 - else:
244.231 - push(ch)
244.232 - newformat = "".join(newformat)
244.233 - return _time.strftime(newformat, timetuple)
244.234 -
244.235 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
244.236 - if tzinfo is None:
244.237 - return None
244.238 - return getattr(tzinfo, methname)(tzinfoarg)
244.239 -
244.240 -# Just raise TypeError if the arg isn't None or a string.
244.241 -def _check_tzname(name):
244.242 - if name is not None and not isinstance(name, str):
244.243 - raise TypeError("tzinfo.tzname() must return None or string, "
244.244 - "not '%s'" % type(name))
244.245 -
244.246 -# name is the offset-producing method, "utcoffset" or "dst".
244.247 -# offset is what it returned.
244.248 -# If offset isn't None or timedelta, raises TypeError.
244.249 -# If offset is None, returns None.
244.250 -# Else offset is checked for being in range, and a whole # of minutes.
244.251 -# If it is, its integer value is returned. Else ValueError is raised.
244.252 -def _check_utc_offset(name, offset):
244.253 - assert name in ("utcoffset", "dst")
244.254 - if offset is None:
244.255 - return None
244.256 - if not isinstance(offset, timedelta):
244.257 - raise TypeError("tzinfo.%s() must return None "
244.258 - "or timedelta, not '%s'" % (name, type(offset)))
244.259 - days = offset.days
244.260 - if days < -1 or days > 0:
244.261 - offset = 1440 # trigger out-of-range
244.262 - else:
244.263 - seconds = days * 86400 + offset.seconds
244.264 - minutes, seconds = divmod(seconds, 60)
244.265 - if seconds or offset.microseconds:
244.266 - raise ValueError("tzinfo.%s() must return a whole number "
244.267 - "of minutes" % name)
244.268 - offset = minutes
244.269 - if -1440 < offset < 1440:
244.270 - return offset
244.271 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
244.272 -
244.273 -def _check_date_fields(year, month, day):
244.274 - if not MINYEAR <= year <= MAXYEAR:
244.275 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
244.276 - if not 1 <= month <= 12:
244.277 - raise ValueError('month must be in 1..12', month)
244.278 - dim = _days_in_month(year, month)
244.279 - if not 1 <= day <= dim:
244.280 - raise ValueError('day must be in 1..%d' % dim, day)
244.281 -
244.282 -def _check_time_fields(hour, minute, second, microsecond):
244.283 - if not 0 <= hour <= 23:
244.284 - raise ValueError('hour must be in 0..23', hour)
244.285 - if not 0 <= minute <= 59:
244.286 - raise ValueError('minute must be in 0..59', minute)
244.287 - if not 0 <= second <= 59:
244.288 - raise ValueError('second must be in 0..59', second)
244.289 - if not 0 <= microsecond <= 999999:
244.290 - raise ValueError('microsecond must be in 0..999999', microsecond)
244.291 -
244.292 -def _check_tzinfo_arg(tz):
244.293 - if tz is not None and not isinstance(tz, tzinfo):
244.294 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
244.295 -
244.296 -
244.297 -# Notes on comparison: In general, datetime module comparison operators raise
244.298 -# TypeError when they don't know how to do a comparison themself. If they
244.299 -# returned NotImplemented instead, comparison could (silently) fall back to
244.300 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
244.301 -# and that's not helpful. There are two exceptions:
244.302 -#
244.303 -# 1. For date and datetime, if the other object has a "timetuple" attr,
244.304 -# NotImplemented is returned. This is a hook to allow other kinds of
244.305 -# datetime-like objects a chance to intercept the comparison.
244.306 -#
244.307 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
244.308 -# so opertaions like
244.309 -#
244.310 -# x == y
244.311 -# x != y
244.312 -# x in sequence
244.313 -# x not in sequence
244.314 -# dict[x] = y
244.315 -#
244.316 -# don't raise annoying TypeErrors just because a datetime object
244.317 -# is part of a heterogeneous collection. If there's no known way to
244.318 -# compare X to a datetime, saying they're not equal is reasonable.
244.319 -
244.320 -def _cmperror(x, y):
244.321 - raise TypeError("can't compare '%s' to '%s'" % (
244.322 - type(x).__name__, type(y).__name__))
244.323 -
244.324 -# This is a start at a struct tm workalike. Goals:
244.325 -#
244.326 -# + Works the same way across platforms.
244.327 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
244.328 -#
244.329 -# Note: I suspect it's best if this flavor of tm does *not* try to
244.330 -# second-guess timezones or DST. Instead fold whatever adjustments you want
244.331 -# into the minutes argument (and the constructor will normalize).
244.332 -
244.333 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
244.334 -
244.335 -class tmxxx:
244.336 -
244.337 - ordinal = None
244.338 -
244.339 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
244.340 - microsecond=0):
244.341 - # Normalize all the inputs, and store the normalized values.
244.342 - if not 0 <= microsecond <= 999999:
244.343 - carry, microsecond = divmod(microsecond, 1000000)
244.344 - second += carry
244.345 - if not 0 <= second <= 59:
244.346 - carry, second = divmod(second, 60)
244.347 - minute += carry
244.348 - if not 0 <= minute <= 59:
244.349 - carry, minute = divmod(minute, 60)
244.350 - hour += carry
244.351 - if not 0 <= hour <= 23:
244.352 - carry, hour = divmod(hour, 24)
244.353 - day += carry
244.354 -
244.355 - # That was easy. Now it gets muddy: the proper range for day
244.356 - # can't be determined without knowing the correct month and year,
244.357 - # but if day is, e.g., plus or minus a million, the current month
244.358 - # and year values make no sense (and may also be out of bounds
244.359 - # themselves).
244.360 - # Saying 12 months == 1 year should be non-controversial.
244.361 - if not 1 <= month <= 12:
244.362 - carry, month = divmod(month-1, 12)
244.363 - year += carry
244.364 - month += 1
244.365 - assert 1 <= month <= 12
244.366 -
244.367 - # Now only day can be out of bounds (year may also be out of bounds
244.368 - # for a datetime object, but we don't care about that here).
244.369 - # If day is out of bounds, what to do is arguable, but at least the
244.370 - # method here is principled and explainable.
244.371 - dim = _days_in_month(year, month)
244.372 - if not 1 <= day <= dim:
244.373 - # Move day-1 days from the first of the month. First try to
244.374 - # get off cheap if we're only one day out of range (adjustments
244.375 - # for timezone alone can't be worse than that).
244.376 - if day == 0: # move back a day
244.377 - month -= 1
244.378 - if month > 0:
244.379 - day = _days_in_month(year, month)
244.380 - else:
244.381 - year, month, day = year-1, 12, 31
244.382 - elif day == dim + 1: # move forward a day
244.383 - month += 1
244.384 - day = 1
244.385 - if month > 12:
244.386 - month = 1
244.387 - year += 1
244.388 - else:
244.389 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
244.390 - year, month, day = _ord2ymd(self.ordinal)
244.391 -
244.392 - self.year, self.month, self.day = year, month, day
244.393 - self.hour, self.minute, self.second = hour, minute, second
244.394 - self.microsecond = microsecond
244.395 -
244.396 - def toordinal(self):
244.397 - """Return proleptic Gregorian ordinal for the year, month and day.
244.398 -
244.399 - January 1 of year 1 is day 1. Only the year, month and day values
244.400 - contribute to the result.
244.401 - """
244.402 - if self.ordinal is None:
244.403 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
244.404 - return self.ordinal
244.405 -
244.406 - def time(self):
244.407 - "Return Unixish timestamp, as a float (assuming UTC)."
244.408 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
244.409 - seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
244.410 - return seconds + self.second + self.microsecond / 1e6
244.411 -
244.412 - def ctime(self):
244.413 - "Return ctime() style string."
244.414 - weekday = self.toordinal() % 7 or 7
244.415 - return "%s %s %2d %02d:%02d:%02d %04d" % (
244.416 - _DAYNAMES[weekday],
244.417 - _MONTHNAMES[self.month],
244.418 - self.day,
244.419 - self.hour, self.minute, self.second,
244.420 - self.year)
244.421 -
244.422 -class timedelta(object):
244.423 - """Represent the difference between two datetime objects.
244.424 -
244.425 - Supported operators:
244.426 -
244.427 - - add, subtract timedelta
244.428 - - unary plus, minus, abs
244.429 - - compare to timedelta
244.430 - - multiply, divide by int/long
244.431 -
244.432 - In addition, datetime supports subtraction of two datetime objects
244.433 - returning a timedelta, and addition or subtraction of a datetime
244.434 - and a timedelta giving a datetime.
244.435 -
244.436 - Representation: (days, seconds, microseconds). Why? Because I
244.437 - felt like it.
244.438 - """
244.439 -
244.440 - def __new__(cls, days=0, seconds=0, microseconds=0,
244.441 - # XXX The following should only be used as keyword args:
244.442 - milliseconds=0, minutes=0, hours=0, weeks=0):
244.443 - # Doing this efficiently and accurately in C is going to be difficult
244.444 - # and error-prone, due to ubiquitous overflow possibilities, and that
244.445 - # C double doesn't have enough bits of precision to represent
244.446 - # microseconds over 10K years faithfully. The code here tries to make
244.447 - # explicit where go-fast assumptions can be relied on, in order to
244.448 - # guide the C implementation; it's way more convoluted than speed-
244.449 - # ignoring auto-overflow-to-long idiomatic Python could be.
244.450 -
244.451 - # XXX Check that all inputs are ints, longs or floats.
244.452 -
244.453 - # Final values, all integer.
244.454 - # s and us fit in 32-bit signed ints; d isn't bounded.
244.455 - d = s = us = 0
244.456 -
244.457 - # Normalize everything to days, seconds, microseconds.
244.458 - days += weeks*7
244.459 - seconds += minutes*60 + hours*3600
244.460 - microseconds += milliseconds*1000
244.461 -
244.462 - # Get rid of all fractions, and normalize s and us.
244.463 - # Take a deep breath <wink>.
244.464 - if isinstance(days, float):
244.465 - dayfrac, days = _math.modf(days)
244.466 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
244.467 - assert daysecondswhole == int(daysecondswhole) # can't overflow
244.468 - s = int(daysecondswhole)
244.469 - assert days == long(days)
244.470 - d = long(days)
244.471 - else:
244.472 - daysecondsfrac = 0.0
244.473 - d = days
244.474 - assert isinstance(daysecondsfrac, float)
244.475 - assert abs(daysecondsfrac) <= 1.0
244.476 - assert isinstance(d, (int, long))
244.477 - assert abs(s) <= 24 * 3600
244.478 - # days isn't referenced again before redefinition
244.479 -
244.480 - if isinstance(seconds, float):
244.481 - secondsfrac, seconds = _math.modf(seconds)
244.482 - assert seconds == long(seconds)
244.483 - seconds = long(seconds)
244.484 - secondsfrac += daysecondsfrac
244.485 - assert abs(secondsfrac) <= 2.0
244.486 - else:
244.487 - secondsfrac = daysecondsfrac
244.488 - # daysecondsfrac isn't referenced again
244.489 - assert isinstance(secondsfrac, float)
244.490 - assert abs(secondsfrac) <= 2.0
244.491 -
244.492 - assert isinstance(seconds, (int, long))
244.493 - days, seconds = divmod(seconds, 24*3600)
244.494 - d += days
244.495 - s += int(seconds) # can't overflow
244.496 - assert isinstance(s, int)
244.497 - assert abs(s) <= 2 * 24 * 3600
244.498 - # seconds isn't referenced again before redefinition
244.499 -
244.500 - usdouble = secondsfrac * 1e6
244.501 - assert abs(usdouble) < 2.1e6 # exact value not critical
244.502 - # secondsfrac isn't referenced again
244.503 -
244.504 - if isinstance(microseconds, float):
244.505 - microseconds += usdouble
244.506 - microseconds = round(microseconds)
244.507 - seconds, microseconds = divmod(microseconds, 1e6)
244.508 - assert microseconds == int(microseconds)
244.509 - assert seconds == long(seconds)
244.510 - days, seconds = divmod(seconds, 24.*3600.)
244.511 - assert days == long(days)
244.512 - assert seconds == int(seconds)
244.513 - d += long(days)
244.514 - s += int(seconds) # can't overflow
244.515 - assert isinstance(s, int)
244.516 - assert abs(s) <= 3 * 24 * 3600
244.517 - else:
244.518 - seconds, microseconds = divmod(microseconds, 1000000)
244.519 - days, seconds = divmod(seconds, 24*3600)
244.520 - d += days
244.521 - s += int(seconds) # can't overflow
244.522 - assert isinstance(s, int)
244.523 - assert abs(s) <= 3 * 24 * 3600
244.524 - microseconds = float(microseconds)
244.525 - microseconds += usdouble
244.526 - microseconds = round(microseconds)
244.527 - assert abs(s) <= 3 * 24 * 3600
244.528 - assert abs(microseconds) < 3.1e6
244.529 -
244.530 - # Just a little bit of carrying possible for microseconds and seconds.
244.531 - assert isinstance(microseconds, float)
244.532 - assert int(microseconds) == microseconds
244.533 - us = int(microseconds)
244.534 - seconds, us = divmod(us, 1000000)
244.535 - s += seconds # cant't overflow
244.536 - assert isinstance(s, int)
244.537 - days, s = divmod(s, 24*3600)
244.538 - d += days
244.539 -
244.540 - assert isinstance(d, (int, long))
244.541 - assert isinstance(s, int) and 0 <= s < 24*3600
244.542 - assert isinstance(us, int) and 0 <= us < 1000000
244.543 -
244.544 - self = object.__new__(cls)
244.545 -
244.546 - self.__days = d
244.547 - self.__seconds = s
244.548 - self.__microseconds = us
244.549 - if abs(d) > 999999999:
244.550 - raise OverflowError("timedelta # of days is too large: %d" % d)
244.551 -
244.552 - return self
244.553 -
244.554 - def __repr__(self):
244.555 - if self.__microseconds:
244.556 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
244.557 - self.__days,
244.558 - self.__seconds,
244.559 - self.__microseconds)
244.560 - if self.__seconds:
244.561 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
244.562 - self.__days,
244.563 - self.__seconds)
244.564 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
244.565 -
244.566 - def __str__(self):
244.567 - mm, ss = divmod(self.__seconds, 60)
244.568 - hh, mm = divmod(mm, 60)
244.569 - s = "%d:%02d:%02d" % (hh, mm, ss)
244.570 - if self.__days:
244.571 - def plural(n):
244.572 - return n, abs(n) != 1 and "s" or ""
244.573 - s = ("%d day%s, " % plural(self.__days)) + s
244.574 - if self.__microseconds:
244.575 - s = s + ".%06d" % self.__microseconds
244.576 - return s
244.577 -
244.578 - days = property(lambda self: self.__days, doc="days")
244.579 - seconds = property(lambda self: self.__seconds, doc="seconds")
244.580 - microseconds = property(lambda self: self.__microseconds,
244.581 - doc="microseconds")
244.582 -
244.583 - def __add__(self, other):
244.584 - if isinstance(other, timedelta):
244.585 - return timedelta(self.__days + other.__days,
244.586 - self.__seconds + other.__seconds,
244.587 - self.__microseconds + other.__microseconds)
244.588 - return NotImplemented
244.589 -
244.590 - __radd__ = __add__
244.591 -
244.592 - def __sub__(self, other):
244.593 - if isinstance(other, timedelta):
244.594 - return self + -other
244.595 - return NotImplemented
244.596 -
244.597 - def __rsub__(self, other):
244.598 - if isinstance(other, timedelta):
244.599 - return -self + other
244.600 - return NotImplemented
244.601 -
244.602 - def __neg__(self):
244.603 - return self.__class__(-self.__days,
244.604 - -self.__seconds,
244.605 - -self.__microseconds)
244.606 -
244.607 - def __pos__(self):
244.608 - return self
244.609 -
244.610 - def __abs__(self):
244.611 - if self.__days < 0:
244.612 - return -self
244.613 - else:
244.614 - return self
244.615 -
244.616 - def __mul__(self, other):
244.617 - if isinstance(other, (int, long)):
244.618 - return self.__class__(self.__days * other,
244.619 - self.__seconds * other,
244.620 - self.__microseconds * other)
244.621 - return NotImplemented
244.622 -
244.623 - __rmul__ = __mul__
244.624 -
244.625 - def __div__(self, other):
244.626 - if isinstance(other, (int, long)):
244.627 - usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
244.628 - self.__microseconds)
244.629 - return self.__class__(0, 0, usec // other)
244.630 - return NotImplemented
244.631 -
244.632 - __floordiv__ = __div__
244.633 -
244.634 - # Comparisons.
244.635 -
244.636 - def __eq__(self, other):
244.637 - if isinstance(other, timedelta):
244.638 - return self.__cmp(other) == 0
244.639 - else:
244.640 - return False
244.641 -
244.642 - def __ne__(self, other):
244.643 - if isinstance(other, timedelta):
244.644 - return self.__cmp(other) != 0
244.645 - else:
244.646 - return True
244.647 -
244.648 - def __le__(self, other):
244.649 - if isinstance(other, timedelta):
244.650 - return self.__cmp(other) <= 0
244.651 - else:
244.652 - _cmperror(self, other)
244.653 -
244.654 - def __lt__(self, other):
244.655 - if isinstance(other, timedelta):
244.656 - return self.__cmp(other) < 0
244.657 - else:
244.658 - _cmperror(self, other)
244.659 -
244.660 - def __ge__(self, other):
244.661 - if isinstance(other, timedelta):
244.662 - return self.__cmp(other) >= 0
244.663 - else:
244.664 - _cmperror(self, other)
244.665 -
244.666 - def __gt__(self, other):
244.667 - if isinstance(other, timedelta):
244.668 - return self.__cmp(other) > 0
244.669 - else:
244.670 - _cmperror(self, other)
244.671 -
244.672 - def __cmp(self, other):
244.673 - assert isinstance(other, timedelta)
244.674 - return cmp(self.__getstate(), other.__getstate())
244.675 -
244.676 - def __hash__(self):
244.677 - return hash(self.__getstate())
244.678 -
244.679 - def __nonzero__(self):
244.680 - return (self.__days != 0 or
244.681 - self.__seconds != 0 or
244.682 - self.__microseconds != 0)
244.683 -
244.684 - # Pickle support.
244.685 -
244.686 - __safe_for_unpickling__ = True # For Python 2.2
244.687 -
244.688 - def __getstate(self):
244.689 - return (self.__days, self.__seconds, self.__microseconds)
244.690 -
244.691 - def __reduce__(self):
244.692 - return (self.__class__, self.__getstate())
244.693 -
244.694 -timedelta.min = timedelta(-999999999)
244.695 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
244.696 - microseconds=999999)
244.697 -timedelta.resolution = timedelta(microseconds=1)
244.698 -
244.699 -class date(object):
244.700 - """Concrete date type.
244.701 -
244.702 - Constructors:
244.703 -
244.704 - __new__()
244.705 - fromtimestamp()
244.706 - today()
244.707 - fromordinal()
244.708 -
244.709 - Operators:
244.710 -
244.711 - __repr__, __str__
244.712 - __cmp__, __hash__
244.713 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
244.714 -
244.715 - Methods:
244.716 -
244.717 - timetuple()
244.718 - toordinal()
244.719 - weekday()
244.720 - isoweekday(), isocalendar(), isoformat()
244.721 - ctime()
244.722 - strftime()
244.723 -
244.724 - Properties (readonly):
244.725 - year, month, day
244.726 - """
244.727 -
244.728 - def __new__(cls, year, month=None, day=None):
244.729 - """Constructor.
244.730 -
244.731 - Arguments:
244.732 -
244.733 - year, month, day (required, base 1)
244.734 - """
244.735 - if isinstance(year, str):
244.736 - # Pickle support
244.737 - self = object.__new__(cls)
244.738 - self.__setstate((year,))
244.739 - return self
244.740 - _check_date_fields(year, month, day)
244.741 - self = object.__new__(cls)
244.742 - self.__year = year
244.743 - self.__month = month
244.744 - self.__day = day
244.745 - return self
244.746 -
244.747 - # Additional constructors
244.748 -
244.749 - def fromtimestamp(cls, t):
244.750 - "Construct a date from a POSIX timestamp (like time.time())."
244.751 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
244.752 - return cls(y, m, d)
244.753 - fromtimestamp = classmethod(fromtimestamp)
244.754 -
244.755 - def today(cls):
244.756 - "Construct a date from time.time()."
244.757 - t = _time.time()
244.758 - return cls.fromtimestamp(t)
244.759 - today = classmethod(today)
244.760 -
244.761 - def fromordinal(cls, n):
244.762 - """Contruct a date from a proleptic Gregorian ordinal.
244.763 -
244.764 - January 1 of year 1 is day 1. Only the year, month and day are
244.765 - non-zero in the result.
244.766 - """
244.767 - y, m, d = _ord2ymd(n)
244.768 - return cls(y, m, d)
244.769 - fromordinal = classmethod(fromordinal)
244.770 -
244.771 - # Conversions to string
244.772 -
244.773 - def __repr__(self):
244.774 - "Convert to formal string, for repr()."
244.775 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
244.776 - self.__year,
244.777 - self.__month,
244.778 - self.__day)
244.779 - # XXX These shouldn't depend on time.localtime(), because that
244.780 - # clips the usable dates to [1970 .. 2038). At least ctime() is
244.781 - # easily done without using strftime() -- that's better too because
244.782 - # strftime("%c", ...) is locale specific.
244.783 -
244.784 - def ctime(self):
244.785 - "Format a la ctime()."
244.786 - return tmxxx(self.__year, self.__month, self.__day).ctime()
244.787 -
244.788 - def strftime(self, fmt):
244.789 - "Format using strftime()."
244.790 - return _wrap_strftime(self, fmt, self.timetuple())
244.791 -
244.792 - def isoformat(self):
244.793 - """Return the date formatted according to ISO.
244.794 -
244.795 - This is 'YYYY-MM-DD'.
244.796 -
244.797 - References:
244.798 - - http://www.w3.org/TR/NOTE-datetime
244.799 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
244.800 - """
244.801 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
244.802 -
244.803 - __str__ = isoformat
244.804 -
244.805 - # Read-only field accessors
244.806 - year = property(lambda self: self.__year,
244.807 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
244.808 - month = property(lambda self: self.__month, doc="month (1-12)")
244.809 - day = property(lambda self: self.__day, doc="day (1-31)")
244.810 -
244.811 - # Standard conversions, __cmp__, __hash__ (and helpers)
244.812 -
244.813 - def timetuple(self):
244.814 - "Return local time tuple compatible with time.localtime()."
244.815 - return _build_struct_time(self.__year, self.__month, self.__day,
244.816 - 0, 0, 0, -1)
244.817 -
244.818 - def toordinal(self):
244.819 - """Return proleptic Gregorian ordinal for the year, month and day.
244.820 -
244.821 - January 1 of year 1 is day 1. Only the year, month and day values
244.822 - contribute to the result.
244.823 - """
244.824 - return _ymd2ord(self.__year, self.__month, self.__day)
244.825 -
244.826 - def replace(self, year=None, month=None, day=None):
244.827 - """Return a new date with new values for the specified fields."""
244.828 - if year is None:
244.829 - year = self.__year
244.830 - if month is None:
244.831 - month = self.__month
244.832 - if day is None:
244.833 - day = self.__day
244.834 - _check_date_fields(year, month, day)
244.835 - return date(year, month, day)
244.836 -
244.837 - # Comparisons.
244.838 -
244.839 - def __eq__(self, other):
244.840 - if isinstance(other, date):
244.841 - return self.__cmp(other) == 0
244.842 - elif hasattr(other, "timetuple"):
244.843 - return NotImplemented
244.844 - else:
244.845 - return False
244.846 -
244.847 - def __ne__(self, other):
244.848 - if isinstance(other, date):
244.849 - return self.__cmp(other) != 0
244.850 - elif hasattr(other, "timetuple"):
244.851 - return NotImplemented
244.852 - else:
244.853 - return True
244.854 -
244.855 - def __le__(self, other):
244.856 - if isinstance(other, date):
244.857 - return self.__cmp(other) <= 0
244.858 - elif hasattr(other, "timetuple"):
244.859 - return NotImplemented
244.860 - else:
244.861 - _cmperror(self, other)
244.862 -
244.863 - def __lt__(self, other):
244.864 - if isinstance(other, date):
244.865 - return self.__cmp(other) < 0
244.866 - elif hasattr(other, "timetuple"):
244.867 - return NotImplemented
244.868 - else:
244.869 - _cmperror(self, other)
244.870 -
244.871 - def __ge__(self, other):
244.872 - if isinstance(other, date):
244.873 - return self.__cmp(other) >= 0
244.874 - elif hasattr(other, "timetuple"):
244.875 - return NotImplemented
244.876 - else:
244.877 - _cmperror(self, other)
244.878 -
244.879 - def __gt__(self, other):
244.880 - if isinstance(other, date):
244.881 - return self.__cmp(other) > 0
244.882 - elif hasattr(other, "timetuple"):
244.883 - return NotImplemented
244.884 - else:
244.885 - _cmperror(self, other)
244.886 -
244.887 - def __cmp(self, other):
244.888 - assert isinstance(other, date)
244.889 - y, m, d = self.__year, self.__month, self.__day
244.890 - y2, m2, d2 = other.__year, other.__month, other.__day
244.891 - return cmp((y, m, d), (y2, m2, d2))
244.892 -
244.893 - def __hash__(self):
244.894 - "Hash."
244.895 - return hash(self.__getstate())
244.896 -
244.897 - # Computations
244.898 -
244.899 - def _checkOverflow(self, year):
244.900 - if not MINYEAR <= year <= MAXYEAR:
244.901 - raise OverflowError("date +/-: result year %d not in %d..%d" %
244.902 - (year, MINYEAR, MAXYEAR))
244.903 -
244.904 - def __add__(self, other):
244.905 - "Add a date to a timedelta."
244.906 - if isinstance(other, timedelta):
244.907 - t = tmxxx(self.__year,
244.908 - self.__month,
244.909 - self.__day + other.days)
244.910 - self._checkOverflow(t.year)
244.911 - result = self.__class__(t.year, t.month, t.day)
244.912 - return result
244.913 - return NotImplemented
244.914 -
244.915 - __radd__ = __add__
244.916 -
244.917 - def __sub__(self, other):
244.918 - """Subtract two dates, or a date and a timedelta."""
244.919 - if isinstance(other, timedelta):
244.920 - return self + timedelta(-other.days)
244.921 - if isinstance(other, date):
244.922 - days1 = self.toordinal()
244.923 - days2 = other.toordinal()
244.924 - return timedelta(days1 - days2)
244.925 - return NotImplemented
244.926 -
244.927 - def weekday(self):
244.928 - "Return day of the week, where Monday == 0 ... Sunday == 6."
244.929 - return (self.toordinal() + 6) % 7
244.930 -
244.931 - # Day-of-the-week and week-of-the-year, according to ISO
244.932 -
244.933 - def isoweekday(self):
244.934 - "Return day of the week, where Monday == 1 ... Sunday == 7."
244.935 - # 1-Jan-0001 is a Monday
244.936 - return self.toordinal() % 7 or 7
244.937 -
244.938 - def isocalendar(self):
244.939 - """Return a 3-tuple containing ISO year, week number, and weekday.
244.940 -
244.941 - The first ISO week of the year is the (Mon-Sun) week
244.942 - containing the year's first Thursday; everything else derives
244.943 - from that.
244.944 -
244.945 - The first week is 1; Monday is 1 ... Sunday is 7.
244.946 -
244.947 - ISO calendar algorithm taken from
244.948 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
244.949 - """
244.950 - year = self.__year
244.951 - week1monday = _isoweek1monday(year)
244.952 - today = _ymd2ord(self.__year, self.__month, self.__day)
244.953 - # Internally, week and day have origin 0
244.954 - week, day = divmod(today - week1monday, 7)
244.955 - if week < 0:
244.956 - year -= 1
244.957 - week1monday = _isoweek1monday(year)
244.958 - week, day = divmod(today - week1monday, 7)
244.959 - elif week >= 52:
244.960 - if today >= _isoweek1monday(year+1):
244.961 - year += 1
244.962 - week = 0
244.963 - return year, week+1, day+1
244.964 -
244.965 - # Pickle support.
244.966 -
244.967 - __safe_for_unpickling__ = True # For Python 2.2
244.968 -
244.969 - def __getstate(self):
244.970 - yhi, ylo = divmod(self.__year, 256)
244.971 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
244.972 -
244.973 - def __setstate(self, t):
244.974 - assert isinstance(t, tuple) and len(t) == 1, `t`
244.975 - string = t[0]
244.976 - assert len(string) == 4
244.977 - yhi, ylo, self.__month, self.__day = map(ord, string)
244.978 - self.__year = yhi * 256 + ylo
244.979 -
244.980 - def __reduce__(self):
244.981 - return (self.__class__, self.__getstate())
244.982 -
244.983 -_date_class = date # so functions w/ args named "date" can get at the class
244.984 -
244.985 -date.min = date(1, 1, 1)
244.986 -date.max = date(9999, 12, 31)
244.987 -date.resolution = timedelta(days=1)
244.988 -
244.989 -class tzinfo(object):
244.990 - """Abstract base class for time zone info classes.
244.991 -
244.992 - Subclasses must override the name(), utcoffset() and dst() methods.
244.993 - """
244.994 -
244.995 - def tzname(self, dt):
244.996 - "datetime -> string name of time zone."
244.997 - raise NotImplementedError("tzinfo subclass must override tzname()")
244.998 -
244.999 - def utcoffset(self, dt):
244.1000 - "datetime -> minutes east of UTC (negative for west of UTC)"
244.1001 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
244.1002 -
244.1003 - def dst(self, dt):
244.1004 - """datetime -> DST offset in minutes east of UTC.
244.1005 -
244.1006 - Return 0 if DST not in effect. utcoffset() must include the DST
244.1007 - offset.
244.1008 - """
244.1009 - raise NotImplementedError("tzinfo subclass must override dst()")
244.1010 -
244.1011 - def fromutc(self, dt):
244.1012 - "datetime in UTC -> datetime in local time."
244.1013 -
244.1014 - if not isinstance(dt, datetime):
244.1015 - raise TypeError("fromutc() requires a datetime argument")
244.1016 - if dt.tzinfo is not self:
244.1017 - raise ValueError("dt.tzinfo is not self")
244.1018 -
244.1019 - dtoff = dt.utcoffset()
244.1020 - if dtoff is None:
244.1021 - raise ValueError("fromutc() requires a non-None utcoffset() "
244.1022 - "result")
244.1023 -
244.1024 - # See the long comment block at the end of this file for an
244.1025 - # explanation of this algorithm.
244.1026 - dtdst = dt.dst()
244.1027 - if dtdst is None:
244.1028 - raise ValueError("fromutc() requires a non-None dst() result")
244.1029 - delta = dtoff - dtdst
244.1030 - if delta:
244.1031 - dt += delta
244.1032 - dtdst = dt.dst()
244.1033 - if dtdst is None:
244.1034 - raise ValueError("fromutc(): dt.dst gave inconsistent "
244.1035 - "results; cannot convert")
244.1036 - if dtdst:
244.1037 - return dt + dtdst
244.1038 - else:
244.1039 - return dt
244.1040 -
244.1041 - # Pickle support.
244.1042 -
244.1043 - __safe_for_unpickling__ = True # For Python 2.2
244.1044 -
244.1045 - def __reduce__(self):
244.1046 - getinitargs = getattr(self, "__getinitargs__", None)
244.1047 - if getinitargs:
244.1048 - args = getinitargs()
244.1049 - else:
244.1050 - args = ()
244.1051 - getstate = getattr(self, "__getstate__", None)
244.1052 - if getstate:
244.1053 - state = getstate()
244.1054 - else:
244.1055 - state = getattr(self, "__dict__", None) or None
244.1056 - if state is None:
244.1057 - return (self.__class__, args)
244.1058 - else:
244.1059 - return (self.__class__, args, state)
244.1060 -
244.1061 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
244.1062 -
244.1063 -class time(object):
244.1064 - """Time with time zone.
244.1065 -
244.1066 - Constructors:
244.1067 -
244.1068 - __new__()
244.1069 -
244.1070 - Operators:
244.1071 -
244.1072 - __repr__, __str__
244.1073 - __cmp__, __hash__
244.1074 -
244.1075 - Methods:
244.1076 -
244.1077 - strftime()
244.1078 - isoformat()
244.1079 - utcoffset()
244.1080 - tzname()
244.1081 - dst()
244.1082 -
244.1083 - Properties (readonly):
244.1084 - hour, minute, second, microsecond, tzinfo
244.1085 - """
244.1086 -
244.1087 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
244.1088 - """Constructor.
244.1089 -
244.1090 - Arguments:
244.1091 -
244.1092 - hour, minute (required)
244.1093 - second, microsecond (default to zero)
244.1094 - tzinfo (default to None)
244.1095 - """
244.1096 - self = object.__new__(cls)
244.1097 - if isinstance(hour, str):
244.1098 - # Pickle support
244.1099 - self.__setstate((hour, minute or None))
244.1100 - return self
244.1101 - _check_tzinfo_arg(tzinfo)
244.1102 - _check_time_fields(hour, minute, second, microsecond)
244.1103 - self.__hour = hour
244.1104 - self.__minute = minute
244.1105 - self.__second = second
244.1106 - self.__microsecond = microsecond
244.1107 - self._tzinfo = tzinfo
244.1108 - return self
244.1109 -
244.1110 - # Read-only field accessors
244.1111 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
244.1112 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
244.1113 - second = property(lambda self: self.__second, doc="second (0-59)")
244.1114 - microsecond = property(lambda self: self.__microsecond,
244.1115 - doc="microsecond (0-999999)")
244.1116 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
244.1117 -
244.1118 - # Standard conversions, __hash__ (and helpers)
244.1119 -
244.1120 - # Comparisons.
244.1121 -
244.1122 - def __eq__(self, other):
244.1123 - if isinstance(other, time):
244.1124 - return self.__cmp(other) == 0
244.1125 - else:
244.1126 - return False
244.1127 -
244.1128 - def __ne__(self, other):
244.1129 - if isinstance(other, time):
244.1130 - return self.__cmp(other) != 0
244.1131 - else:
244.1132 - return True
244.1133 -
244.1134 - def __le__(self, other):
244.1135 - if isinstance(other, time):
244.1136 - return self.__cmp(other) <= 0
244.1137 - else:
244.1138 - _cmperror(self, other)
244.1139 -
244.1140 - def __lt__(self, other):
244.1141 - if isinstance(other, time):
244.1142 - return self.__cmp(other) < 0
244.1143 - else:
244.1144 - _cmperror(self, other)
244.1145 -
244.1146 - def __ge__(self, other):
244.1147 - if isinstance(other, time):
244.1148 - return self.__cmp(other) >= 0
244.1149 - else:
244.1150 - _cmperror(self, other)
244.1151 -
244.1152 - def __gt__(self, other):
244.1153 - if isinstance(other, time):
244.1154 - return self.__cmp(other) > 0
244.1155 - else:
244.1156 - _cmperror(self, other)
244.1157 -
244.1158 - def __cmp(self, other):
244.1159 - assert isinstance(other, time)
244.1160 - mytz = self._tzinfo
244.1161 - ottz = other._tzinfo
244.1162 - myoff = otoff = None
244.1163 -
244.1164 - if mytz is ottz:
244.1165 - base_compare = True
244.1166 - else:
244.1167 - myoff = self._utcoffset()
244.1168 - otoff = other._utcoffset()
244.1169 - base_compare = myoff == otoff
244.1170 -
244.1171 - if base_compare:
244.1172 - return cmp((self.__hour, self.__minute, self.__second,
244.1173 - self.__microsecond),
244.1174 - (other.__hour, other.__minute, other.__second,
244.1175 - other.__microsecond))
244.1176 - if myoff is None or otoff is None:
244.1177 - # XXX Buggy in 2.2.2.
244.1178 - raise TypeError("cannot compare naive and aware times")
244.1179 - myhhmm = self.__hour * 60 + self.__minute - myoff
244.1180 - othhmm = other.__hour * 60 + other.__minute - otoff
244.1181 - return cmp((myhhmm, self.__second, self.__microsecond),
244.1182 - (othhmm, other.__second, other.__microsecond))
244.1183 -
244.1184 - def __hash__(self):
244.1185 - """Hash."""
244.1186 - tzoff = self._utcoffset()
244.1187 - if not tzoff: # zero or None
244.1188 - return hash(self.__getstate()[0])
244.1189 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
244.1190 - if 0 <= h < 24:
244.1191 - return hash(time(h, m, self.second, self.microsecond))
244.1192 - return hash((h, m, self.second, self.microsecond))
244.1193 -
244.1194 - # Conversion to string
244.1195 -
244.1196 - def _tzstr(self, sep=":"):
244.1197 - """Return formatted timezone offset (+xx:xx) or None."""
244.1198 - off = self._utcoffset()
244.1199 - if off is not None:
244.1200 - if off < 0:
244.1201 - sign = "-"
244.1202 - off = -off
244.1203 - else:
244.1204 - sign = "+"
244.1205 - hh, mm = divmod(off, 60)
244.1206 - assert 0 <= hh < 24
244.1207 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
244.1208 - return off
244.1209 -
244.1210 - def __repr__(self):
244.1211 - """Convert to formal string, for repr()."""
244.1212 - if self.__microsecond != 0:
244.1213 - s = ", %d, %d" % (self.__second, self.__microsecond)
244.1214 - elif self.__second != 0:
244.1215 - s = ", %d" % self.__second
244.1216 - else:
244.1217 - s = ""
244.1218 - s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
244.1219 - self.__hour, self.__minute, s)
244.1220 - if self._tzinfo is not None:
244.1221 - assert s[-1:] == ")"
244.1222 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
244.1223 - return s
244.1224 -
244.1225 - def isoformat(self):
244.1226 - """Return the time formatted according to ISO.
244.1227 -
244.1228 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
244.1229 - self.microsecond == 0.
244.1230 - """
244.1231 - s = _format_time(self.__hour, self.__minute, self.__second,
244.1232 - self.__microsecond)
244.1233 - tz = self._tzstr()
244.1234 - if tz:
244.1235 - s += tz
244.1236 - return s
244.1237 -
244.1238 - __str__ = isoformat
244.1239 -
244.1240 - def strftime(self, fmt):
244.1241 - """Format using strftime(). The date part of the timestamp passed
244.1242 - to underlying strftime should not be used.
244.1243 - """
244.1244 - # The year must be >= 1900 else Python's strftime implementation
244.1245 - # can raise a bogus exception.
244.1246 - timetuple = (1900, 1, 1,
244.1247 - self.__hour, self.__minute, self.__second,
244.1248 - 0, 1, -1)
244.1249 - return _wrap_strftime(self, fmt, timetuple)
244.1250 -
244.1251 - # Timezone functions
244.1252 -
244.1253 - def utcoffset(self):
244.1254 - """Return the timezone offset in minutes east of UTC (negative west of
244.1255 - UTC)."""
244.1256 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
244.1257 - offset = _check_utc_offset("utcoffset", offset)
244.1258 - if offset is not None:
244.1259 - offset = timedelta(minutes=offset)
244.1260 - return offset
244.1261 -
244.1262 - # Return an integer (or None) instead of a timedelta (or None).
244.1263 - def _utcoffset(self):
244.1264 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
244.1265 - offset = _check_utc_offset("utcoffset", offset)
244.1266 - return offset
244.1267 -
244.1268 - def tzname(self):
244.1269 - """Return the timezone name.
244.1270 -
244.1271 - Note that the name is 100% informational -- there's no requirement that
244.1272 - it mean anything in particular. For example, "GMT", "UTC", "-500",
244.1273 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
244.1274 - """
244.1275 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
244.1276 - _check_tzname(name)
244.1277 - return name
244.1278 -
244.1279 - def dst(self):
244.1280 - """Return 0 if DST is not in effect, or the DST offset (in minutes
244.1281 - eastward) if DST is in effect.
244.1282 -
244.1283 - This is purely informational; the DST offset has already been added to
244.1284 - the UTC offset returned by utcoffset() if applicable, so there's no
244.1285 - need to consult dst() unless you're interested in displaying the DST
244.1286 - info.
244.1287 - """
244.1288 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
244.1289 - offset = _check_utc_offset("dst", offset)
244.1290 - if offset is not None:
244.1291 - offset = timedelta(minutes=offset)
244.1292 - return offset
244.1293 -
244.1294 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
244.1295 - tzinfo=True):
244.1296 - """Return a new time with new values for the specified fields."""
244.1297 - if hour is None:
244.1298 - hour = self.hour
244.1299 - if minute is None:
244.1300 - minute = self.minute
244.1301 - if second is None:
244.1302 - second = self.second
244.1303 - if microsecond is None:
244.1304 - microsecond = self.microsecond
244.1305 - if tzinfo is True:
244.1306 - tzinfo = self.tzinfo
244.1307 - _check_time_fields(hour, minute, second, microsecond)
244.1308 - _check_tzinfo_arg(tzinfo)
244.1309 - return time(hour, minute, second, microsecond, tzinfo)
244.1310 -
244.1311 - # Return an integer (or None) instead of a timedelta (or None).
244.1312 - def _dst(self):
244.1313 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
244.1314 - offset = _check_utc_offset("dst", offset)
244.1315 - return offset
244.1316 -
244.1317 - def __nonzero__(self):
244.1318 - if self.second or self.microsecond:
244.1319 - return 1
244.1320 - offset = self._utcoffset() or 0
244.1321 - return self.hour * 60 + self.minute - offset != 0
244.1322 -
244.1323 - # Pickle support.
244.1324 -
244.1325 - __safe_for_unpickling__ = True # For Python 2.2
244.1326 -
244.1327 - def __getstate(self):
244.1328 - us2, us3 = divmod(self.__microsecond, 256)
244.1329 - us1, us2 = divmod(us2, 256)
244.1330 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
244.1331 - us1, us2, us3)
244.1332 - if self._tzinfo is None:
244.1333 - return (basestate,)
244.1334 - else:
244.1335 - return (basestate, self._tzinfo)
244.1336 -
244.1337 - def __setstate(self, state):
244.1338 - assert isinstance(state, tuple)
244.1339 - assert 1 <= len(state) <= 2
244.1340 - string = state[0]
244.1341 - assert len(string) == 6
244.1342 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
244.1343 - map(ord, string)
244.1344 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
244.1345 - if len(state) == 1:
244.1346 - self._tzinfo = None
244.1347 - else:
244.1348 - self._tzinfo = state[1]
244.1349 -
244.1350 - def __reduce__(self):
244.1351 - return (self.__class__, self.__getstate())
244.1352 -
244.1353 -_time_class = time # so functions w/ args named "time" can get at the class
244.1354 -
244.1355 -time.min = time(0, 0, 0)
244.1356 -time.max = time(23, 59, 59, 999999)
244.1357 -time.resolution = timedelta(microseconds=1)
244.1358 -
244.1359 -class datetime(date):
244.1360 -
244.1361 - # XXX needs docstrings
244.1362 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
244.1363 -
244.1364 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
244.1365 - microsecond=0, tzinfo=None):
244.1366 - if isinstance(year, str):
244.1367 - # Pickle support
244.1368 - self = date.__new__(cls, year[:4])
244.1369 - self.__setstate((year, month))
244.1370 - return self
244.1371 - _check_tzinfo_arg(tzinfo)
244.1372 - _check_time_fields(hour, minute, second, microsecond)
244.1373 - self = date.__new__(cls, year, month, day)
244.1374 - # XXX This duplicates __year, __month, __day for convenience :-(
244.1375 - self.__year = year
244.1376 - self.__month = month
244.1377 - self.__day = day
244.1378 - self.__hour = hour
244.1379 - self.__minute = minute
244.1380 - self.__second = second
244.1381 - self.__microsecond = microsecond
244.1382 - self._tzinfo = tzinfo
244.1383 - return self
244.1384 -
244.1385 - # Read-only field accessors
244.1386 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
244.1387 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
244.1388 - second = property(lambda self: self.__second, doc="second (0-59)")
244.1389 - microsecond = property(lambda self: self.__microsecond,
244.1390 - doc="microsecond (0-999999)")
244.1391 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
244.1392 -
244.1393 - def fromtimestamp(cls, t, tz=None):
244.1394 - """Construct a datetime from a POSIX timestamp (like time.time()).
244.1395 -
244.1396 - A timezone info object may be passed in as well.
244.1397 - """
244.1398 -
244.1399 - _check_tzinfo_arg(tz)
244.1400 - if tz is None:
244.1401 - converter = _time.localtime
244.1402 - else:
244.1403 - converter = _time.gmtime
244.1404 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
244.1405 - us = int((t % 1.0) * 1000000)
244.1406 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
244.1407 - result = cls(y, m, d, hh, mm, ss, us, tz)
244.1408 - if tz is not None:
244.1409 - result = tz.fromutc(result)
244.1410 - return result
244.1411 - fromtimestamp = classmethod(fromtimestamp)
244.1412 -
244.1413 - def utcfromtimestamp(cls, t):
244.1414 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
244.1415 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
244.1416 - us = int((t % 1.0) * 1000000)
244.1417 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
244.1418 - return cls(y, m, d, hh, mm, ss, us)
244.1419 - utcfromtimestamp = classmethod(utcfromtimestamp)
244.1420 -
244.1421 - # XXX This is supposed to do better than we *can* do by using time.time(),
244.1422 - # XXX if the platform supports a more accurate way. The C implementation
244.1423 - # XXX uses gettimeofday on platforms that have it, but that isn't
244.1424 - # XXX available from Python. So now() may return different results
244.1425 - # XXX across the implementations.
244.1426 - def now(cls, tz=None):
244.1427 - "Construct a datetime from time.time() and optional time zone info."
244.1428 - t = _time.time()
244.1429 - return cls.fromtimestamp(t, tz)
244.1430 - now = classmethod(now)
244.1431 -
244.1432 - def utcnow(cls):
244.1433 - "Construct a UTC datetime from time.time()."
244.1434 - t = _time.time()
244.1435 - return cls.utcfromtimestamp(t)
244.1436 - utcnow = classmethod(utcnow)
244.1437 -
244.1438 - def combine(cls, date, time):
244.1439 - "Construct a datetime from a given date and a given time."
244.1440 - if not isinstance(date, _date_class):
244.1441 - raise TypeError("date argument must be a date instance")
244.1442 - if not isinstance(time, _time_class):
244.1443 - raise TypeError("time argument must be a time instance")
244.1444 - return cls(date.year, date.month, date.day,
244.1445 - time.hour, time.minute, time.second, time.microsecond,
244.1446 - time.tzinfo)
244.1447 - combine = classmethod(combine)
244.1448 -
244.1449 - def timetuple(self):
244.1450 - "Return local time tuple compatible with time.localtime()."
244.1451 - dst = self._dst()
244.1452 - if dst is None:
244.1453 - dst = -1
244.1454 - elif dst:
244.1455 - dst = 1
244.1456 - return _build_struct_time(self.year, self.month, self.day,
244.1457 - self.hour, self.minute, self.second,
244.1458 - dst)
244.1459 -
244.1460 - def utctimetuple(self):
244.1461 - "Return UTC time tuple compatible with time.gmtime()."
244.1462 - y, m, d = self.year, self.month, self.day
244.1463 - hh, mm, ss = self.hour, self.minute, self.second
244.1464 - offset = self._utcoffset()
244.1465 - if offset: # neither None nor 0
244.1466 - tm = tmxxx(y, m, d, hh, mm - offset)
244.1467 - y, m, d = tm.year, tm.month, tm.day
244.1468 - hh, mm = tm.hour, tm.minute
244.1469 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
244.1470 -
244.1471 - def date(self):
244.1472 - "Return the date part."
244.1473 - return date(self.__year, self.__month, self.__day)
244.1474 -
244.1475 - def time(self):
244.1476 - "Return the time part, with tzinfo None."
244.1477 - return time(self.hour, self.minute, self.second, self.microsecond)
244.1478 -
244.1479 - def timetz(self):
244.1480 - "Return the time part, with same tzinfo."
244.1481 - return time(self.hour, self.minute, self.second, self.microsecond,
244.1482 - self._tzinfo)
244.1483 -
244.1484 - def replace(self, year=None, month=None, day=None, hour=None,
244.1485 - minute=None, second=None, microsecond=None, tzinfo=True):
244.1486 - """Return a new datetime with new values for the specified fields."""
244.1487 - if year is None:
244.1488 - year = self.year
244.1489 - if month is None:
244.1490 - month = self.month
244.1491 - if day is None:
244.1492 - day = self.day
244.1493 - if hour is None:
244.1494 - hour = self.hour
244.1495 - if minute is None:
244.1496 - minute = self.minute
244.1497 - if second is None:
244.1498 - second = self.second
244.1499 - if microsecond is None:
244.1500 - microsecond = self.microsecond
244.1501 - if tzinfo is True:
244.1502 - tzinfo = self.tzinfo
244.1503 - _check_date_fields(year, month, day)
244.1504 - _check_time_fields(hour, minute, second, microsecond)
244.1505 - _check_tzinfo_arg(tzinfo)
244.1506 - return datetime(year, month, day, hour, minute, second,
244.1507 - microsecond, tzinfo)
244.1508 -
244.1509 - def astimezone(self, tz):
244.1510 - if not isinstance(tz, tzinfo):
244.1511 - raise TypeError("tz argument must be an instance of tzinfo")
244.1512 -
244.1513 - mytz = self.tzinfo
244.1514 - if mytz is None:
244.1515 - raise ValueError("astimezone() requires an aware datetime")
244.1516 -
244.1517 - if tz is mytz:
244.1518 - return self
244.1519 -
244.1520 - # Convert self to UTC, and attach the new time zone object.
244.1521 - myoffset = self.utcoffset()
244.1522 - if myoffset is None:
244.1523 - raise ValuError("astimezone() requires an aware datetime")
244.1524 - utc = (self - myoffset).replace(tzinfo=tz)
244.1525 -
244.1526 - # Convert from UTC to tz's local time.
244.1527 - return tz.fromutc(utc)
244.1528 -
244.1529 - # Ways to produce a string.
244.1530 -
244.1531 - def ctime(self):
244.1532 - "Format a la ctime()."
244.1533 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
244.1534 - self.__minute, self.__second)
244.1535 - return t.ctime()
244.1536 -
244.1537 - def isoformat(self, sep='T'):
244.1538 - """Return the time formatted according to ISO.
244.1539 -
244.1540 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
244.1541 - self.microsecond == 0.
244.1542 -
244.1543 - If self.tzinfo is not None, the UTC offset is also attached, giving
244.1544 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
244.1545 -
244.1546 - Optional argument sep specifies the separator between date and
244.1547 - time, default 'T'.
244.1548 - """
244.1549 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
244.1550 - sep) +
244.1551 - _format_time(self.__hour, self.__minute, self.__second,
244.1552 - self.__microsecond))
244.1553 - off = self._utcoffset()
244.1554 - if off is not None:
244.1555 - if off < 0:
244.1556 - sign = "-"
244.1557 - off = -off
244.1558 - else:
244.1559 - sign = "+"
244.1560 - hh, mm = divmod(off, 60)
244.1561 - s += "%s%02d:%02d" % (sign, hh, mm)
244.1562 - return s
244.1563 -
244.1564 - def __repr__(self):
244.1565 - "Convert to formal string, for repr()."
244.1566 - L = [self.__year, self.__month, self.__day, # These are never zero
244.1567 - self.__hour, self.__minute, self.__second, self.__microsecond]
244.1568 - if L[-1] == 0:
244.1569 - del L[-1]
244.1570 - if L[-1] == 0:
244.1571 - del L[-1]
244.1572 - s = ", ".join(map(str, L))
244.1573 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
244.1574 - if self._tzinfo is not None:
244.1575 - assert s[-1:] == ")"
244.1576 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
244.1577 - return s
244.1578 -
244.1579 - def __str__(self):
244.1580 - "Convert to string, for str()."
244.1581 - return self.isoformat(sep=' ')
244.1582 -
244.1583 - def utcoffset(self):
244.1584 - """Return the timezone offset in minutes east of UTC (negative west of
244.1585 - UTC)."""
244.1586 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
244.1587 - offset = _check_utc_offset("utcoffset", offset)
244.1588 - if offset is not None:
244.1589 - offset = timedelta(minutes=offset)
244.1590 - return offset
244.1591 -
244.1592 - # Return an integer (or None) instead of a timedelta (or None).
244.1593 - def _utcoffset(self):
244.1594 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
244.1595 - offset = _check_utc_offset("utcoffset", offset)
244.1596 - return offset
244.1597 -
244.1598 - def tzname(self):
244.1599 - """Return the timezone name.
244.1600 -
244.1601 - Note that the name is 100% informational -- there's no requirement that
244.1602 - it mean anything in particular. For example, "GMT", "UTC", "-500",
244.1603 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
244.1604 - """
244.1605 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
244.1606 - _check_tzname(name)
244.1607 - return name
244.1608 -
244.1609 - def dst(self):
244.1610 - """Return 0 if DST is not in effect, or the DST offset (in minutes
244.1611 - eastward) if DST is in effect.
244.1612 -
244.1613 - This is purely informational; the DST offset has already been added to
244.1614 - the UTC offset returned by utcoffset() if applicable, so there's no
244.1615 - need to consult dst() unless you're interested in displaying the DST
244.1616 - info.
244.1617 - """
244.1618 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
244.1619 - offset = _check_utc_offset("dst", offset)
244.1620 - if offset is not None:
244.1621 - offset = timedelta(minutes=offset)
244.1622 - return offset
244.1623 -
244.1624 - # Return an integer (or None) instead of a timedelta (or None).1573
244.1625 - def _dst(self):
244.1626 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
244.1627 - offset = _check_utc_offset("dst", offset)
244.1628 - return offset
244.1629 -
244.1630 - # Comparisons.
244.1631 -
244.1632 - def __eq__(self, other):
244.1633 - if isinstance(other, datetime):
244.1634 - return self.__cmp(other) == 0
244.1635 - elif hasattr(other, "timetuple"):
244.1636 - return NotImplemented
244.1637 - else:
244.1638 - return False
244.1639 -
244.1640 - def __ne__(self, other):
244.1641 - if isinstance(other, datetime):
244.1642 - return self.__cmp(other) != 0
244.1643 - elif hasattr(other, "timetuple"):
244.1644 - return NotImplemented
244.1645 - else:
244.1646 - return True
244.1647 -
244.1648 - def __le__(self, other):
244.1649 - if isinstance(other, datetime):
244.1650 - return self.__cmp(other) <= 0
244.1651 - elif hasattr(other, "timetuple"):
244.1652 - return NotImplemented
244.1653 - else:
244.1654 - _cmperror(self, other)
244.1655 -
244.1656 - def __lt__(self, other):
244.1657 - if isinstance(other, datetime):
244.1658 - return self.__cmp(other) < 0
244.1659 - elif hasattr(other, "timetuple"):
244.1660 - return NotImplemented
244.1661 - else:
244.1662 - _cmperror(self, other)
244.1663 -
244.1664 - def __ge__(self, other):
244.1665 - if isinstance(other, datetime):
244.1666 - return self.__cmp(other) >= 0
244.1667 - elif hasattr(other, "timetuple"):
244.1668 - return NotImplemented
244.1669 - else:
244.1670 - _cmperror(self, other)
244.1671 -
244.1672 - def __gt__(self, other):
244.1673 - if isinstance(other, datetime):
244.1674 - return self.__cmp(other) > 0
244.1675 - elif hasattr(other, "timetuple"):
244.1676 - return NotImplemented
244.1677 - else:
244.1678 - _cmperror(self, other)
244.1679 -
244.1680 - def __cmp(self, other):
244.1681 - assert isinstance(other, datetime)
244.1682 - mytz = self._tzinfo
244.1683 - ottz = other._tzinfo
244.1684 - myoff = otoff = None
244.1685 -
244.1686 - if mytz is ottz:
244.1687 - base_compare = True
244.1688 - else:
244.1689 - if mytz is not None:
244.1690 - myoff = self._utcoffset()
244.1691 - if ottz is not None:
244.1692 - otoff = other._utcoffset()
244.1693 - base_compare = myoff == otoff
244.1694 -
244.1695 - if base_compare:
244.1696 - return cmp((self.__year, self.__month, self.__day,
244.1697 - self.__hour, self.__minute, self.__second,
244.1698 - self.__microsecond),
244.1699 - (other.__year, other.__month, other.__day,
244.1700 - other.__hour, other.__minute, other.__second,
244.1701 - other.__microsecond))
244.1702 - if myoff is None or otoff is None:
244.1703 - # XXX Buggy in 2.2.2.
244.1704 - raise TypeError("cannot compare naive and aware datetimes")
244.1705 - # XXX What follows could be done more efficiently...
244.1706 - diff = self - other # this will take offsets into account
244.1707 - if diff.days < 0:
244.1708 - return -1
244.1709 - return diff and 1 or 0
244.1710 -
244.1711 - def __add__(self, other):
244.1712 - "Add a datetime and a timedelta."
244.1713 - if not isinstance(other, timedelta):
244.1714 - return NotImplemented
244.1715 - t = tmxxx(self.__year,
244.1716 - self.__month,
244.1717 - self.__day + other.days,
244.1718 - self.__hour,
244.1719 - self.__minute,
244.1720 - self.__second + other.seconds,
244.1721 - self.__microsecond + other.microseconds)
244.1722 - self._checkOverflow(t.year)
244.1723 - result = self.__class__(t.year, t.month, t.day,
244.1724 - t.hour, t.minute, t.second,
244.1725 - t.microsecond, tzinfo=self._tzinfo)
244.1726 - return result
244.1727 -
244.1728 - __radd__ = __add__
244.1729 -
244.1730 - def __sub__(self, other):
244.1731 - "Subtract two datetimes, or a datetime and a timedelta."
244.1732 - if not isinstance(other, datetime):
244.1733 - if isinstance(other, timedelta):
244.1734 - return self + -other
244.1735 - return NotImplemented
244.1736 -
244.1737 - days1 = self.toordinal()
244.1738 - days2 = other.toordinal()
244.1739 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
244.1740 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
244.1741 - base = timedelta(days1 - days2,
244.1742 - secs1 - secs2,
244.1743 - self.__microsecond - other.__microsecond)
244.1744 - if self._tzinfo is other._tzinfo:
244.1745 - return base
244.1746 - myoff = self._utcoffset()
244.1747 - otoff = other._utcoffset()
244.1748 - if myoff == otoff:
244.1749 - return base
244.1750 - if myoff is None or otoff is None:
244.1751 - raise TypeError, "cannot mix naive and timezone-aware time"
244.1752 - return base + timedelta(minutes = otoff-myoff)
244.1753 -
244.1754 - def __hash__(self):
244.1755 - tzoff = self._utcoffset()
244.1756 - if tzoff is None:
244.1757 - return hash(self.__getstate()[0])
244.1758 - days = _ymd2ord(self.year, self.month, self.day)
244.1759 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
244.1760 - return hash(timedelta(days, seconds, self.microsecond))
244.1761 -
244.1762 - # Pickle support.
244.1763 -
244.1764 - __safe_for_unpickling__ = True # For Python 2.2
244.1765 -
244.1766 - def __getstate(self):
244.1767 - yhi, ylo = divmod(self.__year, 256)
244.1768 - us2, us3 = divmod(self.__microsecond, 256)
244.1769 - us1, us2 = divmod(us2, 256)
244.1770 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
244.1771 - self.__hour, self.__minute, self.__second,
244.1772 - us1, us2, us3)
244.1773 - if self._tzinfo is None:
244.1774 - return (basestate,)
244.1775 - else:
244.1776 - return (basestate, self._tzinfo)
244.1777 -
244.1778 - def __setstate(self, state):
244.1779 - assert isinstance(state, tuple)
244.1780 - assert 1 <= len(state) <= 2
244.1781 - string = state[0]
244.1782 - assert len(string) == 10
244.1783 - (yhi, ylo, self.__month, self.__day, self.__hour,
244.1784 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
244.1785 - self.__year = yhi * 256 + ylo
244.1786 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
244.1787 - if len(state) == 1:
244.1788 - self._tzinfo = None
244.1789 - else:
244.1790 - self._tzinfo = state[1]
244.1791 -
244.1792 - def __reduce__(self):
244.1793 - return (self.__class__, self.__getstate())
244.1794 -
244.1795 -
244.1796 -datetime.min = datetime(1, 1, 1)
244.1797 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
244.1798 -datetime.resolution = timedelta(microseconds=1)
244.1799 -
244.1800 -
244.1801 -def _isoweek1monday(year):
244.1802 - # Helper to calculate the day number of the Monday starting week 1
244.1803 - # XXX This could be done more efficiently
244.1804 - THURSDAY = 3
244.1805 - firstday = _ymd2ord(year, 1, 1)
244.1806 - firstweekday = (firstday + 6) % 7 # See weekday() above
244.1807 - week1monday = firstday - firstweekday
244.1808 - if firstweekday > THURSDAY:
244.1809 - week1monday += 7
244.1810 - return week1monday
244.1811 -
244.1812 -"""
244.1813 -Some time zone algebra. For a datetime x, let
244.1814 - x.n = x stripped of its timezone -- its naive time.
244.1815 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
244.1816 - return None
244.1817 - x.d = x.dst(), and assuming that doesn't raise an exception or
244.1818 - return None
244.1819 - x.s = x's standard offset, x.o - x.d
244.1820 -
244.1821 -Now some derived rules, where k is a duration (timedelta).
244.1822 -
244.1823 -1. x.o = x.s + x.d
244.1824 - This follows from the definition of x.s.
244.1825 -
244.1826 -2. If x and y have the same tzinfo member, x.s = y.s.
244.1827 - This is actually a requirement, an assumption we need to make about
244.1828 - sane tzinfo classes.
244.1829 -
244.1830 -3. The naive UTC time corresponding to x is x.n - x.o.
244.1831 - This is again a requirement for a sane tzinfo class.
244.1832 -
244.1833 -4. (x+k).s = x.s
244.1834 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
244.1835 -
244.1836 -5. (x+k).n = x.n + k
244.1837 - Again follows from how arithmetic is defined.
244.1838 -
244.1839 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
244.1840 -(meaning that the various tzinfo methods exist, and don't blow up or return
244.1841 -None when called).
244.1842 -
244.1843 -The function wants to return a datetime y with timezone tz, equivalent to x.
244.1844 -x is already in UTC.
244.1845 -
244.1846 -By #3, we want
244.1847 -
244.1848 - y.n - y.o = x.n [1]
244.1849 -
244.1850 -The algorithm starts by attaching tz to x.n, and calling that y. So
244.1851 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
244.1852 -becomes true; in effect, we want to solve [2] for k:
244.1853 -
244.1854 - (y+k).n - (y+k).o = x.n [2]
244.1855 -
244.1856 -By #1, this is the same as
244.1857 -
244.1858 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
244.1859 -
244.1860 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
244.1861 -Substituting that into [3],
244.1862 -
244.1863 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
244.1864 - k - (y+k).s - (y+k).d = 0; rearranging,
244.1865 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
244.1866 - k = y.s - (y+k).d
244.1867 -
244.1868 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
244.1869 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
244.1870 -very large, since all offset-returning methods return a duration of magnitude
244.1871 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
244.1872 -be 0, so ignoring it has no consequence then.
244.1873 -
244.1874 -In any case, the new value is
244.1875 -
244.1876 - z = y + y.s [4]
244.1877 -
244.1878 -It's helpful to step back at look at [4] from a higher level: it's simply
244.1879 -mapping from UTC to tz's standard time.
244.1880 -
244.1881 -At this point, if
244.1882 -
244.1883 - z.n - z.o = x.n [5]
244.1884 -
244.1885 -we have an equivalent time, and are almost done. The insecurity here is
244.1886 -at the start of daylight time. Picture US Eastern for concreteness. The wall
244.1887 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
244.1888 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
244.1889 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
244.1890 -on the day DST starts. We want to return the 1:MM EST spelling because that's
244.1891 -the only spelling that makes sense on the local wall clock.
244.1892 -
244.1893 -In fact, if [5] holds at this point, we do have the standard-time spelling,
244.1894 -but that takes a bit of proof. We first prove a stronger result. What's the
244.1895 -difference between the LHS and RHS of [5]? Let
244.1896 -
244.1897 - diff = x.n - (z.n - z.o) [6]
244.1898 -
244.1899 -Now
244.1900 - z.n = by [4]
244.1901 - (y + y.s).n = by #5
244.1902 - y.n + y.s = since y.n = x.n
244.1903 - x.n + y.s = since z and y are have the same tzinfo member,
244.1904 - y.s = z.s by #2
244.1905 - x.n + z.s
244.1906 -
244.1907 -Plugging that back into [6] gives
244.1908 -
244.1909 - diff =
244.1910 - x.n - ((x.n + z.s) - z.o) = expanding
244.1911 - x.n - x.n - z.s + z.o = cancelling
244.1912 - - z.s + z.o = by #2
244.1913 - z.d
244.1914 -
244.1915 -So diff = z.d.
244.1916 -
244.1917 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
244.1918 -spelling we wanted in the endcase described above. We're done. Contrarily,
244.1919 -if z.d = 0, then we have a UTC equivalent, and are also done.
244.1920 -
244.1921 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
244.1922 -add to z (in effect, z is in tz's standard time, and we need to shift the
244.1923 -local clock into tz's daylight time).
244.1924 -
244.1925 -Let
244.1926 -
244.1927 - z' = z + z.d = z + diff [7]
244.1928 -
244.1929 -and we can again ask whether
244.1930 -
244.1931 - z'.n - z'.o = x.n [8]
244.1932 -
244.1933 -If so, we're done. If not, the tzinfo class is insane, according to the
244.1934 -assumptions we've made. This also requires a bit of proof. As before, let's
244.1935 -compute the difference between the LHS and RHS of [8] (and skipping some of
244.1936 -the justifications for the kinds of substitutions we've done several times
244.1937 -already):
244.1938 -
244.1939 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
244.1940 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
244.1941 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
244.1942 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
244.1943 - - z.n + z.n - z.o + z'.o = cancel z.n
244.1944 - - z.o + z'.o = #1 twice
244.1945 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
244.1946 - z'.d - z.d
244.1947 -
244.1948 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
244.1949 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
244.1950 -return z', not bothering to compute z'.d.
244.1951 -
244.1952 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
244.1953 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
244.1954 -would have to change the result dst() returns: we start in DST, and moving
244.1955 -a little further into it takes us out of DST.
244.1956 -
244.1957 -There isn't a sane case where this can happen. The closest it gets is at
244.1958 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
244.1959 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
244.1960 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
244.1961 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
244.1962 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
244.1963 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
244.1964 -standard time. Since that's what the local clock *does*, we want to map both
244.1965 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
244.1966 -in local time, but so it goes -- it's the way the local clock works.
244.1967 -
244.1968 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
244.1969 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
244.1970 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
244.1971 -(correctly) concludes that z' is not UTC-equivalent to x.
244.1972 -
244.1973 -Because we know z.d said z was in daylight time (else [5] would have held and
244.1974 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
244.1975 -and we we have stopped then), and there are only 2 possible values dst() can
244.1976 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
244.1977 -but the reasoning doesn't depend on the example -- it depends on there being
244.1978 -two possible dst() outcomes, one zero and the other non-zero). Therefore
244.1979 -z' must be in standard time, and is the spelling we want in this case.
244.1980 -
244.1981 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
244.1982 -concerned (because it takes z' as being in standard time rather than the
244.1983 -daylight time we intend here), but returning it gives the real-life "local
244.1984 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
244.1985 -tz.
244.1986 -
244.1987 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
244.1988 -the 1:MM standard time spelling we want.
244.1989 -
244.1990 -So how can this break? One of the assumptions must be violated. Two
244.1991 -possibilities:
244.1992 -
244.1993 -1) [2] effectively says that y.s is invariant across all y belong to a given
244.1994 - time zone. This isn't true if, for political reasons or continental drift,
244.1995 - a region decides to change its base offset from UTC.
244.1996 -
244.1997 -2) There may be versions of "double daylight" time where the tail end of
244.1998 - the analysis gives up a step too early. I haven't thought about that
244.1999 - enough to say.
244.2000 -
244.2001 -In any case, it's clear that the default fromutc() is strong enough to handle
244.2002 -"almost all" time zones: so long as the standard offset is invariant, it
244.2003 -doesn't matter if daylight time transition points change from year to year, or
244.2004 -if daylight time is skipped in some years; it doesn't matter how large or
244.2005 -small dst() may get within its bounds; and it doesn't even matter if some
244.2006 -perverse time zone returns a negative dst()). So a breaking case must be
244.2007 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
244.2008 -"""
244.2009 -
244.2010 -def _test():
244.2011 - import test_datetime
244.2012 - test_datetime.test_main()
244.2013 -
244.2014 -if __name__ == "__main__":
244.2015 - _test()
245.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testFix5.fixed Sun Jan 04 13:11:53 2015 -0600
245.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
245.3 @@ -1,2011 +0,0 @@
245.4 -"""Concrete date/time and related types -- prototype implemented in Python.
245.5 -
245.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
245.7 -
245.8 -See also http://dir.yahoo.com/Reference/calendars/
245.9 -
245.10 -For a primer on DST, including many current DST rules, see
245.11 -http://webexhibits.org/daylightsaving/
245.12 -
245.13 -For more about DST than you ever wanted to know, see
245.14 -ftp://elsie.nci.nih.gov/pub/
245.15 -
245.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
245.17 -
245.18 -"""
245.19 -
245.20 -import time as _time
245.21 -import math as _math
245.22 -
245.23 -MINYEAR = 1
245.24 -MAXYEAR = 9999
245.25 -
245.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
245.27 -# also assumes the current Gregorian calendar indefinitely extended in
245.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
245.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
245.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
245.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
245.32 -# for all computations. See the book for algorithms for converting between
245.33 -# proleptic Gregorian ordinals and many other calendar systems.
245.34 -
245.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
245.36 -
245.37 -_DAYS_BEFORE_MONTH = [None]
245.38 -dbm = 0
245.39 -for dim in _DAYS_IN_MONTH[1:]:
245.40 - _DAYS_BEFORE_MONTH.append(dbm)
245.41 - dbm += dim
245.42 -del dbm, dim
245.43 -
245.44 -def _is_leap(year):
245.45 - "year -> 1 if leap year, else 0."
245.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
245.47 -
245.48 -def _days_in_year(year):
245.49 - "year -> number of days in year (366 if a leap year, else 365)."
245.50 - return 365 + _is_leap(year)
245.51 -
245.52 -def _days_before_year(year):
245.53 - "year -> number of days before January 1st of year."
245.54 - y = year - 1
245.55 - return y*365 + y//4 - y//100 + y//400
245.56 -
245.57 -def _days_in_month(year, month):
245.58 - "year, month -> number of days in that month in that year."
245.59 - assert 1 <= month <= 12, month
245.60 - if month == 2 and _is_leap(year):
245.61 - return 29
245.62 - return _DAYS_IN_MONTH[month]
245.63 -
245.64 -def _days_before_month(year, month):
245.65 - "year, month -> number of days in year preceeding first day of month."
245.66 - if not 1 <= month <= 12:
245.67 - raise ValueError('month must be in 1..12', month)
245.68 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
245.69 -
245.70 -def _ymd2ord(year, month, day):
245.71 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
245.72 - if not 1 <= month <= 12:
245.73 - raise ValueError('month must be in 1..12', month)
245.74 - dim = _days_in_month(year, month)
245.75 - if not 1 <= day <= dim:
245.76 - raise ValueError('day must be in 1..%d' % dim, day)
245.77 - return (_days_before_year(year) +
245.78 - _days_before_month(year, month) +
245.79 - day)
245.80 -
245.81 -try:
245.82 - _DI400Y = _days_before_year(401) # number of days in 400 years
245.83 - _DI100Y = _days_before_year(101) # " " " " 100 "
245.84 -finally:
245.85 -
245.86 -_DI4Y = _days_before_year(5) # " " " " 4 "
245.87 -
245.88 -# A 4-year cycle has an extra leap day over what we'd get from pasting
245.89 -# together 4 single years.
245.90 -assert _DI4Y == 4 * 365 + 1
245.91 -
245.92 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
245.93 -# pasting together 4 100-year cycles.
245.94 -assert _DI400Y == 4 * _DI100Y + 1
245.95 -
245.96 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
245.97 -# pasting together 25 4-year cycles.
245.98 -assert _DI100Y == 25 * _DI4Y - 1
245.99 -
245.100 -def _ord2ymd(n):
245.101 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
245.102 -
245.103 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
245.104 - # repeats exactly every 400 years. The basic strategy is to find the
245.105 - # closest 400-year boundary at or before n, then work with the offset
245.106 - # from that boundary to n. Life is much clearer if we subtract 1 from
245.107 - # n first -- then the values of n at 400-year boundaries are exactly
245.108 - # those divisible by _DI400Y:
245.109 - #
245.110 - # D M Y n n-1
245.111 - # -- --- ---- ---------- ----------------
245.112 - # 31 Dec -400 -_DI400Y -_DI400Y -1
245.113 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
245.114 - # ...
245.115 - # 30 Dec 000 -1 -2
245.116 - # 31 Dec 000 0 -1
245.117 - # 1 Jan 001 1 0 400-year boundary
245.118 - # 2 Jan 001 2 1
245.119 - # 3 Jan 001 3 2
245.120 - # ...
245.121 - # 31 Dec 400 _DI400Y _DI400Y -1
245.122 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
245.123 - n -= 1
245.124 - n400, n = divmod(n, _DI400Y)
245.125 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
245.126 -
245.127 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
245.128 - # the desired date. Now compute how many 100-year cycles precede n.
245.129 - # Note that it's possible for n100 to equal 4! In that case 4 full
245.130 - # 100-year cycles precede the desired day, which implies the desired
245.131 - # day is December 31 at the end of a 400-year cycle.
245.132 - n100, n = divmod(n, _DI100Y)
245.133 -
245.134 - # Now compute how many 4-year cycles precede it.
245.135 - n4, n = divmod(n, _DI4Y)
245.136 -
245.137 - # And now how many single years. Again n1 can be 4, and again meaning
245.138 - # that the desired day is December 31 at the end of the 4-year cycle.
245.139 - n1, n = divmod(n, 365)
245.140 -
245.141 - year += n100 * 100 + n4 * 4 + n1
245.142 - if n1 == 4 or n100 == 4:
245.143 - assert n == 0
245.144 - return year-1, 12, 31
245.145 -
245.146 - # Now the year is correct, and n is the offset from January 1. We find
245.147 - # the month via an estimate that's either exact or one too large.
245.148 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
245.149 - assert leapyear == _is_leap(year)
245.150 - month = (n + 50) >> 5
245.151 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
245.152 - if preceding > n: # estimate is too large
245.153 - month -= 1
245.154 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
245.155 - n -= preceding
245.156 - assert 0 <= n < _days_in_month(year, month)
245.157 -
245.158 - # Now the year and month are correct, and n is the offset from the
245.159 - # start of that month: we're done!
245.160 - return year, month, n+1
245.161 -
245.162 -# Month and day names. For localized versions, see the calendar module.
245.163 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
245.164 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
245.165 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
245.166 -
245.167 -
245.168 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
245.169 - wday = (_ymd2ord(y, m, d) + 6) % 7
245.170 - dnum = _days_before_month(y, m) + d
245.171 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
245.172 -
245.173 -def _format_time(hh, mm, ss, us):
245.174 - # Skip trailing microseconds when us==0.
245.175 - result = "%02d:%02d:%02d" % (hh, mm, ss)
245.176 - if us:
245.177 - result += ".%06d" % us
245.178 - return result
245.179 -
245.180 -# Correctly substitute for %z and %Z escapes in strftime formats.
245.181 -def _wrap_strftime(object, format, timetuple):
245.182 - year = timetuple[0]
245.183 - if year < 1900:
245.184 - raise ValueError("year=%d is before 1900; the datetime strftime() "
245.185 - "methods require year >= 1900" % year)
245.186 - # Don't call _utcoffset() or tzname() unless actually needed.
245.187 - zreplace = None # the string to use for %z
245.188 - Zreplace = None # the string to use for %Z
245.189 -
245.190 - # Scan format for %z and %Z escapes, replacing as needed.
245.191 - newformat = []
245.192 - push = newformat.append
245.193 - i, n = 0, len(format)
245.194 - while i < n:
245.195 - ch = format[i]
245.196 - i += 1
245.197 - if ch == '%':
245.198 - if i < n:
245.199 - ch = format[i]
245.200 - i += 1
245.201 - if ch == 'z':
245.202 - if zreplace is None:
245.203 - zreplace = ""
245.204 - if hasattr(object, "_utcoffset"):
245.205 - offset = object._utcoffset()
245.206 - if offset is not None:
245.207 - sign = '+'
245.208 - if offset < 0:
245.209 - offset = -offset
245.210 - sign = '-'
245.211 - h, m = divmod(offset, 60)
245.212 - zreplace = '%c%02d%02d' % (sign, h, m)
245.213 - assert '%' not in zreplace
245.214 - newformat.append(zreplace)
245.215 - elif ch == 'Z':
245.216 - if Zreplace is None:
245.217 - Zreplace = ""
245.218 - if hasattr(object, "tzname"):
245.219 - s = object.tzname()
245.220 - if s is not None:
245.221 - # strftime is going to have at this: escape %
245.222 - Zreplace = s.replace('%', '%%')
245.223 - newformat.append(Zreplace)
245.224 - else:
245.225 - push('%')
245.226 - push(ch)
245.227 - else:
245.228 - push('%')
245.229 - else:
245.230 - push(ch)
245.231 - newformat = "".join(newformat)
245.232 - return _time.strftime(newformat, timetuple)
245.233 -
245.234 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
245.235 - if tzinfo is None:
245.236 - return None
245.237 - return getattr(tzinfo, methname)(tzinfoarg)
245.238 -
245.239 -# Just raise TypeError if the arg isn't None or a string.
245.240 -def _check_tzname(name):
245.241 - if name is not None and not isinstance(name, str):
245.242 - raise TypeError("tzinfo.tzname() must return None or string, "
245.243 - "not '%s'" % type(name))
245.244 -
245.245 -# name is the offset-producing method, "utcoffset" or "dst".
245.246 -# offset is what it returned.
245.247 -# If offset isn't None or timedelta, raises TypeError.
245.248 -# If offset is None, returns None.
245.249 -# Else offset is checked for being in range, and a whole # of minutes.
245.250 -# If it is, its integer value is returned. Else ValueError is raised.
245.251 -def _check_utc_offset(name, offset):
245.252 - assert name in ("utcoffset", "dst")
245.253 - if offset is None:
245.254 - return None
245.255 - if not isinstance(offset, timedelta):
245.256 - raise TypeError("tzinfo.%s() must return None "
245.257 - "or timedelta, not '%s'" % (name, type(offset)))
245.258 - days = offset.days
245.259 - if days < -1 or days > 0:
245.260 - offset = 1440 # trigger out-of-range
245.261 - else:
245.262 - seconds = days * 86400 + offset.seconds
245.263 - minutes, seconds = divmod(seconds, 60)
245.264 - if seconds or offset.microseconds:
245.265 - raise ValueError("tzinfo.%s() must return a whole number "
245.266 - "of minutes" % name)
245.267 - offset = minutes
245.268 - if -1440 < offset < 1440:
245.269 - return offset
245.270 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
245.271 -
245.272 -def _check_date_fields(year, month, day):
245.273 - if not MINYEAR <= year <= MAXYEAR:
245.274 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
245.275 - if not 1 <= month <= 12:
245.276 - raise ValueError('month must be in 1..12', month)
245.277 - dim = _days_in_month(year, month)
245.278 - if not 1 <= day <= dim:
245.279 - raise ValueError('day must be in 1..%d' % dim, day)
245.280 -
245.281 -def _check_time_fields(hour, minute, second, microsecond):
245.282 - if not 0 <= hour <= 23:
245.283 - raise ValueError('hour must be in 0..23', hour)
245.284 - if not 0 <= minute <= 59:
245.285 - raise ValueError('minute must be in 0..59', minute)
245.286 - if not 0 <= second <= 59:
245.287 - raise ValueError('second must be in 0..59', second)
245.288 - if not 0 <= microsecond <= 999999:
245.289 - raise ValueError('microsecond must be in 0..999999', microsecond)
245.290 -
245.291 -def _check_tzinfo_arg(tz):
245.292 - if tz is not None and not isinstance(tz, tzinfo):
245.293 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
245.294 -
245.295 -
245.296 -# Notes on comparison: In general, datetime module comparison operators raise
245.297 -# TypeError when they don't know how to do a comparison themself. If they
245.298 -# returned NotImplemented instead, comparison could (silently) fall back to
245.299 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
245.300 -# and that's not helpful. There are two exceptions:
245.301 -#
245.302 -# 1. For date and datetime, if the other object has a "timetuple" attr,
245.303 -# NotImplemented is returned. This is a hook to allow other kinds of
245.304 -# datetime-like objects a chance to intercept the comparison.
245.305 -#
245.306 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
245.307 -# so opertaions like
245.308 -#
245.309 -# x == y
245.310 -# x != y
245.311 -# x in sequence
245.312 -# x not in sequence
245.313 -# dict[x] = y
245.314 -#
245.315 -# don't raise annoying TypeErrors just because a datetime object
245.316 -# is part of a heterogeneous collection. If there's no known way to
245.317 -# compare X to a datetime, saying they're not equal is reasonable.
245.318 -
245.319 -def _cmperror(x, y):
245.320 - raise TypeError("can't compare '%s' to '%s'" % (
245.321 - type(x).__name__, type(y).__name__))
245.322 -
245.323 -# This is a start at a struct tm workalike. Goals:
245.324 -#
245.325 -# + Works the same way across platforms.
245.326 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
245.327 -#
245.328 -# Note: I suspect it's best if this flavor of tm does *not* try to
245.329 -# second-guess timezones or DST. Instead fold whatever adjustments you want
245.330 -# into the minutes argument (and the constructor will normalize).
245.331 -
245.332 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
245.333 -
245.334 -class tmxxx:
245.335 -
245.336 - ordinal = None
245.337 -
245.338 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
245.339 - microsecond=0):
245.340 - # Normalize all the inputs, and store the normalized values.
245.341 - if not 0 <= microsecond <= 999999:
245.342 - carry, microsecond = divmod(microsecond, 1000000)
245.343 - second += carry
245.344 - if not 0 <= second <= 59:
245.345 - carry, second = divmod(second, 60)
245.346 - minute += carry
245.347 - if not 0 <= minute <= 59:
245.348 - carry, minute = divmod(minute, 60)
245.349 - hour += carry
245.350 - if not 0 <= hour <= 23:
245.351 - carry, hour = divmod(hour, 24)
245.352 - day += carry
245.353 -
245.354 - # That was easy. Now it gets muddy: the proper range for day
245.355 - # can't be determined without knowing the correct month and year,
245.356 - # but if day is, e.g., plus or minus a million, the current month
245.357 - # and year values make no sense (and may also be out of bounds
245.358 - # themselves).
245.359 - # Saying 12 months == 1 year should be non-controversial.
245.360 - if not 1 <= month <= 12:
245.361 - carry, month = divmod(month-1, 12)
245.362 - year += carry
245.363 - month += 1
245.364 - assert 1 <= month <= 12
245.365 -
245.366 - # Now only day can be out of bounds (year may also be out of bounds
245.367 - # for a datetime object, but we don't care about that here).
245.368 - # If day is out of bounds, what to do is arguable, but at least the
245.369 - # method here is principled and explainable.
245.370 - dim = _days_in_month(year, month)
245.371 - if not 1 <= day <= dim:
245.372 - # Move day-1 days from the first of the month. First try to
245.373 - # get off cheap if we're only one day out of range (adjustments
245.374 - # for timezone alone can't be worse than that).
245.375 - if day == 0: # move back a day
245.376 - month -= 1
245.377 - if month > 0:
245.378 - day = _days_in_month(year, month)
245.379 - else:
245.380 - year, month, day = year-1, 12, 31
245.381 - elif day == dim + 1: # move forward a day
245.382 - month += 1
245.383 - day = 1
245.384 - if month > 12:
245.385 - month = 1
245.386 - year += 1
245.387 - else:
245.388 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
245.389 - year, month, day = _ord2ymd(self.ordinal)
245.390 -
245.391 - self.year, self.month, self.day = year, month, day
245.392 - self.hour, self.minute, self.second = hour, minute, second
245.393 - self.microsecond = microsecond
245.394 -
245.395 - def toordinal(self):
245.396 - """Return proleptic Gregorian ordinal for the year, month and day.
245.397 -
245.398 - January 1 of year 1 is day 1. Only the year, month and day values
245.399 - contribute to the result.
245.400 - """
245.401 - if self.ordinal is None:
245.402 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
245.403 - return self.ordinal
245.404 -
245.405 - def time(self):
245.406 - "Return Unixish timestamp, as a float (assuming UTC)."
245.407 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
245.408 - seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
245.409 - return seconds + self.second + self.microsecond / 1e6
245.410 -
245.411 - def ctime(self):
245.412 - "Return ctime() style string."
245.413 - weekday = self.toordinal() % 7 or 7
245.414 - return "%s %s %2d %02d:%02d:%02d %04d" % (
245.415 - _DAYNAMES[weekday],
245.416 - _MONTHNAMES[self.month],
245.417 - self.day,
245.418 - self.hour, self.minute, self.second,
245.419 - self.year)
245.420 -
245.421 -class timedelta(object):
245.422 - """Represent the difference between two datetime objects.
245.423 -
245.424 - Supported operators:
245.425 -
245.426 - - add, subtract timedelta
245.427 - - unary plus, minus, abs
245.428 - - compare to timedelta
245.429 - - multiply, divide by int/long
245.430 -
245.431 - In addition, datetime supports subtraction of two datetime objects
245.432 - returning a timedelta, and addition or subtraction of a datetime
245.433 - and a timedelta giving a datetime.
245.434 -
245.435 - Representation: (days, seconds, microseconds). Why? Because I
245.436 - felt like it.
245.437 - """
245.438 -
245.439 - def __new__(cls, days=0, seconds=0, microseconds=0,
245.440 - # XXX The following should only be used as keyword args:
245.441 - milliseconds=0, minutes=0, hours=0, weeks=0):
245.442 - # Doing this efficiently and accurately in C is going to be difficult
245.443 - # and error-prone, due to ubiquitous overflow possibilities, and that
245.444 - # C double doesn't have enough bits of precision to represent
245.445 - # microseconds over 10K years faithfully. The code here tries to make
245.446 - # explicit where go-fast assumptions can be relied on, in order to
245.447 - # guide the C implementation; it's way more convoluted than speed-
245.448 - # ignoring auto-overflow-to-long idiomatic Python could be.
245.449 -
245.450 - # XXX Check that all inputs are ints, longs or floats.
245.451 -
245.452 - # Final values, all integer.
245.453 - # s and us fit in 32-bit signed ints; d isn't bounded.
245.454 - d = s = us = 0
245.455 -
245.456 - # Normalize everything to days, seconds, microseconds.
245.457 - days += weeks*7
245.458 - seconds += minutes*60 + hours*3600
245.459 - microseconds += milliseconds*1000
245.460 -
245.461 - # Get rid of all fractions, and normalize s and us.
245.462 - # Take a deep breath <wink>.
245.463 - if isinstance(days, float):
245.464 - dayfrac, days = _math.modf(days)
245.465 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
245.466 - assert daysecondswhole == int(daysecondswhole) # can't overflow
245.467 - s = int(daysecondswhole)
245.468 - assert days == long(days)
245.469 - d = long(days)
245.470 - else:
245.471 - daysecondsfrac = 0.0
245.472 - d = days
245.473 - assert isinstance(daysecondsfrac, float)
245.474 - assert abs(daysecondsfrac) <= 1.0
245.475 - assert isinstance(d, (int, long))
245.476 - assert abs(s) <= 24 * 3600
245.477 - # days isn't referenced again before redefinition
245.478 -
245.479 - if isinstance(seconds, float):
245.480 - secondsfrac, seconds = _math.modf(seconds)
245.481 - assert seconds == long(seconds)
245.482 - seconds = long(seconds)
245.483 - secondsfrac += daysecondsfrac
245.484 - assert abs(secondsfrac) <= 2.0
245.485 - else:
245.486 - secondsfrac = daysecondsfrac
245.487 - # daysecondsfrac isn't referenced again
245.488 - assert isinstance(secondsfrac, float)
245.489 - assert abs(secondsfrac) <= 2.0
245.490 -
245.491 - assert isinstance(seconds, (int, long))
245.492 - days, seconds = divmod(seconds, 24*3600)
245.493 - d += days
245.494 - s += int(seconds) # can't overflow
245.495 - assert isinstance(s, int)
245.496 - assert abs(s) <= 2 * 24 * 3600
245.497 - # seconds isn't referenced again before redefinition
245.498 -
245.499 - usdouble = secondsfrac * 1e6
245.500 - assert abs(usdouble) < 2.1e6 # exact value not critical
245.501 - # secondsfrac isn't referenced again
245.502 -
245.503 - if isinstance(microseconds, float):
245.504 - microseconds += usdouble
245.505 - microseconds = round(microseconds)
245.506 - seconds, microseconds = divmod(microseconds, 1e6)
245.507 - assert microseconds == int(microseconds)
245.508 - assert seconds == long(seconds)
245.509 - days, seconds = divmod(seconds, 24.*3600.)
245.510 - assert days == long(days)
245.511 - assert seconds == int(seconds)
245.512 - d += long(days)
245.513 - s += int(seconds) # can't overflow
245.514 - assert isinstance(s, int)
245.515 - assert abs(s) <= 3 * 24 * 3600
245.516 - else:
245.517 - seconds, microseconds = divmod(microseconds, 1000000)
245.518 - days, seconds = divmod(seconds, 24*3600)
245.519 - d += days
245.520 - s += int(seconds) # can't overflow
245.521 - assert isinstance(s, int)
245.522 - assert abs(s) <= 3 * 24 * 3600
245.523 - microseconds = float(microseconds)
245.524 - microseconds += usdouble
245.525 - microseconds = round(microseconds)
245.526 - assert abs(s) <= 3 * 24 * 3600
245.527 - assert abs(microseconds) < 3.1e6
245.528 -
245.529 - # Just a little bit of carrying possible for microseconds and seconds.
245.530 - assert isinstance(microseconds, float)
245.531 - assert int(microseconds) == microseconds
245.532 - us = int(microseconds)
245.533 - seconds, us = divmod(us, 1000000)
245.534 - s += seconds # cant't overflow
245.535 - assert isinstance(s, int)
245.536 - days, s = divmod(s, 24*3600)
245.537 - d += days
245.538 -
245.539 - assert isinstance(d, (int, long))
245.540 - assert isinstance(s, int) and 0 <= s < 24*3600
245.541 - assert isinstance(us, int) and 0 <= us < 1000000
245.542 -
245.543 - self = object.__new__(cls)
245.544 -
245.545 - self.__days = d
245.546 - self.__seconds = s
245.547 - self.__microseconds = us
245.548 - if abs(d) > 999999999:
245.549 - raise OverflowError("timedelta # of days is too large: %d" % d)
245.550 -
245.551 - return self
245.552 -
245.553 - def __repr__(self):
245.554 - if self.__microseconds:
245.555 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
245.556 - self.__days,
245.557 - self.__seconds,
245.558 - self.__microseconds)
245.559 - if self.__seconds:
245.560 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
245.561 - self.__days,
245.562 - self.__seconds)
245.563 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
245.564 -
245.565 - def __str__(self):
245.566 - mm, ss = divmod(self.__seconds, 60)
245.567 - hh, mm = divmod(mm, 60)
245.568 - s = "%d:%02d:%02d" % (hh, mm, ss)
245.569 - if self.__days:
245.570 - def plural(n):
245.571 - return n, abs(n) != 1 and "s" or ""
245.572 - s = ("%d day%s, " % plural(self.__days)) + s
245.573 - if self.__microseconds:
245.574 - s = s + ".%06d" % self.__microseconds
245.575 - return s
245.576 -
245.577 - days = property(lambda self: self.__days, doc="days")
245.578 - seconds = property(lambda self: self.__seconds, doc="seconds")
245.579 - microseconds = property(lambda self: self.__microseconds,
245.580 - doc="microseconds")
245.581 -
245.582 - def __add__(self, other):
245.583 - if isinstance(other, timedelta):
245.584 - return timedelta(self.__days + other.__days,
245.585 - self.__seconds + other.__seconds,
245.586 - self.__microseconds + other.__microseconds)
245.587 - return NotImplemented
245.588 -
245.589 - __radd__ = __add__
245.590 -
245.591 - def __sub__(self, other):
245.592 - if isinstance(other, timedelta):
245.593 - return self + -other
245.594 - return NotImplemented
245.595 -
245.596 - def __rsub__(self, other):
245.597 - if isinstance(other, timedelta):
245.598 - return -self + other
245.599 - return NotImplemented
245.600 -
245.601 - def __neg__(self):
245.602 - return self.__class__(-self.__days,
245.603 - -self.__seconds,
245.604 - -self.__microseconds)
245.605 -
245.606 - def __pos__(self):
245.607 - return self
245.608 -
245.609 - def __abs__(self):
245.610 - if self.__days < 0:
245.611 - return -self
245.612 - else:
245.613 - return self
245.614 -
245.615 - def __mul__(self, other):
245.616 - if isinstance(other, (int, long)):
245.617 - return self.__class__(self.__days * other,
245.618 - self.__seconds * other,
245.619 - self.__microseconds * other)
245.620 - return NotImplemented
245.621 -
245.622 - __rmul__ = __mul__
245.623 -
245.624 - def __div__(self, other):
245.625 - if isinstance(other, (int, long)):
245.626 - usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
245.627 - self.__microseconds)
245.628 - return self.__class__(0, 0, usec // other)
245.629 - return NotImplemented
245.630 -
245.631 - __floordiv__ = __div__
245.632 -
245.633 - # Comparisons.
245.634 -
245.635 - def __eq__(self, other):
245.636 - if isinstance(other, timedelta):
245.637 - return self.__cmp(other) == 0
245.638 - else:
245.639 - return False
245.640 -
245.641 - def __ne__(self, other):
245.642 - if isinstance(other, timedelta):
245.643 - return self.__cmp(other) != 0
245.644 - else:
245.645 - return True
245.646 -
245.647 - def __le__(self, other):
245.648 - if isinstance(other, timedelta):
245.649 - return self.__cmp(other) <= 0
245.650 - else:
245.651 - _cmperror(self, other)
245.652 -
245.653 - def __lt__(self, other):
245.654 - if isinstance(other, timedelta):
245.655 - return self.__cmp(other) < 0
245.656 - else:
245.657 - _cmperror(self, other)
245.658 -
245.659 - def __ge__(self, other):
245.660 - if isinstance(other, timedelta):
245.661 - return self.__cmp(other) >= 0
245.662 - else:
245.663 - _cmperror(self, other)
245.664 -
245.665 - def __gt__(self, other):
245.666 - if isinstance(other, timedelta):
245.667 - return self.__cmp(other) > 0
245.668 - else:
245.669 - _cmperror(self, other)
245.670 -
245.671 - def __cmp(self, other):
245.672 - assert isinstance(other, timedelta)
245.673 - return cmp(self.__getstate(), other.__getstate())
245.674 -
245.675 - def __hash__(self):
245.676 - return hash(self.__getstate())
245.677 -
245.678 - def __nonzero__(self):
245.679 - return (self.__days != 0 or
245.680 - self.__seconds != 0 or
245.681 - self.__microseconds != 0)
245.682 -
245.683 - # Pickle support.
245.684 -
245.685 - __safe_for_unpickling__ = True # For Python 2.2
245.686 -
245.687 - def __getstate(self):
245.688 - return (self.__days, self.__seconds, self.__microseconds)
245.689 -
245.690 - def __reduce__(self):
245.691 - return (self.__class__, self.__getstate())
245.692 -
245.693 -timedelta.min = timedelta(-999999999)
245.694 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
245.695 - microseconds=999999)
245.696 -timedelta.resolution = timedelta(microseconds=1)
245.697 -
245.698 -class date(object):
245.699 - """Concrete date type.
245.700 -
245.701 - Constructors:
245.702 -
245.703 - __new__()
245.704 - fromtimestamp()
245.705 - today()
245.706 - fromordinal()
245.707 -
245.708 - Operators:
245.709 -
245.710 - __repr__, __str__
245.711 - __cmp__, __hash__
245.712 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
245.713 -
245.714 - Methods:
245.715 -
245.716 - timetuple()
245.717 - toordinal()
245.718 - weekday()
245.719 - isoweekday(), isocalendar(), isoformat()
245.720 - ctime()
245.721 - strftime()
245.722 -
245.723 - Properties (readonly):
245.724 - year, month, day
245.725 - """
245.726 -
245.727 - def __new__(cls, year, month=None, day=None):
245.728 - """Constructor.
245.729 -
245.730 - Arguments:
245.731 -
245.732 - year, month, day (required, base 1)
245.733 - """
245.734 - if isinstance(year, str):
245.735 - # Pickle support
245.736 - self = object.__new__(cls)
245.737 - self.__setstate((year,))
245.738 - return self
245.739 - _check_date_fields(year, month, day)
245.740 - self = object.__new__(cls)
245.741 - self.__year = year
245.742 - self.__month = month
245.743 - self.__day = day
245.744 - return self
245.745 -
245.746 - # Additional constructors
245.747 -
245.748 - def fromtimestamp(cls, t):
245.749 - "Construct a date from a POSIX timestamp (like time.time())."
245.750 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
245.751 - return cls(y, m, d)
245.752 - fromtimestamp = classmethod(fromtimestamp)
245.753 -
245.754 - def today(cls):
245.755 - "Construct a date from time.time()."
245.756 - t = _time.time()
245.757 - return cls.fromtimestamp(t)
245.758 - today = classmethod(today)
245.759 -
245.760 - def fromordinal(cls, n):
245.761 - """Contruct a date from a proleptic Gregorian ordinal.
245.762 -
245.763 - January 1 of year 1 is day 1. Only the year, month and day are
245.764 - non-zero in the result.
245.765 - """
245.766 - y, m, d = _ord2ymd(n)
245.767 - return cls(y, m, d)
245.768 - fromordinal = classmethod(fromordinal)
245.769 -
245.770 - # Conversions to string
245.771 -
245.772 - def __repr__(self):
245.773 - "Convert to formal string, for repr()."
245.774 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
245.775 - self.__year,
245.776 - self.__month,
245.777 - self.__day)
245.778 - # XXX These shouldn't depend on time.localtime(), because that
245.779 - # clips the usable dates to [1970 .. 2038). At least ctime() is
245.780 - # easily done without using strftime() -- that's better too because
245.781 - # strftime("%c", ...) is locale specific.
245.782 -
245.783 - def ctime(self):
245.784 - "Format a la ctime()."
245.785 - return tmxxx(self.__year, self.__month, self.__day).ctime()
245.786 -
245.787 - def strftime(self, fmt):
245.788 - "Format using strftime()."
245.789 - return _wrap_strftime(self, fmt, self.timetuple())
245.790 -
245.791 - def isoformat(self):
245.792 - """Return the date formatted according to ISO.
245.793 -
245.794 - This is 'YYYY-MM-DD'.
245.795 -
245.796 - References:
245.797 - - http://www.w3.org/TR/NOTE-datetime
245.798 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
245.799 - """
245.800 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
245.801 -
245.802 - __str__ = isoformat
245.803 -
245.804 - # Read-only field accessors
245.805 - year = property(lambda self: self.__year,
245.806 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
245.807 - month = property(lambda self: self.__month, doc="month (1-12)")
245.808 - day = property(lambda self: self.__day, doc="day (1-31)")
245.809 -
245.810 - # Standard conversions, __cmp__, __hash__ (and helpers)
245.811 -
245.812 - def timetuple(self):
245.813 - "Return local time tuple compatible with time.localtime()."
245.814 - return _build_struct_time(self.__year, self.__month, self.__day,
245.815 - 0, 0, 0, -1)
245.816 -
245.817 - def toordinal(self):
245.818 - """Return proleptic Gregorian ordinal for the year, month and day.
245.819 -
245.820 - January 1 of year 1 is day 1. Only the year, month and day values
245.821 - contribute to the result.
245.822 - """
245.823 - return _ymd2ord(self.__year, self.__month, self.__day)
245.824 -
245.825 - def replace(self, year=None, month=None, day=None):
245.826 - """Return a new date with new values for the specified fields."""
245.827 - if year is None:
245.828 - year = self.__year
245.829 - if month is None:
245.830 - month = self.__month
245.831 - if day is None:
245.832 - day = self.__day
245.833 - _check_date_fields(year, month, day)
245.834 - return date(year, month, day)
245.835 -
245.836 - # Comparisons.
245.837 -
245.838 - def __eq__(self, other):
245.839 - if isinstance(other, date):
245.840 - return self.__cmp(other) == 0
245.841 - elif hasattr(other, "timetuple"):
245.842 - return NotImplemented
245.843 - else:
245.844 - return False
245.845 -
245.846 - def __ne__(self, other):
245.847 - if isinstance(other, date):
245.848 - return self.__cmp(other) != 0
245.849 - elif hasattr(other, "timetuple"):
245.850 - return NotImplemented
245.851 - else:
245.852 - return True
245.853 -
245.854 - def __le__(self, other):
245.855 - if isinstance(other, date):
245.856 - return self.__cmp(other) <= 0
245.857 - elif hasattr(other, "timetuple"):
245.858 - return NotImplemented
245.859 - else:
245.860 - _cmperror(self, other)
245.861 -
245.862 - def __lt__(self, other):
245.863 - if isinstance(other, date):
245.864 - return self.__cmp(other) < 0
245.865 - elif hasattr(other, "timetuple"):
245.866 - return NotImplemented
245.867 - else:
245.868 - _cmperror(self, other)
245.869 -
245.870 - def __ge__(self, other):
245.871 - if isinstance(other, date):
245.872 - return self.__cmp(other) >= 0
245.873 - elif hasattr(other, "timetuple"):
245.874 - return NotImplemented
245.875 - else:
245.876 - _cmperror(self, other)
245.877 -
245.878 - def __gt__(self, other):
245.879 - if isinstance(other, date):
245.880 - return self.__cmp(other) > 0
245.881 - elif hasattr(other, "timetuple"):
245.882 - return NotImplemented
245.883 - else:
245.884 - _cmperror(self, other)
245.885 -
245.886 - def __cmp(self, other):
245.887 - assert isinstance(other, date)
245.888 - y, m, d = self.__year, self.__month, self.__day
245.889 - y2, m2, d2 = other.__year, other.__month, other.__day
245.890 - return cmp((y, m, d), (y2, m2, d2))
245.891 -
245.892 - def __hash__(self):
245.893 - "Hash."
245.894 - return hash(self.__getstate())
245.895 -
245.896 - # Computations
245.897 -
245.898 - def _checkOverflow(self, year):
245.899 - if not MINYEAR <= year <= MAXYEAR:
245.900 - raise OverflowError("date +/-: result year %d not in %d..%d" %
245.901 - (year, MINYEAR, MAXYEAR))
245.902 -
245.903 - def __add__(self, other):
245.904 - "Add a date to a timedelta."
245.905 - if isinstance(other, timedelta):
245.906 - t = tmxxx(self.__year,
245.907 - self.__month,
245.908 - self.__day + other.days)
245.909 - self._checkOverflow(t.year)
245.910 - result = self.__class__(t.year, t.month, t.day)
245.911 - return result
245.912 - return NotImplemented
245.913 -
245.914 - __radd__ = __add__
245.915 -
245.916 - def __sub__(self, other):
245.917 - """Subtract two dates, or a date and a timedelta."""
245.918 - if isinstance(other, timedelta):
245.919 - return self + timedelta(-other.days)
245.920 - if isinstance(other, date):
245.921 - days1 = self.toordinal()
245.922 - days2 = other.toordinal()
245.923 - return timedelta(days1 - days2)
245.924 - return NotImplemented
245.925 -
245.926 - def weekday(self):
245.927 - "Return day of the week, where Monday == 0 ... Sunday == 6."
245.928 - return (self.toordinal() + 6) % 7
245.929 -
245.930 - # Day-of-the-week and week-of-the-year, according to ISO
245.931 -
245.932 - def isoweekday(self):
245.933 - "Return day of the week, where Monday == 1 ... Sunday == 7."
245.934 - # 1-Jan-0001 is a Monday
245.935 - return self.toordinal() % 7 or 7
245.936 -
245.937 - def isocalendar(self):
245.938 - """Return a 3-tuple containing ISO year, week number, and weekday.
245.939 -
245.940 - The first ISO week of the year is the (Mon-Sun) week
245.941 - containing the year's first Thursday; everything else derives
245.942 - from that.
245.943 -
245.944 - The first week is 1; Monday is 1 ... Sunday is 7.
245.945 -
245.946 - ISO calendar algorithm taken from
245.947 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
245.948 - """
245.949 - year = self.__year
245.950 - week1monday = _isoweek1monday(year)
245.951 - today = _ymd2ord(self.__year, self.__month, self.__day)
245.952 - # Internally, week and day have origin 0
245.953 - week, day = divmod(today - week1monday, 7)
245.954 - if week < 0:
245.955 - year -= 1
245.956 - week1monday = _isoweek1monday(year)
245.957 - week, day = divmod(today - week1monday, 7)
245.958 - elif week >= 52:
245.959 - if today >= _isoweek1monday(year+1):
245.960 - year += 1
245.961 - week = 0
245.962 - return year, week+1, day+1
245.963 -
245.964 - # Pickle support.
245.965 -
245.966 - __safe_for_unpickling__ = True # For Python 2.2
245.967 -
245.968 - def __getstate(self):
245.969 - yhi, ylo = divmod(self.__year, 256)
245.970 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
245.971 -
245.972 - def __setstate(self, t):
245.973 - assert isinstance(t, tuple) and len(t) == 1, `t`
245.974 - string = t[0]
245.975 - assert len(string) == 4
245.976 - yhi, ylo, self.__month, self.__day = map(ord, string)
245.977 - self.__year = yhi * 256 + ylo
245.978 -
245.979 - def __reduce__(self):
245.980 - return (self.__class__, self.__getstate())
245.981 -
245.982 -_date_class = date # so functions w/ args named "date" can get at the class
245.983 -
245.984 -date.min = date(1, 1, 1)
245.985 -date.max = date(9999, 12, 31)
245.986 -date.resolution = timedelta(days=1)
245.987 -
245.988 -class tzinfo(object):
245.989 - """Abstract base class for time zone info classes.
245.990 -
245.991 - Subclasses must override the name(), utcoffset() and dst() methods.
245.992 - """
245.993 -
245.994 - def tzname(self, dt):
245.995 - "datetime -> string name of time zone."
245.996 - raise NotImplementedError("tzinfo subclass must override tzname()")
245.997 -
245.998 - def utcoffset(self, dt):
245.999 - "datetime -> minutes east of UTC (negative for west of UTC)"
245.1000 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
245.1001 -
245.1002 - def dst(self, dt):
245.1003 - """datetime -> DST offset in minutes east of UTC.
245.1004 -
245.1005 - Return 0 if DST not in effect. utcoffset() must include the DST
245.1006 - offset.
245.1007 - """
245.1008 - raise NotImplementedError("tzinfo subclass must override dst()")
245.1009 -
245.1010 - def fromutc(self, dt):
245.1011 - "datetime in UTC -> datetime in local time."
245.1012 -
245.1013 - if not isinstance(dt, datetime):
245.1014 - raise TypeError("fromutc() requires a datetime argument")
245.1015 - if dt.tzinfo is not self:
245.1016 - raise ValueError("dt.tzinfo is not self")
245.1017 -
245.1018 - dtoff = dt.utcoffset()
245.1019 - if dtoff is None:
245.1020 - raise ValueError("fromutc() requires a non-None utcoffset() "
245.1021 - "result")
245.1022 -
245.1023 - # See the long comment block at the end of this file for an
245.1024 - # explanation of this algorithm.
245.1025 - dtdst = dt.dst()
245.1026 - if dtdst is None:
245.1027 - raise ValueError("fromutc() requires a non-None dst() result")
245.1028 - delta = dtoff - dtdst
245.1029 - if delta:
245.1030 - dt += delta
245.1031 - dtdst = dt.dst()
245.1032 - if dtdst is None:
245.1033 - raise ValueError("fromutc(): dt.dst gave inconsistent "
245.1034 - "results; cannot convert")
245.1035 - if dtdst:
245.1036 - return dt + dtdst
245.1037 - else:
245.1038 - return dt
245.1039 -
245.1040 - # Pickle support.
245.1041 -
245.1042 - __safe_for_unpickling__ = True # For Python 2.2
245.1043 -
245.1044 - def __reduce__(self):
245.1045 - getinitargs = getattr(self, "__getinitargs__", None)
245.1046 - if getinitargs:
245.1047 - args = getinitargs()
245.1048 - else:
245.1049 - args = ()
245.1050 - getstate = getattr(self, "__getstate__", None)
245.1051 - if getstate:
245.1052 - state = getstate()
245.1053 - else:
245.1054 - state = getattr(self, "__dict__", None) or None
245.1055 - if state is None:
245.1056 - return (self.__class__, args)
245.1057 - else:
245.1058 - return (self.__class__, args, state)
245.1059 -
245.1060 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
245.1061 -
245.1062 -class time(object):
245.1063 - """Time with time zone.
245.1064 -
245.1065 - Constructors:
245.1066 -
245.1067 - __new__()
245.1068 -
245.1069 - Operators:
245.1070 -
245.1071 - __repr__, __str__
245.1072 - __cmp__, __hash__
245.1073 -
245.1074 - Methods:
245.1075 -
245.1076 - strftime()
245.1077 - isoformat()
245.1078 - utcoffset()
245.1079 - tzname()
245.1080 - dst()
245.1081 -
245.1082 - Properties (readonly):
245.1083 - hour, minute, second, microsecond, tzinfo
245.1084 - """
245.1085 -
245.1086 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
245.1087 - """Constructor.
245.1088 -
245.1089 - Arguments:
245.1090 -
245.1091 - hour, minute (required)
245.1092 - second, microsecond (default to zero)
245.1093 - tzinfo (default to None)
245.1094 - """
245.1095 - self = object.__new__(cls)
245.1096 - if isinstance(hour, str):
245.1097 - # Pickle support
245.1098 - self.__setstate((hour, minute or None))
245.1099 - return self
245.1100 - _check_tzinfo_arg(tzinfo)
245.1101 - _check_time_fields(hour, minute, second, microsecond)
245.1102 - self.__hour = hour
245.1103 - self.__minute = minute
245.1104 - self.__second = second
245.1105 - self.__microsecond = microsecond
245.1106 - self._tzinfo = tzinfo
245.1107 - return self
245.1108 -
245.1109 - # Read-only field accessors
245.1110 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
245.1111 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
245.1112 - second = property(lambda self: self.__second, doc="second (0-59)")
245.1113 - microsecond = property(lambda self: self.__microsecond,
245.1114 - doc="microsecond (0-999999)")
245.1115 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
245.1116 -
245.1117 - # Standard conversions, __hash__ (and helpers)
245.1118 -
245.1119 - # Comparisons.
245.1120 -
245.1121 - def __eq__(self, other):
245.1122 - if isinstance(other, time):
245.1123 - return self.__cmp(other) == 0
245.1124 - else:
245.1125 - return False
245.1126 -
245.1127 - def __ne__(self, other):
245.1128 - if isinstance(other, time):
245.1129 - return self.__cmp(other) != 0
245.1130 - else:
245.1131 - return True
245.1132 -
245.1133 - def __le__(self, other):
245.1134 - if isinstance(other, time):
245.1135 - return self.__cmp(other) <= 0
245.1136 - else:
245.1137 - _cmperror(self, other)
245.1138 -
245.1139 - def __lt__(self, other):
245.1140 - if isinstance(other, time):
245.1141 - return self.__cmp(other) < 0
245.1142 - else:
245.1143 - _cmperror(self, other)
245.1144 -
245.1145 - def __ge__(self, other):
245.1146 - if isinstance(other, time):
245.1147 - return self.__cmp(other) >= 0
245.1148 - else:
245.1149 - _cmperror(self, other)
245.1150 -
245.1151 - def __gt__(self, other):
245.1152 - if isinstance(other, time):
245.1153 - return self.__cmp(other) > 0
245.1154 - else:
245.1155 - _cmperror(self, other)
245.1156 -
245.1157 - def __cmp(self, other):
245.1158 - assert isinstance(other, time)
245.1159 - mytz = self._tzinfo
245.1160 - ottz = other._tzinfo
245.1161 - myoff = otoff = None
245.1162 -
245.1163 - if mytz is ottz:
245.1164 - base_compare = True
245.1165 - else:
245.1166 - myoff = self._utcoffset()
245.1167 - otoff = other._utcoffset()
245.1168 - base_compare = myoff == otoff
245.1169 -
245.1170 - if base_compare:
245.1171 - return cmp((self.__hour, self.__minute, self.__second,
245.1172 - self.__microsecond),
245.1173 - (other.__hour, other.__minute, other.__second,
245.1174 - other.__microsecond))
245.1175 - if myoff is None or otoff is None:
245.1176 - # XXX Buggy in 2.2.2.
245.1177 - raise TypeError("cannot compare naive and aware times")
245.1178 - myhhmm = self.__hour * 60 + self.__minute - myoff
245.1179 - othhmm = other.__hour * 60 + other.__minute - otoff
245.1180 - return cmp((myhhmm, self.__second, self.__microsecond),
245.1181 - (othhmm, other.__second, other.__microsecond))
245.1182 -
245.1183 - def __hash__(self):
245.1184 - """Hash."""
245.1185 - tzoff = self._utcoffset()
245.1186 - if not tzoff: # zero or None
245.1187 - return hash(self.__getstate()[0])
245.1188 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
245.1189 - if 0 <= h < 24:
245.1190 - return hash(time(h, m, self.second, self.microsecond))
245.1191 - return hash((h, m, self.second, self.microsecond))
245.1192 -
245.1193 - # Conversion to string
245.1194 -
245.1195 - def _tzstr(self, sep=":"):
245.1196 - """Return formatted timezone offset (+xx:xx) or None."""
245.1197 - off = self._utcoffset()
245.1198 - if off is not None:
245.1199 - if off < 0:
245.1200 - sign = "-"
245.1201 - off = -off
245.1202 - else:
245.1203 - sign = "+"
245.1204 - hh, mm = divmod(off, 60)
245.1205 - assert 0 <= hh < 24
245.1206 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
245.1207 - return off
245.1208 -
245.1209 - def __repr__(self):
245.1210 - """Convert to formal string, for repr()."""
245.1211 - if self.__microsecond != 0:
245.1212 - s = ", %d, %d" % (self.__second, self.__microsecond)
245.1213 - elif self.__second != 0:
245.1214 - s = ", %d" % self.__second
245.1215 - else:
245.1216 - s = ""
245.1217 - s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
245.1218 - self.__hour, self.__minute, s)
245.1219 - if self._tzinfo is not None:
245.1220 - assert s[-1:] == ")"
245.1221 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
245.1222 - return s
245.1223 -
245.1224 - def isoformat(self):
245.1225 - """Return the time formatted according to ISO.
245.1226 -
245.1227 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
245.1228 - self.microsecond == 0.
245.1229 - """
245.1230 - s = _format_time(self.__hour, self.__minute, self.__second,
245.1231 - self.__microsecond)
245.1232 - tz = self._tzstr()
245.1233 - if tz:
245.1234 - s += tz
245.1235 - return s
245.1236 -
245.1237 - __str__ = isoformat
245.1238 -
245.1239 - def strftime(self, fmt):
245.1240 - """Format using strftime(). The date part of the timestamp passed
245.1241 - to underlying strftime should not be used.
245.1242 - """
245.1243 - # The year must be >= 1900 else Python's strftime implementation
245.1244 - # can raise a bogus exception.
245.1245 - timetuple = (1900, 1, 1,
245.1246 - self.__hour, self.__minute, self.__second,
245.1247 - 0, 1, -1)
245.1248 - return _wrap_strftime(self, fmt, timetuple)
245.1249 -
245.1250 - # Timezone functions
245.1251 -
245.1252 - def utcoffset(self):
245.1253 - """Return the timezone offset in minutes east of UTC (negative west of
245.1254 - UTC)."""
245.1255 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
245.1256 - offset = _check_utc_offset("utcoffset", offset)
245.1257 - if offset is not None:
245.1258 - offset = timedelta(minutes=offset)
245.1259 - return offset
245.1260 -
245.1261 - # Return an integer (or None) instead of a timedelta (or None).
245.1262 - def _utcoffset(self):
245.1263 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
245.1264 - offset = _check_utc_offset("utcoffset", offset)
245.1265 - return offset
245.1266 -
245.1267 - def tzname(self):
245.1268 - """Return the timezone name.
245.1269 -
245.1270 - Note that the name is 100% informational -- there's no requirement that
245.1271 - it mean anything in particular. For example, "GMT", "UTC", "-500",
245.1272 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
245.1273 - """
245.1274 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
245.1275 - _check_tzname(name)
245.1276 - return name
245.1277 -
245.1278 - def dst(self):
245.1279 - """Return 0 if DST is not in effect, or the DST offset (in minutes
245.1280 - eastward) if DST is in effect.
245.1281 -
245.1282 - This is purely informational; the DST offset has already been added to
245.1283 - the UTC offset returned by utcoffset() if applicable, so there's no
245.1284 - need to consult dst() unless you're interested in displaying the DST
245.1285 - info.
245.1286 - """
245.1287 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
245.1288 - offset = _check_utc_offset("dst", offset)
245.1289 - if offset is not None:
245.1290 - offset = timedelta(minutes=offset)
245.1291 - return offset
245.1292 -
245.1293 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
245.1294 - tzinfo=True):
245.1295 - """Return a new time with new values for the specified fields."""
245.1296 - if hour is None:
245.1297 - hour = self.hour
245.1298 - if minute is None:
245.1299 - minute = self.minute
245.1300 - if second is None:
245.1301 - second = self.second
245.1302 - if microsecond is None:
245.1303 - microsecond = self.microsecond
245.1304 - if tzinfo is True:
245.1305 - tzinfo = self.tzinfo
245.1306 - _check_time_fields(hour, minute, second, microsecond)
245.1307 - _check_tzinfo_arg(tzinfo)
245.1308 - return time(hour, minute, second, microsecond, tzinfo)
245.1309 -
245.1310 - # Return an integer (or None) instead of a timedelta (or None).
245.1311 - def _dst(self):
245.1312 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
245.1313 - offset = _check_utc_offset("dst", offset)
245.1314 - return offset
245.1315 -
245.1316 - def __nonzero__(self):
245.1317 - if self.second or self.microsecond:
245.1318 - return 1
245.1319 - offset = self._utcoffset() or 0
245.1320 - return self.hour * 60 + self.minute - offset != 0
245.1321 -
245.1322 - # Pickle support.
245.1323 -
245.1324 - __safe_for_unpickling__ = True # For Python 2.2
245.1325 -
245.1326 - def __getstate(self):
245.1327 - us2, us3 = divmod(self.__microsecond, 256)
245.1328 - us1, us2 = divmod(us2, 256)
245.1329 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
245.1330 - us1, us2, us3)
245.1331 - if self._tzinfo is None:
245.1332 - return (basestate,)
245.1333 - else:
245.1334 - return (basestate, self._tzinfo)
245.1335 -
245.1336 - def __setstate(self, state):
245.1337 - assert isinstance(state, tuple)
245.1338 - assert 1 <= len(state) <= 2
245.1339 - string = state[0]
245.1340 - assert len(string) == 6
245.1341 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
245.1342 - map(ord, string)
245.1343 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
245.1344 - if len(state) == 1:
245.1345 - self._tzinfo = None
245.1346 - else:
245.1347 - self._tzinfo = state[1]
245.1348 -
245.1349 - def __reduce__(self):
245.1350 - return (self.__class__, self.__getstate())
245.1351 -
245.1352 -_time_class = time # so functions w/ args named "time" can get at the class
245.1353 -
245.1354 -time.min = time(0, 0, 0)
245.1355 -time.max = time(23, 59, 59, 999999)
245.1356 -time.resolution = timedelta(microseconds=1)
245.1357 -
245.1358 -class datetime(date):
245.1359 -
245.1360 - # XXX needs docstrings
245.1361 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
245.1362 -
245.1363 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
245.1364 - microsecond=0, tzinfo=None):
245.1365 - if isinstance(year, str):
245.1366 - # Pickle support
245.1367 - self = date.__new__(cls, year[:4])
245.1368 - self.__setstate((year, month))
245.1369 - return self
245.1370 - _check_tzinfo_arg(tzinfo)
245.1371 - _check_time_fields(hour, minute, second, microsecond)
245.1372 - self = date.__new__(cls, year, month, day)
245.1373 - # XXX This duplicates __year, __month, __day for convenience :-(
245.1374 - self.__year = year
245.1375 - self.__month = month
245.1376 - self.__day = day
245.1377 - self.__hour = hour
245.1378 - self.__minute = minute
245.1379 - self.__second = second
245.1380 - self.__microsecond = microsecond
245.1381 - self._tzinfo = tzinfo
245.1382 - return self
245.1383 -
245.1384 - # Read-only field accessors
245.1385 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
245.1386 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
245.1387 - second = property(lambda self: self.__second, doc="second (0-59)")
245.1388 - microsecond = property(lambda self: self.__microsecond,
245.1389 - doc="microsecond (0-999999)")
245.1390 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
245.1391 -
245.1392 - def fromtimestamp(cls, t, tz=None):
245.1393 - """Construct a datetime from a POSIX timestamp (like time.time()).
245.1394 -
245.1395 - A timezone info object may be passed in as well.
245.1396 - """
245.1397 -
245.1398 - _check_tzinfo_arg(tz)
245.1399 - if tz is None:
245.1400 - converter = _time.localtime
245.1401 - else:
245.1402 - converter = _time.gmtime
245.1403 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
245.1404 - us = int((t % 1.0) * 1000000)
245.1405 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
245.1406 - result = cls(y, m, d, hh, mm, ss, us, tz)
245.1407 - if tz is not None:
245.1408 - result = tz.fromutc(result)
245.1409 - return result
245.1410 - fromtimestamp = classmethod(fromtimestamp)
245.1411 -
245.1412 - def utcfromtimestamp(cls, t):
245.1413 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
245.1414 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
245.1415 - us = int((t % 1.0) * 1000000)
245.1416 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
245.1417 - return cls(y, m, d, hh, mm, ss, us)
245.1418 - utcfromtimestamp = classmethod(utcfromtimestamp)
245.1419 -
245.1420 - # XXX This is supposed to do better than we *can* do by using time.time(),
245.1421 - # XXX if the platform supports a more accurate way. The C implementation
245.1422 - # XXX uses gettimeofday on platforms that have it, but that isn't
245.1423 - # XXX available from Python. So now() may return different results
245.1424 - # XXX across the implementations.
245.1425 - def now(cls, tz=None):
245.1426 - "Construct a datetime from time.time() and optional time zone info."
245.1427 - t = _time.time()
245.1428 - return cls.fromtimestamp(t, tz)
245.1429 - now = classmethod(now)
245.1430 -
245.1431 - def utcnow(cls):
245.1432 - "Construct a UTC datetime from time.time()."
245.1433 - t = _time.time()
245.1434 - return cls.utcfromtimestamp(t)
245.1435 - utcnow = classmethod(utcnow)
245.1436 -
245.1437 - def combine(cls, date, time):
245.1438 - "Construct a datetime from a given date and a given time."
245.1439 - if not isinstance(date, _date_class):
245.1440 - raise TypeError("date argument must be a date instance")
245.1441 - if not isinstance(time, _time_class):
245.1442 - raise TypeError("time argument must be a time instance")
245.1443 - return cls(date.year, date.month, date.day,
245.1444 - time.hour, time.minute, time.second, time.microsecond,
245.1445 - time.tzinfo)
245.1446 - combine = classmethod(combine)
245.1447 -
245.1448 - def timetuple(self):
245.1449 - "Return local time tuple compatible with time.localtime()."
245.1450 - dst = self._dst()
245.1451 - if dst is None:
245.1452 - dst = -1
245.1453 - elif dst:
245.1454 - dst = 1
245.1455 - return _build_struct_time(self.year, self.month, self.day,
245.1456 - self.hour, self.minute, self.second,
245.1457 - dst)
245.1458 -
245.1459 - def utctimetuple(self):
245.1460 - "Return UTC time tuple compatible with time.gmtime()."
245.1461 - y, m, d = self.year, self.month, self.day
245.1462 - hh, mm, ss = self.hour, self.minute, self.second
245.1463 - offset = self._utcoffset()
245.1464 - if offset: # neither None nor 0
245.1465 - tm = tmxxx(y, m, d, hh, mm - offset)
245.1466 - y, m, d = tm.year, tm.month, tm.day
245.1467 - hh, mm = tm.hour, tm.minute
245.1468 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
245.1469 -
245.1470 - def date(self):
245.1471 - "Return the date part."
245.1472 - return date(self.__year, self.__month, self.__day)
245.1473 -
245.1474 - def time(self):
245.1475 - "Return the time part, with tzinfo None."
245.1476 - return time(self.hour, self.minute, self.second, self.microsecond)
245.1477 -
245.1478 - def timetz(self):
245.1479 - "Return the time part, with same tzinfo."
245.1480 - return time(self.hour, self.minute, self.second, self.microsecond,
245.1481 - self._tzinfo)
245.1482 -
245.1483 - def replace(self, year=None, month=None, day=None, hour=None,
245.1484 - minute=None, second=None, microsecond=None, tzinfo=True):
245.1485 - """Return a new datetime with new values for the specified fields."""
245.1486 - if year is None:
245.1487 - year = self.year
245.1488 - if month is None:
245.1489 - month = self.month
245.1490 - if day is None:
245.1491 - day = self.day
245.1492 - if hour is None:
245.1493 - hour = self.hour
245.1494 - if minute is None:
245.1495 - minute = self.minute
245.1496 - if second is None:
245.1497 - second = self.second
245.1498 - if microsecond is None:
245.1499 - microsecond = self.microsecond
245.1500 - if tzinfo is True:
245.1501 - tzinfo = self.tzinfo
245.1502 - _check_date_fields(year, month, day)
245.1503 - _check_time_fields(hour, minute, second, microsecond)
245.1504 - _check_tzinfo_arg(tzinfo)
245.1505 - return datetime(year, month, day, hour, minute, second,
245.1506 - microsecond, tzinfo)
245.1507 -
245.1508 - def astimezone(self, tz):
245.1509 - if not isinstance(tz, tzinfo):
245.1510 - raise TypeError("tz argument must be an instance of tzinfo")
245.1511 -
245.1512 - mytz = self.tzinfo
245.1513 - if mytz is None:
245.1514 - raise ValueError("astimezone() requires an aware datetime")
245.1515 -
245.1516 - if tz is mytz:
245.1517 - return self
245.1518 -
245.1519 - # Convert self to UTC, and attach the new time zone object.
245.1520 - myoffset = self.utcoffset()
245.1521 - if myoffset is None:
245.1522 - raise ValuError("astimezone() requires an aware datetime")
245.1523 - utc = (self - myoffset).replace(tzinfo=tz)
245.1524 -
245.1525 - # Convert from UTC to tz's local time.
245.1526 - return tz.fromutc(utc)
245.1527 -
245.1528 - # Ways to produce a string.
245.1529 -
245.1530 - def ctime(self):
245.1531 - "Format a la ctime()."
245.1532 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
245.1533 - self.__minute, self.__second)
245.1534 - return t.ctime()
245.1535 -
245.1536 - def isoformat(self, sep='T'):
245.1537 - """Return the time formatted according to ISO.
245.1538 -
245.1539 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
245.1540 - self.microsecond == 0.
245.1541 -
245.1542 - If self.tzinfo is not None, the UTC offset is also attached, giving
245.1543 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
245.1544 -
245.1545 - Optional argument sep specifies the separator between date and
245.1546 - time, default 'T'.
245.1547 - """
245.1548 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
245.1549 - sep) +
245.1550 - _format_time(self.__hour, self.__minute, self.__second,
245.1551 - self.__microsecond))
245.1552 - off = self._utcoffset()
245.1553 - if off is not None:
245.1554 - if off < 0:
245.1555 - sign = "-"
245.1556 - off = -off
245.1557 - else:
245.1558 - sign = "+"
245.1559 - hh, mm = divmod(off, 60)
245.1560 - s += "%s%02d:%02d" % (sign, hh, mm)
245.1561 - return s
245.1562 -
245.1563 - def __repr__(self):
245.1564 - "Convert to formal string, for repr()."
245.1565 - L = [self.__year, self.__month, self.__day, # These are never zero
245.1566 - self.__hour, self.__minute, self.__second, self.__microsecond]
245.1567 - if L[-1] == 0:
245.1568 - del L[-1]
245.1569 - if L[-1] == 0:
245.1570 - del L[-1]
245.1571 - s = ", ".join(map(str, L))
245.1572 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
245.1573 - if self._tzinfo is not None:
245.1574 - assert s[-1:] == ")"
245.1575 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
245.1576 - return s
245.1577 -
245.1578 - def __str__(self):
245.1579 - "Convert to string, for str()."
245.1580 - return self.isoformat(sep=' ')
245.1581 -
245.1582 - def utcoffset(self):
245.1583 - """Return the timezone offset in minutes east of UTC (negative west of
245.1584 - UTC)."""
245.1585 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
245.1586 - offset = _check_utc_offset("utcoffset", offset)
245.1587 - if offset is not None:
245.1588 - offset = timedelta(minutes=offset)
245.1589 - return offset
245.1590 -
245.1591 - # Return an integer (or None) instead of a timedelta (or None).
245.1592 - def _utcoffset(self):
245.1593 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
245.1594 - offset = _check_utc_offset("utcoffset", offset)
245.1595 - return offset
245.1596 -
245.1597 - def tzname(self):
245.1598 - """Return the timezone name.
245.1599 -
245.1600 - Note that the name is 100% informational -- there's no requirement that
245.1601 - it mean anything in particular. For example, "GMT", "UTC", "-500",
245.1602 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
245.1603 - """
245.1604 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
245.1605 - _check_tzname(name)
245.1606 - return name
245.1607 -
245.1608 - def dst(self):
245.1609 - """Return 0 if DST is not in effect, or the DST offset (in minutes
245.1610 - eastward) if DST is in effect.
245.1611 -
245.1612 - This is purely informational; the DST offset has already been added to
245.1613 - the UTC offset returned by utcoffset() if applicable, so there's no
245.1614 - need to consult dst() unless you're interested in displaying the DST
245.1615 - info.
245.1616 - """
245.1617 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
245.1618 - offset = _check_utc_offset("dst", offset)
245.1619 - if offset is not None:
245.1620 - offset = timedelta(minutes=offset)
245.1621 - return offset
245.1622 -
245.1623 - # Return an integer (or None) instead of a timedelta (or None).1573
245.1624 - def _dst(self):
245.1625 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
245.1626 - offset = _check_utc_offset("dst", offset)
245.1627 - return offset
245.1628 -
245.1629 - # Comparisons.
245.1630 -
245.1631 - def __eq__(self, other):
245.1632 - if isinstance(other, datetime):
245.1633 - return self.__cmp(other) == 0
245.1634 - elif hasattr(other, "timetuple"):
245.1635 - return NotImplemented
245.1636 - else:
245.1637 - return False
245.1638 -
245.1639 - def __ne__(self, other):
245.1640 - if isinstance(other, datetime):
245.1641 - return self.__cmp(other) != 0
245.1642 - elif hasattr(other, "timetuple"):
245.1643 - return NotImplemented
245.1644 - else:
245.1645 - return True
245.1646 -
245.1647 - def __le__(self, other):
245.1648 - if isinstance(other, datetime):
245.1649 - return self.__cmp(other) <= 0
245.1650 - elif hasattr(other, "timetuple"):
245.1651 - return NotImplemented
245.1652 - else:
245.1653 - _cmperror(self, other)
245.1654 -
245.1655 - def __lt__(self, other):
245.1656 - if isinstance(other, datetime):
245.1657 - return self.__cmp(other) < 0
245.1658 - elif hasattr(other, "timetuple"):
245.1659 - return NotImplemented
245.1660 - else:
245.1661 - _cmperror(self, other)
245.1662 -
245.1663 - def __ge__(self, other):
245.1664 - if isinstance(other, datetime):
245.1665 - return self.__cmp(other) >= 0
245.1666 - elif hasattr(other, "timetuple"):
245.1667 - return NotImplemented
245.1668 - else:
245.1669 - _cmperror(self, other)
245.1670 -
245.1671 - def __gt__(self, other):
245.1672 - if isinstance(other, datetime):
245.1673 - return self.__cmp(other) > 0
245.1674 - elif hasattr(other, "timetuple"):
245.1675 - return NotImplemented
245.1676 - else:
245.1677 - _cmperror(self, other)
245.1678 -
245.1679 - def __cmp(self, other):
245.1680 - assert isinstance(other, datetime)
245.1681 - mytz = self._tzinfo
245.1682 - ottz = other._tzinfo
245.1683 - myoff = otoff = None
245.1684 -
245.1685 - if mytz is ottz:
245.1686 - base_compare = True
245.1687 - else:
245.1688 - if mytz is not None:
245.1689 - myoff = self._utcoffset()
245.1690 - if ottz is not None:
245.1691 - otoff = other._utcoffset()
245.1692 - base_compare = myoff == otoff
245.1693 -
245.1694 - if base_compare:
245.1695 - return cmp((self.__year, self.__month, self.__day,
245.1696 - self.__hour, self.__minute, self.__second,
245.1697 - self.__microsecond),
245.1698 - (other.__year, other.__month, other.__day,
245.1699 - other.__hour, other.__minute, other.__second,
245.1700 - other.__microsecond))
245.1701 - if myoff is None or otoff is None:
245.1702 - # XXX Buggy in 2.2.2.
245.1703 - raise TypeError("cannot compare naive and aware datetimes")
245.1704 - # XXX What follows could be done more efficiently...
245.1705 - diff = self - other # this will take offsets into account
245.1706 - if diff.days < 0:
245.1707 - return -1
245.1708 - return diff and 1 or 0
245.1709 -
245.1710 - def __add__(self, other):
245.1711 - "Add a datetime and a timedelta."
245.1712 - if not isinstance(other, timedelta):
245.1713 - return NotImplemented
245.1714 - t = tmxxx(self.__year,
245.1715 - self.__month,
245.1716 - self.__day + other.days,
245.1717 - self.__hour,
245.1718 - self.__minute,
245.1719 - self.__second + other.seconds,
245.1720 - self.__microsecond + other.microseconds)
245.1721 - self._checkOverflow(t.year)
245.1722 - result = self.__class__(t.year, t.month, t.day,
245.1723 - t.hour, t.minute, t.second,
245.1724 - t.microsecond, tzinfo=self._tzinfo)
245.1725 - return result
245.1726 -
245.1727 - __radd__ = __add__
245.1728 -
245.1729 - def __sub__(self, other):
245.1730 - "Subtract two datetimes, or a datetime and a timedelta."
245.1731 - if not isinstance(other, datetime):
245.1732 - if isinstance(other, timedelta):
245.1733 - return self + -other
245.1734 - return NotImplemented
245.1735 -
245.1736 - days1 = self.toordinal()
245.1737 - days2 = other.toordinal()
245.1738 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
245.1739 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
245.1740 - base = timedelta(days1 - days2,
245.1741 - secs1 - secs2,
245.1742 - self.__microsecond - other.__microsecond)
245.1743 - if self._tzinfo is other._tzinfo:
245.1744 - return base
245.1745 - myoff = self._utcoffset()
245.1746 - otoff = other._utcoffset()
245.1747 - if myoff == otoff:
245.1748 - return base
245.1749 - if myoff is None or otoff is None:
245.1750 - raise TypeError, "cannot mix naive and timezone-aware time"
245.1751 - return base + timedelta(minutes = otoff-myoff)
245.1752 -
245.1753 - def __hash__(self):
245.1754 - tzoff = self._utcoffset()
245.1755 - if tzoff is None:
245.1756 - return hash(self.__getstate()[0])
245.1757 - days = _ymd2ord(self.year, self.month, self.day)
245.1758 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
245.1759 - return hash(timedelta(days, seconds, self.microsecond))
245.1760 -
245.1761 - # Pickle support.
245.1762 -
245.1763 - __safe_for_unpickling__ = True # For Python 2.2
245.1764 -
245.1765 - def __getstate(self):
245.1766 - yhi, ylo = divmod(self.__year, 256)
245.1767 - us2, us3 = divmod(self.__microsecond, 256)
245.1768 - us1, us2 = divmod(us2, 256)
245.1769 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
245.1770 - self.__hour, self.__minute, self.__second,
245.1771 - us1, us2, us3)
245.1772 - if self._tzinfo is None:
245.1773 - return (basestate,)
245.1774 - else:
245.1775 - return (basestate, self._tzinfo)
245.1776 -
245.1777 - def __setstate(self, state):
245.1778 - assert isinstance(state, tuple)
245.1779 - assert 1 <= len(state) <= 2
245.1780 - string = state[0]
245.1781 - assert len(string) == 10
245.1782 - (yhi, ylo, self.__month, self.__day, self.__hour,
245.1783 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
245.1784 - self.__year = yhi * 256 + ylo
245.1785 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
245.1786 - if len(state) == 1:
245.1787 - self._tzinfo = None
245.1788 - else:
245.1789 - self._tzinfo = state[1]
245.1790 -
245.1791 - def __reduce__(self):
245.1792 - return (self.__class__, self.__getstate())
245.1793 -
245.1794 -
245.1795 -datetime.min = datetime(1, 1, 1)
245.1796 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
245.1797 -datetime.resolution = timedelta(microseconds=1)
245.1798 -
245.1799 -
245.1800 -def _isoweek1monday(year):
245.1801 - # Helper to calculate the day number of the Monday starting week 1
245.1802 - # XXX This could be done more efficiently
245.1803 - THURSDAY = 3
245.1804 - firstday = _ymd2ord(year, 1, 1)
245.1805 - firstweekday = (firstday + 6) % 7 # See weekday() above
245.1806 - week1monday = firstday - firstweekday
245.1807 - if firstweekday > THURSDAY:
245.1808 - week1monday += 7
245.1809 - return week1monday
245.1810 -
245.1811 -"""
245.1812 -Some time zone algebra. For a datetime x, let
245.1813 - x.n = x stripped of its timezone -- its naive time.
245.1814 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
245.1815 - return None
245.1816 - x.d = x.dst(), and assuming that doesn't raise an exception or
245.1817 - return None
245.1818 - x.s = x's standard offset, x.o - x.d
245.1819 -
245.1820 -Now some derived rules, where k is a duration (timedelta).
245.1821 -
245.1822 -1. x.o = x.s + x.d
245.1823 - This follows from the definition of x.s.
245.1824 -
245.1825 -2. If x and y have the same tzinfo member, x.s = y.s.
245.1826 - This is actually a requirement, an assumption we need to make about
245.1827 - sane tzinfo classes.
245.1828 -
245.1829 -3. The naive UTC time corresponding to x is x.n - x.o.
245.1830 - This is again a requirement for a sane tzinfo class.
245.1831 -
245.1832 -4. (x+k).s = x.s
245.1833 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
245.1834 -
245.1835 -5. (x+k).n = x.n + k
245.1836 - Again follows from how arithmetic is defined.
245.1837 -
245.1838 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
245.1839 -(meaning that the various tzinfo methods exist, and don't blow up or return
245.1840 -None when called).
245.1841 -
245.1842 -The function wants to return a datetime y with timezone tz, equivalent to x.
245.1843 -x is already in UTC.
245.1844 -
245.1845 -By #3, we want
245.1846 -
245.1847 - y.n - y.o = x.n [1]
245.1848 -
245.1849 -The algorithm starts by attaching tz to x.n, and calling that y. So
245.1850 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
245.1851 -becomes true; in effect, we want to solve [2] for k:
245.1852 -
245.1853 - (y+k).n - (y+k).o = x.n [2]
245.1854 -
245.1855 -By #1, this is the same as
245.1856 -
245.1857 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
245.1858 -
245.1859 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
245.1860 -Substituting that into [3],
245.1861 -
245.1862 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
245.1863 - k - (y+k).s - (y+k).d = 0; rearranging,
245.1864 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
245.1865 - k = y.s - (y+k).d
245.1866 -
245.1867 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
245.1868 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
245.1869 -very large, since all offset-returning methods return a duration of magnitude
245.1870 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
245.1871 -be 0, so ignoring it has no consequence then.
245.1872 -
245.1873 -In any case, the new value is
245.1874 -
245.1875 - z = y + y.s [4]
245.1876 -
245.1877 -It's helpful to step back at look at [4] from a higher level: it's simply
245.1878 -mapping from UTC to tz's standard time.
245.1879 -
245.1880 -At this point, if
245.1881 -
245.1882 - z.n - z.o = x.n [5]
245.1883 -
245.1884 -we have an equivalent time, and are almost done. The insecurity here is
245.1885 -at the start of daylight time. Picture US Eastern for concreteness. The wall
245.1886 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
245.1887 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
245.1888 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
245.1889 -on the day DST starts. We want to return the 1:MM EST spelling because that's
245.1890 -the only spelling that makes sense on the local wall clock.
245.1891 -
245.1892 -In fact, if [5] holds at this point, we do have the standard-time spelling,
245.1893 -but that takes a bit of proof. We first prove a stronger result. What's the
245.1894 -difference between the LHS and RHS of [5]? Let
245.1895 -
245.1896 - diff = x.n - (z.n - z.o) [6]
245.1897 -
245.1898 -Now
245.1899 - z.n = by [4]
245.1900 - (y + y.s).n = by #5
245.1901 - y.n + y.s = since y.n = x.n
245.1902 - x.n + y.s = since z and y are have the same tzinfo member,
245.1903 - y.s = z.s by #2
245.1904 - x.n + z.s
245.1905 -
245.1906 -Plugging that back into [6] gives
245.1907 -
245.1908 - diff =
245.1909 - x.n - ((x.n + z.s) - z.o) = expanding
245.1910 - x.n - x.n - z.s + z.o = cancelling
245.1911 - - z.s + z.o = by #2
245.1912 - z.d
245.1913 -
245.1914 -So diff = z.d.
245.1915 -
245.1916 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
245.1917 -spelling we wanted in the endcase described above. We're done. Contrarily,
245.1918 -if z.d = 0, then we have a UTC equivalent, and are also done.
245.1919 -
245.1920 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
245.1921 -add to z (in effect, z is in tz's standard time, and we need to shift the
245.1922 -local clock into tz's daylight time).
245.1923 -
245.1924 -Let
245.1925 -
245.1926 - z' = z + z.d = z + diff [7]
245.1927 -
245.1928 -and we can again ask whether
245.1929 -
245.1930 - z'.n - z'.o = x.n [8]
245.1931 -
245.1932 -If so, we're done. If not, the tzinfo class is insane, according to the
245.1933 -assumptions we've made. This also requires a bit of proof. As before, let's
245.1934 -compute the difference between the LHS and RHS of [8] (and skipping some of
245.1935 -the justifications for the kinds of substitutions we've done several times
245.1936 -already):
245.1937 -
245.1938 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
245.1939 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
245.1940 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
245.1941 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
245.1942 - - z.n + z.n - z.o + z'.o = cancel z.n
245.1943 - - z.o + z'.o = #1 twice
245.1944 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
245.1945 - z'.d - z.d
245.1946 -
245.1947 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
245.1948 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
245.1949 -return z', not bothering to compute z'.d.
245.1950 -
245.1951 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
245.1952 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
245.1953 -would have to change the result dst() returns: we start in DST, and moving
245.1954 -a little further into it takes us out of DST.
245.1955 -
245.1956 -There isn't a sane case where this can happen. The closest it gets is at
245.1957 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
245.1958 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
245.1959 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
245.1960 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
245.1961 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
245.1962 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
245.1963 -standard time. Since that's what the local clock *does*, we want to map both
245.1964 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
245.1965 -in local time, but so it goes -- it's the way the local clock works.
245.1966 -
245.1967 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
245.1968 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
245.1969 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
245.1970 -(correctly) concludes that z' is not UTC-equivalent to x.
245.1971 -
245.1972 -Because we know z.d said z was in daylight time (else [5] would have held and
245.1973 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
245.1974 -and we we have stopped then), and there are only 2 possible values dst() can
245.1975 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
245.1976 -but the reasoning doesn't depend on the example -- it depends on there being
245.1977 -two possible dst() outcomes, one zero and the other non-zero). Therefore
245.1978 -z' must be in standard time, and is the spelling we want in this case.
245.1979 -
245.1980 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
245.1981 -concerned (because it takes z' as being in standard time rather than the
245.1982 -daylight time we intend here), but returning it gives the real-life "local
245.1983 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
245.1984 -tz.
245.1985 -
245.1986 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
245.1987 -the 1:MM standard time spelling we want.
245.1988 -
245.1989 -So how can this break? One of the assumptions must be violated. Two
245.1990 -possibilities:
245.1991 -
245.1992 -1) [2] effectively says that y.s is invariant across all y belong to a given
245.1993 - time zone. This isn't true if, for political reasons or continental drift,
245.1994 - a region decides to change its base offset from UTC.
245.1995 -
245.1996 -2) There may be versions of "double daylight" time where the tail end of
245.1997 - the analysis gives up a step too early. I haven't thought about that
245.1998 - enough to say.
245.1999 -
245.2000 -In any case, it's clear that the default fromutc() is strong enough to handle
245.2001 -"almost all" time zones: so long as the standard offset is invariant, it
245.2002 -doesn't matter if daylight time transition points change from year to year, or
245.2003 -if daylight time is skipped in some years; it doesn't matter how large or
245.2004 -small dst() may get within its bounds; and it doesn't even matter if some
245.2005 -perverse time zone returns a negative dst()). So a breaking case must be
245.2006 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
245.2007 -"""
245.2008 -
245.2009 -def _test():
245.2010 - import test_datetime
245.2011 - test_datetime.test_main()
245.2012 -
245.2013 -if __name__ == "__main__":
245.2014 - _test()
246.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testHint1.hints Sun Jan 04 13:11:53 2015 -0600
246.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
246.3 @@ -1,7 +0,0 @@
246.4 -for dim in _DAYS_IN_MONTH[1:]:
246.5 -
246.6 -HINT:Surround With...
246.7 -FIX:Surround With Try/Except
246.8 -FIX:Surround With Try/Except/Finally
246.9 -FIX:Surround With Try/Finally
246.10 -del dbm, dim^
247.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testHint2.hints Sun Jan 04 13:11:53 2015 -0600
247.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
247.3 @@ -1,6 +0,0 @@
247.4 - "year -> number of days in year (366 if a leap year, else 365)."^
247.5 - ----------------------------------------------------------------
247.6 -HINT:Surround With...
247.7 -FIX:Surround With Try/Except
247.8 -FIX:Surround With Try/Except/Finally
247.9 -FIX:Surround With Try/Finally
248.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testHint3.hints Sun Jan 04 13:11:53 2015 -0600
248.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
248.3 @@ -1,7 +0,0 @@
248.4 - # Now compute how many 4-year cycles precede it.
248.5 -
248.6 -HINT:Surround With...
248.7 -FIX:Surround With Try/Except
248.8 -FIX:Surround With Try/Except/Finally
248.9 -FIX:Surround With Try/Finally
248.10 -^ # And now how many single years. Again n1 can be 4, and again meaning
249.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testHint5.hints Sun Jan 04 13:11:53 2015 -0600
249.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
249.3 @@ -1,54 +0,0 @@
249.4 -class tmxxx:
249.5 - -----
249.6 -HINT:Name "tmxxx" is not a valid class name according to your code style (CapitalizedWords)
249.7 -FIX:Ignore name violations for "tmxxx"
249.8 -FIX:Change preferred class name style to lowercase
249.9 -FIX:Change preferred class name style to lowercase_with_underscores
249.10 -FIX:Change preferred class name style to mixedCase
249.11 -FIX:Turn off class name style checks
249.12 -class timedelta(object):
249.13 - ---------
249.14 -HINT:Name "timedelta" is not a valid class name according to your code style (CapitalizedWords)
249.15 -FIX:Ignore name violations for "timedelta"
249.16 -FIX:Change preferred class name style to lowercase
249.17 -FIX:Change preferred class name style to lowercase_with_underscores
249.18 -FIX:Change preferred class name style to mixedCase
249.19 -FIX:Turn off class name style checks
249.20 -class date(object):
249.21 - ----
249.22 -HINT:Name "date" is not a valid class name according to your code style (CapitalizedWords)
249.23 -FIX:Ignore name violations for "date"
249.24 -FIX:Change preferred class name style to lowercase
249.25 -FIX:Change preferred class name style to lowercase_with_underscores
249.26 -FIX:Change preferred class name style to mixedCase
249.27 -FIX:Turn off class name style checks
249.28 - def _checkOverflow(self, year):
249.29 - --------------
249.30 -HINT:Name "_checkOverflow" is not a valid function name according to your code style (lowercase_with_underscores)
249.31 -FIX:Ignore name violations for "_checkOverflow"
249.32 -FIX:Change preferred function name style to mixedCase
249.33 -FIX:Turn off function name style checks
249.34 -class tzinfo(object):
249.35 - ------
249.36 -HINT:Name "tzinfo" is not a valid class name according to your code style (CapitalizedWords)
249.37 -FIX:Ignore name violations for "tzinfo"
249.38 -FIX:Change preferred class name style to lowercase
249.39 -FIX:Change preferred class name style to lowercase_with_underscores
249.40 -FIX:Change preferred class name style to mixedCase
249.41 -FIX:Turn off class name style checks
249.42 -class time(object):
249.43 - ----
249.44 -HINT:Name "time" is not a valid class name according to your code style (CapitalizedWords)
249.45 -FIX:Ignore name violations for "time"
249.46 -FIX:Change preferred class name style to lowercase
249.47 -FIX:Change preferred class name style to lowercase_with_underscores
249.48 -FIX:Change preferred class name style to mixedCase
249.49 -FIX:Turn off class name style checks
249.50 -class datetime(date):
249.51 - --------
249.52 -HINT:Name "datetime" is not a valid class name according to your code style (CapitalizedWords)
249.53 -FIX:Ignore name violations for "datetime"
249.54 -FIX:Change preferred class name style to lowercase
249.55 -FIX:Change preferred class name style to lowercase_with_underscores
249.56 -FIX:Change preferred class name style to mixedCase
249.57 -FIX:Turn off class name style checks
250.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testLocals2.completion Sun Jan 04 13:11:53 2015 -0600
250.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
250.3 @@ -1,1276 +0,0 @@
250.4 -Code completion result for source line:
250.5 -|dnum = _days_before_month(y, m) + d
250.6 -(QueryType=COMPLETION, NameKind=PREFIX)
250.7 -MODULE _math [PRIVATE]
250.8 -MODULE _time [PRIVATE]
250.9 -CLASS date
250.10 -CLASS datetime
250.11 -CLASS time
250.12 -CLASS timedelta
250.13 -CLASS tmxxx
250.14 -CLASS tzinfo
250.15 -METHOD _build_struct_time(y, m, d, hh [PRIVATE]
250.16 -METHOD _call_tzinfo_method(tzinfo, me [PRIVATE]
250.17 -METHOD _check_date_fields(year, month [PRIVATE]
250.18 -METHOD _check_time_fields(hour, minut [PRIVATE]
250.19 -METHOD _check_tzinfo_arg(tz) [PRIVATE]
250.20 -METHOD _check_tzname(name) [PRIVATE]
250.21 -METHOD _check_utc_offset(name, offset [PRIVATE]
250.22 -METHOD _cmperror(x, y) [PRIVATE]
250.23 -METHOD _days_before_month(year, month [PRIVATE]
250.24 -METHOD _days_before_year(year) [PRIVATE]
250.25 -METHOD _days_in_month(year, month) [PRIVATE]
250.26 -METHOD _days_in_year(year) [PRIVATE]
250.27 -METHOD _format_time(hh, mm, ss, us) [PRIVATE]
250.28 -METHOD _is_leap(year) [PRIVATE]
250.29 -METHOD _isoweek1monday(year) [PRIVATE]
250.30 -METHOD _ord2ymd(n) [PRIVATE]
250.31 -METHOD _test() [PRIVATE]
250.32 -METHOD _wrap_strftime(object, format, [PRIVATE]
250.33 -METHOD _ymd2ord(year, month, day) [PRIVATE]
250.34 -VARIABLE MAXYEAR
250.35 -VARIABLE MINYEAR
250.36 -VARIABLE _DAYNAMES [PRIVATE]
250.37 -VARIABLE _DAYS_BEFORE_MONTH [PRIVATE]
250.38 -VARIABLE _DAYS_IN_MONTH [PRIVATE]
250.39 -VARIABLE _DI100Y [PRIVATE]
250.40 -VARIABLE _DI400Y [PRIVATE]
250.41 -VARIABLE _DI4Y [PRIVATE]
250.42 -VARIABLE _MONTHNAMES [PRIVATE]
250.43 -VARIABLE _ORD1970 [PRIVATE]
250.44 -VARIABLE _date_class [PRIVATE]
250.45 -VARIABLE _time_class [PRIVATE]
250.46 -VARIABLE _tzinfo_class [PRIVATE]
250.47 -VARIABLE d
250.48 -VARIABLE dbm
250.49 -VARIABLE dim
250.50 -VARIABLE dnum
250.51 -VARIABLE dstflag
250.52 -VARIABLE hh
250.53 -VARIABLE m
250.54 -VARIABLE mm
250.55 -VARIABLE ss
250.56 -VARIABLE wday
250.57 -VARIABLE y
250.58 -------------------------------------
250.59 -CLASS A
250.60 -CLASS ABCMeta
250.61 -CLASS AEServer
250.62 -CLASS AEText
250.63 -CLASS ASTVisitor
250.64 -CLASS AbstractBasicAuthHandler
250.65 -CLASS AbstractClassCode
250.66 -CLASS AbstractCompileMode
250.67 -CLASS AbstractDigestAuthHandler
250.68 -CLASS AbstractFormatter
250.69 -CLASS AbstractFunctionCode
250.70 -CLASS AbstractHTTPHandler
250.71 -CLASS AbstractWriter
250.72 -CLASS Add
250.73 -CLASS And
250.74 -CLASS Application
250.75 -CLASS ArgumentError
250.76 -CLASS ArithmeticError
250.77 -CLASS ArithmeticError
250.78 -CLASS Array
250.79 -CLASS ArrayInstance
250.80 -CLASS AssAttr
250.81 -CLASS AssList
250.82 -CLASS AssName
250.83 -CLASS AssTuple
250.84 -CLASS Assert
250.85 -CLASS AssertionError
250.86 -CLASS AssertionError
250.87 -CLASS Assign
250.88 -CLASS AsyncResult
250.89 -CLASS Attr
250.90 -CLASS AttributeError
250.91 -CLASS AttributeError
250.92 -CLASS AttributeList
250.93 -CLASS AttributeMap
250.94 -CLASS Attributes
250.95 -CLASS AttributesImpl
250.96 -CLASS AttributesNS
250.97 -CLASS AttributesNSImpl
250.98 -CLASS AugAssign
250.99 -CLASS AugGetattr
250.100 -CLASS AugName
250.101 -CLASS AugSlice
250.102 -CLASS AugSubscript
250.103 -CLASS AuthenticationError
250.104 -CLASS AutoGILError
250.105 -CLASS B
250.106 -CLASS BCPPCompiler
250.107 -CLASS BCPTestCase
250.108 -CLASS BZ2Compressor
250.109 -CLASS BZ2Decompressor
250.110 -CLASS BZ2File
250.111 -CLASS Babyl
250.112 -CLASS BabylMailbox
250.113 -CLASS BabylMessage
250.114 -CLASS Backquote
250.115 -CLASS BadBoundaryPointsErr
250.116 -CLASS BadFutureParser
250.117 -CLASS BadOptionError
250.118 -CLASS BadStatusLine
250.119 -CLASS BadZipfile
250.120 -CLASS Balloon
250.121 -CLASS Bar
250.122 -CLASS BaseCGIHandler
250.123 -CLASS BaseCookie
250.124 -CLASS BaseException
250.125 -CLASS BaseException
250.126 -CLASS BaseHTTPRequestHandler
250.127 -CLASS BaseHandler
250.128 -CLASS BaseIncrementalParser
250.129 -CLASS BaseManager
250.130 -CLASS BaseProxy
250.131 -CLASS BaseRequestHandler
250.132 -CLASS BaseRotatingHandler
250.133 -CLASS BaseSet
250.134 -CLASS BasicModuleImporter
250.135 -CLASS BasicModuleLoader
250.136 -CLASS BastionClass
250.137 -CLASS Baz
250.138 -CLASS Bdb
250.139 -CLASS BdbQuit
250.140 -CLASS BigEndianStructure
250.141 -CLASS Binary
250.142 -CLASS Bitand
250.143 -CLASS Bitor
250.144 -CLASS Bitxor
250.145 -CLASS Block
250.146 -CLASS BlockFinder
250.147 -CLASS BlockingIOError
250.148 -CLASS Boolean
250.149 -CLASS BoundaryError
250.150 -CLASS BoundedSemaphore
250.151 -CLASS Break
250.152 -CLASS Breakpoint
250.153 -CLASS BsdDbShelf
250.154 -CLASS BufferTooShort
250.155 -CLASS BufferedIOBase
250.156 -CLASS BufferedRWPair
250.157 -CLASS BufferedRandom
250.158 -CLASS BufferedReader
250.159 -CLASS BufferedWriter
250.160 -CLASS BufferingFormatter
250.161 -CLASS BufferingHandler
250.162 -CLASS BuildPyTestCase
250.163 -CLASS BuildScriptsTestCase
250.164 -CLASS BuiltinImporter
250.165 -CLASS Bulkcopy
250.166 -CLASS ButtonBox
250.167 -CLASS BytesIO
250.168 -CLASS C
250.169 -CLASS CAB
250.170 -CLASS CCompiler
250.171 -CLASS CCompilerError
250.172 -CLASS CDATASection
250.173 -CLASS CDLL
250.174 -CLASS CGIHTTPRequestHandler
250.175 -CLASS CGIHandler
250.176 -CLASS CGIXMLRPCRequestHandler
250.177 -CLASS CacheFTPHandler
250.178 -CLASS CallFunc
250.179 -CLASS CalledProcessError
250.180 -CLASS CannotSendHeader
250.181 -CLASS CannotSendRequest
250.182 -CLASS Canonizer
250.183 -CLASS CharacterData
250.184 -CLASS Charset
250.185 -CLASS CharsetError
250.186 -CLASS CheckList
250.187 -CLASS Childless
250.188 -CLASS Chunk
250.189 -CLASS Clamped
250.190 -CLASS Class
250.191 -CLASS ClassCodeGenerator
250.192 -CLASS ClassScope
250.193 -CLASS Cmd
250.194 -CLASS CodeGenerator
250.195 -CLASS Codec
250.196 -CLASS CodecRegistryError
250.197 -CLASS ComboBox
250.198 -CLASS Command
250.199 -CLASS CommandCompiler
250.200 -CLASS Comment
250.201 -CLASS Compare
250.202 -CLASS Comparison
250.203 -CLASS Compile
250.204 -CLASS CompileError
250.205 -CLASS Completer
250.206 -CLASS Complex
250.207 -CLASS ComponentItem
250.208 -CLASS Condition
250.209 -CLASS ConfigParser
250.210 -CLASS Connection
250.211 -CLASS Const
250.212 -CLASS ContentGenerator
250.213 -CLASS ContentHandler
250.214 -CLASS Context
250.215 -CLASS Continue
250.216 -CLASS Control
250.217 -CLASS ControlsWindow
250.218 -CLASS ConversionError
250.219 -CLASS Cookie
250.220 -CLASS CookieError
250.221 -CLASS CookieJar
250.222 -CLASS CookiePolicy
250.223 -CLASS CoverageResults
250.224 -CLASS Cursor
250.225 -CLASS CygwinCCompiler
250.226 -CLASS D
250.227 -CLASS DOMBuilder
250.228 -CLASS DOMEntityResolver
250.229 -CLASS DOMError
250.230 -CLASS DOMEventStream
250.231 -CLASS DOMException
250.232 -CLASS DOMImplementation
250.233 -CLASS DOMInputSource
250.234 -CLASS DOMStringSizeErr
250.235 -CLASS DTDHandler
250.236 -CLASS Data
250.237 -CLASS Database
250.238 -CLASS DatagramHandler
250.239 -CLASS DatagramRequestHandler
250.240 -CLASS DateTime
250.241 -CLASS DbfilenameShelf
250.242 -CLASS DebugRunner
250.243 -CLASS DebuggingServer
250.244 -CLASS Decimal
250.245 -CLASS DecimalException
250.246 -CLASS DeclHandler
250.247 -CLASS DecodedGenerator
250.248 -CLASS Decorators
250.249 -CLASS DefaultCookiePolicy
250.250 -CLASS DefaultHandler
250.251 -CLASS Delegator
250.252 -CLASS DeprecationWarning
250.253 -CLASS DeprecationWarning
250.254 -CLASS Dialect
250.255 -CLASS Dialog
250.256 -CLASS DialogWindow
250.257 -CLASS Dict
250.258 -CLASS DictMixin
250.259 -CLASS DictReader
250.260 -CLASS DictWriter
250.261 -CLASS Differ
250.262 -CLASS DirList
250.263 -CLASS DirSelectBox
250.264 -CLASS DirSelectDialog
250.265 -CLASS DirTree
250.266 -CLASS Directory
250.267 -CLASS Discard
250.268 -CLASS Distribution
250.269 -CLASS DistributionMetadata
250.270 -CLASS DistributionTestCase
250.271 -CLASS DistutilsArgError
250.272 -CLASS DistutilsClassError
250.273 -CLASS DistutilsError
250.274 -CLASS DistutilsExecError
250.275 -CLASS DistutilsFileError
250.276 -CLASS DistutilsGetoptError
250.277 -CLASS DistutilsInternalError
250.278 -CLASS DistutilsModuleError
250.279 -CLASS DistutilsOptionError
250.280 -CLASS DistutilsPlatformError
250.281 -CLASS DistutilsSetupError
250.282 -CLASS DistutilsTemplateError
250.283 -CLASS Div
250.284 -CLASS DivisionByZero
250.285 -CLASS Doc
250.286 -CLASS DocCGIXMLRPCRequestHandler
250.287 -CLASS DocTest
250.288 -CLASS DocTestFailure
250.289 -CLASS DocTestFinder
250.290 -CLASS DocTestParser
250.291 -CLASS DocTestRunner
250.292 -CLASS DocXMLRPCRequestHandler
250.293 -CLASS DocXMLRPCServer
250.294 -CLASS Document
250.295 -CLASS DocumentFragment
250.296 -CLASS DocumentHandler
250.297 -CLASS DocumentType
250.298 -CLASS DomstringSizeErr
250.299 -CLASS DumbWriter
250.300 -CLASS DummyCommand
250.301 -CLASS DuplicateSectionError
250.302 -CLASS DynLoadSuffixImporter
250.303 -CLASS EMXCCompiler
250.304 -CLASS EOFError
250.305 -CLASS EOFError
250.306 -CLASS ESISDocHandler
250.307 -CLASS Element
250.308 -CLASS ElementInfo
250.309 -CLASS ElementTree
250.310 -CLASS Ellipsis
250.311 -CLASS Empty
250.312 -CLASS EmptyNode
250.313 -CLASS EndOfBlock
250.314 -CLASS Entity
250.315 -CLASS EntityResolver
250.316 -CLASS Enum
250.317 -CLASS EnvironmentError
250.318 -CLASS EnvironmentError
250.319 -CLASS Error
250.320 -CLASS ErrorDuringImport
250.321 -CLASS ErrorHandler
250.322 -CLASS ErrorPrinter
250.323 -CLASS ErrorRaiser
250.324 -CLASS Event
250.325 -CLASS EventBroadcaster
250.326 -CLASS EventException
250.327 -CLASS ExFileSelectBox
250.328 -CLASS Example
250.329 -CLASS ExampleASTVisitor
250.330 -CLASS Exception
250.331 -CLASS Exception
250.332 -CLASS Exec
250.333 -CLASS ExitNow
250.334 -CLASS ExpatError
250.335 -CLASS ExpatParser
250.336 -CLASS Expression
250.337 -CLASS ExpressionCodeGenerator
250.338 -CLASS Extension
250.339 -CLASS F
250.340 -CLASS FTP
250.341 -CLASS FTPHandler
250.342 -CLASS Factory
250.343 -CLASS FancyGetopt
250.344 -CLASS FancyModuleLoader
250.345 -CLASS FancyURLopener
250.346 -CLASS Fault
250.347 -CLASS Feature
250.348 -CLASS FeedParser
250.349 -CLASS FieldStorage
250.350 -CLASS FileCookieJar
250.351 -CLASS FileEntry
250.352 -CLASS FileHandler
250.353 -CLASS FileIO
250.354 -CLASS FileInput
250.355 -CLASS FileList
250.356 -CLASS FileSelectBox
250.357 -CLASS FileWrapper
250.358 -CLASS Filter
250.359 -CLASS Filterer
250.360 -CLASS FingerHandler
250.361 -CLASS FirstHeaderLineIsContinuationD
250.362 -CLASS FloatingPointError
250.363 -CLASS FloatingPointError
250.364 -CLASS FloorDiv
250.365 -CLASS FlowGraph
250.366 -CLASS Folder
250.367 -CLASS Foo
250.368 -CLASS For
250.369 -CLASS ForkingMixIn
250.370 -CLASS ForkingTCPServer
250.371 -CLASS ForkingUDPServer
250.372 -CLASS Form
250.373 -CLASS FormContent
250.374 -CLASS FormContentDict
250.375 -CLASS Formatter
250.376 -CLASS Fraction
250.377 -CLASS From
250.378 -CLASS FtException
250.379 -CLASS Full
250.380 -CLASS FuncPtr
250.381 -CLASS Function
250.382 -CLASS FunctionCodeGenerator
250.383 -CLASS FunctionScope
250.384 -CLASS FunctionTestCase
250.385 -CLASS FutureParser
250.386 -CLASS FutureWarning
250.387 -CLASS FutureWarning
250.388 -CLASS GNUTranslations
250.389 -CLASS GenExpr
250.390 -CLASS GenExprFor
250.391 -CLASS GenExprIf
250.392 -CLASS GenExprInner
250.393 -CLASS GenExprScope
250.394 -CLASS Generator
250.395 -CLASS GeneratorExit
250.396 -CLASS GeneratorExit
250.397 -CLASS Getattr
250.398 -CLASS GetattrMagic
250.399 -CLASS GetoptError
250.400 -CLASS Global
250.401 -CLASS GopherError
250.402 -CLASS GopherHandler
250.403 -CLASS GridBag
250.404 -CLASS GzipFile
250.405 -CLASS HList
250.406 -CLASS HMAC
250.407 -CLASS HRESULT
250.408 -CLASS HTMLDoc
250.409 -CLASS HTMLParseError
250.410 -CLASS HTMLParser
250.411 -CLASS HTMLRepr
250.412 -CLASS HTTP
250.413 -CLASS HTTPBasicAuthHandler
250.414 -CLASS HTTPConnection
250.415 -CLASS HTTPCookieProcessor
250.416 -CLASS HTTPDefaultErrorHandler
250.417 -CLASS HTTPDigestAuthHandler
250.418 -CLASS HTTPError
250.419 -CLASS HTTPErrorProcessor
250.420 -CLASS HTTPException
250.421 -CLASS HTTPHandler
250.422 -CLASS HTTPPasswordMgr
250.423 -CLASS HTTPPasswordMgrWithDefaultReal
250.424 -CLASS HTTPRedirectHandler
250.425 -CLASS HTTPResponse
250.426 -CLASS HTTPSConnection
250.427 -CLASS HTTPSHandler
250.428 -CLASS HTTPServer
250.429 -CLASS Handler
250.430 -CLASS HandlerBase
250.431 -CLASS Header
250.432 -CLASS HeaderParseError
250.433 -CLASS HeaderParser
250.434 -CLASS Headers
250.435 -CLASS HelpFormatter
250.436 -CLASS Helper
250.437 -CLASS HierarchyRequestErr
250.438 -CLASS Hook
250.439 -CLASS Hooks
250.440 -CLASS HtmlDiff
250.441 -CLASS IC
250.442 -CLASS IMAP4
250.443 -CLASS IMAP4_SSL
250.444 -CLASS IMAP4_stream
250.445 -CLASS IOBase
250.446 -CLASS IOError
250.447 -CLASS IOError
250.448 -CLASS Identified
250.449 -CLASS If
250.450 -CLASS IfExp
250.451 -CLASS Ignore
250.452 -CLASS IllegalMonthError
250.453 -CLASS IllegalWeekdayError
250.454 -CLASS ImmutableSet
250.455 -CLASS ImpImporter
250.456 -CLASS ImpLoader
250.457 -CLASS Import
250.458 -CLASS ImportError
250.459 -CLASS ImportError
250.460 -CLASS ImportManager
250.461 -CLASS ImportWarning
250.462 -CLASS ImportWarning
250.463 -CLASS Importer
250.464 -CLASS ImproperConnectionState
250.465 -CLASS Incomplete
250.466 -CLASS IncompleteRead
250.467 -CLASS IncrementalDecoder
250.468 -CLASS IncrementalEncoder
250.469 -CLASS IncrementalNewlineDecoder
250.470 -CLASS IncrementalParser
250.471 -CLASS IndentedHelpFormatter
250.472 -CLASS IndexError
250.473 -CLASS IndexError
250.474 -CLASS IndexSizeErr
250.475 -CLASS Inexact
250.476 -CLASS IniParser
250.477 -CLASS InputOnly
250.478 -CLASS InputSource
250.479 -CLASS InsertionLoc
250.480 -CLASS InstallScriptsTestCase
250.481 -CLASS InstallTestCase
250.482 -CLASS Integral
250.483 -CLASS Interactive
250.484 -CLASS InteractiveCodeGenerator
250.485 -CLASS InteractiveConsole
250.486 -CLASS InteractiveInterpreter
250.487 -CLASS InterpFormContentDict
250.488 -CLASS InterpolationDepthError
250.489 -CLASS InterpolationError
250.490 -CLASS InterpolationSyntaxError
250.491 -CLASS IntlText
250.492 -CLASS IntlWritingCode
250.493 -CLASS InuseAttributeErr
250.494 -CLASS InvalidAccessErr
250.495 -CLASS InvalidCharacterErr
250.496 -CLASS InvalidModificationErr
250.497 -CLASS InvalidNodeTypeErr
250.498 -CLASS InvalidOperation
250.499 -CLASS InvalidStateErr
250.500 -CLASS InvalidURL
250.501 -CLASS Invert
250.502 -CLASS IsqlCmd
250.503 -CLASS IsqlExit
250.504 -CLASS IterableUserDict
250.505 -CLASS JSONDecoder
250.506 -CLASS JSONEncoder
250.507 -CLASS JavaSAXParser
250.508 -CLASS JoinableQueue
250.509 -CLASS JyDTDHandlerWrapper
250.510 -CLASS JyEntityResolverWrapper
250.511 -CLASS JyErrorHandlerWrapper
250.512 -CLASS JyInputSourceWrapper
250.513 -CLASS JythonCompiler
250.514 -CLASS JythonSignalHandler
250.515 -CLASS KeyError
250.516 -CLASS KeyError
250.517 -CLASS KeyboardInterrupt
250.518 -CLASS KeyboardInterrupt
250.519 -CLASS Keyword
250.520 -CLASS LOBTestCase
250.521 -CLASS LWPCookieJar
250.522 -CLASS LabelEntry
250.523 -CLASS LabelFrame
250.524 -CLASS Lambda
250.525 -CLASS LambdaScope
250.526 -CLASS LargeZipFile
250.527 -CLASS LeftShift
250.528 -CLASS LexicalHandler
250.529 -CLASS LexicalXMLGenerator
250.530 -CLASS LibError
250.531 -CLASS LibraryLoader
250.532 -CLASS LineAddrTable
250.533 -CLASS LinkError
250.534 -CLASS List
250.535 -CLASS ListComp
250.536 -CLASS ListCompFor
250.537 -CLASS ListCompIf
250.538 -CLASS ListNoteBook
250.539 -CLASS Listener
250.540 -CLASS LittleEndianStructure
250.541 -CLASS LoadError
250.542 -CLASS LocalNameFinder
250.543 -CLASS Location
250.544 -CLASS Locator
250.545 -CLASS Lock
250.546 -CLASS Log
250.547 -CLASS LogRecord
250.548 -CLASS Logger
250.549 -CLASS LoggingSilencer
250.550 -CLASS Logical
250.551 -CLASS LookupError
250.552 -CLASS LookupError
250.553 -CLASS LooseVersion
250.554 -CLASS MH
250.555 -CLASS MHMailbox
250.556 -CLASS MHMessage
250.557 -CLASS MIMEApplication
250.558 -CLASS MIMEAudio
250.559 -CLASS MIMEBase
250.560 -CLASS MIMEImage
250.561 -CLASS MIMEMessage
250.562 -CLASS MIMEMultipart
250.563 -CLASS MIMENonMultipart
250.564 -CLASS MIMEText
250.565 -CLASS MMDF
250.566 -CLASS MMDFMessage
250.567 -CLASS MSVCCompiler
250.568 -CLASS MWerksCompiler
250.569 -CLASS MacroExpander
250.570 -CLASS Mailbox
250.571 -CLASS Maildir
250.572 -CLASS MaildirMessage
250.573 -CLASS MailmanProxy
250.574 -CLASS MalformedHeaderDefect
250.575 -CLASS Manager
250.576 -CLASS Marshaller
250.577 -CLASS MemoryError
250.578 -CLASS MemoryError
250.579 -CLASS MemoryHandler
250.580 -CLASS Message
250.581 -CLASS MessageDefect
250.582 -CLASS MessageError
250.583 -CLASS MessageParseError
250.584 -CLASS MetadataTestCase
250.585 -CLASS Meter
250.586 -CLASS MimeWriter
250.587 -CLASS Mingw32CCompiler
250.588 -CLASS MiniApplication
250.589 -CLASS MiniFieldStorage
250.590 -CLASS MisplacedEnvelopeHeaderDefect
250.591 -CLASS MissingSectionHeaderError
250.592 -CLASS MmdfMailbox
250.593 -CLASS Mod
250.594 -CLASS Model
250.595 -CLASS Module
250.596 -CLASS ModuleCodeGenerator
250.597 -CLASS ModuleFinder
250.598 -CLASS ModuleImporter
250.599 -CLASS ModuleLoader
250.600 -CLASS ModuleScanner
250.601 -CLASS ModuleScope
250.602 -CLASS MozillaCookieJar
250.603 -CLASS Mul
250.604 -CLASS MultiCall
250.605 -CLASS MultiCallIterator
250.606 -CLASS MultiFile
250.607 -CLASS MultipartConversionError
250.608 -CLASS MultipartInvariantViolationDef
250.609 -CLASS MutableString
250.610 -CLASS MyClass
250.611 -CLASS MyTest
250.612 -CLASS NNTP
250.613 -CLASS NNTPDataError
250.614 -CLASS NNTPPermanentError
250.615 -CLASS NNTPProtocolError
250.616 -CLASS NNTPReplyError
250.617 -CLASS NNTPTemporaryError
250.618 -CLASS NProperty
250.619 -CLASS NTEventLogHandler
250.620 -CLASS NULL
250.621 -CLASS Name
250.622 -CLASS NameError
250.623 -CLASS NameError
250.624 -CLASS NamedNodeMap
250.625 -CLASS NamespaceErr
250.626 -CLASS NannyNag
250.627 -CLASS NestedScopeMixin
250.628 -CLASS Netrc
250.629 -CLASS NetrcParseError
250.630 -CLASS NewStyle
250.631 -CLASS NoBoundaryInMultipartDefect
250.632 -CLASS NoDataAllowedErr
250.633 -CLASS NoModificationAllowedErr
250.634 -CLASS NoOpMetaClass
250.635 -CLASS NoOptionError
250.636 -CLASS NoSectionError
250.637 -CLASS Node
250.638 -CLASS NodeFilter
250.639 -CLASS NodeTransformer
250.640 -CLASS NodeVisitor
250.641 -CLASS Not
250.642 -CLASS NotANumber
250.643 -CLASS NotConnected
250.644 -CLASS NotFoundErr
250.645 -CLASS NotImplementedError
250.646 -CLASS NotImplementedError
250.647 -CLASS NotSupportedErr
250.648 -CLASS Notation
250.649 -CLASS NoteBook
250.650 -CLASS NullFormatter
250.651 -CLASS NullImporter
250.652 -CLASS NullTranslations
250.653 -CLASS NullWriter
250.654 -CLASS Number
250.655 -CLASS OSError
250.656 -CLASS OSError
250.657 -CLASS OSSAudioError
250.658 -CLASS ObjectSpecifier
250.659 -CLASS OleDLL
250.660 -CLASS OpFinder
250.661 -CLASS OpenerDirector
250.662 -CLASS OptParseError
250.663 -CLASS Option
250.664 -CLASS OptionConflictError
250.665 -CLASS OptionContainer
250.666 -CLASS OptionDummy
250.667 -CLASS OptionError
250.668 -CLASS OptionGroup
250.669 -CLASS OptionMenu
250.670 -CLASS OptionParser
250.671 -CLASS OptionValueError
250.672 -CLASS Or
250.673 -CLASS OracleSPTest
250.674 -CLASS Ordinal
250.675 -CLASS OutputChecker
250.676 -CLASS Overflow
250.677 -CLASS OverflowError
250.678 -CLASS OverflowError
250.679 -CLASS POP3
250.680 -CLASS POP3_SSL
250.681 -CLASS Packer
250.682 -CLASS PanedWindow
250.683 -CLASS Panel
250.684 -CLASS Parser
250.685 -CLASS ParserBase
250.686 -CLASS ParserError
250.687 -CLASS ParsingError
250.688 -CLASS Pass
250.689 -CLASS Pattern
250.690 -CLASS Pdb
250.691 -CLASS PendingDeprecationWarning
250.692 -CLASS PendingDeprecationWarning
250.693 -CLASS PickleError
250.694 -CLASS Pickler
250.695 -CLASS PicklingError
250.696 -CLASS PlaceHolder
250.697 -CLASS Popen
250.698 -CLASS Popen3
250.699 -CLASS Popen4
250.700 -CLASS PopupMenu
250.701 -CLASS PortableUnixMailbox
250.702 -CLASS Power
250.703 -CLASS PreprocessError
250.704 -CLASS PrettyPrinter
250.705 -CLASS Print
250.706 -CLASS Printnl
250.707 -CLASS Process
250.708 -CLASS ProcessingInstruction
250.709 -CLASS Profile
250.710 -CLASS ProgressBar
250.711 -CLASS Prompt
250.712 -CLASS ProtocolError
250.713 -CLASS ProxyBasicAuthHandler
250.714 -CLASS ProxyDigestAuthHandler
250.715 -CLASS ProxyHandler
250.716 -CLASS PullDOM
250.717 -CLASS PureProxy
250.718 -CLASS PyCompileError
250.719 -CLASS PyDLL
250.720 -CLASS PyDialog
250.721 -CLASS PyFlowGraph
250.722 -CLASS PyHKEY
250.723 -CLASS PyZipFile
250.724 -CLASS QDPoint
250.725 -CLASS QDRectangle
250.726 -CLASS QName
250.727 -CLASS Queue
250.728 -CLASS RExec
250.729 -CLASS RGBColor
250.730 -CLASS RLock
250.731 -CLASS RadioButtonGroup
250.732 -CLASS Raise
250.733 -CLASS Random
250.734 -CLASS Range
250.735 -CLASS RangeException
250.736 -CLASS Rational
250.737 -CLASS RawIOBase
250.738 -CLASS RawTurtle
250.739 -CLASS ReadOnlySequentialNamedNodeMap
250.740 -CLASS Real
250.741 -CLASS Record
250.742 -CLASS ReferenceError
250.743 -CLASS ReferenceError
250.744 -CLASS Repr
250.745 -CLASS Request
250.746 -CLASS ResponseError
250.747 -CLASS ResponseNotReady
250.748 -CLASS ResultSet
250.749 -CLASS ResultSetRow
250.750 -CLASS Return
250.751 -CLASS RightShift
250.752 -CLASS RobotFileParser
250.753 -CLASS RootLogger
250.754 -CLASS RotatingFileHandler
250.755 -CLASS Rounded
250.756 -CLASS Row
250.757 -CLASS RuntimeError
250.758 -CLASS RuntimeError
250.759 -CLASS RuntimeWarning
250.760 -CLASS RuntimeWarning
250.761 -CLASS SAX2DOM
250.762 -CLASS SAXException
250.763 -CLASS SAXNotRecognizedException
250.764 -CLASS SAXNotSupportedException
250.765 -CLASS SAXParseException
250.766 -CLASS SAXReaderNotAvailable
250.767 -CLASS SGMLParseError
250.768 -CLASS SGMLParser
250.769 -CLASS SMTP
250.770 -CLASS SMTPAuthenticationError
250.771 -CLASS SMTPConnectError
250.772 -CLASS SMTPDataError
250.773 -CLASS SMTPException
250.774 -CLASS SMTPHandler
250.775 -CLASS SMTPHeloError
250.776 -CLASS SMTPRecipientsRefused
250.777 -CLASS SMTPResponseException
250.778 -CLASS SMTPSenderRefused
250.779 -CLASS SMTPServer
250.780 -CLASS SMTPServerDisconnected
250.781 -CLASS SQLServerSPTest
250.782 -CLASS SQLTestCase
250.783 -CLASS SSLError
250.784 -CLASS SSLSocket
250.785 -CLASS ST
250.786 -CLASS SafeConfigParser
250.787 -CLASS SafeTransport
250.788 -CLASS Scanner
250.789 -CLASS Schema
250.790 -CLASS Scope
250.791 -CLASS Screen
250.792 -CLASS ScrolledCavas
250.793 -CLASS ScrolledText
250.794 -CLASS ScrolledWindow
250.795 -CLASS Select
250.796 -CLASS Semaphore
250.797 -CLASS SequenceMatcher
250.798 -CLASS SerialCookie
250.799 -CLASS Server
250.800 -CLASS ServerHTMLDoc
250.801 -CLASS ServerProxy
250.802 -CLASS Set
250.803 -CLASS SgmlopParser
250.804 -CLASS Shape
250.805 -CLASS Shelf
250.806 -CLASS SimpleCookie
250.807 -CLASS SimpleHTTPRequestHandler
250.808 -CLASS SimpleHandler
250.809 -CLASS SimpleLocator
250.810 -CLASS SimpleXMLRPCDispatcher
250.811 -CLASS SimpleXMLRPCRequestHandler
250.812 -CLASS SimpleXMLRPCServer
250.813 -CLASS Slice
250.814 -CLASS Sliceobj
250.815 -CLASS SlowParser
250.816 -CLASS SmartCookie
250.817 -CLASS Sniffer
250.818 -CLASS SocketHandler
250.819 -CLASS SocketType
250.820 -CLASS Stack
250.821 -CLASS StackDepthTracker
250.822 -CLASS StandardError
250.823 -CLASS StandardError
250.824 -CLASS StartBoundaryNotFoundDefect
250.825 -CLASS Stats
250.826 -CLASS StdButtonBox
250.827 -CLASS Stmt
250.828 -CLASS StopIteration
250.829 -CLASS StopIteration
250.830 -CLASS StopTokenizing
250.831 -CLASS Strange
250.832 -CLASS StreamConverter
250.833 -CLASS StreamHandler
250.834 -CLASS StreamReader
250.835 -CLASS StreamRequestHandler
250.836 -CLASS StreamWriter
250.837 -CLASS StrictVersion
250.838 -CLASS StringIO
250.839 -CLASS Struct
250.840 -CLASS Structure
250.841 -CLASS StyledText
250.842 -CLASS Sub
250.843 -CLASS SubPattern
250.844 -CLASS Subnormal
250.845 -CLASS Subscript
250.846 -CLASS SummaryInformation
250.847 -CLASS Super
250.848 -CLASS SuperSuper
250.849 -CLASS SvFormContentDict
250.850 -CLASS Symbol
250.851 -CLASS SymbolTable
250.852 -CLASS SymbolVisitor
250.853 -CLASS SyncManager
250.854 -CLASS SyntaxErr
250.855 -CLASS SyntaxError
250.856 -CLASS SyntaxError
250.857 -CLASS SyntaxErrorChecker
250.858 -CLASS SyntaxWarning
250.859 -CLASS SyntaxWarning
250.860 -CLASS SysLogHandler
250.861 -CLASS SystemError
250.862 -CLASS SystemError
250.863 -CLASS SystemExit
250.864 -CLASS SystemExit
250.865 -CLASS SystemRandom
250.866 -CLASS TCPServer
250.867 -CLASS TList
250.868 -CLASS TalkTo
250.869 -CLASS TarError
250.870 -CLASS TarFile
250.871 -CLASS TarInfo
250.872 -CLASS Telnet
250.873 -CLASS TempdirManager
250.874 -CLASS Template
250.875 -CLASS Test
250.876 -CLASS TestCase
250.877 -CLASS TestClass
250.878 -CLASS TestCrispinTorture
250.879 -CLASS TestDistribution
250.880 -CLASS TestLoader
250.881 -CLASS TestResult
250.882 -CLASS TestSuite
250.883 -CLASS TestThread
250.884 -CLASS TestXMLParser
250.885 -CLASS Testcase
250.886 -CLASS Tester
250.887 -CLASS Text
250.888 -CLASS TextDoc
250.889 -CLASS TextFile
250.890 -CLASS TextIOBase
250.891 -CLASS TextIOWrapper
250.892 -CLASS TextRepr
250.893 -CLASS TextTestRunner
250.894 -CLASS TextWrapper
250.895 -CLASS Textbox
250.896 -CLASS Thread
250.897 -CLASS ThreadingMixIn
250.898 -CLASS ThreadingTCPServer
250.899 -CLASS ThreadingUDPServer
250.900 -CLASS ThreadingUnixDatagramServer
250.901 -CLASS ThreadingUnixStreamServer
250.902 -CLASS TimedRotatingFileHandler
250.903 -CLASS Timer
250.904 -CLASS TitledHelpFormatter
250.905 -CLASS Tix
250.906 -CLASS Tk
250.907 -CLASS TokenError
250.908 -CLASS Tokenizer
250.909 -CLASS TortureBase
250.910 -CLASS Trace
250.911 -CLASS Transformer
250.912 -CLASS Transport
250.913 -CLASS Tree
250.914 -CLASS TreeBuilder
250.915 -CLASS TryExcept
250.916 -CLASS TryFinally
250.917 -CLASS Tuple
250.918 -CLASS TupleArg
250.919 -CLASS Turtle
250.920 -CLASS TurtleScreen
250.921 -CLASS Type
250.922 -CLASS TypeError
250.923 -CLASS TypeError
250.924 -CLASS TypeInfo
250.925 -CLASS UDPServer
250.926 -CLASS URLError
250.927 -CLASS URLopener
250.928 -CLASS UUID
250.929 -CLASS UnaryAdd
250.930 -CLASS UnarySub
250.931 -CLASS UnboundLocalError
250.932 -CLASS UnboundLocalError
250.933 -CLASS Underflow
250.934 -CLASS UnexpectedException
250.935 -CLASS UnicodeDecodeError
250.936 -CLASS UnicodeDecodeError
250.937 -CLASS UnicodeEncodeError
250.938 -CLASS UnicodeEncodeError
250.939 -CLASS UnicodeError
250.940 -CLASS UnicodeError
250.941 -CLASS UnicodeTranslateError
250.942 -CLASS UnicodeTranslateError
250.943 -CLASS UnicodeWarning
250.944 -CLASS UnicodeWarning
250.945 -CLASS UnimplementedFileMode
250.946 -CLASS Union
250.947 -CLASS UnixCCompiler
250.948 -CLASS UnixDatagramServer
250.949 -CLASS UnixMailbox
250.950 -CLASS UnixStreamServer
250.951 -CLASS Unknown
250.952 -CLASS UnknownFileError
250.953 -CLASS UnknownHandler
250.954 -CLASS UnknownProtocol
250.955 -CLASS UnknownTransferEncoding
250.956 -CLASS Unload
250.957 -CLASS Unmarshaller
250.958 -CLASS Unpacker
250.959 -CLASS Unpickler
250.960 -CLASS UnpicklingError
250.961 -CLASS UnspecifiedEventTypeErr
250.962 -CLASS UnsupportedOperation
250.963 -CLASS UserDataHandler
250.964 -CLASS UserDict
250.965 -CLASS UserList
250.966 -CLASS UserString
250.967 -CLASS UserWarning
250.968 -CLASS UserWarning
250.969 -CLASS ValidationErr
250.970 -CLASS ValueError
250.971 -CLASS ValueError
250.972 -CLASS Values
250.973 -CLASS Vec2D
250.974 -CLASS Vendor
250.975 -CLASS Version
250.976 -CLASS VersionPredicate
250.977 -CLASS View
250.978 -CLASS WSGIRequestHandler
250.979 -CLASS WSGIServer
250.980 -CLASS Warning
250.981 -CLASS Warning
250.982 -CLASS Wave_read
250.983 -CLASS Wave_write
250.984 -CLASS WeakKeyDictionary
250.985 -CLASS WeakValueDictionary
250.986 -CLASS While
250.987 -CLASS WichmannHill
250.988 -CLASS WinDLL
250.989 -CLASS Window
250.990 -CLASS WindowsError
250.991 -CLASS WindowsError
250.992 -CLASS With
250.993 -CLASS WrongDocumentErr
250.994 -CLASS X
250.995 -CLASS XMLFilter
250.996 -CLASS XMLFilterBase
250.997 -CLASS XMLFilterImpl
250.998 -CLASS XMLGenerator
250.999 -CLASS XMLParser
250.1000 -CLASS XMLRPCDocGenerator
250.1001 -CLASS XMLReader
250.1002 -CLASS XMLTreeBuilder
250.1003 -CLASS XmlParseErr
250.1004 -CLASS Yield
250.1005 -CLASS Yuck
250.1006 -CLASS ZeroDivisionError
250.1007 -CLASS ZeroDivisionError
250.1008 -CLASS ZipFile
250.1009 -CLASS ZipImportError
250.1010 -CLASS ZipInfo
250.1011 -CLASS _CData [PROTECTE
250.1012 -CLASS _FuncPtr [PROTECTE
250.1013 -CLASS _SimpleCData [PROTECTE
250.1014 -CLASS _date_class [PRIVATE]
250.1015 -CLASS _posixfile_
250.1016 -CLASS _time_class [PRIVATE]
250.1017 -CLASS array
250.1018 -CLASS async_chat
250.1019 -CLASS bdist
250.1020 -CLASS bdist_dumb
250.1021 -CLASS bdist_msi
250.1022 -CLASS bdist_rpm
250.1023 -CLASS bdist_wininst
250.1024 -CLASS bool
250.1025 -CLASS bsddbobject
250.1026 -CLASS build
250.1027 -CLASS build_clib
250.1028 -CLASS build_ext
250.1029 -CLASS build_py
250.1030 -CLASS build_scripts
250.1031 -CLASS c_bool
250.1032 -CLASS c_byte
250.1033 -CLASS c_char
250.1034 -CLASS c_char_p
250.1035 -CLASS c_double
250.1036 -CLASS c_float
250.1037 -CLASS c_int
250.1038 -CLASS c_int16
250.1039 -CLASS c_int32
250.1040 -CLASS c_int64
250.1041 -CLASS c_int8
250.1042 -CLASS c_long
250.1043 -CLASS c_longdouble
250.1044 -CLASS c_longlong
250.1045 -CLASS c_short
250.1046 -CLASS c_size_t
250.1047 -CLASS c_ubyte
250.1048 -CLASS c_uint
250.1049 -CLASS c_uint16
250.1050 -CLASS c_uint32
250.1051 -CLASS c_uint64
250.1052 -CLASS c_uint8
250.1053 -CLASS c_ulong
250.1054 -CLASS c_ulonglong
250.1055 -CLASS c_ushort
250.1056 -CLASS c_void_p
250.1057 -CLASS c_wchar
250.1058 -CLASS c_wchar_p
250.1059 -CLASS class
250.1060 -CLASS class
250.1061 -CLASS clean
250.1062 -CLASS closing
250.1063 -CLASS complex
250.1064 -CLASS compressobj
250.1065 -CLASS config
250.1066 -CLASS container
250.1067 -CLASS container
250.1068 -CLASS contextmanager
250.1069 -CLASS contextmanager
250.1070 -CLASS controller
250.1071 -CLASS date
250.1072 -CLASS datetime
250.1073 -CLASS dbexts
250.1074 -CLASS dbextsTestCase
250.1075 -CLASS dbhash
250.1076 -CLASS decompressobj
250.1077 -CLASS deque
250.1078 -CLASS dict
250.1079 -CLASS dict
250.1080 -CLASS dircmp
250.1081 -CLASS dispatcher
250.1082 -CLASS dispatcher_with_send
250.1083 -CLASS dl
250.1084 -CLASS error
250.1085 -CLASS error_data
250.1086 -CLASS error_perm
250.1087 -CLASS error_proto
250.1088 -CLASS error_reply
250.1089 -CLASS excel
250.1090 -CLASS excel_tab
250.1091 -CLASS executor
250.1092 -CLASS fifo
250.1093 -CLASS file
250.1094 -CLASS file
250.1095 -CLASS file_dispatcher
250.1096 -CLASS file_wrapper
250.1097 -CLASS float
250.1098 -CLASS float
250.1099 -CLASS foo
250.1100 -CLASS gaierror
250.1101 -CLASS herror
250.1102 -CLASS install
250.1103 -CLASS install_data
250.1104 -CLASS install_egg_info
250.1105 -CLASS install_headers
250.1106 -CLASS install_lib
250.1107 -CLASS install_misc
250.1108 -CLASS install_scripts
250.1109 -CLASS instance
250.1110 -CLASS instance
250.1111 -CLASS int
250.1112 -CLASS iterator
250.1113 -CLASS iterator
250.1114 -CLASS list
250.1115 -CLASS local
250.1116 -CLASS lock
250.1117 -CLASS long
250.1118 -CLASS main
250.1119 -CLASS mbox
250.1120 -CLASS mboxMessage
250.1121 -CLASS mllib
250.1122 -CLASS mmap
250.1123 -CLASS multiprocessing.Pool
250.1124 -CLASS mutex
250.1125 -CLASS mxODBCProxy
250.1126 -CLASS netrc
250.1127 -CLASS object
250.1128 -CLASS object
250.1129 -CLASS oss_audio_device
250.1130 -CLASS oss_mixer_device
250.1131 -CLASS poll
250.1132 -CLASS py_object
250.1133 -CLASS register
250.1134 -CLASS scheduler
250.1135 -CLASS sdist
250.1136 -CLASS set
250.1137 -CLASS set
250.1138 -CLASS shlex
250.1139 -CLASS simple_producer
250.1140 -CLASS socket
250.1141 -CLASS stat_result
250.1142 -CLASS str
250.1143 -CLASS str
250.1144 -CLASS test_dist
250.1145 -CLASS test_zxjdbc
250.1146 -CLASS time
250.1147 -CLASS timedelta
250.1148 -CLASS timeout
250.1149 -CLASS tixCommand
250.1150 -CLASS tmxxx
250.1151 -CLASS tuple
250.1152 -CLASS tzinfo
250.1153 -CLASS unicode
250.1154 -CLASS unicode
250.1155 -CLASS upload
250.1156 -CLASS window
250.1157 -CLASS xmlparser
250.1158 -CLASS zipimporter
250.1159 -CLASS zxAPITestCase
250.1160 -CLASS zxCoreTestCase
250.1161 -CLASS zxJDBCTestCase
250.1162 -METHOD __import__(name, globals, loca
250.1163 -METHOD abs(x)
250.1164 -METHOD all(iterable)
250.1165 -METHOD any(iterable)
250.1166 -METHOD ---apply(function, args, ke---
250.1167 -METHOD basestring()
250.1168 -METHOD bin(x)
250.1169 -METHOD bool(x)
250.1170 -METHOD buffer(object, offset, size)
250.1171 -METHOD callable(object)
250.1172 -METHOD chr(i)
250.1173 -METHOD classmethod(function)
250.1174 -METHOD cmp(x, y)
250.1175 -METHOD coerce(x, y)
250.1176 -METHOD compile(source, filename, mode
250.1177 -METHOD complex(real, imag)
250.1178 -METHOD delattr(object, name)
250.1179 -METHOD dict(arg)
250.1180 -METHOD dir(object)
250.1181 -METHOD divmod(a, b)
250.1182 -METHOD enumerate(sequence, start)
250.1183 -METHOD eval(expression, globals, loca
250.1184 -METHOD execfile(filename, globals, lo
250.1185 -METHOD exit(code)
250.1186 -METHOD file(filename, mode, bufsize)
250.1187 -METHOD filter(function, iterable)
250.1188 -METHOD float(x)
250.1189 -METHOD frozenset(iterable)
250.1190 -METHOD getattr(object, name, default)
250.1191 -METHOD globals()
250.1192 -METHOD hasattr(object, name)
250.1193 -METHOD hash(object)
250.1194 -METHOD help(object)
250.1195 -METHOD hex(x)
250.1196 -METHOD id(object)
250.1197 -METHOD input(prompt)
250.1198 -METHOD int(x, radix)
250.1199 -METHOD intern(string)
250.1200 -METHOD isinstance(object, classinfo)
250.1201 -METHOD issubclass(class, classinfo)
250.1202 -METHOD iter(o, sentinel)
250.1203 -METHOD len(s)
250.1204 -METHOD list(iterable)
250.1205 -METHOD locals()
250.1206 -METHOD long(x, radix)
250.1207 -METHOD map(function, iterable)
250.1208 -METHOD max(iterable, argskey)
250.1209 -METHOD min(iterable, argskey)
250.1210 -METHOD next(iterator, default)
250.1211 -METHOD object()
250.1212 -METHOD oct(x)
250.1213 -METHOD open(filename, mode, bufsize)
250.1214 -METHOD ord(c)
250.1215 -METHOD pow(x, y, z)
250.1216 -METHOD print(object, sep, end, file)
250.1217 -METHOD property(fget, fset, fdel, doc
250.1218 -METHOD quit(code)
250.1219 -METHOD range(start, stop, step)
250.1220 -METHOD raw_input(prompt)
250.1221 -METHOD reduce(function, iterable, ini
250.1222 -METHOD reload(module)
250.1223 -METHOD repr(object)
250.1224 -METHOD reversed(seq)
250.1225 -METHOD round(x, n)
250.1226 -METHOD set(iterable)
250.1227 -METHOD setattr(object, name, value)
250.1228 -METHOD slice(start, stop, step)
250.1229 -METHOD sorted(iterable, cmp, key, rev
250.1230 -METHOD staticmethod(function)
250.1231 -METHOD str(object)
250.1232 -METHOD sum(iterable, start)
250.1233 -METHOD super(type, object-or-type)
250.1234 -METHOD tuple(iterable)
250.1235 -METHOD type(name, bases, dict)
250.1236 -METHOD type(object)
250.1237 -METHOD unichr(i)
250.1238 -METHOD unicode(object, encoding, erro
250.1239 -METHOD vars(object)
250.1240 -METHOD xrange(start, stop, step)
250.1241 -METHOD zip(iterable)
250.1242 -VARIABLE Ellipsis
250.1243 -VARIABLE False
250.1244 -VARIABLE None
250.1245 -VARIABLE NotImplemented
250.1246 -VARIABLE True
250.1247 -VARIABLE __debug__
250.1248 -VARIABLE copyright
250.1249 -KEYWORD and
250.1250 -KEYWORD as
250.1251 -KEYWORD assert
250.1252 -KEYWORD break
250.1253 -KEYWORD class
250.1254 -KEYWORD continue
250.1255 -KEYWORD def
250.1256 -KEYWORD del
250.1257 -KEYWORD elif
250.1258 -KEYWORD else
250.1259 -KEYWORD except
250.1260 -KEYWORD exec
250.1261 -KEYWORD finally
250.1262 -KEYWORD for
250.1263 -KEYWORD from
250.1264 -KEYWORD global
250.1265 -KEYWORD if
250.1266 -KEYWORD import
250.1267 -KEYWORD in
250.1268 -KEYWORD is
250.1269 -KEYWORD lambda
250.1270 -KEYWORD not
250.1271 -KEYWORD or
250.1272 -KEYWORD pass
250.1273 -KEYWORD print
250.1274 -KEYWORD raise
250.1275 -KEYWORD return
250.1276 -KEYWORD try
250.1277 -KEYWORD while
250.1278 -KEYWORD with
250.1279 -KEYWORD yield
251.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testMarks10.occurrences 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 - def __init__(|>MARK_OCCURRENCES:self<|, year, month, day, hour=0, minute=0, second=0,
251.5 - |>MARK_OCCURRENCES:self<|.ordinal = _ymd2ord(year, month, 1) + (day - 1)
251.6 - year, month, day = _ord2ymd(|>MARK_OCCURRENCES:self<|.ordinal)
251.7 - |>MARK_OCCURRENCES:sel^f<|.year, |>MARK_OCCURRENCES:self<|.month, |>MARK_OCCURRENCES:self<|.day = year, month, day
251.8 - |>MARK_OCCURRENCES:self<|.hour, |>MARK_OCCURRENCES:self<|.minute, |>MARK_OCCURRENCES:self<|.second = hour, minute, second
251.9 - |>MARK_OCCURRENCES:self<|.microsecond = microsecond
252.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testMarks3.occurrences 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 - |>MARK_OCCURRENCES:newformat<| = []
252.5 - push = |>MARK_OCCURRENCES:newformat<|.append
252.6 - |>MARK_OCCURRENCES:new^format<|.append(zreplace)
252.7 - |>MARK_OCCURRENCES:newformat<|.append(Zreplace)
252.8 - |>MARK_OCCURRENCES:newformat<| = "".join(|>MARK_OCCURRENCES:newformat<|)
252.9 - return _time.strftime(|>MARK_OCCURRENCES:newformat<|, timetuple)
253.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testMarks9.occurrences Sun Jan 04 13:11:53 2015 -0600
253.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
253.3 @@ -1,4 +0,0 @@
253.4 -def |>MARK_OCCURRENCES:_bu^ild_struct_time<|(y, m, d, hh, mm, ss, dstflag):
253.5 - return |>MARK_OCCURRENCES:_build_struct_time<|(self.__year, self.__month, self.__day,
253.6 - return |>MARK_OCCURRENCES:_build_struct_time<|(self.year, self.month, self.day,
253.7 - return |>MARK_OCCURRENCES:_build_struct_time<|(y, m, d, hh, mm, ss, 0)
254.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testUnresolvedHints7.hints Sun Jan 04 13:11:53 2015 -0600
254.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
254.3 @@ -1,3 +0,0 @@
254.4 - raise ValuError("astimezone() requires an aware datetime")
254.5 - ---------
254.6 -HINT:Undefined name "ValuError"
255.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testUnusedHints.hints Sun Jan 04 13:11:53 2015 -0600
255.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
255.3 @@ -1,27 +0,0 @@
255.4 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
255.5 - ---
255.6 -HINT:Unused Variable dst
255.7 -HINT:Unused Variable hh
255.8 -HINT:Unused Variable jday
255.9 -HINT:Unused Variable mm
255.10 -HINT:Unused Variable ss
255.11 -HINT:Unused Variable weekday
255.12 - def tzname(self, dt):
255.13 - --
255.14 -HINT:Unused Variable dt
255.15 - def utcoffset(self, dt):
255.16 - --
255.17 -HINT:Unused Variable dt
255.18 - def dst(self, dt):
255.19 - --
255.20 -HINT:Unused Variable dt
255.21 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
255.22 - ---
255.23 -HINT:Unused Variable dst
255.24 -HINT:Unused Variable jday
255.25 -HINT:Unused Variable weekday
255.26 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
255.27 - ---
255.28 -HINT:Unused Variable dst
255.29 -HINT:Unused Variable jday
255.30 -HINT:Unused Variable weekday
256.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testUnusedHints3.hints Sun Jan 04 13:11:53 2015 -0600
256.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
256.3 @@ -1,18 +0,0 @@
256.4 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
256.5 - ---
256.6 -HINT:Unused Variable dst
256.7 -HINT:Unused Variable hh
256.8 -HINT:Unused Variable jday
256.9 -HINT:Unused Variable mm
256.10 -HINT:Unused Variable ss
256.11 -HINT:Unused Variable weekday
256.12 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
256.13 - ---
256.14 -HINT:Unused Variable dst
256.15 -HINT:Unused Variable jday
256.16 -HINT:Unused Variable weekday
256.17 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
256.18 - ---
256.19 -HINT:Unused Variable dst
256.20 -HINT:Unused Variable jday
256.21 -HINT:Unused Variable weekday
257.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testUnusedHints4.hints Sun Jan 04 13:11:53 2015 -0600
257.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
257.3 @@ -1,18 +0,0 @@
257.4 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
257.5 - ---
257.6 -HINT:Unused Variable dst
257.7 -HINT:Unused Variable hh
257.8 -HINT:Unused Variable jday
257.9 -HINT:Unused Variable mm
257.10 -HINT:Unused Variable ss
257.11 -HINT:Unused Variable weekday
257.12 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
257.13 - ---
257.14 -HINT:Unused Variable dst
257.15 -HINT:Unused Variable jday
257.16 -HINT:Unused Variable weekday
257.17 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
257.18 - ---
257.19 -HINT:Unused Variable dst
257.20 -HINT:Unused Variable jday
257.21 -HINT:Unused Variable weekday
258.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testUnusedHints5.hints Sun Jan 04 13:11:53 2015 -0600
258.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
258.3 @@ -1,23 +0,0 @@
258.4 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
258.5 - ---
258.6 -HINT:Unused Variable dst
258.7 -HINT:Unused Variable hh
258.8 -HINT:Unused Variable ss
258.9 -HINT:Unused Variable weekday
258.10 - def tzname(self, dt):
258.11 - --
258.12 -HINT:Unused Variable dt
258.13 - def utcoffset(self, dt):
258.14 - --
258.15 -HINT:Unused Variable dt
258.16 - def dst(self, dt):
258.17 - --
258.18 -HINT:Unused Variable dt
258.19 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
258.20 - ---
258.21 -HINT:Unused Variable dst
258.22 -HINT:Unused Variable weekday
258.23 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
258.24 - ---
258.25 -HINT:Unused Variable dst
258.26 -HINT:Unused Variable weekday
259.1 --- a/python.editor/test/unit/data/testfiles/declarations.py Sun Jan 04 13:11:53 2015 -0600
259.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
259.3 @@ -1,3 +0,0 @@
259.4 -# Go to random function
259.5 -fnmatchcase(x)
259.6 -
260.1 --- a/python.editor/test/unit/data/testfiles/decorators.py Sun Jan 04 13:11:53 2015 -0600
260.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
260.3 @@ -1,5 +0,0 @@
260.4 -@classmethod
260.5 -@synchronized(lock)
260.6 -def foo(cls):
260.7 - pass
260.8 -
261.1 --- a/python.editor/test/unit/data/testfiles/decorators.py.scopes Sun Jan 04 13:11:53 2015 -0600
261.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
261.3 @@ -1,11 +0,0 @@
261.4 -=============================================
261.5 -<file-top>: Module : OffsetRange[0,56>
261.6 -classmethod [read][UNRESOLVED][node=Name]
261.7 -foo [bound][function][def][node=FunctionDef]
261.8 -lock [read][UNRESOLVED][node=Name]
261.9 -synchronized [read][called][UNRESOLVED][node=Name]
261.10 -
261.11 - =============================================
261.12 - foo: FunctionDef : OffsetRange[0,56>
261.13 - cls [bound][param][data][unused][node=Name]
261.14 -
262.1 --- a/python.editor/test/unit/data/testfiles/decorators.py.semantic Sun Jan 04 13:11:53 2015 -0600
262.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
262.3 @@ -1,5 +0,0 @@
262.4 -@classmethod
262.5 -@synchronized(lock)
262.6 -def |>METHOD:foo<|(|>PARAMETER,UNUSED:cls<|):
262.7 - pass
262.8 -
263.1 --- a/python.editor/test/unit/data/testfiles/decorators.py.testDecorators2.completion Sun Jan 04 13:11:53 2015 -0600
263.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
263.3 @@ -1,5 +0,0 @@
263.4 -Code completion result for source line:
263.5 -@c|lassmethod
263.6 -(QueryType=COMPLETION, NameKind=PREFIX)
263.7 -METHOD classmethod
263.8 -METHOD contextmanager
264.1 --- a/python.editor/test/unit/data/testfiles/delete.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 -# From http://www.netbeans.org/issues/show_bug.cgi?id=155586
264.5 -def test_lock():
264.6 - lck = self.lock_somehow()
264.7 - try:
264.8 - do_some_atomic_stuff()
264.9 - finally:
264.10 - del lck
264.11 -
265.1 --- a/python.editor/test/unit/data/testfiles/delete2.py Sun Jan 04 13:11:53 2015 -0600
265.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
265.3 @@ -1,6 +0,0 @@
265.4 -# From http://www.netbeans.org/issues/show_bug.cgi?id=155586
265.5 -lck = self.lock_somehow()
265.6 -try:
265.7 - do_some_atomic_stuff()
265.8 -finally:
265.9 - del lck
266.1 --- a/python.editor/test/unit/data/testfiles/delete2.py.scopes Sun Jan 04 13:11:53 2015 -0600
266.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
266.3 @@ -1,6 +0,0 @@
266.4 -=============================================
266.5 -<file-top>: Module : OffsetRange[61,137>
266.6 -do_some_atomic_stuff [read][called][UNRESOLVED][node=Name]
266.7 -lck [bound][data][read][node=Name]
266.8 -self [read][UNRESOLVED][node=Name]
266.9 -
267.1 --- a/python.editor/test/unit/data/testfiles/deprecated-imports.py Sun Jan 04 13:11:53 2015 -0600
267.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
267.3 @@ -1,56 +0,0 @@
267.4 -import cl
267.5 -import sv
267.6 -import timing
267.7 -import addpack
267.8 -import cmp
267.9 -import cmpcache
267.10 -import codehack
267.11 -import dircmp
267.12 -import dump
267.13 -import find
267.14 -import fmt
267.15 -import grep
267.16 -import lockfile
267.17 -import newdir
267.18 -import ni
267.19 -import packmail
267.20 -import Para
267.21 -import poly
267.22 -import rand
267.23 -import reconvert
267.24 -import regex
267.25 -import regsub
267.26 -import statcache
267.27 -import tb
267.28 -import tzparse
267.29 -import util
267.30 -import whatsound
267.31 -import whrandom
267.32 -import zmod
267.33 -import gopherlib
267.34 -import rgbimg
267.35 -import macfs
267.36 -
267.37 -
267.38 -import posixfile
267.39 -import gopherlib
267.40 -import rgbimgmodule
267.41 -import pre
267.42 -import whrandom
267.43 -import rfc822
267.44 -import mimetools
267.45 -import MimeWriter
267.46 -import mimify
267.47 -import rotor
267.48 -import TERMIOS.py
267.49 -import statcache
267.50 -import mpz
267.51 -import xreadlines
267.52 -import multifile
267.53 -import sets
267.54 -import buildtools
267.55 -import cfmfile
267.56 -import macfs
267.57 -import md5
267.58 -import sha
267.59 -
268.1 --- a/python.editor/test/unit/data/testfiles/deprecated-imports.py.testDeprecations.hints Sun Jan 04 13:11:53 2015 -0600
268.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
268.3 @@ -1,159 +0,0 @@
268.4 -import cl
268.5 ----------
268.6 -HINT:cl is deprecated. Listed as obsolete in the library documentation
268.7 -import sv
268.8 ----------
268.9 -HINT:sv is deprecated. Listed as obsolete in the library documentation
268.10 -import timing
268.11 --------------
268.12 -HINT:timing is deprecated. Listed as obsolete in the library documentation
268.13 -import addpack
268.14 ---------------
268.15 -HINT:addpack is deprecated. Obsolete module, removed in Python 2.5
268.16 -import cmp
268.17 -----------
268.18 -HINT:cmp is deprecated. Obsolete module, removed in Python 2.5
268.19 -import cmpcache
268.20 ----------------
268.21 -HINT:cmpcache is deprecated. Obsolete module, removed in Python 2.5
268.22 -import codehack
268.23 ----------------
268.24 -HINT:codehack is deprecated. Obsolete module, removed in Python 2.5
268.25 -import dircmp
268.26 --------------
268.27 -HINT:dircmp is deprecated. Obsolete module, removed in Python 2.5
268.28 -import dump
268.29 ------------
268.30 -HINT:dump is deprecated. Obsolete module, removed in Python 2.5
268.31 -import find
268.32 ------------
268.33 -HINT:find is deprecated. Obsolete module, removed in Python 2.5
268.34 -import fmt
268.35 -----------
268.36 -HINT:fmt is deprecated. Obsolete module, removed in Python 2.5
268.37 -import grep
268.38 ------------
268.39 -HINT:grep is deprecated. Obsolete module, removed in Python 2.5
268.40 -import lockfile
268.41 ----------------
268.42 -HINT:lockfile is deprecated. Obsolete module, removed in Python 2.5
268.43 -import newdir
268.44 --------------
268.45 -HINT:newdir is deprecated. Obsolete module, removed in Python 2.5
268.46 -import ni
268.47 ----------
268.48 -HINT:ni is deprecated. Obsolete module, removed in Python 2.5
268.49 -import packmail
268.50 ----------------
268.51 -HINT:packmail is deprecated. Obsolete module, removed in Python 2.5
268.52 -import Para
268.53 ------------
268.54 -HINT:Para is deprecated. Obsolete module, removed in Python 2.5
268.55 -import poly
268.56 ------------
268.57 -HINT:poly is deprecated. Obsolete module, removed in Python 2.5
268.58 -import rand
268.59 ------------
268.60 -HINT:rand is deprecated. Obsolete module, removed in Python 2.5
268.61 -import reconvert
268.62 -----------------
268.63 -HINT:reconvert is deprecated. Obsolete module, removed in Python 2.5
268.64 -import regex
268.65 -------------
268.66 -HINT:regex is deprecated. Obsolete module, removed in Python 2.5
268.67 -import regsub
268.68 --------------
268.69 -HINT:regsub is deprecated. Obsolete module, removed in Python 2.5
268.70 -import statcache
268.71 -----------------
268.72 -HINT:statcache is deprecated. Using the cache can be fragile and error-prone; applications should just use os.stat() directly.
268.73 -import tb
268.74 ----------
268.75 -HINT:tb is deprecated. Obsolete module, removed in Python 2.5
268.76 -import tzparse
268.77 ---------------
268.78 -HINT:tzparse is deprecated. Obsolete module, removed in Python 2.5
268.79 -import util
268.80 ------------
268.81 -HINT:util is deprecated. Obsolete module, removed in Python 2.5
268.82 -import whatsound
268.83 -----------------
268.84 -HINT:whatsound is deprecated. Obsolete module, removed in Python 2.5
268.85 -import whrandom
268.86 ----------------
268.87 -HINT:whrandom is deprecated. The module's default seed computation was inherently insecure; the random module should be used instead.
268.88 -import zmod
268.89 ------------
268.90 -HINT:zmod is deprecated. Obsolete module, removed in Python 2.5
268.91 -import gopherlib
268.92 -----------------
268.93 -HINT:gopherlib is deprecated. The gopher protocol is not in active use anymore.
268.94 -import rgbimg
268.95 --------------
268.96 -HINT:rgbimg is deprecated. Obsolete module, removed in Python 2.6
268.97 -import macfs
268.98 -------------
268.99 -HINT:macfs is deprecated
268.100 -import posixfile
268.101 -----------------
268.102 -HINT:posixfile is deprecated. Locking is better done by fcntl.lockf().
268.103 -import gopherlib
268.104 -----------------
268.105 -HINT:gopherlib is deprecated. The gopher protocol is not in active use anymore.
268.106 -import rgbimgmodule
268.107 --------------------
268.108 -HINT:rgbimgmodule is deprecated
268.109 -import pre
268.110 -----------
268.111 -HINT:pre is deprecated. The underlying PCRE engine doesn't support Unicode, and has been unmaintained since Python 1.5.2.
268.112 -import whrandom
268.113 ----------------
268.114 -HINT:whrandom is deprecated. The module's default seed computation was inherently insecure; the random module should be used instead.
268.115 -import rfc822
268.116 --------------
268.117 -HINT:rfc822 is deprecated. Supplanted by Python 2.2's email package.
268.118 -import mimetools
268.119 -----------------
268.120 -HINT:mimetools is deprecated. Supplanted by Python 2.2's email package.
268.121 -import MimeWriter
268.122 ------------------
268.123 -HINT:MimeWriter is deprecated. Supplanted by Python 2.2's email package.
268.124 -import mimify
268.125 --------------
268.126 -HINT:mimify is deprecated. Supplanted by Python 2.2's email package.
268.127 -import rotor
268.128 -------------
268.129 -HINT:rotor is deprecated. Uses insecure algorithm.
268.130 -import TERMIOS.py
268.131 ------------------
268.132 -HINT:TERMIOS.py is deprecated. The constants in this file are now in the 'termios' module.
268.133 -import statcache
268.134 -----------------
268.135 -HINT:statcache is deprecated. Using the cache can be fragile and error-prone; applications should just use os.stat() directly.
268.136 -import mpz
268.137 -----------
268.138 -HINT:mpz is deprecated. Third-party packages provide similiar features and wrap more of GMP's API.
268.139 -import xreadlines
268.140 ------------------
268.141 -HINT:xreadlines is deprecated. Using 'for line in file', introduced in 2.3, is preferable.
268.142 -import multifile
268.143 -----------------
268.144 -HINT:multifile is deprecated. Supplanted by the email package.
268.145 -import sets
268.146 ------------
268.147 -HINT:sets is deprecated. The built-in set/frozenset types, introduced in Python 2.4, supplant the module.
268.148 -import buildtools
268.149 ------------------
268.150 -HINT:buildtools is deprecated
268.151 -import cfmfile
268.152 ---------------
268.153 -HINT:cfmfile is deprecated
268.154 -import macfs
268.155 -------------
268.156 -HINT:macfs is deprecated
268.157 -import md5
268.158 -----------
268.159 -HINT:md5 is deprecated. Replaced by the 'hashlib' module.
268.160 -import sha
268.161 -----------
268.162 -HINT:sha is deprecated. Replaced by the 'hashlib' module.
269.1 --- a/python.editor/test/unit/data/testfiles/doc.py Sun Jan 04 13:11:53 2015 -0600
269.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
269.3 @@ -1,123 +0,0 @@
269.4 -"""Configuration file parser.
269.5 -
269.6 -A setup file consists of sections, lead by a "[section]" header,
269.7 -and followed by "name: value" entries, with continuations and such in
269.8 -the style of RFC 822.
269.9 -
269.10 - the same section, or values in a special [DEFAULT] section.
269.11 -
269.12 -For example:
269.13 -
269.14 - something: %(dir)s/whatever
269.15 -
269.16 -would resolve the "%(dir)s" to the value of dir. All reference
269.17 -expansions are done late, on demand.
269.18 -
269.19 -Intrinsic defaults can be specified by passing them into the
269.20 -ConfigParser constructor as a dictionary.
269.21 -
269.22 -class:
269.23 -
269.24 -ConfigParser -- responsible for parsing a list of
269.25 - configuration files, and managing the parsed database.
269.26 -
269.27 - methods:
269.28 -
269.29 - __init__(defaults=None)
269.30 - create the parser and specify a dictionary of intrinsic defaults. The
269.31 - keys must be strings, the values must be appropriate for %()s string
269.32 - interpolation. Note that `__name__' is always an intrinsic default;
269.33 - it's value is the section's name.
269.34 -
269.35 - sections()
269.36 - return all the configuration section names, sans DEFAULT
269.37 -
269.38 - has_section(section)
269.39 - return whether the given section exists
269.40 -
269.41 - has_option(section, option)
269.42 - return whether the given option exists in the given section
269.43 -
269.44 - options(section)
269.45 - return list of configuration options for the named section
269.46 -
269.47 - read(filenames)
269.48 - read and parse the list of named configuration files, given by
269.49 - name. A single filename is also allowed. Non-existing files
269.50 - are ignored.
269.51 -
269.52 - readfp(fp, filename=None)
269.53 - read and parse one configuration file, given as a file object.
269.54 - The filename defaults to fp.name; it is only used in error
269.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
269.56 -
269.57 - get(section, option, raw=False, vars=None)
269.58 - return a string value for the named option. All % interpolations are
269.59 - expanded in the return values, based on the defaults passed into the
269.60 - constructor and the DEFAULT section. Additional substitutions may be
269.61 - provided using the `vars' argument, which must be a dictionary whose
269.62 - contents override any pre-existing defaults.
269.63 -
269.64 - getint(section, options)
269.65 - like get(), but convert value to an integer
269.66 -
269.67 - getfloat(section, options)
269.68 - like get(), but convert value to a float
269.69 -
269.70 - getboolean(section, options)
269.71 - like get(), but convert value to a boolean (currently case
269.72 - insensitively defined as 0, false, no, off for False, and 1, true,
269.73 - yes, on for True). Returns False or True.
269.74 -
269.75 - items(section, raw=False, vars=None)
269.76 - return a list of tuples with (name, value) for each option
269.77 - in the section.
269.78 -
269.79 - remove_section(section)
269.80 - remove the given file section and all its options
269.81 -
269.82 - remove_option(section, option)
269.83 - remove the given option from the given section
269.84 -
269.85 - set(section, option, value)
269.86 - set the given option
269.87 -
269.88 - write(fp)
269.89 - write the configuration state in .ini format
269.90 -"""
269.91 -
269.92 -# exception classes
269.93 -class Error(Exception):
269.94 - """Base class for ConfigParser exceptions."""
269.95 -
269.96 - def readfp(self, fp, filename=None):
269.97 - """Like read() but the argument must be a file-like object.
269.98 -
269.99 - The `fp' argument must have a `readline' method. Optional
269.100 - second argument is the `filename', which if not given, is
269.101 - taken from fp.name. If fp has no `name' attribute, `<???>' is
269.102 - used.
269.103 -
269.104 - """
269.105 - if filename is None:
269.106 - try:
269.107 - filename = fp.name
269.108 - except AttributeError:
269.109 - filename = '<???>'
269.110 - self._read(fp, filename)
269.111 -
269.112 - def get(self, section, option):
269.113 - opt = self.optionxform(option)
269.114 - if section not in self._sections:
269.115 - if section != DEFAULTSECT:
269.116 - raise NoSectionError(section)
269.117 - if opt in self._defaults:
269.118 - return self._defaults[opt]
269.119 - else:
269.120 - raise NoOptionError(option, section)
269.121 - elif opt in self._sections[section]:
269.122 - return self._sections[section][opt]
269.123 - elif opt in self._defaults:
269.124 - return self._defaults[opt]
269.125 - else:
269.126 - raise NoOptionError(option, section)
270.1 --- a/python.editor/test/unit/data/testfiles/doc.py.indexed Sun Jan 04 13:11:53 2015 -0600
270.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
270.3 @@ -1,20 +0,0 @@
270.4 -
270.5 -
270.6 -Document 0
270.7 -Searchable Keys:
270.8 - class : Error
270.9 - class-ig : error
270.10 - extends : Exception
270.11 - in : doc
270.12 - member : get;F;;self,section,option;
270.13 - member : readfp;F;;self,fp,filename;
270.14 -
270.15 -Not Searchable Keys:
270.16 -
270.17 -
270.18 -Document 1
270.19 -Searchable Keys:
270.20 - item : Error;C;;
270.21 - module : doc
270.22 -
270.23 -Not Searchable Keys:
271.1 --- a/python.editor/test/unit/data/testfiles/doctest.py Sun Jan 04 13:11:53 2015 -0600
271.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
271.3 @@ -1,2637 +0,0 @@
271.4 -# Module doctest.
271.5 -# Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
271.6 -# Major enhancements and refactoring by:
271.7 -# Jim Fulton
271.8 -# Edward Loper
271.9 -
271.10 -# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
271.11 -
271.12 -r"""Module doctest -- a framework for running examples in docstrings.
271.13 -
271.14 -In simplest use, end each module M to be tested with:
271.15 -
271.16 -def _test():
271.17 - import doctest
271.18 - doctest.testmod()
271.19 -
271.20 -if __name__ == "__main__":
271.21 - _test()
271.22 -
271.23 -Then running the module as a script will cause the examples in the
271.24 -docstrings to get executed and verified:
271.25 -
271.26 -python M.py
271.27 -
271.28 -This won't display anything unless an example fails, in which case the
271.29 -failing example(s) and the cause(s) of the failure(s) are printed to stdout
271.30 -(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
271.31 -line of output is "Test failed.".
271.32 -
271.33 -Run it with the -v switch instead:
271.34 -
271.35 -python M.py -v
271.36 -
271.37 -and a detailed report of all examples tried is printed to stdout, along
271.38 -with assorted summaries at the end.
271.39 -
271.40 -You can force verbose mode by passing "verbose=True" to testmod, or prohibit
271.41 -it by passing "verbose=False". In either of those cases, sys.argv is not
271.42 -examined by testmod.
271.43 -
271.44 -There are a variety of other ways to run doctests, including integration
271.45 -with the unittest framework, and support for running non-Python text
271.46 -files containing doctests. There are also many ways to override parts
271.47 -of doctest's default behaviors. See the Library Reference Manual for
271.48 -details.
271.49 -"""
271.50 -
271.51 -__docformat__ = 'reStructuredText en'
271.52 -
271.53 -__all__ = [
271.54 - # 0, Option Flags
271.55 - 'register_optionflag',
271.56 - 'DONT_ACCEPT_TRUE_FOR_1',
271.57 - 'DONT_ACCEPT_BLANKLINE',
271.58 - 'NORMALIZE_WHITESPACE',
271.59 - 'ELLIPSIS',
271.60 - 'SKIP',
271.61 - 'IGNORE_EXCEPTION_DETAIL',
271.62 - 'COMPARISON_FLAGS',
271.63 - 'REPORT_UDIFF',
271.64 - 'REPORT_CDIFF',
271.65 - 'REPORT_NDIFF',
271.66 - 'REPORT_ONLY_FIRST_FAILURE',
271.67 - 'REPORTING_FLAGS',
271.68 - # 1. Utility Functions
271.69 - # 2. Example & DocTest
271.70 - 'Example',
271.71 - 'DocTest',
271.72 - # 3. Doctest Parser
271.73 - 'DocTestParser',
271.74 - # 4. Doctest Finder
271.75 - 'DocTestFinder',
271.76 - # 5. Doctest Runner
271.77 - 'DocTestRunner',
271.78 - 'OutputChecker',
271.79 - 'DocTestFailure',
271.80 - 'UnexpectedException',
271.81 - 'DebugRunner',
271.82 - # 6. Test Functions
271.83 - 'testmod',
271.84 - 'testfile',
271.85 - 'run_docstring_examples',
271.86 - # 7. Tester
271.87 - 'Tester',
271.88 - # 8. Unittest Support
271.89 - 'DocTestSuite',
271.90 - 'DocFileSuite',
271.91 - 'set_unittest_reportflags',
271.92 - # 9. Debugging Support
271.93 - 'script_from_examples',
271.94 - 'testsource',
271.95 - 'debug_src',
271.96 - 'debug',
271.97 -]
271.98 -
271.99 -import __future__
271.100 -
271.101 -import sys, traceback, inspect, linecache, os, re
271.102 -import unittest, difflib, pdb, tempfile
271.103 -import warnings
271.104 -from StringIO import StringIO
271.105 -
271.106 -# There are 4 basic classes:
271.107 -# - Example: a <source, want> pair, plus an intra-docstring line number.
271.108 -# - DocTest: a collection of examples, parsed from a docstring, plus
271.109 -# info about where the docstring came from (name, filename, lineno).
271.110 -# - DocTestFinder: extracts DocTests from a given object's docstring and
271.111 -# its contained objects' docstrings.
271.112 -# - DocTestRunner: runs DocTest cases, and accumulates statistics.
271.113 -#
271.114 -# So the basic picture is:
271.115 -#
271.116 -# list of:
271.117 -# +------+ +---------+ +-------+
271.118 -# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
271.119 -# +------+ +---------+ +-------+
271.120 -# | Example |
271.121 -# | ... |
271.122 -# | Example |
271.123 -# +---------+
271.124 -
271.125 -# Option constants.
271.126 -
271.127 -OPTIONFLAGS_BY_NAME = {}
271.128 -def register_optionflag(name):
271.129 - # Create a new flag unless `name` is already known.
271.130 - return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
271.131 -
271.132 -DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
271.133 -DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
271.134 -NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
271.135 -ELLIPSIS = register_optionflag('ELLIPSIS')
271.136 -SKIP = register_optionflag('SKIP')
271.137 -IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
271.138 -
271.139 -COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 |
271.140 - DONT_ACCEPT_BLANKLINE |
271.141 - NORMALIZE_WHITESPACE |
271.142 - ELLIPSIS |
271.143 - SKIP |
271.144 - IGNORE_EXCEPTION_DETAIL)
271.145 -
271.146 -REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
271.147 -REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
271.148 -REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
271.149 -REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
271.150 -
271.151 -REPORTING_FLAGS = (REPORT_UDIFF |
271.152 - REPORT_CDIFF |
271.153 - REPORT_NDIFF |
271.154 - REPORT_ONLY_FIRST_FAILURE)
271.155 -
271.156 -# Special string markers for use in `want` strings:
271.157 -BLANKLINE_MARKER = '<BLANKLINE>'
271.158 -ELLIPSIS_MARKER = '...'
271.159 -
271.160 -######################################################################
271.161 -## Table of Contents
271.162 -######################################################################
271.163 -# 1. Utility Functions
271.164 -# 2. Example & DocTest -- store test cases
271.165 -# 3. DocTest Parser -- extracts examples from strings
271.166 -# 4. DocTest Finder -- extracts test cases from objects
271.167 -# 5. DocTest Runner -- runs test cases
271.168 -# 6. Test Functions -- convenient wrappers for testing
271.169 -# 7. Tester Class -- for backwards compatibility
271.170 -# 8. Unittest Support
271.171 -# 9. Debugging Support
271.172 -# 10. Example Usage
271.173 -
271.174 -######################################################################
271.175 -## 1. Utility Functions
271.176 -######################################################################
271.177 -
271.178 -def _extract_future_flags(globs):
271.179 - """
271.180 - Return the compiler-flags associated with the future features that
271.181 - have been imported into the given namespace (globs).
271.182 - """
271.183 - flags = 0
271.184 - for fname in __future__.all_feature_names:
271.185 - feature = globs.get(fname, None)
271.186 - if feature is getattr(__future__, fname):
271.187 - flags |= feature.compiler_flag
271.188 - return flags
271.189 -
271.190 -def _normalize_module(module, depth=2):
271.191 - """
271.192 - Return the module specified by `module`. In particular:
271.193 - - If `module` is a module, then return module.
271.194 - - If `module` is a string, then import and return the
271.195 - module with that name.
271.196 - - If `module` is None, then return the calling module.
271.197 - The calling module is assumed to be the module of
271.198 - the stack frame at the given depth in the call stack.
271.199 - """
271.200 - if inspect.ismodule(module):
271.201 - return module
271.202 - elif isinstance(module, (str, unicode)):
271.203 - return __import__(module, globals(), locals(), ["*"])
271.204 - elif module is None:
271.205 - return sys.modules[sys._getframe(depth).f_globals['__name__']]
271.206 - else:
271.207 - raise TypeError("Expected a module, string, or None")
271.208 -
271.209 -def _load_testfile(filename, package, module_relative):
271.210 - if module_relative:
271.211 - package = _normalize_module(package, 3)
271.212 - filename = _module_relative_path(package, filename)
271.213 - if hasattr(package, '__loader__'):
271.214 - if hasattr(package.__loader__, 'get_data'):
271.215 - return package.__loader__.get_data(filename), filename
271.216 - return open(filename).read(), filename
271.217 -
271.218 -def _indent(s, indent=4):
271.219 - """
271.220 - Add the given number of space characters to the beginning every
271.221 - non-blank line in `s`, and return the result.
271.222 - """
271.223 - # This regexp matches the start of non-blank lines:
271.224 - return re.sub('(?m)^(?!$)', indent*' ', s)
271.225 -
271.226 -def _exception_traceback(exc_info):
271.227 - """
271.228 - Return a string containing a traceback message for the given
271.229 - exc_info tuple (as returned by sys.exc_info()).
271.230 - """
271.231 - # Get a traceback message.
271.232 - excout = StringIO()
271.233 - exc_type, exc_val, exc_tb = exc_info
271.234 - traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
271.235 - return excout.getvalue()
271.236 -
271.237 -# Override some StringIO methods.
271.238 -class _SpoofOut(StringIO):
271.239 - def getvalue(self):
271.240 - result = StringIO.getvalue(self)
271.241 - # If anything at all was written, make sure there's a trailing
271.242 - # newline. There's no way for the expected output to indicate
271.243 - # that a trailing newline is missing.
271.244 - if result and not result.endswith("\n"):
271.245 - result += "\n"
271.246 - # Prevent softspace from screwing up the next test case, in
271.247 - # case they used print with a trailing comma in an example.
271.248 - if hasattr(self, "softspace"):
271.249 - del self.softspace
271.250 - return result
271.251 -
271.252 - def truncate(self, size=None):
271.253 - StringIO.truncate(self, size)
271.254 - if hasattr(self, "softspace"):
271.255 - del self.softspace
271.256 -
271.257 -# Worst-case linear-time ellipsis matching.
271.258 -def _ellipsis_match(want, got):
271.259 - """
271.260 - Essentially the only subtle case:
271.261 - >>> _ellipsis_match('aa...aa', 'aaa')
271.262 - False
271.263 - """
271.264 - if ELLIPSIS_MARKER not in want:
271.265 - return want == got
271.266 -
271.267 - # Find "the real" strings.
271.268 - ws = want.split(ELLIPSIS_MARKER)
271.269 - assert len(ws) >= 2
271.270 -
271.271 - # Deal with exact matches possibly needed at one or both ends.
271.272 - startpos, endpos = 0, len(got)
271.273 - w = ws[0]
271.274 - if w: # starts with exact match
271.275 - if got.startswith(w):
271.276 - startpos = len(w)
271.277 - del ws[0]
271.278 - else:
271.279 - return False
271.280 - w = ws[-1]
271.281 - if w: # ends with exact match
271.282 - if got.endswith(w):
271.283 - endpos -= len(w)
271.284 - del ws[-1]
271.285 - else:
271.286 - return False
271.287 -
271.288 - if startpos > endpos:
271.289 - # Exact end matches required more characters than we have, as in
271.290 - # _ellipsis_match('aa...aa', 'aaa')
271.291 - return False
271.292 -
271.293 - # For the rest, we only need to find the leftmost non-overlapping
271.294 - # match for each piece. If there's no overall match that way alone,
271.295 - # there's no overall match period.
271.296 - for w in ws:
271.297 - # w may be '' at times, if there are consecutive ellipses, or
271.298 - # due to an ellipsis at the start or end of `want`. That's OK.
271.299 - # Search for an empty string succeeds, and doesn't change startpos.
271.300 - startpos = got.find(w, startpos, endpos)
271.301 - if startpos < 0:
271.302 - return False
271.303 - startpos += len(w)
271.304 -
271.305 - return True
271.306 -
271.307 -def _comment_line(line):
271.308 - "Return a commented form of the given line"
271.309 - line = line.rstrip()
271.310 - if line:
271.311 - return '# '+line
271.312 - else:
271.313 - return '#'
271.314 -
271.315 -class _OutputRedirectingPdb(pdb.Pdb):
271.316 - """
271.317 - A specialized version of the python debugger that redirects stdout
271.318 - to a given stream when interacting with the user. Stdout is *not*
271.319 - redirected when traced code is executed.
271.320 - """
271.321 - def __init__(self, out):
271.322 - self.__out = out
271.323 - pdb.Pdb.__init__(self, stdout=out)
271.324 -
271.325 - def trace_dispatch(self, *args):
271.326 - # Redirect stdout to the given stream.
271.327 - save_stdout = sys.stdout
271.328 - sys.stdout = self.__out
271.329 - # Call Pdb's trace dispatch method.
271.330 - try:
271.331 - return pdb.Pdb.trace_dispatch(self, *args)
271.332 - finally:
271.333 - sys.stdout = save_stdout
271.334 -
271.335 -# [XX] Normalize with respect to os.path.pardir?
271.336 -def _module_relative_path(module, path):
271.337 - if not inspect.ismodule(module):
271.338 - raise TypeError, 'Expected a module: %r' % module
271.339 - if path.startswith('/'):
271.340 - raise ValueError, 'Module-relative files may not have absolute paths'
271.341 -
271.342 - # Find the base directory for the path.
271.343 - if hasattr(module, '__file__'):
271.344 - # A normal module/package
271.345 - basedir = os.path.split(module.__file__)[0]
271.346 - elif module.__name__ == '__main__':
271.347 - # An interactive session.
271.348 - if len(sys.argv)>0 and sys.argv[0] != '':
271.349 - basedir = os.path.split(sys.argv[0])[0]
271.350 - else:
271.351 - basedir = os.curdir
271.352 - else:
271.353 - # A module w/o __file__ (this includes builtins)
271.354 - raise ValueError("Can't resolve paths relative to the module " +
271.355 - module + " (it has no __file__)")
271.356 -
271.357 - # Combine the base directory and the path.
271.358 - return os.path.join(basedir, *(path.split('/')))
271.359 -
271.360 -######################################################################
271.361 -## 2. Example & DocTest
271.362 -######################################################################
271.363 -## - An "example" is a <source, want> pair, where "source" is a
271.364 -## fragment of source code, and "want" is the expected output for
271.365 -## "source." The Example class also includes information about
271.366 -## where the example was extracted from.
271.367 -##
271.368 -## - A "doctest" is a collection of examples, typically extracted from
271.369 -## a string (such as an object's docstring). The DocTest class also
271.370 -## includes information about where the string was extracted from.
271.371 -
271.372 -class Example:
271.373 - """
271.374 - A single doctest example, consisting of source code and expected
271.375 - output. `Example` defines the following attributes:
271.376 -
271.377 - - source: A single Python statement, always ending with a newline.
271.378 - The constructor adds a newline if needed.
271.379 -
271.380 - - want: The expected output from running the source code (either
271.381 - from stdout, or a traceback in case of exception). `want` ends
271.382 - with a newline unless it's empty, in which case it's an empty
271.383 - string. The constructor adds a newline if needed.
271.384 -
271.385 - - exc_msg: The exception message generated by the example, if
271.386 - the example is expected to generate an exception; or `None` if
271.387 - it is not expected to generate an exception. This exception
271.388 - message is compared against the return value of
271.389 - `traceback.format_exception_only()`. `exc_msg` ends with a
271.390 - newline unless it's `None`. The constructor adds a newline
271.391 - if needed.
271.392 -
271.393 - - lineno: The line number within the DocTest string containing
271.394 - this Example where the Example begins. This line number is
271.395 - zero-based, with respect to the beginning of the DocTest.
271.396 -
271.397 - - indent: The example's indentation in the DocTest string.
271.398 - I.e., the number of space characters that preceed the
271.399 - example's first prompt.
271.400 -
271.401 - - options: A dictionary mapping from option flags to True or
271.402 - False, which is used to override default options for this
271.403 - example. Any option flags not contained in this dictionary
271.404 - are left at their default value (as specified by the
271.405 - DocTestRunner's optionflags). By default, no options are set.
271.406 - """
271.407 - def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
271.408 - options=None):
271.409 - # Normalize inputs.
271.410 - if not source.endswith('\n'):
271.411 - source += '\n'
271.412 - if want and not want.endswith('\n'):
271.413 - want += '\n'
271.414 - if exc_msg is not None and not exc_msg.endswith('\n'):
271.415 - exc_msg += '\n'
271.416 - # Store properties.
271.417 - self.source = source
271.418 - self.want = want
271.419 - self.lineno = lineno
271.420 - self.indent = indent
271.421 - if options is None: options = {}
271.422 - self.options = options
271.423 - self.exc_msg = exc_msg
271.424 -
271.425 -class DocTest:
271.426 - """
271.427 - A collection of doctest examples that should be run in a single
271.428 - namespace. Each `DocTest` defines the following attributes:
271.429 -
271.430 - - examples: the list of examples.
271.431 -
271.432 - - globs: The namespace (aka globals) that the examples should
271.433 - be run in.
271.434 -
271.435 - - name: A name identifying the DocTest (typically, the name of
271.436 - the object whose docstring this DocTest was extracted from).
271.437 -
271.438 - - filename: The name of the file that this DocTest was extracted
271.439 - from, or `None` if the filename is unknown.
271.440 -
271.441 - - lineno: The line number within filename where this DocTest
271.442 - begins, or `None` if the line number is unavailable. This
271.443 - line number is zero-based, with respect to the beginning of
271.444 - the file.
271.445 -
271.446 - - docstring: The string that the examples were extracted from,
271.447 - or `None` if the string is unavailable.
271.448 - """
271.449 - def __init__(self, examples, globs, name, filename, lineno, docstring):
271.450 - """
271.451 - Create a new DocTest containing the given examples. The
271.452 - DocTest's globals are initialized with a copy of `globs`.
271.453 - """
271.454 - assert not isinstance(examples, basestring), \
271.455 - "DocTest no longer accepts str; use DocTestParser instead"
271.456 - self.examples = examples
271.457 - self.docstring = docstring
271.458 - self.globs = globs.copy()
271.459 - self.name = name
271.460 - self.filename = filename
271.461 - self.lineno = lineno
271.462 -
271.463 - def __repr__(self):
271.464 - if len(self.examples) == 0:
271.465 - examples = 'no examples'
271.466 - elif len(self.examples) == 1:
271.467 - examples = '1 example'
271.468 - else:
271.469 - examples = '%d examples' % len(self.examples)
271.470 - return ('<DocTest %s from %s:%s (%s)>' %
271.471 - (self.name, self.filename, self.lineno, examples))
271.472 -
271.473 -
271.474 - # This lets us sort tests by name:
271.475 - def __cmp__(self, other):
271.476 - if not isinstance(other, DocTest):
271.477 - return -1
271.478 - return cmp((self.name, self.filename, self.lineno, id(self)),
271.479 - (other.name, other.filename, other.lineno, id(other)))
271.480 -
271.481 -######################################################################
271.482 -## 3. DocTestParser
271.483 -######################################################################
271.484 -
271.485 -class DocTestParser:
271.486 - """
271.487 - A class used to parse strings containing doctest examples.
271.488 - """
271.489 - # This regular expression is used to find doctest examples in a
271.490 - # string. It defines three groups: `source` is the source code
271.491 - # (including leading indentation and prompts); `indent` is the
271.492 - # indentation of the first (PS1) line of the source code; and
271.493 - # `want` is the expected output (including leading indentation).
271.494 - _EXAMPLE_RE = re.compile(r'''
271.495 - # Source consists of a PS1 line followed by zero or more PS2 lines.
271.496 - (?P<source>
271.497 - (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
271.498 - (?:\n [ ]* \.\.\. .*)*) # PS2 lines
271.499 - \n?
271.500 - # Want consists of any non-blank lines that do not start with PS1.
271.501 - (?P<want> (?:(?![ ]*$) # Not a blank line
271.502 - (?![ ]*>>>) # Not a line starting with PS1
271.503 - .*$\n? # But any other line
271.504 - )*)
271.505 - ''', re.MULTILINE | re.VERBOSE)
271.506 -
271.507 - # A regular expression for handling `want` strings that contain
271.508 - # expected exceptions. It divides `want` into three pieces:
271.509 - # - the traceback header line (`hdr`)
271.510 - # - the traceback stack (`stack`)
271.511 - # - the exception message (`msg`), as generated by
271.512 - # traceback.format_exception_only()
271.513 - # `msg` may have multiple lines. We assume/require that the
271.514 - # exception message is the first non-indented line starting with a word
271.515 - # character following the traceback header line.
271.516 - _EXCEPTION_RE = re.compile(r"""
271.517 - # Grab the traceback header. Different versions of Python have
271.518 - # said different things on the first traceback line.
271.519 - ^(?P<hdr> Traceback\ \(
271.520 - (?: most\ recent\ call\ last
271.521 - | innermost\ last
271.522 - ) \) :
271.523 - )
271.524 - \s* $ # toss trailing whitespace on the header.
271.525 - (?P<stack> .*?) # don't blink: absorb stuff until...
271.526 - ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
271.527 - """, re.VERBOSE | re.MULTILINE | re.DOTALL)
271.528 -
271.529 - # A callable returning a true value iff its argument is a blank line
271.530 - # or contains a single comment.
271.531 - _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
271.532 -
271.533 - def parse(self, string, name='<string>'):
271.534 - """
271.535 - Divide the given string into examples and intervening text,
271.536 - and return them as a list of alternating Examples and strings.
271.537 - Line numbers for the Examples are 0-based. The optional
271.538 - argument `name` is a name identifying this string, and is only
271.539 - used for error messages.
271.540 - """
271.541 - string = string.expandtabs()
271.542 - # If all lines begin with the same indentation, then strip it.
271.543 - min_indent = self._min_indent(string)
271.544 - if min_indent > 0:
271.545 - string = '\n'.join([l[min_indent:] for l in string.split('\n')])
271.546 -
271.547 - output = []
271.548 - charno, lineno = 0, 0
271.549 - # Find all doctest examples in the string:
271.550 - for m in self._EXAMPLE_RE.finditer(string):
271.551 - # Add the pre-example text to `output`.
271.552 - output.append(string[charno:m.start()])
271.553 - # Update lineno (lines before this example)
271.554 - lineno += string.count('\n', charno, m.start())
271.555 - # Extract info from the regexp match.
271.556 - (source, options, want, exc_msg) = \
271.557 - self._parse_example(m, name, lineno)
271.558 - # Create an Example, and add it to the list.
271.559 - if not self._IS_BLANK_OR_COMMENT(source):
271.560 - output.append( Example(source, want, exc_msg,
271.561 - lineno=lineno,
271.562 - indent=min_indent+len(m.group('indent')),
271.563 - options=options) )
271.564 - # Update lineno (lines inside this example)
271.565 - lineno += string.count('\n', m.start(), m.end())
271.566 - # Update charno.
271.567 - charno = m.end()
271.568 - # Add any remaining post-example text to `output`.
271.569 - output.append(string[charno:])
271.570 - return output
271.571 -
271.572 - def get_doctest(self, string, globs, name, filename, lineno):
271.573 - """
271.574 - Extract all doctest examples from the given string, and
271.575 - collect them into a `DocTest` object.
271.576 -
271.577 - `globs`, `name`, `filename`, and `lineno` are attributes for
271.578 - the new `DocTest` object. See the documentation for `DocTest`
271.579 - for more information.
271.580 - """
271.581 - return DocTest(self.get_examples(string, name), globs,
271.582 - name, filename, lineno, string)
271.583 -
271.584 - def get_examples(self, string, name='<string>'):
271.585 - """
271.586 - Extract all doctest examples from the given string, and return
271.587 - them as a list of `Example` objects. Line numbers are
271.588 - 0-based, because it's most common in doctests that nothing
271.589 - interesting appears on the same line as opening triple-quote,
271.590 - and so the first interesting line is called \"line 1\" then.
271.591 -
271.592 - The optional argument `name` is a name identifying this
271.593 - string, and is only used for error messages.
271.594 - """
271.595 - return [x for x in self.parse(string, name)
271.596 - if isinstance(x, Example)]
271.597 -
271.598 - def _parse_example(self, m, name, lineno):
271.599 - """
271.600 - Given a regular expression match from `_EXAMPLE_RE` (`m`),
271.601 - return a pair `(source, want)`, where `source` is the matched
271.602 - example's source code (with prompts and indentation stripped);
271.603 - and `want` is the example's expected output (with indentation
271.604 - stripped).
271.605 -
271.606 - `name` is the string's name, and `lineno` is the line number
271.607 - where the example starts; both are used for error messages.
271.608 - """
271.609 - # Get the example's indentation level.
271.610 - indent = len(m.group('indent'))
271.611 -
271.612 - # Divide source into lines; check that they're properly
271.613 - # indented; and then strip their indentation & prompts.
271.614 - source_lines = m.group('source').split('\n')
271.615 - self._check_prompt_blank(source_lines, indent, name, lineno)
271.616 - self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
271.617 - source = '\n'.join([sl[indent+4:] for sl in source_lines])
271.618 -
271.619 - # Divide want into lines; check that it's properly indented; and
271.620 - # then strip the indentation. Spaces before the last newline should
271.621 - # be preserved, so plain rstrip() isn't good enough.
271.622 - want = m.group('want')
271.623 - want_lines = want.split('\n')
271.624 - if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
271.625 - del want_lines[-1] # forget final newline & spaces after it
271.626 - self._check_prefix(want_lines, ' '*indent, name,
271.627 - lineno + len(source_lines))
271.628 - want = '\n'.join([wl[indent:] for wl in want_lines])
271.629 -
271.630 - # If `want` contains a traceback message, then extract it.
271.631 - m = self._EXCEPTION_RE.match(want)
271.632 - if m:
271.633 - exc_msg = m.group('msg')
271.634 - else:
271.635 - exc_msg = None
271.636 -
271.637 - # Extract options from the source.
271.638 - options = self._find_options(source, name, lineno)
271.639 -
271.640 - return source, options, want, exc_msg
271.641 -
271.642 - # This regular expression looks for option directives in the
271.643 - # source code of an example. Option directives are comments
271.644 - # starting with "doctest:". Warning: this may give false
271.645 - # positives for string-literals that contain the string
271.646 - # "#doctest:". Eliminating these false positives would require
271.647 - # actually parsing the string; but we limit them by ignoring any
271.648 - # line containing "#doctest:" that is *followed* by a quote mark.
271.649 - _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
271.650 - re.MULTILINE)
271.651 -
271.652 - def _find_options(self, source, name, lineno):
271.653 - """
271.654 - Return a dictionary containing option overrides extracted from
271.655 - option directives in the given source string.
271.656 -
271.657 - `name` is the string's name, and `lineno` is the line number
271.658 - where the example starts; both are used for error messages.
271.659 - """
271.660 - options = {}
271.661 - # (note: with the current regexp, this will match at most once:)
271.662 - for m in self._OPTION_DIRECTIVE_RE.finditer(source):
271.663 - option_strings = m.group(1).replace(',', ' ').split()
271.664 - for option in option_strings:
271.665 - if (option[0] not in '+-' or
271.666 - option[1:] not in OPTIONFLAGS_BY_NAME):
271.667 - raise ValueError('line %r of the doctest for %s '
271.668 - 'has an invalid option: %r' %
271.669 - (lineno+1, name, option))
271.670 - flag = OPTIONFLAGS_BY_NAME[option[1:]]
271.671 - options[flag] = (option[0] == '+')
271.672 - if options and self._IS_BLANK_OR_COMMENT(source):
271.673 - raise ValueError('line %r of the doctest for %s has an option '
271.674 - 'directive on a line with no example: %r' %
271.675 - (lineno, name, source))
271.676 - return options
271.677 -
271.678 - # This regular expression finds the indentation of every non-blank
271.679 - # line in a string.
271.680 - _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
271.681 -
271.682 - def _min_indent(self, s):
271.683 - "Return the minimum indentation of any non-blank line in `s`"
271.684 - indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
271.685 - if len(indents) > 0:
271.686 - return min(indents)
271.687 - else:
271.688 - return 0
271.689 -
271.690 - def _check_prompt_blank(self, lines, indent, name, lineno):
271.691 - """
271.692 - Given the lines of a source string (including prompts and
271.693 - leading indentation), check to make sure that every prompt is
271.694 - followed by a space character. If any line is not followed by
271.695 - a space character, then raise ValueError.
271.696 - """
271.697 - for i, line in enumerate(lines):
271.698 - if len(line) >= indent+4 and line[indent+3] != ' ':
271.699 - raise ValueError('line %r of the docstring for %s '
271.700 - 'lacks blank after %s: %r' %
271.701 - (lineno+i+1, name,
271.702 - line[indent:indent+3], line))
271.703 -
271.704 - def _check_prefix(self, lines, prefix, name, lineno):
271.705 - """
271.706 - Check that every line in the given list starts with the given
271.707 - prefix; if any line does not, then raise a ValueError.
271.708 - """
271.709 - for i, line in enumerate(lines):
271.710 - if line and not line.startswith(prefix):
271.711 - raise ValueError('line %r of the docstring for %s has '
271.712 - 'inconsistent leading whitespace: %r' %
271.713 - (lineno+i+1, name, line))
271.714 -
271.715 -
271.716 -######################################################################
271.717 -## 4. DocTest Finder
271.718 -######################################################################
271.719 -
271.720 -class DocTestFinder:
271.721 - """
271.722 - A class used to extract the DocTests that are relevant to a given
271.723 - object, from its docstring and the docstrings of its contained
271.724 - objects. Doctests can currently be extracted from the following
271.725 - object types: modules, functions, classes, methods, staticmethods,
271.726 - classmethods, and properties.
271.727 - """
271.728 -
271.729 - def __init__(self, verbose=False, parser=DocTestParser(),
271.730 - recurse=True, exclude_empty=True):
271.731 - """
271.732 - Create a new doctest finder.
271.733 -
271.734 - The optional argument `parser` specifies a class or
271.735 - function that should be used to create new DocTest objects (or
271.736 - objects that implement the same interface as DocTest). The
271.737 - signature for this factory function should match the signature
271.738 - of the DocTest constructor.
271.739 -
271.740 - If the optional argument `recurse` is false, then `find` will
271.741 - only examine the given object, and not any contained objects.
271.742 -
271.743 - If the optional argument `exclude_empty` is false, then `find`
271.744 - will include tests for objects with empty docstrings.
271.745 - """
271.746 - self._parser = parser
271.747 - self._verbose = verbose
271.748 - self._recurse = recurse
271.749 - self._exclude_empty = exclude_empty
271.750 -
271.751 - def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
271.752 - """
271.753 - Return a list of the DocTests that are defined by the given
271.754 - object's docstring, or by any of its contained objects'
271.755 - docstrings.
271.756 -
271.757 - The optional parameter `module` is the module that contains
271.758 - the given object. If the module is not specified or is None, then
271.759 - the test finder will attempt to automatically determine the
271.760 - correct module. The object's module is used:
271.761 -
271.762 - - As a default namespace, if `globs` is not specified.
271.763 - - To prevent the DocTestFinder from extracting DocTests
271.764 - from objects that are imported from other modules.
271.765 - - To find the name of the file containing the object.
271.766 - - To help find the line number of the object within its
271.767 - file.
271.768 -
271.769 - Contained objects whose module does not match `module` are ignored.
271.770 -
271.771 - If `module` is False, no attempt to find the module will be made.
271.772 - This is obscure, of use mostly in tests: if `module` is False, or
271.773 - is None but cannot be found automatically, then all objects are
271.774 - considered to belong to the (non-existent) module, so all contained
271.775 - objects will (recursively) be searched for doctests.
271.776 -
271.777 - The globals for each DocTest is formed by combining `globs`
271.778 - and `extraglobs` (bindings in `extraglobs` override bindings
271.779 - in `globs`). A new copy of the globals dictionary is created
271.780 - for each DocTest. If `globs` is not specified, then it
271.781 - defaults to the module's `__dict__`, if specified, or {}
271.782 - otherwise. If `extraglobs` is not specified, then it defaults
271.783 - to {}.
271.784 -
271.785 - """
271.786 - # If name was not specified, then extract it from the object.
271.787 - if name is None:
271.788 - name = getattr(obj, '__name__', None)
271.789 - if name is None:
271.790 - raise ValueError("DocTestFinder.find: name must be given "
271.791 - "when obj.__name__ doesn't exist: %r" %
271.792 - (type(obj),))
271.793 -
271.794 - # Find the module that contains the given object (if obj is
271.795 - # a module, then module=obj.). Note: this may fail, in which
271.796 - # case module will be None.
271.797 - if module is False:
271.798 - module = None
271.799 - elif module is None:
271.800 - module = inspect.getmodule(obj)
271.801 -
271.802 - # Read the module's source code. This is used by
271.803 - # DocTestFinder._find_lineno to find the line number for a
271.804 - # given object's docstring.
271.805 - try:
271.806 - file = inspect.getsourcefile(obj) or inspect.getfile(obj)
271.807 - source_lines = linecache.getlines(file)
271.808 - if not source_lines:
271.809 - source_lines = None
271.810 - except TypeError:
271.811 - source_lines = None
271.812 -
271.813 - # Initialize globals, and merge in extraglobs.
271.814 - if globs is None:
271.815 - if module is None:
271.816 - globs = {}
271.817 - else:
271.818 - globs = module.__dict__.copy()
271.819 - else:
271.820 - globs = globs.copy()
271.821 - if extraglobs is not None:
271.822 - globs.update(extraglobs)
271.823 -
271.824 - # Recursively expore `obj`, extracting DocTests.
271.825 - tests = []
271.826 - self._find(tests, obj, name, module, source_lines, globs, {})
271.827 - # Sort the tests by alpha order of names, for consistency in
271.828 - # verbose-mode output. This was a feature of doctest in Pythons
271.829 - # <= 2.3 that got lost by accident in 2.4. It was repaired in
271.830 - # 2.4.4 and 2.5.
271.831 - tests.sort()
271.832 - return tests
271.833 -
271.834 - def _from_module(self, module, object):
271.835 - """
271.836 - Return true if the given object is defined in the given
271.837 - module.
271.838 - """
271.839 - if module is None:
271.840 - return True
271.841 - elif inspect.isfunction(object):
271.842 - return module.__dict__ is object.func_globals
271.843 - elif inspect.isclass(object):
271.844 - return module.__name__ == object.__module__
271.845 - elif inspect.getmodule(object) is not None:
271.846 - return module is inspect.getmodule(object)
271.847 - elif hasattr(object, '__module__'):
271.848 - return module.__name__ == object.__module__
271.849 - elif isinstance(object, property):
271.850 - return True # [XX] no way not be sure.
271.851 - else:
271.852 - raise ValueError("object must be a class or function")
271.853 -
271.854 - def _find(self, tests, obj, name, module, source_lines, globs, seen):
271.855 - """
271.856 - Find tests for the given object and any contained objects, and
271.857 - add them to `tests`.
271.858 - """
271.859 - if self._verbose:
271.860 - print 'Finding tests in %s' % name
271.861 -
271.862 - # If we've already processed this object, then ignore it.
271.863 - if id(obj) in seen:
271.864 - return
271.865 - seen[id(obj)] = 1
271.866 -
271.867 - # Find a test for this object, and add it to the list of tests.
271.868 - test = self._get_test(obj, name, module, globs, source_lines)
271.869 - if test is not None:
271.870 - tests.append(test)
271.871 -
271.872 - # Look for tests in a module's contained objects.
271.873 - if inspect.ismodule(obj) and self._recurse:
271.874 - for valname, val in obj.__dict__.items():
271.875 - valname = '%s.%s' % (name, valname)
271.876 - # Recurse to functions & classes.
271.877 - if ((inspect.isfunction(val) or inspect.isclass(val)) and
271.878 - self._from_module(module, val)):
271.879 - self._find(tests, val, valname, module, source_lines,
271.880 - globs, seen)
271.881 -
271.882 - # Look for tests in a module's __test__ dictionary.
271.883 - if inspect.ismodule(obj) and self._recurse:
271.884 - for valname, val in getattr(obj, '__test__', {}).items():
271.885 - if not isinstance(valname, basestring):
271.886 - raise ValueError("DocTestFinder.find: __test__ keys "
271.887 - "must be strings: %r" %
271.888 - (type(valname),))
271.889 - if not (inspect.isfunction(val) or inspect.isclass(val) or
271.890 - inspect.ismethod(val) or inspect.ismodule(val) or
271.891 - isinstance(val, basestring)):
271.892 - raise ValueError("DocTestFinder.find: __test__ values "
271.893 - "must be strings, functions, methods, "
271.894 - "classes, or modules: %r" %
271.895 - (type(val),))
271.896 - valname = '%s.__test__.%s' % (name, valname)
271.897 - self._find(tests, val, valname, module, source_lines,
271.898 - globs, seen)
271.899 -
271.900 - # Look for tests in a class's contained objects.
271.901 - if inspect.isclass(obj) and self._recurse:
271.902 - for valname, val in obj.__dict__.items():
271.903 - # Special handling for staticmethod/classmethod.
271.904 - if isinstance(val, staticmethod):
271.905 - val = getattr(obj, valname)
271.906 - if isinstance(val, classmethod):
271.907 - val = getattr(obj, valname).im_func
271.908 -
271.909 - # Recurse to methods, properties, and nested classes.
271.910 - if ((inspect.isfunction(val) or inspect.isclass(val) or
271.911 - isinstance(val, property)) and
271.912 - self._from_module(module, val)):
271.913 - valname = '%s.%s' % (name, valname)
271.914 - self._find(tests, val, valname, module, source_lines,
271.915 - globs, seen)
271.916 -
271.917 - def _get_test(self, obj, name, module, globs, source_lines):
271.918 - """
271.919 - Return a DocTest for the given object, if it defines a docstring;
271.920 - otherwise, return None.
271.921 - """
271.922 - # Extract the object's docstring. If it doesn't have one,
271.923 - # then return None (no test for this object).
271.924 - if isinstance(obj, basestring):
271.925 - docstring = obj
271.926 - else:
271.927 - try:
271.928 - if obj.__doc__ is None:
271.929 - docstring = ''
271.930 - else:
271.931 - docstring = obj.__doc__
271.932 - if not isinstance(docstring, basestring):
271.933 - docstring = str(docstring)
271.934 - except (TypeError, AttributeError):
271.935 - docstring = ''
271.936 -
271.937 - # Find the docstring's location in the file.
271.938 - lineno = self._find_lineno(obj, source_lines)
271.939 -
271.940 - # Don't bother if the docstring is empty.
271.941 - if self._exclude_empty and not docstring:
271.942 - return None
271.943 -
271.944 - # Return a DocTest for this object.
271.945 - if module is None:
271.946 - filename = None
271.947 - else:
271.948 - filename = getattr(module, '__file__', module.__name__)
271.949 - if filename[-4:] in (".pyc", ".pyo"):
271.950 - filename = filename[:-1]
271.951 - return self._parser.get_doctest(docstring, globs, name,
271.952 - filename, lineno)
271.953 -
271.954 - def _find_lineno(self, obj, source_lines):
271.955 - """
271.956 - Return a line number of the given object's docstring. Note:
271.957 - this method assumes that the object has a docstring.
271.958 - """
271.959 - lineno = None
271.960 -
271.961 - # Find the line number for modules.
271.962 - if inspect.ismodule(obj):
271.963 - lineno = 0
271.964 -
271.965 - # Find the line number for classes.
271.966 - # Note: this could be fooled if a class is defined multiple
271.967 - # times in a single file.
271.968 - if inspect.isclass(obj):
271.969 - if source_lines is None:
271.970 - return None
271.971 - pat = re.compile(r'^\s*class\s*%s\b' %
271.972 - getattr(obj, '__name__', '-'))
271.973 - for i, line in enumerate(source_lines):
271.974 - if pat.match(line):
271.975 - lineno = i
271.976 - break
271.977 -
271.978 - # Find the line number for functions & methods.
271.979 - if inspect.ismethod(obj): obj = obj.im_func
271.980 - if inspect.isfunction(obj): obj = obj.func_code
271.981 - if inspect.istraceback(obj): obj = obj.tb_frame
271.982 - if inspect.isframe(obj): obj = obj.f_code
271.983 - if inspect.iscode(obj):
271.984 - lineno = getattr(obj, 'co_firstlineno', None)-1
271.985 -
271.986 - # Find the line number where the docstring starts. Assume
271.987 - # that it's the first line that begins with a quote mark.
271.988 - # Note: this could be fooled by a multiline function
271.989 - # signature, where a continuation line begins with a quote
271.990 - # mark.
271.991 - if lineno is not None:
271.992 - if source_lines is None:
271.993 - return lineno+1
271.994 - pat = re.compile('(^|.*:)\s*\w*("|\')')
271.995 - for lineno in range(lineno, len(source_lines)):
271.996 - if pat.match(source_lines[lineno]):
271.997 - return lineno
271.998 -
271.999 - # We couldn't find the line number.
271.1000 - return None
271.1001 -
271.1002 -######################################################################
271.1003 -## 5. DocTest Runner
271.1004 -######################################################################
271.1005 -
271.1006 -class DocTestRunner:
271.1007 - """
271.1008 - A class used to run DocTest test cases, and accumulate statistics.
271.1009 - The `run` method is used to process a single DocTest case. It
271.1010 - returns a tuple `(f, t)`, where `t` is the number of test cases
271.1011 - tried, and `f` is the number of test cases that failed.
271.1012 -
271.1013 - >>> tests = DocTestFinder().find(_TestClass)
271.1014 - >>> runner = DocTestRunner(verbose=False)
271.1015 - >>> tests.sort(key = lambda test: test.name)
271.1016 - >>> for test in tests:
271.1017 - ... print test.name, '->', runner.run(test)
271.1018 - _TestClass -> (0, 2)
271.1019 - _TestClass.__init__ -> (0, 2)
271.1020 - _TestClass.get -> (0, 2)
271.1021 - _TestClass.square -> (0, 1)
271.1022 -
271.1023 - The `summarize` method prints a summary of all the test cases that
271.1024 - have been run by the runner, and returns an aggregated `(f, t)`
271.1025 - tuple:
271.1026 -
271.1027 - >>> runner.summarize(verbose=1)
271.1028 - 4 items passed all tests:
271.1029 - 2 tests in _TestClass
271.1030 - 2 tests in _TestClass.__init__
271.1031 - 2 tests in _TestClass.get
271.1032 - 1 tests in _TestClass.square
271.1033 - 7 tests in 4 items.
271.1034 - 7 passed and 0 failed.
271.1035 - Test passed.
271.1036 - (0, 7)
271.1037 -
271.1038 - The aggregated number of tried examples and failed examples is
271.1039 - also available via the `tries` and `failures` attributes:
271.1040 -
271.1041 - >>> runner.tries
271.1042 - 7
271.1043 - >>> runner.failures
271.1044 - 0
271.1045 -
271.1046 - The comparison between expected outputs and actual outputs is done
271.1047 - by an `OutputChecker`. This comparison may be customized with a
271.1048 - number of option flags; see the documentation for `testmod` for
271.1049 - more information. If the option flags are insufficient, then the
271.1050 - comparison may also be customized by passing a subclass of
271.1051 - `OutputChecker` to the constructor.
271.1052 -
271.1053 - The test runner's display output can be controlled in two ways.
271.1054 - First, an output function (`out) can be passed to
271.1055 - `TestRunner.run`; this function will be called with strings that
271.1056 - should be displayed. It defaults to `sys.stdout.write`. If
271.1057 - capturing the output is not sufficient, then the display output
271.1058 - can be also customized by subclassing DocTestRunner, and
271.1059 - overriding the methods `report_start`, `report_success`,
271.1060 - `report_unexpected_exception`, and `report_failure`.
271.1061 - """
271.1062 - # This divider string is used to separate failure messages, and to
271.1063 - # separate sections of the summary.
271.1064 - DIVIDER = "*" * 70
271.1065 -
271.1066 - def __init__(self, checker=None, verbose=None, optionflags=0):
271.1067 - """
271.1068 - Create a new test runner.
271.1069 -
271.1070 - Optional keyword arg `checker` is the `OutputChecker` that
271.1071 - should be used to compare the expected outputs and actual
271.1072 - outputs of doctest examples.
271.1073 -
271.1074 - Optional keyword arg 'verbose' prints lots of stuff if true,
271.1075 - only failures if false; by default, it's true iff '-v' is in
271.1076 - sys.argv.
271.1077 -
271.1078 - Optional argument `optionflags` can be used to control how the
271.1079 - test runner compares expected output to actual output, and how
271.1080 - it displays failures. See the documentation for `testmod` for
271.1081 - more information.
271.1082 - """
271.1083 - self._checker = checker or OutputChecker()
271.1084 - if verbose is None:
271.1085 - verbose = '-v' in sys.argv
271.1086 - self._verbose = verbose
271.1087 - self.optionflags = optionflags
271.1088 - self.original_optionflags = optionflags
271.1089 -
271.1090 - # Keep track of the examples we've run.
271.1091 - self.tries = 0
271.1092 - self.failures = 0
271.1093 - self._name2ft = {}
271.1094 -
271.1095 - # Create a fake output target for capturing doctest output.
271.1096 - self._fakeout = _SpoofOut()
271.1097 -
271.1098 - #/////////////////////////////////////////////////////////////////
271.1099 - # Reporting methods
271.1100 - #/////////////////////////////////////////////////////////////////
271.1101 -
271.1102 - def report_start(self, out, test, example):
271.1103 - """
271.1104 - Report that the test runner is about to process the given
271.1105 - example. (Only displays a message if verbose=True)
271.1106 - """
271.1107 - if self._verbose:
271.1108 - if example.want:
271.1109 - out('Trying:\n' + _indent(example.source) +
271.1110 - 'Expecting:\n' + _indent(example.want))
271.1111 - else:
271.1112 - out('Trying:\n' + _indent(example.source) +
271.1113 - 'Expecting nothing\n')
271.1114 -
271.1115 - def report_success(self, out, test, example, got):
271.1116 - """
271.1117 - Report that the given example ran successfully. (Only
271.1118 - displays a message if verbose=True)
271.1119 - """
271.1120 - if self._verbose:
271.1121 - out("ok\n")
271.1122 -
271.1123 - def report_failure(self, out, test, example, got):
271.1124 - """
271.1125 - Report that the given example failed.
271.1126 - """
271.1127 - out(self._failure_header(test, example) +
271.1128 - self._checker.output_difference(example, got, self.optionflags))
271.1129 -
271.1130 - def report_unexpected_exception(self, out, test, example, exc_info):
271.1131 - """
271.1132 - Report that the given example raised an unexpected exception.
271.1133 - """
271.1134 - out(self._failure_header(test, example) +
271.1135 - 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
271.1136 -
271.1137 - def _failure_header(self, test, example):
271.1138 - out = [self.DIVIDER]
271.1139 - if test.filename:
271.1140 - if test.lineno is not None and example.lineno is not None:
271.1141 - lineno = test.lineno + example.lineno + 1
271.1142 - else:
271.1143 - lineno = '?'
271.1144 - out.append('File "%s", line %s, in %s' %
271.1145 - (test.filename, lineno, test.name))
271.1146 - else:
271.1147 - out.append('Line %s, in %s' % (example.lineno+1, test.name))
271.1148 - out.append('Failed example:')
271.1149 - source = example.source
271.1150 - out.append(_indent(source))
271.1151 - return '\n'.join(out)
271.1152 -
271.1153 - #/////////////////////////////////////////////////////////////////
271.1154 - # DocTest Running
271.1155 - #/////////////////////////////////////////////////////////////////
271.1156 -
271.1157 - def __run(self, test, compileflags, out):
271.1158 - """
271.1159 - Run the examples in `test`. Write the outcome of each example
271.1160 - with one of the `DocTestRunner.report_*` methods, using the
271.1161 - writer function `out`. `compileflags` is the set of compiler
271.1162 - flags that should be used to execute examples. Return a tuple
271.1163 - `(f, t)`, where `t` is the number of examples tried, and `f`
271.1164 - is the number of examples that failed. The examples are run
271.1165 - in the namespace `test.globs`.
271.1166 - """
271.1167 - # Keep track of the number of failures and tries.
271.1168 - failures = tries = 0
271.1169 -
271.1170 - # Save the option flags (since option directives can be used
271.1171 - # to modify them).
271.1172 - original_optionflags = self.optionflags
271.1173 -
271.1174 - SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
271.1175 -
271.1176 - check = self._checker.check_output
271.1177 -
271.1178 - # Process each example.
271.1179 - for examplenum, example in enumerate(test.examples):
271.1180 -
271.1181 - # If REPORT_ONLY_FIRST_FAILURE is set, then supress
271.1182 - # reporting after the first failure.
271.1183 - quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
271.1184 - failures > 0)
271.1185 -
271.1186 - # Merge in the example's options.
271.1187 - self.optionflags = original_optionflags
271.1188 - if example.options:
271.1189 - for (optionflag, val) in example.options.items():
271.1190 - if val:
271.1191 - self.optionflags |= optionflag
271.1192 - else:
271.1193 - self.optionflags &= ~optionflag
271.1194 -
271.1195 - # If 'SKIP' is set, then skip this example.
271.1196 - if self.optionflags & SKIP:
271.1197 - continue
271.1198 -
271.1199 - # Record that we started this example.
271.1200 - tries += 1
271.1201 - if not quiet:
271.1202 - self.report_start(out, test, example)
271.1203 -
271.1204 - # Use a special filename for compile(), so we can retrieve
271.1205 - # the source code during interactive debugging (see
271.1206 - # __patched_linecache_getlines).
271.1207 - filename = '<doctest %s[%d]>' % (test.name, examplenum)
271.1208 -
271.1209 - # Run the example in the given context (globs), and record
271.1210 - # any exception that gets raised. (But don't intercept
271.1211 - # keyboard interrupts.)
271.1212 - try:
271.1213 - # Don't blink! This is where the user's code gets run.
271.1214 - exec compile(example.source, filename, "single",
271.1215 - compileflags, 1) in test.globs
271.1216 - self.debugger.set_continue() # ==== Example Finished ====
271.1217 - exception = None
271.1218 - except KeyboardInterrupt:
271.1219 - raise
271.1220 - except:
271.1221 - exception = sys.exc_info()
271.1222 - self.debugger.set_continue() # ==== Example Finished ====
271.1223 -
271.1224 - got = self._fakeout.getvalue() # the actual output
271.1225 - self._fakeout.truncate(0)
271.1226 - outcome = FAILURE # guilty until proved innocent or insane
271.1227 -
271.1228 - # If the example executed without raising any exceptions,
271.1229 - # verify its output.
271.1230 - if exception is None:
271.1231 - if check(example.want, got, self.optionflags):
271.1232 - outcome = SUCCESS
271.1233 -
271.1234 - # The example raised an exception: check if it was expected.
271.1235 - else:
271.1236 - exc_info = sys.exc_info()
271.1237 - exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
271.1238 - if not quiet:
271.1239 - got += _exception_traceback(exc_info)
271.1240 -
271.1241 - # If `example.exc_msg` is None, then we weren't expecting
271.1242 - # an exception.
271.1243 - if example.exc_msg is None:
271.1244 - outcome = BOOM
271.1245 -
271.1246 - # We expected an exception: see whether it matches.
271.1247 - elif check(example.exc_msg, exc_msg, self.optionflags):
271.1248 - outcome = SUCCESS
271.1249 -
271.1250 - # Another chance if they didn't care about the detail.
271.1251 - elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
271.1252 - m1 = re.match(r'[^:]*:', example.exc_msg)
271.1253 - m2 = re.match(r'[^:]*:', exc_msg)
271.1254 - if m1 and m2 and check(m1.group(0), m2.group(0),
271.1255 - self.optionflags):
271.1256 - outcome = SUCCESS
271.1257 -
271.1258 - # Report the outcome.
271.1259 - if outcome is SUCCESS:
271.1260 - if not quiet:
271.1261 - self.report_success(out, test, example, got)
271.1262 - elif outcome is FAILURE:
271.1263 - if not quiet:
271.1264 - self.report_failure(out, test, example, got)
271.1265 - failures += 1
271.1266 - elif outcome is BOOM:
271.1267 - if not quiet:
271.1268 - self.report_unexpected_exception(out, test, example,
271.1269 - exc_info)
271.1270 - failures += 1
271.1271 - else:
271.1272 - assert False, ("unknown outcome", outcome)
271.1273 -
271.1274 - # Restore the option flags (in case they were modified)
271.1275 - self.optionflags = original_optionflags
271.1276 -
271.1277 - # Record and return the number of failures and tries.
271.1278 - self.__record_outcome(test, failures, tries)
271.1279 - return failures, tries
271.1280 -
271.1281 - def __record_outcome(self, test, f, t):
271.1282 - """
271.1283 - Record the fact that the given DocTest (`test`) generated `f`
271.1284 - failures out of `t` tried examples.
271.1285 - """
271.1286 - f2, t2 = self._name2ft.get(test.name, (0,0))
271.1287 - self._name2ft[test.name] = (f+f2, t+t2)
271.1288 - self.failures += f
271.1289 - self.tries += t
271.1290 -
271.1291 - __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
271.1292 - r'(?P<name>[\w\.]+)'
271.1293 - r'\[(?P<examplenum>\d+)\]>$')
271.1294 - def __patched_linecache_getlines(self, filename, module_globals=None):
271.1295 - m = self.__LINECACHE_FILENAME_RE.match(filename)
271.1296 - if m and m.group('name') == self.test.name:
271.1297 - example = self.test.examples[int(m.group('examplenum'))]
271.1298 - return example.source.splitlines(True)
271.1299 - else:
271.1300 - return self.save_linecache_getlines(filename, module_globals)
271.1301 -
271.1302 - def run(self, test, compileflags=None, out=None, clear_globs=True):
271.1303 - """
271.1304 - Run the examples in `test`, and display the results using the
271.1305 - writer function `out`.
271.1306 -
271.1307 - The examples are run in the namespace `test.globs`. If
271.1308 - `clear_globs` is true (the default), then this namespace will
271.1309 - be cleared after the test runs, to help with garbage
271.1310 - collection. If you would like to examine the namespace after
271.1311 - the test completes, then use `clear_globs=False`.
271.1312 -
271.1313 - `compileflags` gives the set of flags that should be used by
271.1314 - the Python compiler when running the examples. If not
271.1315 - specified, then it will default to the set of future-import
271.1316 - flags that apply to `globs`.
271.1317 -
271.1318 - The output of each example is checked using
271.1319 - `DocTestRunner.check_output`, and the results are formatted by
271.1320 - the `DocTestRunner.report_*` methods.
271.1321 - """
271.1322 - self.test = test
271.1323 -
271.1324 - if compileflags is None:
271.1325 - compileflags = _extract_future_flags(test.globs)
271.1326 -
271.1327 - save_stdout = sys.stdout
271.1328 - if out is None:
271.1329 - out = save_stdout.write
271.1330 - sys.stdout = self._fakeout
271.1331 -
271.1332 - # Patch pdb.set_trace to restore sys.stdout during interactive
271.1333 - # debugging (so it's not still redirected to self._fakeout).
271.1334 - # Note that the interactive output will go to *our*
271.1335 - # save_stdout, even if that's not the real sys.stdout; this
271.1336 - # allows us to write test cases for the set_trace behavior.
271.1337 - save_set_trace = pdb.set_trace
271.1338 - self.debugger = _OutputRedirectingPdb(save_stdout)
271.1339 - self.debugger.reset()
271.1340 - pdb.set_trace = self.debugger.set_trace
271.1341 -
271.1342 - # Patch linecache.getlines, so we can see the example's source
271.1343 - # when we're inside the debugger.
271.1344 - self.save_linecache_getlines = linecache.getlines
271.1345 - linecache.getlines = self.__patched_linecache_getlines
271.1346 -
271.1347 - try:
271.1348 - return self.__run(test, compileflags, out)
271.1349 - finally:
271.1350 - sys.stdout = save_stdout
271.1351 - pdb.set_trace = save_set_trace
271.1352 - linecache.getlines = self.save_linecache_getlines
271.1353 - if clear_globs:
271.1354 - test.globs.clear()
271.1355 -
271.1356 - #/////////////////////////////////////////////////////////////////
271.1357 - # Summarization
271.1358 - #/////////////////////////////////////////////////////////////////
271.1359 - def summarize(self, verbose=None):
271.1360 - """
271.1361 - Print a summary of all the test cases that have been run by
271.1362 - this DocTestRunner, and return a tuple `(f, t)`, where `f` is
271.1363 - the total number of failed examples, and `t` is the total
271.1364 - number of tried examples.
271.1365 -
271.1366 - The optional `verbose` argument controls how detailed the
271.1367 - summary is. If the verbosity is not specified, then the
271.1368 - DocTestRunner's verbosity is used.
271.1369 - """
271.1370 - if verbose is None:
271.1371 - verbose = self._verbose
271.1372 - notests = []
271.1373 - passed = []
271.1374 - failed = []
271.1375 - totalt = totalf = 0
271.1376 - for x in self._name2ft.items():
271.1377 - name, (f, t) = x
271.1378 - assert f <= t
271.1379 - totalt += t
271.1380 - totalf += f
271.1381 - if t == 0:
271.1382 - notests.append(name)
271.1383 - elif f == 0:
271.1384 - passed.append( (name, t) )
271.1385 - else:
271.1386 - failed.append(x)
271.1387 - if verbose:
271.1388 - if notests:
271.1389 - print len(notests), "items had no tests:"
271.1390 - notests.sort()
271.1391 - for thing in notests:
271.1392 - print " ", thing
271.1393 - if passed:
271.1394 - print len(passed), "items passed all tests:"
271.1395 - passed.sort()
271.1396 - for thing, count in passed:
271.1397 - print " %3d tests in %s" % (count, thing)
271.1398 - if failed:
271.1399 - print self.DIVIDER
271.1400 - print len(failed), "items had failures:"
271.1401 - failed.sort()
271.1402 - for thing, (f, t) in failed:
271.1403 - print " %3d of %3d in %s" % (f, t, thing)
271.1404 - if verbose:
271.1405 - print totalt, "tests in", len(self._name2ft), "items."
271.1406 - print totalt - totalf, "passed and", totalf, "failed."
271.1407 - if totalf:
271.1408 - print "***Test Failed***", totalf, "failures."
271.1409 - elif verbose:
271.1410 - print "Test passed."
271.1411 - return totalf, totalt
271.1412 -
271.1413 - #/////////////////////////////////////////////////////////////////
271.1414 - # Backward compatibility cruft to maintain doctest.master.
271.1415 - #/////////////////////////////////////////////////////////////////
271.1416 - def merge(self, other):
271.1417 - d = self._name2ft
271.1418 - for name, (f, t) in other._name2ft.items():
271.1419 - if name in d:
271.1420 - print "*** DocTestRunner.merge: '" + name + "' in both" \
271.1421 - " testers; summing outcomes."
271.1422 - f2, t2 = d[name]
271.1423 - f = f + f2
271.1424 - t = t + t2
271.1425 - d[name] = f, t
271.1426 -
271.1427 -class OutputChecker:
271.1428 - """
271.1429 - A class used to check the whether the actual output from a doctest
271.1430 - example matches the expected output. `OutputChecker` defines two
271.1431 - methods: `check_output`, which compares a given pair of outputs,
271.1432 - and returns true if they match; and `output_difference`, which
271.1433 - returns a string describing the differences between two outputs.
271.1434 - """
271.1435 - def check_output(self, want, got, optionflags):
271.1436 - """
271.1437 - Return True iff the actual output from an example (`got`)
271.1438 - matches the expected output (`want`). These strings are
271.1439 - always considered to match if they are identical; but
271.1440 - depending on what option flags the test runner is using,
271.1441 - several non-exact match types are also possible. See the
271.1442 - documentation for `TestRunner` for more information about
271.1443 - option flags.
271.1444 - """
271.1445 - # Handle the common case first, for efficiency:
271.1446 - # if they're string-identical, always return true.
271.1447 - if got == want:
271.1448 - return True
271.1449 -
271.1450 - # The values True and False replaced 1 and 0 as the return
271.1451 - # value for boolean comparisons in Python 2.3.
271.1452 - if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
271.1453 - if (got,want) == ("True\n", "1\n"):
271.1454 - return True
271.1455 - if (got,want) == ("False\n", "0\n"):
271.1456 - return True
271.1457 -
271.1458 - # <BLANKLINE> can be used as a special sequence to signify a
271.1459 - # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
271.1460 - if not (optionflags & DONT_ACCEPT_BLANKLINE):
271.1461 - # Replace <BLANKLINE> in want with a blank line.
271.1462 - want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
271.1463 - '', want)
271.1464 - # If a line in got contains only spaces, then remove the
271.1465 - # spaces.
271.1466 - got = re.sub('(?m)^\s*?$', '', got)
271.1467 - if got == want:
271.1468 - return True
271.1469 -
271.1470 - # This flag causes doctest to ignore any differences in the
271.1471 - # contents of whitespace strings. Note that this can be used
271.1472 - # in conjunction with the ELLIPSIS flag.
271.1473 - if optionflags & NORMALIZE_WHITESPACE:
271.1474 - got = ' '.join(got.split())
271.1475 - want = ' '.join(want.split())
271.1476 - if got == want:
271.1477 - return True
271.1478 -
271.1479 - # The ELLIPSIS flag says to let the sequence "..." in `want`
271.1480 - # match any substring in `got`.
271.1481 - if optionflags & ELLIPSIS:
271.1482 - if _ellipsis_match(want, got):
271.1483 - return True
271.1484 -
271.1485 - # We didn't find any match; return false.
271.1486 - return False
271.1487 -
271.1488 - # Should we do a fancy diff?
271.1489 - def _do_a_fancy_diff(self, want, got, optionflags):
271.1490 - # Not unless they asked for a fancy diff.
271.1491 - if not optionflags & (REPORT_UDIFF |
271.1492 - REPORT_CDIFF |
271.1493 - REPORT_NDIFF):
271.1494 - return False
271.1495 -
271.1496 - # If expected output uses ellipsis, a meaningful fancy diff is
271.1497 - # too hard ... or maybe not. In two real-life failures Tim saw,
271.1498 - # a diff was a major help anyway, so this is commented out.
271.1499 - # [todo] _ellipsis_match() knows which pieces do and don't match,
271.1500 - # and could be the basis for a kick-ass diff in this case.
271.1501 - ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
271.1502 - ## return False
271.1503 -
271.1504 - # ndiff does intraline difference marking, so can be useful even
271.1505 - # for 1-line differences.
271.1506 - if optionflags & REPORT_NDIFF:
271.1507 - return True
271.1508 -
271.1509 - # The other diff types need at least a few lines to be helpful.
271.1510 - return want.count('\n') > 2 and got.count('\n') > 2
271.1511 -
271.1512 - def output_difference(self, example, got, optionflags):
271.1513 - """
271.1514 - Return a string describing the differences between the
271.1515 - expected output for a given example (`example`) and the actual
271.1516 - output (`got`). `optionflags` is the set of option flags used
271.1517 - to compare `want` and `got`.
271.1518 - """
271.1519 - want = example.want
271.1520 - # If <BLANKLINE>s are being used, then replace blank lines
271.1521 - # with <BLANKLINE> in the actual output string.
271.1522 - if not (optionflags & DONT_ACCEPT_BLANKLINE):
271.1523 - got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
271.1524 -
271.1525 - # Check if we should use diff.
271.1526 - if self._do_a_fancy_diff(want, got, optionflags):
271.1527 - # Split want & got into lines.
271.1528 - want_lines = want.splitlines(True) # True == keep line ends
271.1529 - got_lines = got.splitlines(True)
271.1530 - # Use difflib to find their differences.
271.1531 - if optionflags & REPORT_UDIFF:
271.1532 - diff = difflib.unified_diff(want_lines, got_lines, n=2)
271.1533 - diff = list(diff)[2:] # strip the diff header
271.1534 - kind = 'unified diff with -expected +actual'
271.1535 - elif optionflags & REPORT_CDIFF:
271.1536 - diff = difflib.context_diff(want_lines, got_lines, n=2)
271.1537 - diff = list(diff)[2:] # strip the diff header
271.1538 - kind = 'context diff with expected followed by actual'
271.1539 - elif optionflags & REPORT_NDIFF:
271.1540 - engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
271.1541 - diff = list(engine.compare(want_lines, got_lines))
271.1542 - kind = 'ndiff with -expected +actual'
271.1543 - else:
271.1544 - assert 0, 'Bad diff option'
271.1545 - # Remove trailing whitespace on diff output.
271.1546 - diff = [line.rstrip() + '\n' for line in diff]
271.1547 - return 'Differences (%s):\n' % kind + _indent(''.join(diff))
271.1548 -
271.1549 - # If we're not using diff, then simply list the expected
271.1550 - # output followed by the actual output.
271.1551 - if want and got:
271.1552 - return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
271.1553 - elif want:
271.1554 - return 'Expected:\n%sGot nothing\n' % _indent(want)
271.1555 - elif got:
271.1556 - return 'Expected nothing\nGot:\n%s' % _indent(got)
271.1557 - else:
271.1558 - return 'Expected nothing\nGot nothing\n'
271.1559 -
271.1560 -class DocTestFailure(Exception):
271.1561 - """A DocTest example has failed in debugging mode.
271.1562 -
271.1563 - The exception instance has variables:
271.1564 -
271.1565 - - test: the DocTest object being run
271.1566 -
271.1567 - - example: the Example object that failed
271.1568 -
271.1569 - - got: the actual output
271.1570 - """
271.1571 - def __init__(self, test, example, got):
271.1572 - self.test = test
271.1573 - self.example = example
271.1574 - self.got = got
271.1575 -
271.1576 - def __str__(self):
271.1577 - return str(self.test)
271.1578 -
271.1579 -class UnexpectedException(Exception):
271.1580 - """A DocTest example has encountered an unexpected exception
271.1581 -
271.1582 - The exception instance has variables:
271.1583 -
271.1584 - - test: the DocTest object being run
271.1585 -
271.1586 - - example: the Example object that failed
271.1587 -
271.1588 - - exc_info: the exception info
271.1589 - """
271.1590 - def __init__(self, test, example, exc_info):
271.1591 - self.test = test
271.1592 - self.example = example
271.1593 - self.exc_info = exc_info
271.1594 -
271.1595 - def __str__(self):
271.1596 - return str(self.test)
271.1597 -
271.1598 -class DebugRunner(DocTestRunner):
271.1599 - r"""Run doc tests but raise an exception as soon as there is a failure.
271.1600 -
271.1601 - If an unexpected exception occurs, an UnexpectedException is raised.
271.1602 - It contains the test, the example, and the original exception:
271.1603 -
271.1604 - >>> runner = DebugRunner(verbose=False)
271.1605 - >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
271.1606 - ... {}, 'foo', 'foo.py', 0)
271.1607 - >>> try:
271.1608 - ... runner.run(test)
271.1609 - ... except UnexpectedException, failure:
271.1610 - ... pass
271.1611 -
271.1612 - >>> failure.test is test
271.1613 - True
271.1614 -
271.1615 - >>> failure.example.want
271.1616 - '42\n'
271.1617 -
271.1618 - >>> exc_info = failure.exc_info
271.1619 - >>> raise exc_info[0], exc_info[1], exc_info[2]
271.1620 - Traceback (most recent call last):
271.1621 - ...
271.1622 - KeyError
271.1623 -
271.1624 - We wrap the original exception to give the calling application
271.1625 - access to the test and example information.
271.1626 -
271.1627 - If the output doesn't match, then a DocTestFailure is raised:
271.1628 -
271.1629 - >>> test = DocTestParser().get_doctest('''
271.1630 - ... >>> x = 1
271.1631 - ... >>> x
271.1632 - ... 2
271.1633 - ... ''', {}, 'foo', 'foo.py', 0)
271.1634 -
271.1635 - >>> try:
271.1636 - ... runner.run(test)
271.1637 - ... except DocTestFailure, failure:
271.1638 - ... pass
271.1639 -
271.1640 - DocTestFailure objects provide access to the test:
271.1641 -
271.1642 - >>> failure.test is test
271.1643 - True
271.1644 -
271.1645 - As well as to the example:
271.1646 -
271.1647 - >>> failure.example.want
271.1648 - '2\n'
271.1649 -
271.1650 - and the actual output:
271.1651 -
271.1652 - >>> failure.got
271.1653 - '1\n'
271.1654 -
271.1655 - If a failure or error occurs, the globals are left intact:
271.1656 -
271.1657 - >>> del test.globs['__builtins__']
271.1658 - >>> test.globs
271.1659 - {'x': 1}
271.1660 -
271.1661 - >>> test = DocTestParser().get_doctest('''
271.1662 - ... >>> x = 2
271.1663 - ... >>> raise KeyError
271.1664 - ... ''', {}, 'foo', 'foo.py', 0)
271.1665 -
271.1666 - >>> runner.run(test)
271.1667 - Traceback (most recent call last):
271.1668 - ...
271.1669 - UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
271.1670 -
271.1671 - >>> del test.globs['__builtins__']
271.1672 - >>> test.globs
271.1673 - {'x': 2}
271.1674 -
271.1675 - But the globals are cleared if there is no error:
271.1676 -
271.1677 - >>> test = DocTestParser().get_doctest('''
271.1678 - ... >>> x = 2
271.1679 - ... ''', {}, 'foo', 'foo.py', 0)
271.1680 -
271.1681 - >>> runner.run(test)
271.1682 - (0, 1)
271.1683 -
271.1684 - >>> test.globs
271.1685 - {}
271.1686 -
271.1687 - """
271.1688 -
271.1689 - def run(self, test, compileflags=None, out=None, clear_globs=True):
271.1690 - r = DocTestRunner.run(self, test, compileflags, out, False)
271.1691 - if clear_globs:
271.1692 - test.globs.clear()
271.1693 - return r
271.1694 -
271.1695 - def report_unexpected_exception(self, out, test, example, exc_info):
271.1696 - raise UnexpectedException(test, example, exc_info)
271.1697 -
271.1698 - def report_failure(self, out, test, example, got):
271.1699 - raise DocTestFailure(test, example, got)
271.1700 -
271.1701 -######################################################################
271.1702 -## 6. Test Functions
271.1703 -######################################################################
271.1704 -# These should be backwards compatible.
271.1705 -
271.1706 -# For backward compatibility, a global instance of a DocTestRunner
271.1707 -# class, updated by testmod.
271.1708 -master = None
271.1709 -
271.1710 -def testmod(m=None, name=None, globs=None, verbose=None,
271.1711 - report=True, optionflags=0, extraglobs=None,
271.1712 - raise_on_error=False, exclude_empty=False):
271.1713 - """m=None, name=None, globs=None, verbose=None, report=True,
271.1714 - optionflags=0, extraglobs=None, raise_on_error=False,
271.1715 - exclude_empty=False
271.1716 -
271.1717 - Test examples in docstrings in functions and classes reachable
271.1718 - from module m (or the current module if m is not supplied), starting
271.1719 - with m.__doc__.
271.1720 -
271.1721 - Also test examples reachable from dict m.__test__ if it exists and is
271.1722 - not None. m.__test__ maps names to functions, classes and strings;
271.1723 - function and class docstrings are tested even if the name is private;
271.1724 - strings are tested directly, as if they were docstrings.
271.1725 -
271.1726 - Return (#failures, #tests).
271.1727 -
271.1728 - See doctest.__doc__ for an overview.
271.1729 -
271.1730 - Optional keyword arg "name" gives the name of the module; by default
271.1731 - use m.__name__.
271.1732 -
271.1733 - Optional keyword arg "globs" gives a dict to be used as the globals
271.1734 - when executing examples; by default, use m.__dict__. A copy of this
271.1735 - dict is actually used for each docstring, so that each docstring's
271.1736 - examples start with a clean slate.
271.1737 -
271.1738 - Optional keyword arg "extraglobs" gives a dictionary that should be
271.1739 - merged into the globals that are used to execute examples. By
271.1740 - default, no extra globals are used. This is new in 2.4.
271.1741 -
271.1742 - Optional keyword arg "verbose" prints lots of stuff if true, prints
271.1743 - only failures if false; by default, it's true iff "-v" is in sys.argv.
271.1744 -
271.1745 - Optional keyword arg "report" prints a summary at the end when true,
271.1746 - else prints nothing at the end. In verbose mode, the summary is
271.1747 - detailed, else very brief (in fact, empty if all tests passed).
271.1748 -
271.1749 - Optional keyword arg "optionflags" or's together module constants,
271.1750 - and defaults to 0. This is new in 2.3. Possible values (see the
271.1751 - docs for details):
271.1752 -
271.1753 - DONT_ACCEPT_TRUE_FOR_1
271.1754 - DONT_ACCEPT_BLANKLINE
271.1755 - NORMALIZE_WHITESPACE
271.1756 - ELLIPSIS
271.1757 - SKIP
271.1758 - IGNORE_EXCEPTION_DETAIL
271.1759 - REPORT_UDIFF
271.1760 - REPORT_CDIFF
271.1761 - REPORT_NDIFF
271.1762 - REPORT_ONLY_FIRST_FAILURE
271.1763 -
271.1764 - Optional keyword arg "raise_on_error" raises an exception on the
271.1765 - first unexpected exception or failure. This allows failures to be
271.1766 - post-mortem debugged.
271.1767 -
271.1768 - Advanced tomfoolery: testmod runs methods of a local instance of
271.1769 - class doctest.Tester, then merges the results into (or creates)
271.1770 - global Tester instance doctest.master. Methods of doctest.master
271.1771 - can be called directly too, if you want to do something unusual.
271.1772 - Passing report=0 to testmod is especially useful then, to delay
271.1773 - displaying a summary. Invoke doctest.master.summarize(verbose)
271.1774 - when you're done fiddling.
271.1775 - """
271.1776 - global master
271.1777 -
271.1778 - # If no module was given, then use __main__.
271.1779 - if m is None:
271.1780 - # DWA - m will still be None if this wasn't invoked from the command
271.1781 - # line, in which case the following TypeError is about as good an error
271.1782 - # as we should expect
271.1783 - m = sys.modules.get('__main__')
271.1784 -
271.1785 - # Check that we were actually given a module.
271.1786 - if not inspect.ismodule(m):
271.1787 - raise TypeError("testmod: module required; %r" % (m,))
271.1788 -
271.1789 - # If no name was given, then use the module's name.
271.1790 - if name is None:
271.1791 - name = m.__name__
271.1792 -
271.1793 - # Find, parse, and run all tests in the given module.
271.1794 - finder = DocTestFinder(exclude_empty=exclude_empty)
271.1795 -
271.1796 - if raise_on_error:
271.1797 - runner = DebugRunner(verbose=verbose, optionflags=optionflags)
271.1798 - else:
271.1799 - runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
271.1800 -
271.1801 - for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
271.1802 - runner.run(test)
271.1803 -
271.1804 - if report:
271.1805 - runner.summarize()
271.1806 -
271.1807 - if master is None:
271.1808 - master = runner
271.1809 - else:
271.1810 - master.merge(runner)
271.1811 -
271.1812 - return runner.failures, runner.tries
271.1813 -
271.1814 -def testfile(filename, module_relative=True, name=None, package=None,
271.1815 - globs=None, verbose=None, report=True, optionflags=0,
271.1816 - extraglobs=None, raise_on_error=False, parser=DocTestParser(),
271.1817 - encoding=None):
271.1818 - """
271.1819 - Test examples in the given file. Return (#failures, #tests).
271.1820 -
271.1821 - Optional keyword arg "module_relative" specifies how filenames
271.1822 - should be interpreted:
271.1823 -
271.1824 - - If "module_relative" is True (the default), then "filename"
271.1825 - specifies a module-relative path. By default, this path is
271.1826 - relative to the calling module's directory; but if the
271.1827 - "package" argument is specified, then it is relative to that
271.1828 - package. To ensure os-independence, "filename" should use
271.1829 - "/" characters to separate path segments, and should not
271.1830 - be an absolute path (i.e., it may not begin with "/").
271.1831 -
271.1832 - - If "module_relative" is False, then "filename" specifies an
271.1833 - os-specific path. The path may be absolute or relative (to
271.1834 - the current working directory).
271.1835 -
271.1836 - Optional keyword arg "name" gives the name of the test; by default
271.1837 - use the file's basename.
271.1838 -
271.1839 - Optional keyword argument "package" is a Python package or the
271.1840 - name of a Python package whose directory should be used as the
271.1841 - base directory for a module relative filename. If no package is
271.1842 - specified, then the calling module's directory is used as the base
271.1843 - directory for module relative filenames. It is an error to
271.1844 - specify "package" if "module_relative" is False.
271.1845 -
271.1846 - Optional keyword arg "globs" gives a dict to be used as the globals
271.1847 - when executing examples; by default, use {}. A copy of this dict
271.1848 - is actually used for each docstring, so that each docstring's
271.1849 - examples start with a clean slate.
271.1850 -
271.1851 - Optional keyword arg "extraglobs" gives a dictionary that should be
271.1852 - merged into the globals that are used to execute examples. By
271.1853 - default, no extra globals are used.
271.1854 -
271.1855 - Optional keyword arg "verbose" prints lots of stuff if true, prints
271.1856 - only failures if false; by default, it's true iff "-v" is in sys.argv.
271.1857 -
271.1858 - Optional keyword arg "report" prints a summary at the end when true,
271.1859 - else prints nothing at the end. In verbose mode, the summary is
271.1860 - detailed, else very brief (in fact, empty if all tests passed).
271.1861 -
271.1862 - Optional keyword arg "optionflags" or's together module constants,
271.1863 - and defaults to 0. Possible values (see the docs for details):
271.1864 -
271.1865 - DONT_ACCEPT_TRUE_FOR_1
271.1866 - DONT_ACCEPT_BLANKLINE
271.1867 - NORMALIZE_WHITESPACE
271.1868 - ELLIPSIS
271.1869 - SKIP
271.1870 - IGNORE_EXCEPTION_DETAIL
271.1871 - REPORT_UDIFF
271.1872 - REPORT_CDIFF
271.1873 - REPORT_NDIFF
271.1874 - REPORT_ONLY_FIRST_FAILURE
271.1875 -
271.1876 - Optional keyword arg "raise_on_error" raises an exception on the
271.1877 - first unexpected exception or failure. This allows failures to be
271.1878 - post-mortem debugged.
271.1879 -
271.1880 - Optional keyword arg "parser" specifies a DocTestParser (or
271.1881 - subclass) that should be used to extract tests from the files.
271.1882 -
271.1883 - Optional keyword arg "encoding" specifies an encoding that should
271.1884 - be used to convert the file to unicode.
271.1885 -
271.1886 - Advanced tomfoolery: testmod runs methods of a local instance of
271.1887 - class doctest.Tester, then merges the results into (or creates)
271.1888 - global Tester instance doctest.master. Methods of doctest.master
271.1889 - can be called directly too, if you want to do something unusual.
271.1890 - Passing report=0 to testmod is especially useful then, to delay
271.1891 - displaying a summary. Invoke doctest.master.summarize(verbose)
271.1892 - when you're done fiddling.
271.1893 - """
271.1894 - global master
271.1895 -
271.1896 - if package and not module_relative:
271.1897 - raise ValueError("Package may only be specified for module-"
271.1898 - "relative paths.")
271.1899 -
271.1900 - # Relativize the path
271.1901 - text, filename = _load_testfile(filename, package, module_relative)
271.1902 -
271.1903 - # If no name was given, then use the file's name.
271.1904 - if name is None:
271.1905 - name = os.path.basename(filename)
271.1906 -
271.1907 - # Assemble the globals.
271.1908 - if globs is None:
271.1909 - globs = {}
271.1910 - else:
271.1911 - globs = globs.copy()
271.1912 - if extraglobs is not None:
271.1913 - globs.update(extraglobs)
271.1914 -
271.1915 - if raise_on_error:
271.1916 - runner = DebugRunner(verbose=verbose, optionflags=optionflags)
271.1917 - else:
271.1918 - runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
271.1919 -
271.1920 - if encoding is not None:
271.1921 - text = text.decode(encoding)
271.1922 -
271.1923 - # Read the file, convert it to a test, and run it.
271.1924 - test = parser.get_doctest(text, globs, name, filename, 0)
271.1925 - runner.run(test)
271.1926 -
271.1927 - if report:
271.1928 - runner.summarize()
271.1929 -
271.1930 - if master is None:
271.1931 - master = runner
271.1932 - else:
271.1933 - master.merge(runner)
271.1934 -
271.1935 - return runner.failures, runner.tries
271.1936 -
271.1937 -def run_docstring_examples(f, globs, verbose=False, name="NoName",
271.1938 - compileflags=None, optionflags=0):
271.1939 - """
271.1940 - Test examples in the given object's docstring (`f`), using `globs`
271.1941 - as globals. Optional argument `name` is used in failure messages.
271.1942 - If the optional argument `verbose` is true, then generate output
271.1943 - even if there are no failures.
271.1944 -
271.1945 - `compileflags` gives the set of flags that should be used by the
271.1946 - Python compiler when running the examples. If not specified, then
271.1947 - it will default to the set of future-import flags that apply to
271.1948 - `globs`.
271.1949 -
271.1950 - Optional keyword arg `optionflags` specifies options for the
271.1951 - testing and output. See the documentation for `testmod` for more
271.1952 - information.
271.1953 - """
271.1954 - # Find, parse, and run all tests in the given module.
271.1955 - finder = DocTestFinder(verbose=verbose, recurse=False)
271.1956 - runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
271.1957 - for test in finder.find(f, name, globs=globs):
271.1958 - runner.run(test, compileflags=compileflags)
271.1959 -
271.1960 -######################################################################
271.1961 -## 7. Tester
271.1962 -######################################################################
271.1963 -# This is provided only for backwards compatibility. It's not
271.1964 -# actually used in any way.
271.1965 -
271.1966 -class Tester:
271.1967 - def __init__(self, mod=None, globs=None, verbose=None, optionflags=0):
271.1968 -
271.1969 - warnings.warn("class Tester is deprecated; "
271.1970 - "use class doctest.DocTestRunner instead",
271.1971 - DeprecationWarning, stacklevel=2)
271.1972 - if mod is None and globs is None:
271.1973 - raise TypeError("Tester.__init__: must specify mod or globs")
271.1974 - if mod is not None and not inspect.ismodule(mod):
271.1975 - raise TypeError("Tester.__init__: mod must be a module; %r" %
271.1976 - (mod,))
271.1977 - if globs is None:
271.1978 - globs = mod.__dict__
271.1979 - self.globs = globs
271.1980 -
271.1981 - self.verbose = verbose
271.1982 - self.optionflags = optionflags
271.1983 - self.testfinder = DocTestFinder()
271.1984 - self.testrunner = DocTestRunner(verbose=verbose,
271.1985 - optionflags=optionflags)
271.1986 -
271.1987 - def runstring(self, s, name):
271.1988 - test = DocTestParser().get_doctest(s, self.globs, name, None, None)
271.1989 - if self.verbose:
271.1990 - print "Running string", name
271.1991 - (f,t) = self.testrunner.run(test)
271.1992 - if self.verbose:
271.1993 - print f, "of", t, "examples failed in string", name
271.1994 - return (f,t)
271.1995 -
271.1996 - def rundoc(self, object, name=None, module=None):
271.1997 - f = t = 0
271.1998 - tests = self.testfinder.find(object, name, module=module,
271.1999 - globs=self.globs)
271.2000 - for test in tests:
271.2001 - (f2, t2) = self.testrunner.run(test)
271.2002 - (f,t) = (f+f2, t+t2)
271.2003 - return (f,t)
271.2004 -
271.2005 - def rundict(self, d, name, module=None):
271.2006 - import new
271.2007 - m = new.module(name)
271.2008 - m.__dict__.update(d)
271.2009 - if module is None:
271.2010 - module = False
271.2011 - return self.rundoc(m, name, module)
271.2012 -
271.2013 - def run__test__(self, d, name):
271.2014 - import new
271.2015 - m = new.module(name)
271.2016 - m.__test__ = d
271.2017 - return self.rundoc(m, name)
271.2018 -
271.2019 - def summarize(self, verbose=None):
271.2020 - return self.testrunner.summarize(verbose)
271.2021 -
271.2022 - def merge(self, other):
271.2023 - self.testrunner.merge(other.testrunner)
271.2024 -
271.2025 -######################################################################
271.2026 -## 8. Unittest Support
271.2027 -######################################################################
271.2028 -
271.2029 -_unittest_reportflags = 0
271.2030 -
271.2031 -def set_unittest_reportflags(flags):
271.2032 - """Sets the unittest option flags.
271.2033 -
271.2034 - The old flag is returned so that a runner could restore the old
271.2035 - value if it wished to:
271.2036 -
271.2037 - >>> import doctest
271.2038 - >>> old = doctest._unittest_reportflags
271.2039 - >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
271.2040 - ... REPORT_ONLY_FIRST_FAILURE) == old
271.2041 - True
271.2042 -
271.2043 - >>> doctest._unittest_reportflags == (REPORT_NDIFF |
271.2044 - ... REPORT_ONLY_FIRST_FAILURE)
271.2045 - True
271.2046 -
271.2047 - Only reporting flags can be set:
271.2048 -
271.2049 - >>> doctest.set_unittest_reportflags(ELLIPSIS)
271.2050 - Traceback (most recent call last):
271.2051 - ...
271.2052 - ValueError: ('Only reporting flags allowed', 8)
271.2053 -
271.2054 - >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
271.2055 - ... REPORT_ONLY_FIRST_FAILURE)
271.2056 - True
271.2057 - """
271.2058 - global _unittest_reportflags
271.2059 -
271.2060 - if (flags & REPORTING_FLAGS) != flags:
271.2061 - raise ValueError("Only reporting flags allowed", flags)
271.2062 - old = _unittest_reportflags
271.2063 - _unittest_reportflags = flags
271.2064 - return old
271.2065 -
271.2066 -
271.2067 -class DocTestCase(unittest.TestCase):
271.2068 -
271.2069 - def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
271.2070 - checker=None):
271.2071 -
271.2072 - unittest.TestCase.__init__(self)
271.2073 - self._dt_optionflags = optionflags
271.2074 - self._dt_checker = checker
271.2075 - self._dt_test = test
271.2076 - self._dt_setUp = setUp
271.2077 - self._dt_tearDown = tearDown
271.2078 -
271.2079 - def setUp(self):
271.2080 - test = self._dt_test
271.2081 -
271.2082 - if self._dt_setUp is not None:
271.2083 - self._dt_setUp(test)
271.2084 -
271.2085 - def tearDown(self):
271.2086 - test = self._dt_test
271.2087 -
271.2088 - if self._dt_tearDown is not None:
271.2089 - self._dt_tearDown(test)
271.2090 -
271.2091 - test.globs.clear()
271.2092 -
271.2093 - def runTest(self):
271.2094 - test = self._dt_test
271.2095 - old = sys.stdout
271.2096 - new = StringIO()
271.2097 - optionflags = self._dt_optionflags
271.2098 -
271.2099 - if not (optionflags & REPORTING_FLAGS):
271.2100 - # The option flags don't include any reporting flags,
271.2101 - # so add the default reporting flags
271.2102 - optionflags |= _unittest_reportflags
271.2103 -
271.2104 - runner = DocTestRunner(optionflags=optionflags,
271.2105 - checker=self._dt_checker, verbose=False)
271.2106 -
271.2107 - try:
271.2108 - runner.DIVIDER = "-"*70
271.2109 - failures, tries = runner.run(
271.2110 - test, out=new.write, clear_globs=False)
271.2111 - finally:
271.2112 - sys.stdout = old
271.2113 -
271.2114 - if failures:
271.2115 - raise self.failureException(self.format_failure(new.getvalue()))
271.2116 -
271.2117 - def format_failure(self, err):
271.2118 - test = self._dt_test
271.2119 - if test.lineno is None:
271.2120 - lineno = 'unknown line number'
271.2121 - else:
271.2122 - lineno = '%s' % test.lineno
271.2123 - lname = '.'.join(test.name.split('.')[-1:])
271.2124 - return ('Failed doctest test for %s\n'
271.2125 - ' File "%s", line %s, in %s\n\n%s'
271.2126 - % (test.name, test.filename, lineno, lname, err)
271.2127 - )
271.2128 -
271.2129 - def debug(self):
271.2130 - r"""Run the test case without results and without catching exceptions
271.2131 -
271.2132 - The unit test framework includes a debug method on test cases
271.2133 - and test suites to support post-mortem debugging. The test code
271.2134 - is run in such a way that errors are not caught. This way a
271.2135 - caller can catch the errors and initiate post-mortem debugging.
271.2136 -
271.2137 - The DocTestCase provides a debug method that raises
271.2138 - UnexpectedException errors if there is an unexepcted
271.2139 - exception:
271.2140 -
271.2141 - >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
271.2142 - ... {}, 'foo', 'foo.py', 0)
271.2143 - >>> case = DocTestCase(test)
271.2144 - >>> try:
271.2145 - ... case.debug()
271.2146 - ... except UnexpectedException, failure:
271.2147 - ... pass
271.2148 -
271.2149 - The UnexpectedException contains the test, the example, and
271.2150 - the original exception:
271.2151 -
271.2152 - >>> failure.test is test
271.2153 - True
271.2154 -
271.2155 - >>> failure.example.want
271.2156 - '42\n'
271.2157 -
271.2158 - >>> exc_info = failure.exc_info
271.2159 - >>> raise exc_info[0], exc_info[1], exc_info[2]
271.2160 - Traceback (most recent call last):
271.2161 - ...
271.2162 - KeyError
271.2163 -
271.2164 - If the output doesn't match, then a DocTestFailure is raised:
271.2165 -
271.2166 - >>> test = DocTestParser().get_doctest('''
271.2167 - ... >>> x = 1
271.2168 - ... >>> x
271.2169 - ... 2
271.2170 - ... ''', {}, 'foo', 'foo.py', 0)
271.2171 - >>> case = DocTestCase(test)
271.2172 -
271.2173 - >>> try:
271.2174 - ... case.debug()
271.2175 - ... except DocTestFailure, failure:
271.2176 - ... pass
271.2177 -
271.2178 - DocTestFailure objects provide access to the test:
271.2179 -
271.2180 - >>> failure.test is test
271.2181 - True
271.2182 -
271.2183 - As well as to the example:
271.2184 -
271.2185 - >>> failure.example.want
271.2186 - '2\n'
271.2187 -
271.2188 - and the actual output:
271.2189 -
271.2190 - >>> failure.got
271.2191 - '1\n'
271.2192 -
271.2193 - """
271.2194 -
271.2195 - self.setUp()
271.2196 - runner = DebugRunner(optionflags=self._dt_optionflags,
271.2197 - checker=self._dt_checker, verbose=False)
271.2198 - runner.run(self._dt_test)
271.2199 - self.tearDown()
271.2200 -
271.2201 - def id(self):
271.2202 - return self._dt_test.name
271.2203 -
271.2204 - def __repr__(self):
271.2205 - name = self._dt_test.name.split('.')
271.2206 - return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
271.2207 -
271.2208 - __str__ = __repr__
271.2209 -
271.2210 - def shortDescription(self):
271.2211 - return "Doctest: " + self._dt_test.name
271.2212 -
271.2213 -def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
271.2214 - **options):
271.2215 - """
271.2216 - Convert doctest tests for a module to a unittest test suite.
271.2217 -
271.2218 - This converts each documentation string in a module that
271.2219 - contains doctest tests to a unittest test case. If any of the
271.2220 - tests in a doc string fail, then the test case fails. An exception
271.2221 - is raised showing the name of the file containing the test and a
271.2222 - (sometimes approximate) line number.
271.2223 -
271.2224 - The `module` argument provides the module to be tested. The argument
271.2225 - can be either a module or a module name.
271.2226 -
271.2227 - If no argument is given, the calling module is used.
271.2228 -
271.2229 - A number of options may be provided as keyword arguments:
271.2230 -
271.2231 - setUp
271.2232 - A set-up function. This is called before running the
271.2233 - tests in each file. The setUp function will be passed a DocTest
271.2234 - object. The setUp function can access the test globals as the
271.2235 - globs attribute of the test passed.
271.2236 -
271.2237 - tearDown
271.2238 - A tear-down function. This is called after running the
271.2239 - tests in each file. The tearDown function will be passed a DocTest
271.2240 - object. The tearDown function can access the test globals as the
271.2241 - globs attribute of the test passed.
271.2242 -
271.2243 - globs
271.2244 - A dictionary containing initial global variables for the tests.
271.2245 -
271.2246 - optionflags
271.2247 - A set of doctest option flags expressed as an integer.
271.2248 - """
271.2249 -
271.2250 - if test_finder is None:
271.2251 - test_finder = DocTestFinder()
271.2252 -
271.2253 - module = _normalize_module(module)
271.2254 - tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
271.2255 - if globs is None:
271.2256 - globs = module.__dict__
271.2257 - if not tests:
271.2258 - # Why do we want to do this? Because it reveals a bug that might
271.2259 - # otherwise be hidden.
271.2260 - raise ValueError(module, "has no tests")
271.2261 -
271.2262 - tests.sort()
271.2263 - suite = unittest.TestSuite()
271.2264 - for test in tests:
271.2265 - if len(test.examples) == 0:
271.2266 - continue
271.2267 - if not test.filename:
271.2268 - filename = module.__file__
271.2269 - if filename[-4:] in (".pyc", ".pyo"):
271.2270 - filename = filename[:-1]
271.2271 - test.filename = filename
271.2272 - suite.addTest(DocTestCase(test, **options))
271.2273 -
271.2274 - return suite
271.2275 -
271.2276 -class DocFileCase(DocTestCase):
271.2277 -
271.2278 - def id(self):
271.2279 - return '_'.join(self._dt_test.name.split('.'))
271.2280 -
271.2281 - def __repr__(self):
271.2282 - return self._dt_test.filename
271.2283 - __str__ = __repr__
271.2284 -
271.2285 - def format_failure(self, err):
271.2286 - return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
271.2287 - % (self._dt_test.name, self._dt_test.filename, err)
271.2288 - )
271.2289 -
271.2290 -def DocFileTest(path, module_relative=True, package=None,
271.2291 - globs=None, parser=DocTestParser(),
271.2292 - encoding=None, **options):
271.2293 - if globs is None:
271.2294 - globs = {}
271.2295 - else:
271.2296 - globs = globs.copy()
271.2297 -
271.2298 - if package and not module_relative:
271.2299 - raise ValueError("Package may only be specified for module-"
271.2300 - "relative paths.")
271.2301 -
271.2302 - # Relativize the path.
271.2303 - doc, path = _load_testfile(path, package, module_relative)
271.2304 -
271.2305 - if "__file__" not in globs:
271.2306 - globs["__file__"] = path
271.2307 -
271.2308 - # Find the file and read it.
271.2309 - name = os.path.basename(path)
271.2310 -
271.2311 - # If an encoding is specified, use it to convert the file to unicode
271.2312 - if encoding is not None:
271.2313 - doc = doc.decode(encoding)
271.2314 -
271.2315 - # Convert it to a test, and wrap it in a DocFileCase.
271.2316 - test = parser.get_doctest(doc, globs, name, path, 0)
271.2317 - return DocFileCase(test, **options)
271.2318 -
271.2319 -def DocFileSuite(*paths, **kw):
271.2320 - """A unittest suite for one or more doctest files.
271.2321 -
271.2322 - The path to each doctest file is given as a string; the
271.2323 - interpretation of that string depends on the keyword argument
271.2324 - "module_relative".
271.2325 -
271.2326 - A number of options may be provided as keyword arguments:
271.2327 -
271.2328 - module_relative
271.2329 - If "module_relative" is True, then the given file paths are
271.2330 - interpreted as os-independent module-relative paths. By
271.2331 - default, these paths are relative to the calling module's
271.2332 - directory; but if the "package" argument is specified, then
271.2333 - they are relative to that package. To ensure os-independence,
271.2334 - "filename" should use "/" characters to separate path
271.2335 - segments, and may not be an absolute path (i.e., it may not
271.2336 - begin with "/").
271.2337 -
271.2338 - If "module_relative" is False, then the given file paths are
271.2339 - interpreted as os-specific paths. These paths may be absolute
271.2340 - or relative (to the current working directory).
271.2341 -
271.2342 - package
271.2343 - A Python package or the name of a Python package whose directory
271.2344 - should be used as the base directory for module relative paths.
271.2345 - If "package" is not specified, then the calling module's
271.2346 - directory is used as the base directory for module relative
271.2347 - filenames. It is an error to specify "package" if
271.2348 - "module_relative" is False.
271.2349 -
271.2350 - setUp
271.2351 - A set-up function. This is called before running the
271.2352 - tests in each file. The setUp function will be passed a DocTest
271.2353 - object. The setUp function can access the test globals as the
271.2354 - globs attribute of the test passed.
271.2355 -
271.2356 - tearDown
271.2357 - A tear-down function. This is called after running the
271.2358 - tests in each file. The tearDown function will be passed a DocTest
271.2359 - object. The tearDown function can access the test globals as the
271.2360 - globs attribute of the test passed.
271.2361 -
271.2362 - globs
271.2363 - A dictionary containing initial global variables for the tests.
271.2364 -
271.2365 - optionflags
271.2366 - A set of doctest option flags expressed as an integer.
271.2367 -
271.2368 - parser
271.2369 - A DocTestParser (or subclass) that should be used to extract
271.2370 - tests from the files.
271.2371 -
271.2372 - encoding
271.2373 - An encoding that will be used to convert the files to unicode.
271.2374 - """
271.2375 - suite = unittest.TestSuite()
271.2376 -
271.2377 - # We do this here so that _normalize_module is called at the right
271.2378 - # level. If it were called in DocFileTest, then this function
271.2379 - # would be the caller and we might guess the package incorrectly.
271.2380 - if kw.get('module_relative', True):
271.2381 - kw['package'] = _normalize_module(kw.get('package'))
271.2382 -
271.2383 - for path in paths:
271.2384 - suite.addTest(DocFileTest(path, **kw))
271.2385 -
271.2386 - return suite
271.2387 -
271.2388 -######################################################################
271.2389 -## 9. Debugging Support
271.2390 -######################################################################
271.2391 -
271.2392 -def script_from_examples(s):
271.2393 - r"""Extract script from text with examples.
271.2394 -
271.2395 - Converts text with examples to a Python script. Example input is
271.2396 - converted to regular code. Example output and all other words
271.2397 - are converted to comments:
271.2398 -
271.2399 - >>> text = '''
271.2400 - ... Here are examples of simple math.
271.2401 - ...
271.2402 - ... Python has super accurate integer addition
271.2403 - ...
271.2404 - ... >>> 2 + 2
271.2405 - ... 5
271.2406 - ...
271.2407 - ... And very friendly error messages:
271.2408 - ...
271.2409 - ... >>> 1/0
271.2410 - ... To Infinity
271.2411 - ... And
271.2412 - ... Beyond
271.2413 - ...
271.2414 - ... You can use logic if you want:
271.2415 - ...
271.2416 - ... >>> if 0:
271.2417 - ... ... blah
271.2418 - ... ... blah
271.2419 - ... ...
271.2420 - ...
271.2421 - ... Ho hum
271.2422 - ... '''
271.2423 -
271.2424 - >>> print script_from_examples(text)
271.2425 - # Here are examples of simple math.
271.2426 - #
271.2427 - # Python has super accurate integer addition
271.2428 - #
271.2429 - 2 + 2
271.2430 - # Expected:
271.2431 - ## 5
271.2432 - #
271.2433 - # And very friendly error messages:
271.2434 - #
271.2435 - 1/0
271.2436 - # Expected:
271.2437 - ## To Infinity
271.2438 - ## And
271.2439 - ## Beyond
271.2440 - #
271.2441 - # You can use logic if you want:
271.2442 - #
271.2443 - if 0:
271.2444 - blah
271.2445 - blah
271.2446 - #
271.2447 - # Ho hum
271.2448 - <BLANKLINE>
271.2449 - """
271.2450 - output = []
271.2451 - for piece in DocTestParser().parse(s):
271.2452 - if isinstance(piece, Example):
271.2453 - # Add the example's source code (strip trailing NL)
271.2454 - output.append(piece.source[:-1])
271.2455 - # Add the expected output:
271.2456 - want = piece.want
271.2457 - if want:
271.2458 - output.append('# Expected:')
271.2459 - output += ['## '+l for l in want.split('\n')[:-1]]
271.2460 - else:
271.2461 - # Add non-example text.
271.2462 - output += [_comment_line(l)
271.2463 - for l in piece.split('\n')[:-1]]
271.2464 -
271.2465 - # Trim junk on both ends.
271.2466 - while output and output[-1] == '#':
271.2467 - output.pop()
271.2468 - while output and output[0] == '#':
271.2469 - output.pop(0)
271.2470 - # Combine the output, and return it.
271.2471 - # Add a courtesy newline to prevent exec from choking (see bug #1172785)
271.2472 - return '\n'.join(output) + '\n'
271.2473 -
271.2474 -def testsource(module, name):
271.2475 - """Extract the test sources from a doctest docstring as a script.
271.2476 -
271.2477 - Provide the module (or dotted name of the module) containing the
271.2478 - test to be debugged and the name (within the module) of the object
271.2479 - with the doc string with tests to be debugged.
271.2480 - """
271.2481 - module = _normalize_module(module)
271.2482 - tests = DocTestFinder().find(module)
271.2483 - test = [t for t in tests if t.name == name]
271.2484 - if not test:
271.2485 - raise ValueError(name, "not found in tests")
271.2486 - test = test[0]
271.2487 - testsrc = script_from_examples(test.docstring)
271.2488 - return testsrc
271.2489 -
271.2490 -def debug_src(src, pm=False, globs=None):
271.2491 - """Debug a single doctest docstring, in argument `src`'"""
271.2492 - testsrc = script_from_examples(src)
271.2493 - debug_script(testsrc, pm, globs)
271.2494 -
271.2495 -def debug_script(src, pm=False, globs=None):
271.2496 - "Debug a test script. `src` is the script, as a string."
271.2497 - import pdb
271.2498 -
271.2499 - # Note that tempfile.NameTemporaryFile() cannot be used. As the
271.2500 - # docs say, a file so created cannot be opened by name a second time
271.2501 - # on modern Windows boxes, and execfile() needs to open it.
271.2502 - srcfilename = tempfile.mktemp(".py", "doctestdebug")
271.2503 - f = open(srcfilename, 'w')
271.2504 - f.write(src)
271.2505 - f.close()
271.2506 -
271.2507 - try:
271.2508 - if globs:
271.2509 - globs = globs.copy()
271.2510 - else:
271.2511 - globs = {}
271.2512 -
271.2513 - if pm:
271.2514 - try:
271.2515 - execfile(srcfilename, globs, globs)
271.2516 - except:
271.2517 - print sys.exc_info()[1]
271.2518 - pdb.post_mortem(sys.exc_info()[2])
271.2519 - else:
271.2520 - # Note that %r is vital here. '%s' instead can, e.g., cause
271.2521 - # backslashes to get treated as metacharacters on Windows.
271.2522 - pdb.run("execfile(%r)" % srcfilename, globs, globs)
271.2523 -
271.2524 - finally:
271.2525 - os.remove(srcfilename)
271.2526 -
271.2527 -def debug(module, name, pm=False):
271.2528 - """Debug a single doctest docstring.
271.2529 -
271.2530 - Provide the module (or dotted name of the module) containing the
271.2531 - test to be debugged and the name (within the module) of the object
271.2532 - with the docstring with tests to be debugged.
271.2533 - """
271.2534 - module = _normalize_module(module)
271.2535 - testsrc = testsource(module, name)
271.2536 - debug_script(testsrc, pm, module.__dict__)
271.2537 -
271.2538 -######################################################################
271.2539 -## 10. Example Usage
271.2540 -######################################################################
271.2541 -class _TestClass:
271.2542 - """
271.2543 - A pointless class, for sanity-checking of docstring testing.
271.2544 -
271.2545 - Methods:
271.2546 - square()
271.2547 - get()
271.2548 -
271.2549 - >>> _TestClass(13).get() + _TestClass(-12).get()
271.2550 - 1
271.2551 - >>> hex(_TestClass(13).square().get())
271.2552 - '0xa9'
271.2553 - """
271.2554 -
271.2555 - def __init__(self, val):
271.2556 - """val -> _TestClass object with associated value val.
271.2557 -
271.2558 - >>> t = _TestClass(123)
271.2559 - >>> print t.get()
271.2560 - 123
271.2561 - """
271.2562 -
271.2563 - self.val = val
271.2564 -
271.2565 - def square(self):
271.2566 - """square() -> square TestClass's associated value
271.2567 -
271.2568 - >>> _TestClass(13).square().get()
271.2569 - 169
271.2570 - """
271.2571 -
271.2572 - self.val = self.val ** 2
271.2573 - return self
271.2574 -
271.2575 - def get(self):
271.2576 - """get() -> return TestClass's associated value.
271.2577 -
271.2578 - >>> x = _TestClass(-42)
271.2579 - >>> print x.get()
271.2580 - -42
271.2581 - """
271.2582 -
271.2583 - return self.val
271.2584 -
271.2585 -__test__ = {"_TestClass": _TestClass,
271.2586 - "string": r"""
271.2587 - Example of a string object, searched as-is.
271.2588 - >>> x = 1; y = 2
271.2589 - >>> x + y, x * y
271.2590 - (3, 2)
271.2591 - """,
271.2592 -
271.2593 - "bool-int equivalence": r"""
271.2594 - In 2.2, boolean expressions displayed
271.2595 - 0 or 1. By default, we still accept
271.2596 - them. This can be disabled by passing
271.2597 - DONT_ACCEPT_TRUE_FOR_1 to the new
271.2598 - optionflags argument.
271.2599 - >>> 4 == 4
271.2600 - 1
271.2601 - >>> 4 == 4
271.2602 - True
271.2603 - >>> 4 > 4
271.2604 - 0
271.2605 - >>> 4 > 4
271.2606 - False
271.2607 - """,
271.2608 -
271.2609 - "blank lines": r"""
271.2610 - Blank lines can be marked with <BLANKLINE>:
271.2611 - >>> print 'foo\n\nbar\n'
271.2612 - foo
271.2613 - <BLANKLINE>
271.2614 - bar
271.2615 - <BLANKLINE>
271.2616 - """,
271.2617 -
271.2618 - "ellipsis": r"""
271.2619 - If the ellipsis flag is used, then '...' can be used to
271.2620 - elide substrings in the desired output:
271.2621 - >>> print range(1000) #doctest: +ELLIPSIS
271.2622 - [0, 1, 2, ..., 999]
271.2623 - """,
271.2624 -
271.2625 - "whitespace normalization": r"""
271.2626 - If the whitespace normalization flag is used, then
271.2627 - differences in whitespace are ignored.
271.2628 - >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
271.2629 - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
271.2630 - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
271.2631 - 27, 28, 29]
271.2632 - """,
271.2633 - }
271.2634 -
271.2635 -def _test():
271.2636 - r = unittest.TextTestRunner()
271.2637 - r.run(DocTestSuite())
271.2638 -
271.2639 -if __name__ == "__main__":
271.2640 - _test()
272.1 --- a/python.editor/test/unit/data/testfiles/doctest.py.indexed Sun Jan 04 13:11:53 2015 -0600
272.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
272.3 @@ -1,344 +0,0 @@
272.4 -
272.5 -
272.6 -Document 0
272.7 -Searchable Keys:
272.8 - class : DebugRunner
272.9 - class-ig : debugrunner
272.10 - extends : DocTestRunner
272.11 - in : doctest
272.12 - member : report_failure;F;;self,out,test,example,got;
272.13 - member : report_unexpected_exception;F;;self,out,test,example,exc_info;
272.14 - member : run;F;;self,test,compileflags,out,clear_globs;
272.15 -
272.16 -Not Searchable Keys:
272.17 -
272.18 -
272.19 -Document 1
272.20 -Searchable Keys:
272.21 - class : DocFileCase
272.22 - class-ig : docfilecase
272.23 - extends : DocTestCase
272.24 - in : doctest
272.25 - member : __repr__;F;|PRIVATE|;self;
272.26 - member : __str__;F;|PRIVATE|;self;
272.27 - member : format_failure;F;|PRIVATE|;self,err;
272.28 - member : id;F;|PRIVATE|;self;
272.29 -
272.30 -Not Searchable Keys:
272.31 - clzattrs : ;|PRIVATE|;
272.32 -
272.33 -
272.34 -Document 2
272.35 -Searchable Keys:
272.36 - class : DocTest
272.37 - class-ig : doctest
272.38 - in : doctest
272.39 - member : __cmp__;F;;self,other;
272.40 - member : __init__;c;|CONSTRUCTOR|;self,examples,globs,name,filename,lineno,docstring;
272.41 - member : __repr__;F;;self;
272.42 - member : docstring;D;;
272.43 - member : examples;D;;
272.44 - member : filename;D;;
272.45 - member : globs;D;;
272.46 - member : lineno;D;;
272.47 - member : name;D;;
272.48 -
272.49 -Not Searchable Keys:
272.50 -
272.51 -
272.52 -Document 3
272.53 -Searchable Keys:
272.54 - class : DocTestCase
272.55 - class-ig : doctestcase
272.56 - extends : TestCase
272.57 - in : doctest
272.58 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,test,optionflags,setUp,tearDown,checker;
272.59 - member : __repr__;F;|PRIVATE|;self;
272.60 - member : __str__;F;|PRIVATE|;self;
272.61 - member : _dt_checker;D;|PRIVATE|;
272.62 - member : _dt_optionflags;D;|PRIVATE|;
272.63 - member : _dt_setUp;D;|PRIVATE|;
272.64 - member : _dt_tearDown;D;|PRIVATE|;
272.65 - member : _dt_test;D;|PRIVATE|;
272.66 - member : debug;F;|PRIVATE|;self;
272.67 - member : format_failure;F;|PRIVATE|;self,err;
272.68 - member : id;F;|PRIVATE|;self;
272.69 - member : runTest;F;|PRIVATE|;self;
272.70 - member : setUp;F;|PRIVATE|;self;
272.71 - member : shortDescription;F;|PRIVATE|;self;
272.72 - member : tearDown;F;|PRIVATE|;self;
272.73 -
272.74 -Not Searchable Keys:
272.75 - clzattrs : ;|PRIVATE|;
272.76 -
272.77 -
272.78 -Document 4
272.79 -Searchable Keys:
272.80 - class : DocTestFailure
272.81 - class-ig : doctestfailure
272.82 - extends : Exception
272.83 - in : doctest
272.84 - member : __init__;c;|CONSTRUCTOR|;self,test,example,got;
272.85 - member : __str__;F;;self;
272.86 - member : example;D;;
272.87 - member : got;D;;
272.88 - member : test;D;;
272.89 -
272.90 -Not Searchable Keys:
272.91 -
272.92 -
272.93 -Document 5
272.94 -Searchable Keys:
272.95 - class : DocTestFinder
272.96 - class-ig : doctestfinder
272.97 - in : doctest
272.98 - member : __init__;c;|CONSTRUCTOR|;self,verbose,parser,recurse,exclude_empty;
272.99 - member : _exclude_empty;D;|PRIVATE|;
272.100 - member : _find;F;|PRIVATE|;self,tests,obj,name,module,source_lines,globs,seen;
272.101 - member : _find_lineno;F;|PRIVATE|;self,obj,source_lines;
272.102 - member : _from_module;F;|PRIVATE|;self,module,object;
272.103 - member : _get_test;F;|PRIVATE|;self,obj,name,module,globs,source_lines;
272.104 - member : _parser;D;|PRIVATE|;
272.105 - member : _recurse;D;|PRIVATE|;
272.106 - member : _verbose;D;|PRIVATE|;
272.107 - member : find;F;;self,obj,name,module,globs,extraglobs;
272.108 -
272.109 -Not Searchable Keys:
272.110 -
272.111 -
272.112 -Document 6
272.113 -Searchable Keys:
272.114 - class : DocTestParser
272.115 - class-ig : doctestparser
272.116 - in : doctest
272.117 - member : _EXAMPLE_RE;D;|PRIVATE|;
272.118 - member : _EXCEPTION_RE;D;|PRIVATE|;
272.119 - member : _INDENT_RE;D;|PRIVATE|;
272.120 - member : _IS_BLANK_OR_COMMENT;D;|PRIVATE|;
272.121 - member : _OPTION_DIRECTIVE_RE;D;|PRIVATE|;
272.122 - member : _check_prefix;F;|PRIVATE|;self,lines,prefix,name,lineno;
272.123 - member : _check_prompt_blank;F;|PRIVATE|;self,lines,indent,name,lineno;
272.124 - member : _find_options;F;|PRIVATE|;self,source,name,lineno;
272.125 - member : _min_indent;F;|PRIVATE|;self,s;
272.126 - member : _parse_example;F;|PRIVATE|;self,m,name,lineno;
272.127 - member : get_doctest;F;;self,string,globs,name,filename,lineno;
272.128 - member : get_examples;F;;self,string,name;
272.129 - member : parse;F;;self,string,name;
272.130 -
272.131 -Not Searchable Keys:
272.132 -
272.133 -
272.134 -Document 7
272.135 -Searchable Keys:
272.136 - class : DocTestRunner
272.137 - class-ig : doctestrunner
272.138 - in : doctest
272.139 - member : DIVIDER;D;;
272.140 - member : __LINECACHE_FILENAME_RE;D;|PRIVATE|;
272.141 - member : __init__;c;|CONSTRUCTOR|;self,checker,verbose,optionflags;
272.142 - member : __patched_linecache_getlines;F;|PRIVATE|;self,filename,module_globals;
272.143 - member : __record_outcome;F;|PRIVATE|;self,test,f,t;
272.144 - member : __run;F;|PRIVATE|;self,test,compileflags,out;
272.145 - member : _checker;D;|PRIVATE|;
272.146 - member : _failure_header;F;|PRIVATE|;self,test,example;
272.147 - member : _fakeout;D;|PRIVATE|;
272.148 - member : _name2ft;D;|PRIVATE|;
272.149 - member : _verbose;D;|PRIVATE|;
272.150 - member : debugger;D;;
272.151 - member : failures;D;;
272.152 - member : merge;F;;self,other;
272.153 - member : optionflags;D;;
272.154 - member : original_optionflags;D;;
272.155 - member : report_failure;F;;self,out,test,example,got;
272.156 - member : report_start;F;;self,out,test,example;
272.157 - member : report_success;F;;self,out,test,example,got;
272.158 - member : report_unexpected_exception;F;;self,out,test,example,exc_info;
272.159 - member : run;F;;self,test,compileflags,out,clear_globs;
272.160 - member : save_linecache_getlines;D;;
272.161 - member : summarize;F;;self,verbose;
272.162 - member : test;D;;
272.163 - member : tries;D;;
272.164 -
272.165 -Not Searchable Keys:
272.166 -
272.167 -
272.168 -Document 8
272.169 -Searchable Keys:
272.170 - class : Example
272.171 - class-ig : example
272.172 - in : doctest
272.173 - member : __init__;c;|CONSTRUCTOR|;self,source,want,exc_msg,lineno,indent,options;
272.174 - member : exc_msg;D;;
272.175 - member : indent;D;;
272.176 - member : lineno;D;;
272.177 - member : options;D;;
272.178 - member : source;D;;
272.179 - member : want;D;;
272.180 -
272.181 -Not Searchable Keys:
272.182 -
272.183 -
272.184 -Document 9
272.185 -Searchable Keys:
272.186 - class : OutputChecker
272.187 - class-ig : outputchecker
272.188 - in : doctest
272.189 - member : _do_a_fancy_diff;F;|PRIVATE|;self,want,got,optionflags;
272.190 - member : check_output;F;;self,want,got,optionflags;
272.191 - member : output_difference;F;;self,example,got,optionflags;
272.192 -
272.193 -Not Searchable Keys:
272.194 -
272.195 -
272.196 -Document 10
272.197 -Searchable Keys:
272.198 - class : Tester
272.199 - class-ig : tester
272.200 - in : doctest
272.201 - member : __init__;c;|CONSTRUCTOR|;self,mod,globs,verbose,optionflags;
272.202 - member : globs;D;;
272.203 - member : merge;F;;self,other;
272.204 - member : optionflags;D;;
272.205 - member : run__test__;F;;self,d,name;
272.206 - member : rundict;F;;self,d,name,module;
272.207 - member : rundoc;F;;self,object,name,module;
272.208 - member : runstring;F;;self,s,name;
272.209 - member : summarize;F;;self,verbose;
272.210 - member : testfinder;D;;
272.211 - member : testrunner;D;;
272.212 - member : verbose;D;;
272.213 -
272.214 -Not Searchable Keys:
272.215 -
272.216 -
272.217 -Document 11
272.218 -Searchable Keys:
272.219 - class : UnexpectedException
272.220 - class-ig : unexpectedexception
272.221 - extends : Exception
272.222 - in : doctest
272.223 - member : __init__;c;|CONSTRUCTOR|;self,test,example,exc_info;
272.224 - member : __str__;F;;self;
272.225 - member : example;D;;
272.226 - member : exc_info;D;;
272.227 - member : test;D;;
272.228 -
272.229 -Not Searchable Keys:
272.230 -
272.231 -
272.232 -Document 12
272.233 -Searchable Keys:
272.234 - class : _OutputRedirectingPdb
272.235 - class-ig : _outputredirectingpdb
272.236 - extends : Pdb
272.237 - in : doctest
272.238 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,out;
272.239 - member : __out;D;|PRIVATE|;
272.240 - member : trace_dispatch;F;|PRIVATE|;self,args;
272.241 -
272.242 -Not Searchable Keys:
272.243 - clzattrs : ;|PRIVATE|;
272.244 -
272.245 -
272.246 -Document 13
272.247 -Searchable Keys:
272.248 - class : _SpoofOut
272.249 - class-ig : _spoofout
272.250 - extends : StringIO
272.251 - in : doctest
272.252 - member : getvalue;F;|PRIVATE|;self;
272.253 - member : truncate;F;|PRIVATE|;self,size;
272.254 -
272.255 -Not Searchable Keys:
272.256 - clzattrs : ;|PRIVATE|;
272.257 -
272.258 -
272.259 -Document 14
272.260 -Searchable Keys:
272.261 - class : _TestClass
272.262 - class-ig : _testclass
272.263 - in : doctest
272.264 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,val;
272.265 - member : get;F;|PRIVATE|;self;
272.266 - member : square;F;|PRIVATE|;self;
272.267 - member : val;D;;
272.268 -
272.269 -Not Searchable Keys:
272.270 - clzattrs : ;|PRIVATE|;
272.271 -
272.272 -
272.273 -Document 15
272.274 -Searchable Keys:
272.275 - item : BLANKLINE_MARKER;D;|PRIVATE|;
272.276 - item : COMPARISON_FLAGS;D;;
272.277 - item : DONT_ACCEPT_BLANKLINE;D;;
272.278 - item : DONT_ACCEPT_TRUE_FOR_1;D;;
272.279 - item : DebugRunner;C;;
272.280 - item : DocFileCase;C;|PRIVATE|;
272.281 - item : DocFileSuite;F;;paths,kw;
272.282 - item : DocFileTest;F;|PRIVATE|;path,module_relative,package,globs,parser,encoding,options;
272.283 - item : DocTest;C;;
272.284 - item : DocTestCase;C;|PRIVATE|;
272.285 - item : DocTestFailure;C;;
272.286 - item : DocTestFinder;C;;
272.287 - item : DocTestParser;C;;
272.288 - item : DocTestRunner;C;;
272.289 - item : DocTestSuite;F;;module,globs,extraglobs,test_finder,options;
272.290 - item : ELLIPSIS;D;;
272.291 - item : ELLIPSIS_MARKER;D;|PRIVATE|;
272.292 - item : Example;C;;
272.293 - item : IGNORE_EXCEPTION_DETAIL;D;;
272.294 - item : NORMALIZE_WHITESPACE;D;;
272.295 - item : OPTIONFLAGS_BY_NAME;D;|PRIVATE|;
272.296 - item : OutputChecker;C;;
272.297 - item : REPORTING_FLAGS;D;;
272.298 - item : REPORT_CDIFF;D;;
272.299 - item : REPORT_NDIFF;D;;
272.300 - item : REPORT_ONLY_FIRST_FAILURE;D;;
272.301 - item : REPORT_UDIFF;D;;
272.302 - item : SKIP;D;;
272.303 - item : StringIO;I;|PRIVATE|;
272.304 - item : Tester;C;;
272.305 - item : UnexpectedException;C;;
272.306 - item : _OutputRedirectingPdb;C;|PRIVATE|;
272.307 - item : _SpoofOut;C;|PRIVATE|;
272.308 - item : _TestClass;C;|PRIVATE|;
272.309 - item : __all__;D;;
272.310 - item : __docformat__;D;|PRIVATE|;
272.311 - item : __future__;I;|PRIVATE|;
272.312 - item : __test__;D;|PRIVATE|;
272.313 - item : _comment_line;F;|PRIVATE|;line;
272.314 - item : _ellipsis_match;F;|PRIVATE|;want,got;
272.315 - item : _exception_traceback;F;|PRIVATE|;exc_info;
272.316 - item : _extract_future_flags;F;|PRIVATE|;globs;
272.317 - item : _indent;F;|PRIVATE|;s,indent;
272.318 - item : _load_testfile;F;|PRIVATE|;filename,package,module_relative;
272.319 - item : _module_relative_path;F;|PRIVATE|;module,path;
272.320 - item : _normalize_module;F;|PRIVATE|;module,depth;
272.321 - item : _test;F;|PRIVATE|;;
272.322 - item : _unittest_reportflags;D;|PRIVATE|;
272.323 - item : debug;F;;module,name,pm;
272.324 - item : debug_script;F;|PRIVATE|;src,pm,globs;
272.325 - item : debug_src;F;;src,pm,globs;
272.326 - item : difflib;I;|PRIVATE|;
272.327 - item : inspect;I;|PRIVATE|;
272.328 - item : linecache;I;|PRIVATE|;
272.329 - item : master;D;|PRIVATE|;
272.330 - item : os;I;|PRIVATE|;
272.331 - item : pdb;I;|PRIVATE|;
272.332 - item : re;I;|PRIVATE|;
272.333 - item : register_optionflag;F;;name;
272.334 - item : run_docstring_examples;F;;f,globs,verbose,name,compileflags,optionflags;
272.335 - item : script_from_examples;F;;s;
272.336 - item : set_unittest_reportflags;F;;flags;
272.337 - item : sys;I;|PRIVATE|;
272.338 - item : tempfile;I;|PRIVATE|;
272.339 - item : testfile;F;;filename,module_relative,name,package,globs,verbose,report,optionflags,extraglobs,raise_on_error,parser,encoding;
272.340 - item : testmod;F;;m,name,globs,verbose,report,optionflags,extraglobs,raise_on_error,exclude_empty;
272.341 - item : testsource;F;;module,name;
272.342 - item : traceback;I;|PRIVATE|;
272.343 - item : unittest;I;|PRIVATE|;
272.344 - item : warnings;I;|PRIVATE|;
272.345 - module : doctest
272.346 -
272.347 -Not Searchable Keys:
273.1 --- a/python.editor/test/unit/data/testfiles/empty.py Sun Jan 04 13:11:53 2015 -0600
273.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
273.3 @@ -1,5 +0,0 @@
273.4 -#! /usr/bin/python
273.5 -
273.6 -print "Hello World!"
273.7 -
273.8 -
274.1 --- a/python.editor/test/unit/data/testfiles/empty.py.folds Sun Jan 04 13:11:53 2015 -0600
274.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
274.3 @@ -1,6 +0,0 @@
274.4 - #! /usr/bin/python
274.5 -
274.6 - print "Hello World!"
274.7 -
274.8 -
274.9 -
275.1 --- a/python.editor/test/unit/data/testfiles/empty.py.nameoffsets Sun Jan 04 13:11:53 2015 -0600
275.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
275.3 @@ -1,6 +0,0 @@
275.4 -
275.5 -#! /usr/bin/python
275.6 -
275.7 -print "Hello World!"
275.8 -
275.9 -
276.1 --- a/python.editor/test/unit/data/testfiles/empty.py.offsets Sun Jan 04 13:11:53 2015 -0600
276.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
276.3 @@ -1,6 +0,0 @@
276.4 -
276.5 -#! /usr/bin/python
276.6 -
276.7 -<Module><Print>print <Str>"Hello World!"</Str></Print></Module>
276.8 -
276.9 -
277.1 --- a/python.editor/test/unit/data/testfiles/empty.py.semantic Sun Jan 04 13:11:53 2015 -0600
277.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
277.3 @@ -1,5 +0,0 @@
277.4 -#! /usr/bin/python
277.5 -
277.6 -print "Hello World!"
277.7 -
277.8 -
278.1 --- a/python.editor/test/unit/data/testfiles/empty.py.testKeywords.completion Sun Jan 04 13:11:53 2015 -0600
278.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
278.3 @@ -1,1220 +0,0 @@
278.4 -Code completion result for source line:
278.5 -|print "Hello World!"
278.6 -(QueryType=COMPLETION, NameKind=PREFIX)
278.7 -------------------------------------
278.8 -CLASS A
278.9 -CLASS ABCMeta
278.10 -CLASS AEServer
278.11 -CLASS AEText
278.12 -CLASS ASTVisitor
278.13 -CLASS AbstractBasicAuthHandler
278.14 -CLASS AbstractClassCode
278.15 -CLASS AbstractCompileMode
278.16 -CLASS AbstractDigestAuthHandler
278.17 -CLASS AbstractFormatter
278.18 -CLASS AbstractFunctionCode
278.19 -CLASS AbstractHTTPHandler
278.20 -CLASS AbstractWriter
278.21 -CLASS Add
278.22 -CLASS And
278.23 -CLASS Application
278.24 -CLASS ArgumentError
278.25 -CLASS ArithmeticError
278.26 -CLASS ArithmeticError
278.27 -CLASS Array
278.28 -CLASS ArrayInstance
278.29 -CLASS AssAttr
278.30 -CLASS AssList
278.31 -CLASS AssName
278.32 -CLASS AssTuple
278.33 -CLASS Assert
278.34 -CLASS AssertionError
278.35 -CLASS AssertionError
278.36 -CLASS Assign
278.37 -CLASS AsyncResult
278.38 -CLASS Attr
278.39 -CLASS AttributeError
278.40 -CLASS AttributeError
278.41 -CLASS AttributeList
278.42 -CLASS AttributeMap
278.43 -CLASS Attributes
278.44 -CLASS AttributesImpl
278.45 -CLASS AttributesNS
278.46 -CLASS AttributesNSImpl
278.47 -CLASS AugAssign
278.48 -CLASS AugGetattr
278.49 -CLASS AugName
278.50 -CLASS AugSlice
278.51 -CLASS AugSubscript
278.52 -CLASS AuthenticationError
278.53 -CLASS AutoGILError
278.54 -CLASS B
278.55 -CLASS BCPPCompiler
278.56 -CLASS BCPTestCase
278.57 -CLASS BZ2Compressor
278.58 -CLASS BZ2Decompressor
278.59 -CLASS BZ2File
278.60 -CLASS Babyl
278.61 -CLASS BabylMailbox
278.62 -CLASS BabylMessage
278.63 -CLASS Backquote
278.64 -CLASS BadBoundaryPointsErr
278.65 -CLASS BadFutureParser
278.66 -CLASS BadOptionError
278.67 -CLASS BadStatusLine
278.68 -CLASS BadZipfile
278.69 -CLASS Balloon
278.70 -CLASS Bar
278.71 -CLASS BaseCGIHandler
278.72 -CLASS BaseCookie
278.73 -CLASS BaseException
278.74 -CLASS BaseException
278.75 -CLASS BaseHTTPRequestHandler
278.76 -CLASS BaseHandler
278.77 -CLASS BaseIncrementalParser
278.78 -CLASS BaseManager
278.79 -CLASS BaseProxy
278.80 -CLASS BaseRequestHandler
278.81 -CLASS BaseRotatingHandler
278.82 -CLASS BaseSet
278.83 -CLASS BasicModuleImporter
278.84 -CLASS BasicModuleLoader
278.85 -CLASS BastionClass
278.86 -CLASS Baz
278.87 -CLASS Bdb
278.88 -CLASS BdbQuit
278.89 -CLASS BigEndianStructure
278.90 -CLASS Binary
278.91 -CLASS Bitand
278.92 -CLASS Bitor
278.93 -CLASS Bitxor
278.94 -CLASS Block
278.95 -CLASS BlockFinder
278.96 -CLASS BlockingIOError
278.97 -CLASS Boolean
278.98 -CLASS BoundaryError
278.99 -CLASS BoundedSemaphore
278.100 -CLASS Break
278.101 -CLASS Breakpoint
278.102 -CLASS BsdDbShelf
278.103 -CLASS BufferTooShort
278.104 -CLASS BufferedIOBase
278.105 -CLASS BufferedRWPair
278.106 -CLASS BufferedRandom
278.107 -CLASS BufferedReader
278.108 -CLASS BufferedWriter
278.109 -CLASS BufferingFormatter
278.110 -CLASS BufferingHandler
278.111 -CLASS BuildPyTestCase
278.112 -CLASS BuildScriptsTestCase
278.113 -CLASS BuiltinImporter
278.114 -CLASS Bulkcopy
278.115 -CLASS ButtonBox
278.116 -CLASS BytesIO
278.117 -CLASS C
278.118 -CLASS CAB
278.119 -CLASS CCompiler
278.120 -CLASS CCompilerError
278.121 -CLASS CDATASection
278.122 -CLASS CDLL
278.123 -CLASS CGIHTTPRequestHandler
278.124 -CLASS CGIHandler
278.125 -CLASS CGIXMLRPCRequestHandler
278.126 -CLASS CacheFTPHandler
278.127 -CLASS CallFunc
278.128 -CLASS CalledProcessError
278.129 -CLASS CannotSendHeader
278.130 -CLASS CannotSendRequest
278.131 -CLASS Canonizer
278.132 -CLASS CharacterData
278.133 -CLASS Charset
278.134 -CLASS CharsetError
278.135 -CLASS CheckList
278.136 -CLASS Childless
278.137 -CLASS Chunk
278.138 -CLASS Clamped
278.139 -CLASS Class
278.140 -CLASS ClassCodeGenerator
278.141 -CLASS ClassScope
278.142 -CLASS Cmd
278.143 -CLASS CodeGenerator
278.144 -CLASS Codec
278.145 -CLASS CodecRegistryError
278.146 -CLASS ComboBox
278.147 -CLASS Command
278.148 -CLASS CommandCompiler
278.149 -CLASS Comment
278.150 -CLASS Compare
278.151 -CLASS Comparison
278.152 -CLASS Compile
278.153 -CLASS CompileError
278.154 -CLASS Completer
278.155 -CLASS Complex
278.156 -CLASS ComponentItem
278.157 -CLASS Condition
278.158 -CLASS ConfigParser
278.159 -CLASS Connection
278.160 -CLASS Const
278.161 -CLASS ContentGenerator
278.162 -CLASS ContentHandler
278.163 -CLASS Context
278.164 -CLASS Continue
278.165 -CLASS Control
278.166 -CLASS ControlsWindow
278.167 -CLASS ConversionError
278.168 -CLASS Cookie
278.169 -CLASS CookieError
278.170 -CLASS CookieJar
278.171 -CLASS CookiePolicy
278.172 -CLASS CoverageResults
278.173 -CLASS Cursor
278.174 -CLASS CygwinCCompiler
278.175 -CLASS D
278.176 -CLASS DOMBuilder
278.177 -CLASS DOMEntityResolver
278.178 -CLASS DOMError
278.179 -CLASS DOMEventStream
278.180 -CLASS DOMException
278.181 -CLASS DOMImplementation
278.182 -CLASS DOMInputSource
278.183 -CLASS DOMStringSizeErr
278.184 -CLASS DTDHandler
278.185 -CLASS Data
278.186 -CLASS Database
278.187 -CLASS DatagramHandler
278.188 -CLASS DatagramRequestHandler
278.189 -CLASS DateTime
278.190 -CLASS DbfilenameShelf
278.191 -CLASS DebugRunner
278.192 -CLASS DebuggingServer
278.193 -CLASS Decimal
278.194 -CLASS DecimalException
278.195 -CLASS DeclHandler
278.196 -CLASS DecodedGenerator
278.197 -CLASS Decorators
278.198 -CLASS DefaultCookiePolicy
278.199 -CLASS DefaultHandler
278.200 -CLASS Delegator
278.201 -CLASS DeprecationWarning
278.202 -CLASS DeprecationWarning
278.203 -CLASS Dialect
278.204 -CLASS Dialog
278.205 -CLASS DialogWindow
278.206 -CLASS Dict
278.207 -CLASS DictMixin
278.208 -CLASS DictReader
278.209 -CLASS DictWriter
278.210 -CLASS Differ
278.211 -CLASS DirList
278.212 -CLASS DirSelectBox
278.213 -CLASS DirSelectDialog
278.214 -CLASS DirTree
278.215 -CLASS Directory
278.216 -CLASS Discard
278.217 -CLASS Distribution
278.218 -CLASS DistributionMetadata
278.219 -CLASS DistributionTestCase
278.220 -CLASS DistutilsArgError
278.221 -CLASS DistutilsClassError
278.222 -CLASS DistutilsError
278.223 -CLASS DistutilsExecError
278.224 -CLASS DistutilsFileError
278.225 -CLASS DistutilsGetoptError
278.226 -CLASS DistutilsInternalError
278.227 -CLASS DistutilsModuleError
278.228 -CLASS DistutilsOptionError
278.229 -CLASS DistutilsPlatformError
278.230 -CLASS DistutilsSetupError
278.231 -CLASS DistutilsTemplateError
278.232 -CLASS Div
278.233 -CLASS DivisionByZero
278.234 -CLASS Doc
278.235 -CLASS DocCGIXMLRPCRequestHandler
278.236 -CLASS DocTest
278.237 -CLASS DocTestFailure
278.238 -CLASS DocTestFinder
278.239 -CLASS DocTestParser
278.240 -CLASS DocTestRunner
278.241 -CLASS DocXMLRPCRequestHandler
278.242 -CLASS DocXMLRPCServer
278.243 -CLASS Document
278.244 -CLASS DocumentFragment
278.245 -CLASS DocumentHandler
278.246 -CLASS DocumentType
278.247 -CLASS DomstringSizeErr
278.248 -CLASS DumbWriter
278.249 -CLASS DummyCommand
278.250 -CLASS DuplicateSectionError
278.251 -CLASS DynLoadSuffixImporter
278.252 -CLASS EMXCCompiler
278.253 -CLASS EOFError
278.254 -CLASS EOFError
278.255 -CLASS ESISDocHandler
278.256 -CLASS Element
278.257 -CLASS ElementInfo
278.258 -CLASS ElementTree
278.259 -CLASS Ellipsis
278.260 -CLASS Empty
278.261 -CLASS EmptyNode
278.262 -CLASS EndOfBlock
278.263 -CLASS Entity
278.264 -CLASS EntityResolver
278.265 -CLASS Enum
278.266 -CLASS EnvironmentError
278.267 -CLASS EnvironmentError
278.268 -CLASS Error
278.269 -CLASS ErrorDuringImport
278.270 -CLASS ErrorHandler
278.271 -CLASS ErrorPrinter
278.272 -CLASS ErrorRaiser
278.273 -CLASS Event
278.274 -CLASS EventBroadcaster
278.275 -CLASS EventException
278.276 -CLASS ExFileSelectBox
278.277 -CLASS Example
278.278 -CLASS ExampleASTVisitor
278.279 -CLASS Exception
278.280 -CLASS Exception
278.281 -CLASS Exec
278.282 -CLASS ExitNow
278.283 -CLASS ExpatError
278.284 -CLASS ExpatParser
278.285 -CLASS Expression
278.286 -CLASS ExpressionCodeGenerator
278.287 -CLASS Extension
278.288 -CLASS F
278.289 -CLASS FTP
278.290 -CLASS FTPHandler
278.291 -CLASS Factory
278.292 -CLASS FancyGetopt
278.293 -CLASS FancyModuleLoader
278.294 -CLASS FancyURLopener
278.295 -CLASS Fault
278.296 -CLASS Feature
278.297 -CLASS FeedParser
278.298 -CLASS FieldStorage
278.299 -CLASS FileCookieJar
278.300 -CLASS FileEntry
278.301 -CLASS FileHandler
278.302 -CLASS FileIO
278.303 -CLASS FileInput
278.304 -CLASS FileList
278.305 -CLASS FileSelectBox
278.306 -CLASS FileWrapper
278.307 -CLASS Filter
278.308 -CLASS Filterer
278.309 -CLASS FingerHandler
278.310 -CLASS FirstHeaderLineIsContinuationD
278.311 -CLASS FloatingPointError
278.312 -CLASS FloatingPointError
278.313 -CLASS FloorDiv
278.314 -CLASS FlowGraph
278.315 -CLASS Folder
278.316 -CLASS Foo
278.317 -CLASS For
278.318 -CLASS ForkingMixIn
278.319 -CLASS ForkingTCPServer
278.320 -CLASS ForkingUDPServer
278.321 -CLASS Form
278.322 -CLASS FormContent
278.323 -CLASS FormContentDict
278.324 -CLASS Formatter
278.325 -CLASS Fraction
278.326 -CLASS From
278.327 -CLASS FtException
278.328 -CLASS Full
278.329 -CLASS FuncPtr
278.330 -CLASS Function
278.331 -CLASS FunctionCodeGenerator
278.332 -CLASS FunctionScope
278.333 -CLASS FunctionTestCase
278.334 -CLASS FutureParser
278.335 -CLASS FutureWarning
278.336 -CLASS FutureWarning
278.337 -CLASS GNUTranslations
278.338 -CLASS GenExpr
278.339 -CLASS GenExprFor
278.340 -CLASS GenExprIf
278.341 -CLASS GenExprInner
278.342 -CLASS GenExprScope
278.343 -CLASS Generator
278.344 -CLASS GeneratorExit
278.345 -CLASS GeneratorExit
278.346 -CLASS Getattr
278.347 -CLASS GetattrMagic
278.348 -CLASS GetoptError
278.349 -CLASS Global
278.350 -CLASS GopherError
278.351 -CLASS GopherHandler
278.352 -CLASS GridBag
278.353 -CLASS GzipFile
278.354 -CLASS HList
278.355 -CLASS HMAC
278.356 -CLASS HRESULT
278.357 -CLASS HTMLDoc
278.358 -CLASS HTMLParseError
278.359 -CLASS HTMLParser
278.360 -CLASS HTMLRepr
278.361 -CLASS HTTP
278.362 -CLASS HTTPBasicAuthHandler
278.363 -CLASS HTTPConnection
278.364 -CLASS HTTPCookieProcessor
278.365 -CLASS HTTPDefaultErrorHandler
278.366 -CLASS HTTPDigestAuthHandler
278.367 -CLASS HTTPError
278.368 -CLASS HTTPErrorProcessor
278.369 -CLASS HTTPException
278.370 -CLASS HTTPHandler
278.371 -CLASS HTTPPasswordMgr
278.372 -CLASS HTTPPasswordMgrWithDefaultReal
278.373 -CLASS HTTPRedirectHandler
278.374 -CLASS HTTPResponse
278.375 -CLASS HTTPSConnection
278.376 -CLASS HTTPSHandler
278.377 -CLASS HTTPServer
278.378 -CLASS Handler
278.379 -CLASS HandlerBase
278.380 -CLASS Header
278.381 -CLASS HeaderParseError
278.382 -CLASS HeaderParser
278.383 -CLASS Headers
278.384 -CLASS HelpFormatter
278.385 -CLASS Helper
278.386 -CLASS HierarchyRequestErr
278.387 -CLASS Hook
278.388 -CLASS Hooks
278.389 -CLASS HtmlDiff
278.390 -CLASS IC
278.391 -CLASS IMAP4
278.392 -CLASS IMAP4_SSL
278.393 -CLASS IMAP4_stream
278.394 -CLASS IOBase
278.395 -CLASS IOError
278.396 -CLASS IOError
278.397 -CLASS Identified
278.398 -CLASS If
278.399 -CLASS IfExp
278.400 -CLASS Ignore
278.401 -CLASS IllegalMonthError
278.402 -CLASS IllegalWeekdayError
278.403 -CLASS ImmutableSet
278.404 -CLASS ImpImporter
278.405 -CLASS ImpLoader
278.406 -CLASS Import
278.407 -CLASS ImportError
278.408 -CLASS ImportError
278.409 -CLASS ImportManager
278.410 -CLASS ImportWarning
278.411 -CLASS ImportWarning
278.412 -CLASS Importer
278.413 -CLASS ImproperConnectionState
278.414 -CLASS Incomplete
278.415 -CLASS IncompleteRead
278.416 -CLASS IncrementalDecoder
278.417 -CLASS IncrementalEncoder
278.418 -CLASS IncrementalNewlineDecoder
278.419 -CLASS IncrementalParser
278.420 -CLASS IndentedHelpFormatter
278.421 -CLASS IndexError
278.422 -CLASS IndexError
278.423 -CLASS IndexSizeErr
278.424 -CLASS Inexact
278.425 -CLASS IniParser
278.426 -CLASS InputOnly
278.427 -CLASS InputSource
278.428 -CLASS InsertionLoc
278.429 -CLASS InstallScriptsTestCase
278.430 -CLASS InstallTestCase
278.431 -CLASS Integral
278.432 -CLASS Interactive
278.433 -CLASS InteractiveCodeGenerator
278.434 -CLASS InteractiveConsole
278.435 -CLASS InteractiveInterpreter
278.436 -CLASS InterpFormContentDict
278.437 -CLASS InterpolationDepthError
278.438 -CLASS InterpolationError
278.439 -CLASS InterpolationSyntaxError
278.440 -CLASS IntlText
278.441 -CLASS IntlWritingCode
278.442 -CLASS InuseAttributeErr
278.443 -CLASS InvalidAccessErr
278.444 -CLASS InvalidCharacterErr
278.445 -CLASS InvalidModificationErr
278.446 -CLASS InvalidNodeTypeErr
278.447 -CLASS InvalidOperation
278.448 -CLASS InvalidStateErr
278.449 -CLASS InvalidURL
278.450 -CLASS Invert
278.451 -CLASS IsqlCmd
278.452 -CLASS IsqlExit
278.453 -CLASS IterableUserDict
278.454 -CLASS JSONDecoder
278.455 -CLASS JSONEncoder
278.456 -CLASS JavaSAXParser
278.457 -CLASS JoinableQueue
278.458 -CLASS JyDTDHandlerWrapper
278.459 -CLASS JyEntityResolverWrapper
278.460 -CLASS JyErrorHandlerWrapper
278.461 -CLASS JyInputSourceWrapper
278.462 -CLASS JythonCompiler
278.463 -CLASS JythonSignalHandler
278.464 -CLASS KeyError
278.465 -CLASS KeyError
278.466 -CLASS KeyboardInterrupt
278.467 -CLASS KeyboardInterrupt
278.468 -CLASS Keyword
278.469 -CLASS LOBTestCase
278.470 -CLASS LWPCookieJar
278.471 -CLASS LabelEntry
278.472 -CLASS LabelFrame
278.473 -CLASS Lambda
278.474 -CLASS LambdaScope
278.475 -CLASS LargeZipFile
278.476 -CLASS LeftShift
278.477 -CLASS LexicalHandler
278.478 -CLASS LexicalXMLGenerator
278.479 -CLASS LibError
278.480 -CLASS LibraryLoader
278.481 -CLASS LineAddrTable
278.482 -CLASS LinkError
278.483 -CLASS List
278.484 -CLASS ListComp
278.485 -CLASS ListCompFor
278.486 -CLASS ListCompIf
278.487 -CLASS ListNoteBook
278.488 -CLASS Listener
278.489 -CLASS LittleEndianStructure
278.490 -CLASS LoadError
278.491 -CLASS LocalNameFinder
278.492 -CLASS Location
278.493 -CLASS Locator
278.494 -CLASS Lock
278.495 -CLASS Log
278.496 -CLASS LogRecord
278.497 -CLASS Logger
278.498 -CLASS LoggingSilencer
278.499 -CLASS Logical
278.500 -CLASS LookupError
278.501 -CLASS LookupError
278.502 -CLASS LooseVersion
278.503 -CLASS MH
278.504 -CLASS MHMailbox
278.505 -CLASS MHMessage
278.506 -CLASS MIMEApplication
278.507 -CLASS MIMEAudio
278.508 -CLASS MIMEBase
278.509 -CLASS MIMEImage
278.510 -CLASS MIMEMessage
278.511 -CLASS MIMEMultipart
278.512 -CLASS MIMENonMultipart
278.513 -CLASS MIMEText
278.514 -CLASS MMDF
278.515 -CLASS MMDFMessage
278.516 -CLASS MSVCCompiler
278.517 -CLASS MWerksCompiler
278.518 -CLASS MacroExpander
278.519 -CLASS Mailbox
278.520 -CLASS Maildir
278.521 -CLASS MaildirMessage
278.522 -CLASS MailmanProxy
278.523 -CLASS MalformedHeaderDefect
278.524 -CLASS Manager
278.525 -CLASS Marshaller
278.526 -CLASS MemoryError
278.527 -CLASS MemoryError
278.528 -CLASS MemoryHandler
278.529 -CLASS Message
278.530 -CLASS MessageDefect
278.531 -CLASS MessageError
278.532 -CLASS MessageParseError
278.533 -CLASS MetadataTestCase
278.534 -CLASS Meter
278.535 -CLASS MimeWriter
278.536 -CLASS Mingw32CCompiler
278.537 -CLASS MiniApplication
278.538 -CLASS MiniFieldStorage
278.539 -CLASS MisplacedEnvelopeHeaderDefect
278.540 -CLASS MissingSectionHeaderError
278.541 -CLASS MmdfMailbox
278.542 -CLASS Mod
278.543 -CLASS Model
278.544 -CLASS Module
278.545 -CLASS ModuleCodeGenerator
278.546 -CLASS ModuleFinder
278.547 -CLASS ModuleImporter
278.548 -CLASS ModuleLoader
278.549 -CLASS ModuleScanner
278.550 -CLASS ModuleScope
278.551 -CLASS MozillaCookieJar
278.552 -CLASS Mul
278.553 -CLASS MultiCall
278.554 -CLASS MultiCallIterator
278.555 -CLASS MultiFile
278.556 -CLASS MultipartConversionError
278.557 -CLASS MultipartInvariantViolationDef
278.558 -CLASS MutableString
278.559 -CLASS MyClass
278.560 -CLASS MyTest
278.561 -CLASS NNTP
278.562 -CLASS NNTPDataError
278.563 -CLASS NNTPPermanentError
278.564 -CLASS NNTPProtocolError
278.565 -CLASS NNTPReplyError
278.566 -CLASS NNTPTemporaryError
278.567 -CLASS NProperty
278.568 -CLASS NTEventLogHandler
278.569 -CLASS NULL
278.570 -CLASS Name
278.571 -CLASS NameError
278.572 -CLASS NameError
278.573 -CLASS NamedNodeMap
278.574 -CLASS NamespaceErr
278.575 -CLASS NannyNag
278.576 -CLASS NestedScopeMixin
278.577 -CLASS Netrc
278.578 -CLASS NetrcParseError
278.579 -CLASS NewStyle
278.580 -CLASS NoBoundaryInMultipartDefect
278.581 -CLASS NoDataAllowedErr
278.582 -CLASS NoModificationAllowedErr
278.583 -CLASS NoOpMetaClass
278.584 -CLASS NoOptionError
278.585 -CLASS NoSectionError
278.586 -CLASS Node
278.587 -CLASS NodeFilter
278.588 -CLASS NodeTransformer
278.589 -CLASS NodeVisitor
278.590 -CLASS Not
278.591 -CLASS NotANumber
278.592 -CLASS NotConnected
278.593 -CLASS NotFoundErr
278.594 -CLASS NotImplementedError
278.595 -CLASS NotImplementedError
278.596 -CLASS NotSupportedErr
278.597 -CLASS Notation
278.598 -CLASS NoteBook
278.599 -CLASS NullFormatter
278.600 -CLASS NullImporter
278.601 -CLASS NullTranslations
278.602 -CLASS NullWriter
278.603 -CLASS Number
278.604 -CLASS OSError
278.605 -CLASS OSError
278.606 -CLASS OSSAudioError
278.607 -CLASS ObjectSpecifier
278.608 -CLASS OleDLL
278.609 -CLASS OpFinder
278.610 -CLASS OpenerDirector
278.611 -CLASS OptParseError
278.612 -CLASS Option
278.613 -CLASS OptionConflictError
278.614 -CLASS OptionContainer
278.615 -CLASS OptionDummy
278.616 -CLASS OptionError
278.617 -CLASS OptionGroup
278.618 -CLASS OptionMenu
278.619 -CLASS OptionParser
278.620 -CLASS OptionValueError
278.621 -CLASS Or
278.622 -CLASS OracleSPTest
278.623 -CLASS Ordinal
278.624 -CLASS OutputChecker
278.625 -CLASS Overflow
278.626 -CLASS OverflowError
278.627 -CLASS OverflowError
278.628 -CLASS POP3
278.629 -CLASS POP3_SSL
278.630 -CLASS Packer
278.631 -CLASS PanedWindow
278.632 -CLASS Panel
278.633 -CLASS Parser
278.634 -CLASS ParserBase
278.635 -CLASS ParserError
278.636 -CLASS ParsingError
278.637 -CLASS Pass
278.638 -CLASS Pattern
278.639 -CLASS Pdb
278.640 -CLASS PendingDeprecationWarning
278.641 -CLASS PendingDeprecationWarning
278.642 -CLASS PickleError
278.643 -CLASS Pickler
278.644 -CLASS PicklingError
278.645 -CLASS PlaceHolder
278.646 -CLASS Popen
278.647 -CLASS Popen3
278.648 -CLASS Popen4
278.649 -CLASS PopupMenu
278.650 -CLASS PortableUnixMailbox
278.651 -CLASS Power
278.652 -CLASS PreprocessError
278.653 -CLASS PrettyPrinter
278.654 -CLASS Print
278.655 -CLASS Printnl
278.656 -CLASS Process
278.657 -CLASS ProcessingInstruction
278.658 -CLASS Profile
278.659 -CLASS ProgressBar
278.660 -CLASS Prompt
278.661 -CLASS ProtocolError
278.662 -CLASS ProxyBasicAuthHandler
278.663 -CLASS ProxyDigestAuthHandler
278.664 -CLASS ProxyHandler
278.665 -CLASS PullDOM
278.666 -CLASS PureProxy
278.667 -CLASS PyCompileError
278.668 -CLASS PyDLL
278.669 -CLASS PyDialog
278.670 -CLASS PyFlowGraph
278.671 -CLASS PyHKEY
278.672 -CLASS PyZipFile
278.673 -CLASS QDPoint
278.674 -CLASS QDRectangle
278.675 -CLASS QName
278.676 -CLASS Queue
278.677 -CLASS RExec
278.678 -CLASS RGBColor
278.679 -CLASS RLock
278.680 -CLASS RadioButtonGroup
278.681 -CLASS Raise
278.682 -CLASS Random
278.683 -CLASS Range
278.684 -CLASS RangeException
278.685 -CLASS Rational
278.686 -CLASS RawIOBase
278.687 -CLASS RawTurtle
278.688 -CLASS ReadOnlySequentialNamedNodeMap
278.689 -CLASS Real
278.690 -CLASS Record
278.691 -CLASS ReferenceError
278.692 -CLASS ReferenceError
278.693 -CLASS Repr
278.694 -CLASS Request
278.695 -CLASS ResponseError
278.696 -CLASS ResponseNotReady
278.697 -CLASS ResultSet
278.698 -CLASS ResultSetRow
278.699 -CLASS Return
278.700 -CLASS RightShift
278.701 -CLASS RobotFileParser
278.702 -CLASS RootLogger
278.703 -CLASS RotatingFileHandler
278.704 -CLASS Rounded
278.705 -CLASS Row
278.706 -CLASS RuntimeError
278.707 -CLASS RuntimeError
278.708 -CLASS RuntimeWarning
278.709 -CLASS RuntimeWarning
278.710 -CLASS SAX2DOM
278.711 -CLASS SAXException
278.712 -CLASS SAXNotRecognizedException
278.713 -CLASS SAXNotSupportedException
278.714 -CLASS SAXParseException
278.715 -CLASS SAXReaderNotAvailable
278.716 -CLASS SGMLParseError
278.717 -CLASS SGMLParser
278.718 -CLASS SMTP
278.719 -CLASS SMTPAuthenticationError
278.720 -CLASS SMTPConnectError
278.721 -CLASS SMTPDataError
278.722 -CLASS SMTPException
278.723 -CLASS SMTPHandler
278.724 -CLASS SMTPHeloError
278.725 -CLASS SMTPRecipientsRefused
278.726 -CLASS SMTPResponseException
278.727 -CLASS SMTPSenderRefused
278.728 -CLASS SMTPServer
278.729 -CLASS SMTPServerDisconnected
278.730 -CLASS SQLServerSPTest
278.731 -CLASS SQLTestCase
278.732 -CLASS SSLError
278.733 -CLASS SSLSocket
278.734 -CLASS ST
278.735 -CLASS SafeConfigParser
278.736 -CLASS SafeTransport
278.737 -CLASS Schema
278.738 -CLASS Scope
278.739 -CLASS Screen
278.740 -CLASS ScrolledCavas
278.741 -CLASS ScrolledText
278.742 -CLASS ScrolledWindow
278.743 -CLASS Select
278.744 -CLASS Semaphore
278.745 -CLASS SequenceMatcher
278.746 -CLASS SerialCookie
278.747 -CLASS Server
278.748 -CLASS ServerHTMLDoc
278.749 -CLASS ServerProxy
278.750 -CLASS Set
278.751 -CLASS SgmlopParser
278.752 -CLASS Shape
278.753 -CLASS Shelf
278.754 -CLASS SimpleCookie
278.755 -CLASS SimpleHTTPRequestHandler
278.756 -CLASS SimpleHandler
278.757 -CLASS SimpleLocator
278.758 -CLASS SimpleXMLRPCDispatcher
278.759 -CLASS SimpleXMLRPCRequestHandler
278.760 -CLASS SimpleXMLRPCServer
278.761 -CLASS Slice
278.762 -CLASS Sliceobj
278.763 -CLASS SlowParser
278.764 -CLASS SmartCookie
278.765 -CLASS Sniffer
278.766 -CLASS SocketHandler
278.767 -CLASS SocketType
278.768 -CLASS Stack
278.769 -CLASS StackDepthTracker
278.770 -CLASS StandardError
278.771 -CLASS StandardError
278.772 -CLASS StartBoundaryNotFoundDefect
278.773 -CLASS Stats
278.774 -CLASS StdButtonBox
278.775 -CLASS Stmt
278.776 -CLASS StopIteration
278.777 -CLASS StopIteration
278.778 -CLASS StopTokenizing
278.779 -CLASS Strange
278.780 -CLASS StreamConverter
278.781 -CLASS StreamHandler
278.782 -CLASS StreamReader
278.783 -CLASS StreamRequestHandler
278.784 -CLASS StreamWriter
278.785 -CLASS StrictVersion
278.786 -CLASS StringIO
278.787 -CLASS Struct
278.788 -CLASS Structure
278.789 -CLASS StyledText
278.790 -CLASS Sub
278.791 -CLASS SubPattern
278.792 -CLASS Subnormal
278.793 -CLASS Subscript
278.794 -CLASS SummaryInformation
278.795 -CLASS Super
278.796 -CLASS SuperSuper
278.797 -CLASS SvFormContentDict
278.798 -CLASS Symbol
278.799 -CLASS SymbolTable
278.800 -CLASS SymbolVisitor
278.801 -CLASS SyncManager
278.802 -CLASS SyntaxErr
278.803 -CLASS SyntaxError
278.804 -CLASS SyntaxError
278.805 -CLASS SyntaxErrorChecker
278.806 -CLASS SyntaxWarning
278.807 -CLASS SyntaxWarning
278.808 -CLASS SysLogHandler
278.809 -CLASS SystemError
278.810 -CLASS SystemError
278.811 -CLASS SystemExit
278.812 -CLASS SystemExit
278.813 -CLASS SystemRandom
278.814 -CLASS TCPServer
278.815 -CLASS TList
278.816 -CLASS TalkTo
278.817 -CLASS TarError
278.818 -CLASS TarFile
278.819 -CLASS TarInfo
278.820 -CLASS Telnet
278.821 -CLASS TempdirManager
278.822 -CLASS Template
278.823 -CLASS Test
278.824 -CLASS TestCase
278.825 -CLASS TestClass
278.826 -CLASS TestCrispinTorture
278.827 -CLASS TestDistribution
278.828 -CLASS TestLoader
278.829 -CLASS TestResult
278.830 -CLASS TestSuite
278.831 -CLASS TestThread
278.832 -CLASS TestXMLParser
278.833 -CLASS Testcase
278.834 -CLASS Tester
278.835 -CLASS Text
278.836 -CLASS TextDoc
278.837 -CLASS TextFile
278.838 -CLASS TextIOBase
278.839 -CLASS TextIOWrapper
278.840 -CLASS TextRepr
278.841 -CLASS TextTestRunner
278.842 -CLASS TextWrapper
278.843 -CLASS Textbox
278.844 -CLASS Thread
278.845 -CLASS ThreadingMixIn
278.846 -CLASS ThreadingTCPServer
278.847 -CLASS ThreadingUDPServer
278.848 -CLASS ThreadingUnixDatagramServer
278.849 -CLASS ThreadingUnixStreamServer
278.850 -CLASS TimedRotatingFileHandler
278.851 -CLASS Timer
278.852 -CLASS TitledHelpFormatter
278.853 -CLASS Tix
278.854 -CLASS Tk
278.855 -CLASS TokenError
278.856 -CLASS Tokenizer
278.857 -CLASS TortureBase
278.858 -CLASS Trace
278.859 -CLASS Transformer
278.860 -CLASS Transport
278.861 -CLASS Tree
278.862 -CLASS TreeBuilder
278.863 -CLASS TryExcept
278.864 -CLASS TryFinally
278.865 -CLASS Tuple
278.866 -CLASS TupleArg
278.867 -CLASS Turtle
278.868 -CLASS TurtleScreen
278.869 -CLASS Type
278.870 -CLASS TypeError
278.871 -CLASS TypeError
278.872 -CLASS TypeInfo
278.873 -CLASS UDPServer
278.874 -CLASS URLError
278.875 -CLASS UUID
278.876 -CLASS UnaryAdd
278.877 -CLASS UnarySub
278.878 -CLASS UnboundLocalError
278.879 -CLASS UnboundLocalError
278.880 -CLASS Underflow
278.881 -CLASS UnexpectedException
278.882 -CLASS UnicodeDecodeError
278.883 -CLASS UnicodeDecodeError
278.884 -CLASS UnicodeEncodeError
278.885 -CLASS UnicodeEncodeError
278.886 -CLASS UnicodeError
278.887 -CLASS UnicodeError
278.888 -CLASS UnicodeTranslateError
278.889 -CLASS UnicodeTranslateError
278.890 -CLASS UnicodeWarning
278.891 -CLASS UnicodeWarning
278.892 -CLASS UnimplementedFileMode
278.893 -CLASS Union
278.894 -CLASS UnixCCompiler
278.895 -CLASS UnixDatagramServer
278.896 -CLASS UnixMailbox
278.897 -CLASS UnixStreamServer
278.898 -CLASS Unknown
278.899 -CLASS UnknownFileError
278.900 -CLASS UnknownHandler
278.901 -CLASS UnknownProtocol
278.902 -CLASS UnknownTransferEncoding
278.903 -CLASS Unload
278.904 -CLASS Unmarshaller
278.905 -CLASS Unpacker
278.906 -CLASS Unpickler
278.907 -CLASS UnpicklingError
278.908 -CLASS UnspecifiedEventTypeErr
278.909 -CLASS UnsupportedOperation
278.910 -CLASS UserDataHandler
278.911 -CLASS UserDict
278.912 -CLASS UserList
278.913 -CLASS UserString
278.914 -CLASS UserWarning
278.915 -CLASS UserWarning
278.916 -CLASS ValidationErr
278.917 -CLASS ValueError
278.918 -CLASS ValueError
278.919 -CLASS Values
278.920 -CLASS Vec2D
278.921 -CLASS Vendor
278.922 -CLASS Version
278.923 -CLASS VersionPredicate
278.924 -CLASS View
278.925 -CLASS WSGIRequestHandler
278.926 -CLASS WSGIServer
278.927 -CLASS Warning
278.928 -CLASS Warning
278.929 -CLASS Wave_read
278.930 -CLASS Wave_write
278.931 -CLASS WeakKeyDictionary
278.932 -CLASS WeakValueDictionary
278.933 -CLASS While
278.934 -CLASS WichmannHill
278.935 -CLASS WinDLL
278.936 -CLASS Window
278.937 -CLASS WindowsError
278.938 -CLASS WindowsError
278.939 -CLASS With
278.940 -CLASS WrongDocumentErr
278.941 -CLASS X
278.942 -CLASS XMLFilter
278.943 -CLASS XMLFilterBase
278.944 -CLASS XMLFilterImpl
278.945 -CLASS XMLGenerator
278.946 -CLASS XMLParser
278.947 -CLASS XMLRPCDocGenerator
278.948 -CLASS XMLReader
278.949 -CLASS XMLTreeBuilder
278.950 -CLASS XmlParseErr
278.951 -CLASS Yield
278.952 -CLASS Yuck
278.953 -CLASS ZeroDivisionError
278.954 -CLASS ZeroDivisionError
278.955 -CLASS ZipFile
278.956 -CLASS ZipImportError
278.957 -CLASS ZipInfo
278.958 -CLASS _CData [PROTECTE
278.959 -CLASS _FuncPtr [PROTECTE
278.960 -CLASS _SimpleCData [PROTECTE
278.961 -CLASS _posixfile_
278.962 -CLASS array
278.963 -CLASS async_chat
278.964 -CLASS bdist
278.965 -CLASS bdist_dumb
278.966 -CLASS bdist_msi
278.967 -CLASS bdist_rpm
278.968 -CLASS bdist_wininst
278.969 -CLASS bool
278.970 -CLASS bsddbobject
278.971 -CLASS build
278.972 -CLASS build_clib
278.973 -CLASS build_ext
278.974 -CLASS build_py
278.975 -CLASS build_scripts
278.976 -CLASS c_bool
278.977 -CLASS c_byte
278.978 -CLASS c_char
278.979 -CLASS c_char_p
278.980 -CLASS c_double
278.981 -CLASS c_float
278.982 -CLASS c_int
278.983 -CLASS c_int16
278.984 -CLASS c_int32
278.985 -CLASS c_int64
278.986 -CLASS c_int8
278.987 -CLASS c_long
278.988 -CLASS c_longdouble
278.989 -CLASS c_longlong
278.990 -CLASS c_short
278.991 -CLASS c_size_t
278.992 -CLASS c_ubyte
278.993 -CLASS c_uint
278.994 -CLASS c_uint16
278.995 -CLASS c_uint32
278.996 -CLASS c_uint64
278.997 -CLASS c_uint8
278.998 -CLASS c_ulong
278.999 -CLASS c_ulonglong
278.1000 -CLASS c_ushort
278.1001 -CLASS c_void_p
278.1002 -CLASS c_wchar
278.1003 -CLASS c_wchar_p
278.1004 -CLASS class
278.1005 -CLASS class
278.1006 -CLASS clean
278.1007 -CLASS closing
278.1008 -CLASS complex
278.1009 -CLASS compressobj
278.1010 -CLASS config
278.1011 -CLASS container
278.1012 -CLASS container
278.1013 -CLASS contextmanager
278.1014 -CLASS contextmanager
278.1015 -CLASS controller
278.1016 -CLASS date
278.1017 -CLASS datetime
278.1018 -CLASS dbexts
278.1019 -CLASS dbextsTestCase
278.1020 -CLASS dbhash
278.1021 -CLASS decompressobj
278.1022 -CLASS deque
278.1023 -CLASS dict
278.1024 -CLASS dict
278.1025 -CLASS dircmp
278.1026 -CLASS dispatcher
278.1027 -CLASS dispatcher_with_send
278.1028 -CLASS dl
278.1029 -CLASS error
278.1030 -CLASS error_data
278.1031 -CLASS error_reply
278.1032 -CLASS error_temp
278.1033 -CLASS excel
278.1034 -CLASS excel_tab
278.1035 -CLASS executor
278.1036 -CLASS fifo
278.1037 -CLASS file
278.1038 -CLASS file
278.1039 -CLASS file_dispatcher
278.1040 -CLASS file_wrapper
278.1041 -CLASS float
278.1042 -CLASS float
278.1043 -CLASS foo
278.1044 -CLASS gaierror
278.1045 -CLASS herror
278.1046 -CLASS install
278.1047 -CLASS install_data
278.1048 -CLASS install_egg_info
278.1049 -CLASS install_headers
278.1050 -CLASS install_lib
278.1051 -CLASS install_misc
278.1052 -CLASS install_scripts
278.1053 -CLASS instance
278.1054 -CLASS instance
278.1055 -CLASS int
278.1056 -CLASS iterator
278.1057 -CLASS iterator
278.1058 -CLASS list
278.1059 -CLASS local
278.1060 -CLASS lock
278.1061 -CLASS long
278.1062 -CLASS main
278.1063 -CLASS mbox
278.1064 -CLASS mboxMessage
278.1065 -CLASS mllib
278.1066 -CLASS mmap
278.1067 -CLASS multiprocessing.Pool
278.1068 -CLASS mutex
278.1069 -CLASS mxODBCProxy
278.1070 -CLASS netrc
278.1071 -CLASS object
278.1072 -CLASS object
278.1073 -CLASS oss_audio_device
278.1074 -CLASS oss_mixer_device
278.1075 -CLASS poll
278.1076 -CLASS py_object
278.1077 -CLASS register
278.1078 -CLASS scheduler
278.1079 -CLASS sdist
278.1080 -CLASS set
278.1081 -CLASS set
278.1082 -CLASS shlex
278.1083 -CLASS simple_producer
278.1084 -CLASS socket
278.1085 -CLASS stat_result
278.1086 -CLASS str
278.1087 -CLASS str
278.1088 -CLASS test_dist
278.1089 -CLASS test_zxjdbc
278.1090 -CLASS time
278.1091 -CLASS timedelta
278.1092 -CLASS timeout
278.1093 -CLASS tixCommand
278.1094 -CLASS tmxxx
278.1095 -CLASS tuple
278.1096 -CLASS tzinfo
278.1097 -CLASS unicode
278.1098 -CLASS unicode
278.1099 -CLASS upload
278.1100 -CLASS window
278.1101 -CLASS xmlparser
278.1102 -CLASS zipimporter
278.1103 -CLASS zxAPITestCase
278.1104 -CLASS zxCoreTestCase
278.1105 -CLASS zxJDBCTestCase
278.1106 -METHOD __import__(name, globals, loca
278.1107 -METHOD abs(x)
278.1108 -METHOD all(iterable)
278.1109 -METHOD any(iterable)
278.1110 -METHOD ---apply(function, args, ke---
278.1111 -METHOD basestring()
278.1112 -METHOD bin(x)
278.1113 -METHOD bool(x)
278.1114 -METHOD buffer(object, offset, size)
278.1115 -METHOD callable(object)
278.1116 -METHOD chr(i)
278.1117 -METHOD classmethod(function)
278.1118 -METHOD cmp(x, y)
278.1119 -METHOD coerce(x, y)
278.1120 -METHOD compile(source, filename, mode
278.1121 -METHOD complex(real, imag)
278.1122 -METHOD delattr(object, name)
278.1123 -METHOD dict(arg)
278.1124 -METHOD dir(object)
278.1125 -METHOD divmod(a, b)
278.1126 -METHOD enumerate(sequence, start)
278.1127 -METHOD eval(expression, globals, loca
278.1128 -METHOD execfile(filename, globals, lo
278.1129 -METHOD exit(code)
278.1130 -METHOD file(filename, mode, bufsize)
278.1131 -METHOD filter(function, iterable)
278.1132 -METHOD float(x)
278.1133 -METHOD frozenset(iterable)
278.1134 -METHOD getattr(object, name, default)
278.1135 -METHOD globals()
278.1136 -METHOD hasattr(object, name)
278.1137 -METHOD hash(object)
278.1138 -METHOD help(object)
278.1139 -METHOD hex(x)
278.1140 -METHOD id(object)
278.1141 -METHOD input(prompt)
278.1142 -METHOD int(x, radix)
278.1143 -METHOD intern(string)
278.1144 -METHOD isinstance(object, classinfo)
278.1145 -METHOD issubclass(class, classinfo)
278.1146 -METHOD iter(o, sentinel)
278.1147 -METHOD len(s)
278.1148 -METHOD list(iterable)
278.1149 -METHOD locals()
278.1150 -METHOD long(x, radix)
278.1151 -METHOD map(function, iterable)
278.1152 -METHOD max(iterable, argskey)
278.1153 -METHOD min(iterable, argskey)
278.1154 -METHOD next(iterator, default)
278.1155 -METHOD object()
278.1156 -METHOD oct(x)
278.1157 -METHOD open(filename, mode, bufsize)
278.1158 -METHOD ord(c)
278.1159 -METHOD pow(x, y, z)
278.1160 -METHOD print(object, sep, end, file)
278.1161 -METHOD property(fget, fset, fdel, doc
278.1162 -METHOD quit(code)
278.1163 -METHOD range(start, stop, step)
278.1164 -METHOD raw_input(prompt)
278.1165 -METHOD reduce(function, iterable, ini
278.1166 -METHOD reload(module)
278.1167 -METHOD repr(object)
278.1168 -METHOD reversed(seq)
278.1169 -METHOD round(x, n)
278.1170 -METHOD set(iterable)
278.1171 -METHOD setattr(object, name, value)
278.1172 -METHOD slice(start, stop, step)
278.1173 -METHOD sorted(iterable, cmp, key, rev
278.1174 -METHOD staticmethod(function)
278.1175 -METHOD str(object)
278.1176 -METHOD sum(iterable, start)
278.1177 -METHOD super(type, object-or-type)
278.1178 -METHOD tuple(iterable)
278.1179 -METHOD type(name, bases, dict)
278.1180 -METHOD type(object)
278.1181 -METHOD unichr(i)
278.1182 -METHOD unicode(object, encoding, erro
278.1183 -METHOD vars(object)
278.1184 -METHOD xrange(start, stop, step)
278.1185 -METHOD zip(iterable)
278.1186 -VARIABLE Ellipsis
278.1187 -VARIABLE False
278.1188 -VARIABLE None
278.1189 -VARIABLE NotImplemented
278.1190 -VARIABLE True
278.1191 -VARIABLE __debug__
278.1192 -VARIABLE copyright
278.1193 -KEYWORD and
278.1194 -KEYWORD as
278.1195 -KEYWORD assert
278.1196 -KEYWORD break
278.1197 -KEYWORD class
278.1198 -KEYWORD continue
278.1199 -KEYWORD def
278.1200 -KEYWORD del
278.1201 -KEYWORD elif
278.1202 -KEYWORD else
278.1203 -KEYWORD except
278.1204 -KEYWORD exec
278.1205 -KEYWORD finally
278.1206 -KEYWORD for
278.1207 -KEYWORD from
278.1208 -KEYWORD global
278.1209 -KEYWORD if
278.1210 -KEYWORD import
278.1211 -KEYWORD in
278.1212 -KEYWORD is
278.1213 -KEYWORD lambda
278.1214 -KEYWORD not
278.1215 -KEYWORD or
278.1216 -KEYWORD pass
278.1217 -KEYWORD print
278.1218 -KEYWORD raise
278.1219 -KEYWORD return
278.1220 -KEYWORD try
278.1221 -KEYWORD while
278.1222 -KEYWORD with
278.1223 -KEYWORD yield
279.1 --- a/python.editor/test/unit/data/testfiles/emptydecorators.py Sun Jan 04 13:11:53 2015 -0600
279.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
279.3 @@ -1,1 +0,0 @@
279.4 -@
280.1 --- a/python.editor/test/unit/data/testfiles/emptydecorators.py.testDecorators1.completion Sun Jan 04 13:11:53 2015 -0600
280.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
280.3 @@ -1,11 +0,0 @@
280.4 -Code completion result for source line:
280.5 -@|
280.6 -(QueryType=COMPLETION, NameKind=PREFIX)
280.7 -METHOD abstractmethod
280.8 -METHOD classmethod
280.9 -METHOD contextmanager
280.10 -METHOD getargspec
280.11 -METHOD setprofile
280.12 -METHOD settrace
280.13 -METHOD staticmethod
280.14 -METHOD wrapper
281.1 --- a/python.editor/test/unit/data/testfiles/errors1.py Sun Jan 04 13:11:53 2015 -0600
281.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
281.3 @@ -1,12 +0,0 @@
281.4 -class A:
281.5 - def foo():
281.6 - self.filename = filename
281.7 -
281.8 -def toplevel(x,y,z):
281.9 - print "hello"
281.10 -
281.11 -def toplevel2():
281.12 - print "hello"
281.13 -
281.14 -class Bar:
281.15 - def noargs():
282.1 --- a/python.editor/test/unit/data/testfiles/errors1.py.errors Sun Jan 04 13:11:53 2015 -0600
282.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
282.3 @@ -1,2 +0,0 @@
282.4 -169-169:mismatched input '' expecting INDENT
282.5 -170-170:mismatched input '' expecting INDENT
283.1 --- a/python.editor/test/unit/data/testfiles/errors10.py Sun Jan 04 13:11:53 2015 -0600
283.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
283.3 @@ -1,6 +0,0 @@
283.4 -def myFunc(p):
283.5 - if p
283.6 - pass
283.7 - else:
283.8 - pass
283.9 -
284.1 --- a/python.editor/test/unit/data/testfiles/errors10.py.errors Sun Jan 04 13:11:53 2015 -0600
284.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
284.3 @@ -1,1 +0,0 @@
284.4 -23-23:mismatched input '\n' expecting COLON
285.1 --- a/python.editor/test/unit/data/testfiles/errors11.py Sun Jan 04 13:11:53 2015 -0600
285.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
285.3 @@ -1,12 +0,0 @@
285.4 -def myFunc(p):
285.5 - if p:
285.6 - pass
285.7 - else
285.8 - pass
285.9 -
285.10 -def myFunc(p):
285.11 - try
285.12 - p
285.13 - except
285.14 - pass
285.15 -
286.1 --- a/python.editor/test/unit/data/testfiles/errors11.py.errors Sun Jan 04 13:11:53 2015 -0600
286.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
286.3 @@ -1,3 +0,0 @@
286.4 -104-104:mismatched input '\n' expecting COLON
286.5 -46-46:mismatched input '\n' expecting COLON
286.6 -83-83:mismatched input '\n' expecting COLON
287.1 --- a/python.editor/test/unit/data/testfiles/errors12.py Sun Jan 04 13:11:53 2015 -0600
287.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
287.3 @@ -1,4 +0,0 @@
287.4 -from Module import ABC,DEF
287.5 -ABC()
287.6 -DEF()
287.7 -
288.1 --- a/python.editor/test/unit/data/testfiles/errors13.py Sun Jan 04 13:11:53 2015 -0600
288.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
288.3 @@ -1,8 +0,0 @@
288.4 -class Test:
288.5 - def myfunc(self, newparam,bla):
288.6 - print 'bla'
288.7 - pass
288.8 -
288.9 - def myfunct_two(self):
288.10 - pass
288.11 -
289.1 --- a/python.editor/test/unit/data/testfiles/errors2.py Sun Jan 04 13:11:53 2015 -0600
289.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
289.3 @@ -1,618 +0,0 @@
289.4 -"""Configuration file parser.
289.5 -
289.6 -A setup file consists of sections, lead by a "[section]" header,
289.7 -and followed by "name: value" entries, with continuations and such in
289.8 -the style of RFC 822.
289.9 -
289.10 - the same section, or values in a special [DEFAULT] section.
289.11 -
289.12 -For example:
289.13 -
289.14 - something: %(dir)s/whatever
289.15 -
289.16 -would resolve the "%(dir)s" to the value of dir. All reference
289.17 -expansions are done late, on demand.
289.18 -
289.19 -Intrinsic defaults can be specified by passing them into the
289.20 -ConfigParser constructor as a dictionary.
289.21 -
289.22 -class:
289.23 -
289.24 -ConfigParser -- responsible for parsing a list of
289.25 - configuration files, and managing the parsed database.
289.26 -
289.27 - methods:
289.28 -
289.29 - __init__(defaults=None)
289.30 - create the parser and specify a dictionary of intrinsic defaults. The
289.31 - keys must be strings, the values must be appropriate for %()s string
289.32 - interpolation. Note that `__name__' is always an intrinsic default;
289.33 - it's value is the section's name.
289.34 -
289.35 - sections()
289.36 - return all the configuration section names, sans DEFAULT
289.37 -
289.38 - has_section(section)
289.39 - return whether the given section exists
289.40 -
289.41 - has_option(section, option)
289.42 - return whether the given option exists in the given section
289.43 -
289.44 - options(section)
289.45 - return list of configuration options for the named section
289.46 -
289.47 - read(filenames)
289.48 - read and parse the list of named configuration files, given by
289.49 - name. A single filename is also allowed. Non-existing files
289.50 - are ignored.
289.51 -
289.52 - readfp(fp, filename=None)
289.53 - read and parse one configuration file, given as a file object.
289.54 - The filename defaults to fp.name; it is only used in error
289.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
289.56 -
289.57 - get(section, option, raw=False, vars=None)
289.58 - return a string value for the named option. All % interpolations are
289.59 - expanded in the return values, based on the defaults passed into the
289.60 - constructor and the DEFAULT section. Additional substitutions may be
289.61 - provided using the `vars' argument, which must be a dictionary whose
289.62 - contents override any pre-existing defaults.
289.63 -
289.64 - getint(section, options)
289.65 - like get(), but convert value to an integer
289.66 -
289.67 - getfloat(section, options)
289.68 - like get(), but convert value to a float
289.69 -
289.70 - getboolean(section, options)
289.71 - like get(), but convert value to a boolean (currently case
289.72 - insensitively defined as 0, false, no, off for False, and 1, true,
289.73 - yes, on for True). Returns False or True.
289.74 -
289.75 - items(section, raw=False, vars=None)
289.76 - return a list of tuples with (name, value) for each option
289.77 - in the section.
289.78 -
289.79 - remove_section(section)
289.80 - remove the given file section and all its options
289.81 -
289.82 - remove_option(section, option)
289.83 - remove the given option from the given section
289.84 -
289.85 - set(section, option, value)
289.86 - set the given option
289.87 -
289.88 - write(fp)
289.89 - write the configuration state in .ini format
289.90 -"""
289.91 -
289.92 -import re
289.93 -
289.94 -__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
289.95 - "InterpolationError", "InterpolationDepthError",
289.96 - "InterpolationSyntaxError", "ParsingError",
289.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
289.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
289.99 -
289.100 -DEFAULTSECT = "DEFAULT"
289.101 -
289.102 -MAX_INTERPOLATION_DEPTH = 10
289.103 -
289.104 -
289.105 -
289.106 -# exception classes
289.107 -class Error(Exception):
289.108 - """Base class for ConfigParser exceptions."""
289.109 -
289.110 - def __init__(self, msg=''):
289.111 - self.message = msg
289.112 - Exception.__init__(self, msg)
289.113 -
289.114 - def __repr__(self):
289.115 - return self.message
289.116 -
289.117 - __str__ = __repr__
289.118 -
289.119 -class NoSectionError(Error):
289.120 - """Rasssised when no section matches a requested option."""
289.121 -
289.122 - def __init__(self, section):
289.123 - Error.__init__(self, 'No section: ' + `section`)
289.124 - self.section = section
289.125 -
289.126 -class DuplicateSectionError(Error):
289.127 - """Raised when a section is multiply-created."""
289.128 -
289.129 - def __init__(self, section):
289.130 - Error.__init__(self, "Section %r already exists" % section)
289.131 - self.section = section
289.132 -
289.133 -class NoOptionError(Error):
289.134 - """A requested option was not found."""
289.135 -
289.136 - def __init__(self, option, section):
289.137 - Error.__init__(self, "No option %r in section: %r" %
289.138 - (option, section))
289.139 - self.option = option
289.140 - self.section = section
289.141 -
289.142 -class InterpolationError(Error):
289.143 - """Base class for interpolation-related exceptions."""
289.144 -
289.145 - def __init__(self, option, section, msg):
289.146 - Error.__init__(self, msg)
289.147 - self.option = option
289.148 - self.section = section
289.149 -
289.150 -class InterpolationMissingOptionError(InterpolationError):
289.151 - """A string substitution required a setting which was not available."""
289.152 -
289.153 - def __init__(self, option, section, rawval, reference):
289.154 - msg = ("Bad value substitution:\n"
289.155 - "\tsection: [%s]\n"
289.156 - "\toption : %s\n"
289.157 - "\tkey : %s\n"
289.158 - "\trawval : %s\n"
289.159 - % (section, option, reference, rawval))
289.160 - InterpolationError.__init__(self, option, section, msg)
289.161 - self.reference = reference
289.162 -
289.163 -class InterpolationSyntaxError(InterpolationError):
289.164 - """Raised when the source text into which substitutions are made
289.165 - does not conform to the required syntax."""
289.166 -
289.167 -class InterpolationDepthError(InterpolationError):
289.168 - """Raised when substitutions are nested too deeply."""
289.169 -
289.170 - def __init__(self, option, section, rawval):
289.171 - msg = ("Value interpolation too deeply recursive:\n"
289.172 - "\tsection: [%s]\n"
289.173 - "\toption : %s\n"
289.174 - "\trawval : %s\n"
289.175 - % (section, option, rawval))
289.176 - InterpolationError.__init__(self, option, section, msg)
289.177 -
289.178 -class ParsingError(Error):
289.179 - """Raised when a configuration file does not follow legal syntax."""
289.180 -
289.181 - def __init__(self, filename):
289.182 - Error.__init__(self, 'File contains parsing errors: %s' % filename)
289.183 - self.filename = filename
289.184 - self.errors = []
289.185 -
289.186 - def append(self, lineno, line):
289.187 - self.errors.append((lineno, line))
289.188 - self.message += '\n\t[line %2d]: %s' % (lineno, line)
289.189 -
289.190 -class MissingSectionHeaderError(ParsingError):
289.191 - """Raised when a key-value pair is found before any section header."""
289.192 -
289.193 - def __init__(self, filename, lineno, line):
289.194 - Error.__init__(
289.195 - self,
289.196 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
289.197 - (filename, lineno, line))
289.198 - self.filename = filename
289.199 - self.lineno = lineno
289.200 - self.line = line
289.201 -
289.202 -
289.203 -
289.204 -class RawConfigParser:
289.205 - def __init__(self, defaults=None):
289.206 - self._sections = {}
289.207 - if defaults is None:
289.208 - self._defaults = {}
289.209 - else:
289.210 - self._defaults = defaults
289.211 -
289.212 - def defaults(self):
289.213 - return self._defaults
289.214 -
289.215 - def sections(self):
289.216 - """Return a list of section names, excluding [DEFAULT]"""
289.217 - # self._sections will never have [DEFAULT] in it
289.218 - return self._sections.keys()
289.219 -
289.220 - def add_section(self, section):
289.221 - """Create a new section in the configuration.
289.222 -
289.223 - Raise DuplicateSectionError if a section by the specified name
289.224 - already exists.
289.225 - """
289.226 - if section in self._sections:
289.227 - raise DuplicateSectionError(section)
289.228 - self._sections[section] = {}
289.229 -
289.230 - def has_section(self, section):
289.231 - """Indicate whether the named section is present in the configuration.
289.232 -
289.233 - The DEFAULT section is not acknowledged.
289.234 - """
289.235 - return section in self._sections
289.236 -
289.237 - def options(self, section):
289.238 - """Return a list of option names for the given section name."""
289.239 - try:
289.240 - opts = self._sections[section].copy()
289.241 - except KeyError:
289.242 - raise NoSectionError(section)
289.243 - opts.update(self._defaults)
289.244 - if '__name__' in opts:
289.245 - del opts['__name__']
289.246 - return opts.keys()
289.247 -
289.248 - def read(self, filenames):
289.249 - """Read and parse a filename or a list of filenames.
289.250 -
289.251 - Files that cannot be opened are silently ignored; this is
289.252 - designed so that you can specify a list of potential
289.253 - configuration file locations (e.g. current directory, user's
289.254 - home directory, systemwide directory), and all existing
289.255 - configuration files in the list will be read. A single
289.256 - filename may also be given.
289.257 - """
289.258 - if isinstance(filenames, basestring):
289.259 - filenames = [filenames]
289.260 - for filename in filenames:
289.261 - try:
289.262 - name = open(filename)
289.263 - fp = open(filename)
289.264 - except IOError:
289.265 - continue
289.266 - var = self._read(fp, filename)
289.267 - fp.close()
289.268 -
289.269 - def readfp(self, fp, filename=None):
289.270 - """Like read() but the argument must be a file-like object.
289.271 -
289.272 - The `fp' argument must have a `readline' method. Optional
289.273 - second argument is the `filename', which if not given, is
289.274 - taken from fp.name. If fp has no `name' attribute, `<???>' is
289.275 - used.
289.276 -
289.277 - """
289.278 - if filename is None:
289.279 - try:
289.280 - filename = fp.name
289.281 - except AttributeError:
289.282 - filename = '<???>'
289.283 - self._read(fp, filename)
289.284 -
289.285 - def get(self, section, option):
289.286 - opt = self.optionxform(option)
289.287 - if section not in self._sections:
289.288 - if section != DEFAULTSECT:
289.289 - raise NoSectionError(section)
289.290 - if opt in self._defaults:
289.291 - return self._defaults[opt]
289.292 - else:
289.293 - raise NoOptionError(option, section)
289.294 - elif opt in self._sections[section]:
289.295 - return self._sections[section][opt]
289.296 - elif opt in self._defaults:
289.297 - return self._defaults[opt]
289.298 - else:
289.299 - raise NoOptionError(option, section)
289.300 -
289.301 - def items(self, section):
289.302 - try:
289.303 - d2 = self._sections[section]
289.304 - except KeyError:
289.305 - if section != DEFAULTSECT:
289.306 - raise NoSectionError(section)
289.307 - d2 = {}
289.308 - d = self._defaults.copy()
289.309 - d.update(d2)
289.310 - if "__name__" in d:
289.311 - del d["__name__"]
289.312 - return d.items()
289.313 -
289.314 - def _get(self, section, conv, option):
289.315 - return conv(self.get(section, option))
289.316 -
289.317 - def getint(self, section, option):
289.318 - return self._get(section, int, option)
289.319 -
289.320 - def getfloat(self, section, option):
289.321 - return self._get(section, float, option)
289.322 -
289.323 - _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
289.324 - '0': False, 'no': False, 'false': False, 'off': False}
289.325 -
289.326 - def getboolean(self, section, option):
289.327 - v = self.get(section, option)
289.328 - if v.lower() not in self._boolean_states:
289.329 - raise ValueError, 'Not a boolean: %s' % v
289.330 - return self._boolean_states[v.lower()]
289.331 -
289.332 - def optionxform(self, optionstr):
289.333 - return optionstr.lower()
289.334 -
289.335 - def has_option(self, section, option):
289.336 - """Check for the existence of a given option in a given section."""
289.337 - if not section or section == DEFAULTSECT:
289.338 - option = self.optionxform(option)
289.339 - return option in self._defaults
289.340 - elif section not in self._sections:
289.341 - return False
289.342 - else:
289.343 - option = self.optionxform(option)
289.344 - return (option in self._sections[section]
289.345 - or option in self._defaults)
289.346 -
289.347 - def set(self, section, option, value):
289.348 - """Set an option."""
289.349 - if not section or section == DEFAULTSECT:
289.350 - sectdict = self._defaults
289.351 - else:
289.352 - try:
289.353 - sectdict = self._sections[section]
289.354 - except KeyError:
289.355 - raise NoSectionError(section)
289.356 - sectdict[self.optionxform(option)] = value
289.357 -
289.358 - def write(self, fp):
289.359 - """Write an .ini-format representation of the configuration state."""
289.360 - if self._defaults:
289.361 - fp.write("[%s]\n" % DEFAULTSECT)
289.362 - for (key, value) in self._defaults.items():
289.363 - fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
289.364 - fp.write("\n")
289.365 - for section in self._sections:
289.366 - fp.write("[%s]\n" % section)
289.367 - for (key, value) in self._sections[section].items():
289.368 - if key != "__name__":
289.369 - fp.write("%s = %s\n" %
289.370 - (key, str(value).replace('\n', '\n\t')))
289.371 - fp.write("\n")
289.372 -
289.373 - def remove_option(self, section, option):
289.374 - """Remove an option."""
289.375 - if not section or section == DEFAULTSECT:
289.376 - sectdict = self._defaults
289.377 - else:
289.378 - try:
289.379 - sectdict = self._sections[section]
289.380 - except KeyError:
289.381 - raise NoSectionError(section)
289.382 - option = self.optionxform(option)
289.383 - existed = option in sectdict
289.384 - if existed:
289.385 - del sectdict[option]
289.386 - return existed
289.387 -
289.388 - def remove_section(self, section):
289.389 - """Remove a file section."""
289.390 - existed = section in self._sections
289.391 - if existed:
289.392 - del self._sections[section]
289.393 - return existed
289.394 -
289.395 - #
289.396 - # Regular expressions for parsing section headers and options.
289.397 - #
289.398 - SECTCRE = re.compile(
289.399 - r'\[' # [
289.400 - r'(?P<header>[^]]+)' # very permissive!
289.401 - r'\]' # ]
289.402 - )
289.403 - OPTCRE = re.compile(
289.404 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
289.405 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
289.406 - # followed by separator
289.407 - # (either : or =), followed
289.408 - # by any # space/tab
289.409 - r'(?P<value>.*)$' # everything up to eol
289.410 - )
289.411 -
289.412 - def _read(self, fp, fpname):
289.413 - """Parse a sectioned setup file.
289.414 -
289.415 - The sections in setup file contains a title line at the top,
289.416 - indicated by a name in square brackets (`[]'), plus key/value
289.417 - options lines, indicated by `name: value' format lines.
289.418 - Continuations are represented by an embedded newline then
289.419 - leading whitespace. Blank lines, lines beginning with a '#',
289.420 - and just about everything else are ignored.
289.421 - """
289.422 - cursect = None # None, or a dictionary
289.423 - optname = None
289.424 - lineno = 0
289.425 - e = None # None, or an exception
289.426 - while True:
289.427 - line = fp.readline()
289.428 - if not line:
289.429 - break
289.430 - lineno +
289.431 - 1
289.432 - lineno = lineno + 1
289.433 - # comment or blank line?
289.434 - if line.strip() == '' or line[0] in '#;':
289.435 - continue
289.436 - if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
289.437 - # no leading whitespace
289.438 - continue
289.439 - # continuation line?
289.440 - if line[0].isspace() and cursect is not None and optname:
289.441 - value = line.strip()
289.442 - if value:
289.443 - cursect[optname] = "%s\n%s" % (cursect[optname], value)
289.444 - # a section header or option header?
289.445 - else:
289.446 - # is it a section header?
289.447 - mo = self.SECTCRE.match(line)
289.448 - if mo:
289.449 - sectname = mo.group('header')
289.450 - if sectname in self._sections:
289.451 - cursect = self._sections[sectname]
289.452 - elif sectname == DEFAULTSECT:
289.453 - cursect = self._defaults
289.454 - else:
289.455 - cursect = {'__name__': sectname}
289.456 - self._sections[sectname] = cursect
289.457 - # So sections can't start with a continuation line
289.458 - optname = None
289.459 - # no section header in the file?
289.460 - elif cursect is None:
289.461 - raise MissingSectionHeaderError(fpname, lineno, `line`)
289.462 - # an option line?
289.463 - else:
289.464 - mo = self.OPTCRE.match(line)
289.465 - if mo:
289.466 - optname, vi, optval = mo.group('option', 'vi', 'value')
289.467 - if vi in ('=', ':') and ';' in optval:
289.468 - # ';' is a comment delimiter only if it follows
289.469 - # a spacing character
289.470 - pos = optval.find(';')
289.471 - if pos != -1 and optval[pos-1].isspace():
289.472 - optval = optval[:pos]
289.473 - optval = optval.strip()
289.474 - # allow empty values
289.475 - if optval == '""':
289.476 - optval = ''
289.477 - optname = self.optionxform(optname.rstrip())
289.478 - cursect[optname] = optval
289.479 - else:
289.480 - # a non-fatal parsing error occurred. set up the
289.481 - # exception but keep going. the exception will be
289.482 - # raised at the end of the file and will contain a
289.483 - # list of all bogus lines
289.484 - if not e:
289.485 - e = ParsingError(fpname)
289.486 - e.append(lineno, `line`)
289.487 - # if any parsing errors occurred, raise an exception
289.488 - if e:
289.489 - raise e
289.490 -
289.491 -
289.492 -class ConfigParser(RawConfigParser):
289.493 -
289.494 - def get(self, section, option, raw=False, vars=None):
289.495 - """Get an option value for a given section.
289.496 -
289.497 - All % interpolations are expanded in the return values, based on the
289.498 - defaults passed into the constructor, unless the optional argument
289.499 - `raw' is true. Additional substitutions may be provided using the
289.500 - `vars' argument, which must be a dictionary whose contents overrides
289.501 - any pre-existing defaults.
289.502 -
289.503 - The section DEFAULT is special.
289.504 - """
289.505 - d = self._defaults.copy()
289.506 - try:
289.507 - d.update(self._sections[section])
289.508 - except KeyError:
289.509 - if section != DEFAULTSECT:
289.510 - raise NoSectionError(section)
289.511 - # Update with the entry specific variables
289.512 - if vars is not None:
289.513 - d.update(vars)
289.514 - option = self.optionxform(option)
289.515 - try:
289.516 - value = d[option]
289.517 - except KeyError:
289.518 - raise NoOptionError(option, section)
289.519 -
289.520 - if raw:
289.521 - return value
289.522 - else:
289.523 - return self._interpolate(section, option, value, d)
289.524 -
289.525 - def items(self, section, raw=False, vars=None):
289.526 - """Return a list of tuples with (name, value) for each option
289.527 - in the section.
289.528 -
289.529 - All % interpolations are expanded in the return values, based on the
289.530 - defaults passed into the constructor, unless the optional argument
289.531 - `raw' is true. Additional substitutions may be provided using the
289.532 - `vars' argument, which must be a dictionary whose contents overrides
289.533 - any pre-existing defaults.
289.534 -
289.535 - The section DEFAULT is special.
289.536 - """
289.537 - d = self._defaults.copy()
289.538 - try:
289.539 - d.update(self._sections[section])
289.540 - except KeyError:
289.541 - if section != DEFAULTSECT:
289.542 - raise NoSectionError(section)
289.543 - # Update with the entry specific variables
289.544 - if vars:
289.545 - d.update(vars)
289.546 - options = d.keys()
289.547 - if "__name__" in options:
289.548 - options.remove("__name__")
289.549 - if raw:
289.550 - return [(option, d[option])
289.551 - for option in options]
289.552 - else:
289.553 - return [(option, self._interpolate(section, option, d[option], d))
289.554 - for option in options]
289.555 -
289.556 - def _interpolate(self, section, option, rawval, vars):
289.557 - # do the string interpolation
289.558 - value = rawval
289.559 - depth = MAX_INTERPOLATION_DEPTH
289.560 - while depth: # Loop through this until it's done
289.561 - depth -= 1
289.562 - if value.find("%(") != -1:
289.563 - try:
289.564 - value = value % vars
289.565 - except KeyError, e:
289.566 - raise InterpolationMissingOptionError(
289.567 - option, section, rawval, e[0])
289.568 - else:
289.569 - break
289.570 - if value.find("%(") != -1:
289.571 - raise InterpolationDepthError(option, section, rawval)
289.572 - return value
289.573 -
289.574 -
289.575 -class SafeConfigParser(ConfigParser):
289.576 -
289.577 - def _interpolate(self, section, option, rawval, vars):
289.578 - # do the string interpolation
289.579 - L = []
289.580 - self._interpolate_some(option, L, rawval, section, vars, 1)
289.581 - return ''.join(L)
289.582 -
289.583 - _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
289.584 -
289.585 - def _interpolate_some(self, option, accum, rest, section, map, depth):
289.586 - if depth > MAX_INTERPOLATION_DEPTH:
289.587 - raise InterpolationDepthError(option, section, rest)
289.588 - while rest:
289.589 - p = rest.find("%")
289.590 - if p < 0:
289.591 - accum.append(rest)
289.592 - return
289.593 - if p > 0:
289.594 - accum.append(rest[:p])
289.595 - rest = rest[p:]
289.596 - # p is no longer used
289.597 - c = rest[1:2]
289.598 - if c == "%":
289.599 - accum.append("%")
289.600 - rest = rest[2:]
289.601 - elif c == "(":
289.602 - m = self._interpvar_match(rest)
289.603 - if m is None:
289.604 - raise InterpolationSyntaxError(option, section,
289.605 - "bad interpolation variable reference %r" % rest)
289.606 - var = m.group(1)
289.607 - rest = rest[m.end():]
289.608 - try:
289.609 - v = map[var]
289.610 - except KeyError:
289.611 - raise InterpolationMissingOptionError(
289.612 - option, section, rest, var)
289.613 - if "%" in v:
289.614 - self._interpolate_some(option, accum, v,
289.615 - section, map, depth + 1)
289.616 - else:
289.617 - accum.append(v)
289.618 - else:
289.619 - raise InterpolationSyntaxError(
289.620 - option, section,
289.621 - "'%' must be followed by '%' or '(', found: " + `ret`)
290.1 --- a/python.editor/test/unit/data/testfiles/errors2.py.errors Sun Jan 04 13:11:53 2015 -0600
290.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
290.3 @@ -1,1 +0,0 @@
290.4 -14596-14596:no viable alternative at input '\n'
291.1 --- a/python.editor/test/unit/data/testfiles/errors3.py Sun Jan 04 13:11:53 2015 -0600
291.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
291.3 @@ -1,32 +0,0 @@
291.4 -class A:
291.5 - def foo():
291.6 - self.filename = filename
291.7 -
291.8 -def toplevel(x,y,z):
291.9 - print "hello"
291.10 -
291.11 -def toplevel2():
291.12 - print "hello
291.13 -
291.14 -class Bar:
291.15 - def noargs():
291.16 - print "hello"
291.17 -
291.18 - def okay1(self):
291.19 - print "hello"
291.20 -
291.21 - def okay2(cls):
291.22 - print "hello"
291.23 -
291.24 - def okay3(self, bar):
291.25 - print "hello"
291.26 -
291.27 - def okay4(cls, bar):
291.28 - print "hello"
291.29 -
291.30 - def bad1():
291.31 - print "hello"
291.32 -
291.33 - def bad2(filename):
291.34 - print "hello"
291.35 -
292.1 --- a/python.editor/test/unit/data/testfiles/errors3.py.errors Sun Jan 04 13:11:53 2015 -0600
292.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
292.3 @@ -1,1 +0,0 @@
292.4 -135-135:mismatched character '\n' expecting '"'
293.1 --- a/python.editor/test/unit/data/testfiles/errors4.py Sun Jan 04 13:11:53 2015 -0600
293.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
293.3 @@ -1,32 +0,0 @@
293.4 -class A:
293.5 - def foo():
293.6 - self.filename = filename
293.7 -
293.8 -def toplevel(x,y,z):
293.9 - """Missing end markers
293.10 -
293.11 -def toplevel2():
293.12 - print "hello"
293.13 -
293.14 -class Bar:
293.15 - def noargs():
293.16 - print "hello"
293.17 -
293.18 - def okay1(self):
293.19 - print "hello"
293.20 -
293.21 - def okay2(cls):
293.22 - print "hello"
293.23 -
293.24 - def okay3(self, bar):
293.25 - print "hello"
293.26 -
293.27 - def okay4(cls, bar):
293.28 - print "hello"
293.29 -
293.30 - def bad1():
293.31 - print "hello"
293.32 -
293.33 - def bad2(filename):
293.34 - print "hello"
293.35 -
294.1 --- a/python.editor/test/unit/data/testfiles/errors4.py.errors Sun Jan 04 13:11:53 2015 -0600
294.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
294.3 @@ -1,4 +0,0 @@
294.4 -83-105:rule STRINGPART failed predicate: {partial}?
294.5 -86-86:mismatched input 'Missing' expecting NEWLINE
294.6 -94-94:mismatched input 'end' expecting NEWLINE
294.7 -98-98:mismatched input 'markers' expecting NEWLINE
295.1 --- a/python.editor/test/unit/data/testfiles/errors5.py Sun Jan 04 13:11:53 2015 -0600
295.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
295.3 @@ -1,20 +0,0 @@
295.4 -
295.5 -__author__="tor"
295.6 -__date__ ="$Oct 16, 2008 4:19:21 PM$"
295.7 -
295.8 -if __name__ == "__main__":
295.9 - print "Hello";
295.10 -
295.11 -class C
295.12 -def foo():
295.13 - doc = "The foo property."
295.14 - def fget(self):
295.15 - return self._foo
295.16 - def fset(self, value):
295.17 - self._foo = value
295.18 - def fdel(self):
295.19 - del self._foo
295.20 - return locals()
295.21 - foo = property(**foo())
295.22 -
295.23 -print foo
296.1 --- a/python.editor/test/unit/data/testfiles/errors6.py Sun Jan 04 13:11:53 2015 -0600
296.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
296.3 @@ -1,13 +0,0 @@
296.4 -from unittest import failUnlessRaises
296.5 -import unittest
296.6 -
296.7 -class MyTest(unittest.TestCase):
296.8 - quit([code=None])
296.9 - def f
296.10 -
296.11 -
296.12 -x = MyTest()
296.13 -
296.14 -
296.15 -
296.16 -
297.1 --- a/python.editor/test/unit/data/testfiles/errors7.py Sun Jan 04 13:11:53 2015 -0600
297.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
297.3 @@ -1,6 +0,0 @@
297.4 -# From issue http://www.netbeans.org/issues/show_bug.cgi?id=155904
297.5 -def main():
297.6 - if "hallo" == "hallo":
297.7 - pass
297.8 - elif 1 =
297.9 -
298.1 --- a/python.editor/test/unit/data/testfiles/errors8.py Sun Jan 04 13:11:53 2015 -0600
298.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
298.3 @@ -1,218 +0,0 @@
298.4 -##############################################################################
298.5 -# Test Runner for NetBeans, based on the unittest TextTestRunner (but prints
298.6 -# out more information during execution that is parsed and swallowed by the
298.7 -# NetBeans test runner GUI.)
298.8 -#
298.9 -# Tor Norbye <tor@netbeans.org> Dec 20 2008
298.10 -##############################################################################
298.11 -
298.12 -import sys
298.13 -import time
298.14 -from optparse import OptionParser
298.15 -import os
298.16 -from unittest import TestResult
298.17 -
298.18 -class _NbWritelnDecorator:
298.19 - """Used to decorate file-like objects with a handy 'writeln' method"""
298.20 - def __init__(self, stream):
298.21 - self.stream = stream
298.22 -
298.23 - def __getattr__(self, attr):
298.24 - return getattr(self.stream, attr)
298.25 -
298.26 - def writeln(self, arg=None):
298.27 - if arg: self.write(arg)
298.28 - self.write('\n') # text-mode streams translate to \r\n if needed
298.29 -
298.30 -class _NbTextTestResult(TestResult):
298.31 - """
298.32 - A test result class that can print specially formatted test status messages for use by
298.33 - the GUI test runner in the NetBeans IDE.
298.34 - """
298.35 -
298.36 - def __init__(self, stream):
298.37 - TestResult.__init__(self)
298.38 - self.stream = stream
298.39 - self._start_time = None
298.40 -
298.41 - def getDescription(self, test):
298.42 - return str(test)
298.43 -
298.44 - def startTest(self, test):
298.45 - TestResult.startTest(self, test)
298.46 - self.stream.writeln("%%TEST_STARTED%% %s" % self.getDescription(test))
298.47 - self._start_time = time.time()
298.48 -
298.49 -
298.50 - def addSuccess(self, test):
298.51 - time_taken = time.time() - self._start_time
298.52 - TestResult.addSuccess(self, test)
298.53 - self.stream.writeln("%%TEST_FINISHED%% time=%.6f %s" % (time_taken, self.getDescription(test)))
298.54 -
298.55 - def _generate_stack(self, tb):
298.56 - # Default stack format:
298.57 - #stack = traceback.format_tb(tb)
298.58 - #stackstr = ""
298.59 - #for line in stack:
298.60 - # stackstr += line
298.61 - #stackstr = stackstr.replace('\n', '%BR%')
298.62 -
298.63 - # More compact stack format
298.64 - stackstr = ""
298.65 - stack = []
298.66 - while tb:
298.67 - stack.append(tb.tb_frame)
298.68 - tb = tb.tb_next
298.69 - stack.reverse()
298.70 - for frame in stack:
298.71 - stackstr += "%s() in %s:%s%%BR%%" % (frame.f_code.co_name,
298.72 - frame.f_code.co_filename,
298.73 - frame.f_lineno)
298.74 -
298.75 - return stackstr
298.76 -
298.77 - def _handle_doctest(self, message, stackstr):
298.78 - if x.startswith("Failed doctest test for "
298.79 -
298.80 - return (message, stackstr)
298.81 -
298.82 - def addError(self, test, err):
298.83 - time_taken = time.time() - self._start_time
298.84 - TestResult.addError(self, test, err)
298.85 - (error, message, tb) = err
298.86 - stackstr = self._generate_stack(tb)
298.87 - (message, stackstr) = self._handle_doctest(message, stackstr)
298.88 - self.stream.writeln("%%TEST_ERROR%% time=%.6f testname=%s message=%s location=%s" %
298.89 - (time_taken, self.getDescription(test), str(message).replace('\n', '%BR%'), stackstr))
298.90 -
298.91 - def addFailure(self, test, err):
298.92 - time_taken = time.time() - self._start_time
298.93 - TestResult.addFailure(self, test, err)
298.94 -
298.95 - (error, message, tb) = err
298.96 - stackstr = self._generate_stack(tb)
298.97 - self.stream.writeln("%%TEST_FAILED%% time=%.6f testname=%s message=%s location=%s" %
298.98 - (time_taken, self.getDescription(test), str(message).replace('\n', '%BR%'), stackstr))
298.99 -
298.100 - def printErrors(self):
298.101 - pass
298.102 -
298.103 - def printErrorList(self, flavour, errors):
298.104 - pass
298.105 -
298.106 -
298.107 -class _NetBeansTestRunner:
298.108 - """A test runner class that displays results in textual form.
298.109 -
298.110 - It prints out the names of tests as they are run, errors as they
298.111 - occur, and a summary of the results at the end of the test run.
298.112 - """
298.113 - def __init__(self, stream=sys.stdout):
298.114 - self.stream = _NbWritelnDecorator(stream)
298.115 -
298.116 -
298.117 - def _makeResult(self):
298.118 - return _NbTextTestResult(self.stream)
298.119 -
298.120 - def _get_suite_name(self, test):
298.121 - if (hasattr(test, "_tests")):
298.122 - name_set = set()
298.123 - for o in test._tests:
298.124 - for s in o._tests:
298.125 - name_set.add(s.__class__)
298.126 - name = ""
298.127 - for s in name_set:
298.128 - if (len(name) > 0):
298.129 - name += ","
298.130 - #name += s.__module__ + '.' + s.__name__
298.131 - name += s.__name__
298.132 - return name;
298.133 - else:
298.134 - class_ = test.__class__
298.135 - classname = class_.__module__ + "." + class_.__name__
298.136 - return classname
298.137 -
298.138 - def run(self, test):
298.139 - "Run the given test case or test suite."
298.140 - suite_name = self._get_suite_name(test)
298.141 - self.stream.writeln("%%SUITE_STARTING%% %s" % suite_name)
298.142 - result = self._makeResult()
298.143 - startTime = time.time()
298.144 - test(result)
298.145 - stopTime = time.time()
298.146 - timeTaken = stopTime - startTime
298.147 - result.printErrors()
298.148 - if not result.wasSuccessful():
298.149 - failed, errored = map(len, (result.failures, result.errors))
298.150 - if failed:
298.151 - self.stream.writeln("%%SUITE_FAILURES%% %d" % failed)
298.152 - if errored:
298.153 - self.stream.writeln("%%SUITE_ERRORS%% %d" % errored)
298.154 - else:
298.155 - print "%SUITE_SUCCESS%"
298.156 - self.stream.writeln("%%SUITE_FINISHED%% time=%.4f" % timeTaken)
298.157 - return result
298.158 -
298.159 -##############################################################################
298.160 -# Driver for running tests from NetBeans
298.161 -##############################################################################
298.162 -if __name__ == '__main__':
298.163 - import unittest
298.164 - import doctest
298.165 -
298.166 - parser = OptionParser(usage="%prog <[--method <name> ]--file|--directory> <files/directories...>", version="%prog 1.0")
298.167 - parser.add_option("-f", "--file",
298.168 - action="store_true", dest="filename",
298.169 - help="Test the given file")
298.170 - parser.add_option("-m", "--method",
298.171 - action="store", type="string", dest="method",
298.172 - help="Test the given method")
298.173 - parser.add_option("-d", "--directory",
298.174 - action="store_true", dest="directory",
298.175 - help="Test the given directory")
298.176 - (options, args) = parser.parse_args()
298.177 - if len(args) == 0:
298.178 - parser.error("Don't forget to specify files/directories")
298.179 - if (options.method and not options.filename):
298.180 - parser.error("must specify --file if you specify --method")
298.181 - if (options.filename and options.directory):
298.182 - parser.error("--directory and --file are mutually exclusive")
298.183 - if (not options.filename and not options.directory):
298.184 - parser.error("You must specify at least one of --file, --method and --directory")
298.185 -
298.186 - if options.filename or options.method:
298.187 - if len(args) > 1:
298.188 - parser.error("You can only specify one file with --file")
298.189 - file_name = args[0]
298.190 - module_name = os.path.splitext(file_name)[0:-1][0]
298.191 - module = __import__(module_name, globals(), locals(), module_name)
298.192 - if (options.method):
298.193 - suite = unittest.TestLoader().loadTestsFromName(options.method, module)
298.194 - else:
298.195 - suite = unittest.TestLoader().loadTestsFromModule(module)
298.196 - # Doctest
298.197 - suite.addTest(doctest.DocTestSuite(module))
298.198 -
298.199 - else:
298.200 - assert options.directory;
298.201 - test_modules = []
298.202 - for dir in args:
298.203 - file_list = os.listdir(dir)
298.204 - for file_name in file_list:
298.205 - extension = os.path.splitext(file_name)[-1]
298.206 - if extension == '.py':
298.207 - test_module_name = os.path.splitext(file_name)[0:-1][0]
298.208 - try:
298.209 - module = __import__(test_module_name, globals(), locals(), test_module_name)
298.210 - test_modules.append(module)
298.211 - except:
298.212 - # No complaints - just test the files we can (user may have run
298.213 - # test project on an unfinished project where not all files are valid)
298.214 - pass
298.215 - suite = unittest.TestSuite(map(unittest.defaultTestLoader.loadTestsFromModule, test_modules))
298.216 - # Doctest
298.217 - for module in test_modules:
298.218 - suite.addTest(doctest.DocTestSuite(module))
298.219 -
298.220 - # Run all the tests
298.221 - _NetBeansTestRunner().run(suite)
299.1 --- a/python.editor/test/unit/data/testfiles/errors9.py Sun Jan 04 13:11:53 2015 -0600
299.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
299.3 @@ -1,265 +0,0 @@
299.4 -##############################################################################
299.5 -# Test Runner for NetBeans, based on the unittest TextTestRunner (but prints
299.6 -# out more information during execution that is parsed and swallowed by the
299.7 -# NetBeans test runner GUI.)
299.8 -#
299.9 -# Tor Norbye <tor@netbeans.org> Dec 20 2008
299.10 -##############################################################################
299.11 -
299.12 -import sys
299.13 -import time
299.14 -from optparse import OptionParser
299.15 -import os
299.16 -import re
299.17 -from unittest import TestResult
299.18 -
299.19 -class _NbWritelnDecorator:
299.20 - """Used to decorate file-like objects with a handy 'writeln' method"""
299.21 - def __init__(self, stream):
299.22 - self.stream = stream
299.23 -
299.24 - def __getattr__(self, attr):
299.25 - return getattr(self.stream, attr)
299.26 -
299.27 - def writeln(self, arg=None):
299.28 - if arg: self.write(arg)
299.29 - self.write('\n') # text-mode streams translate to \r\n if needed
299.30 -
299.31 -class _NbTextTestResult(TestResult):
299.32 - """
299.33 - A test result class that can print specially formatted test status messages for use by
299.34 - the GUI test runner in the NetBeans IDE.
299.35 - """
299.36 -
299.37 - def __init__(self, stream):
299.38 - TestResult.__init__(self)
299.39 - self.stream = stream
299.40 - self._start_time = None
299.41 -
299.42 - def getDescription(self, test):
299.43 - return str(test)
299.44 -
299.45 - def startTest(self, test):
299.46 - TestResult.startTest(self, test)
299.47 - self.stream.writeln("%%TEST_STARTED%% %s" % self.getDescription(test))
299.48 - self._start_time = time.time()
299.49 -
299.50 -
299.51 - def addSuccess(self, test):
299.52 - time_taken = time.time() - self._start_time
299.53 - TestResult.addSuccess(self, test)
299.54 - self.stream.writeln("%%TEST_FINISHED%% time=%.6f %s" % (time_taken, self.getDescription(test)))
299.55 -
299.56 - def _generate_stack(self, tb):
299.57 - # Default stack format:
299.58 - #stack = traceback.format_tb(tb)
299.59 - #stackstr = ""
299.60 - #for line in stack:
299.61 - # stackstr += line
299.62 - #stackstr = stackstr.replace('\n', '%BR%')
299.63 -
299.64 - # More compact stack format
299.65 - stackstr = ""
299.66 - stack = []
299.67 - while tb:
299.68 - stack.append(tb.tb_frame)
299.69 - tb = tb.tb_next
299.70 - stack.reverse()
299.71 - for frame in stack:
299.72 - stackstr += "%s() in %s:%s%%BR%%" % (frame.f_code.co_name,
299.73 - frame.f_code.co_filename,
299.74 - frame.f_lineno)
299.75 -
299.76 - return stackstr
299.77 -
299.78 - def _handle_doctest(self, message, stackstr):
299.79 - message_str = str(message)
299.80 - if message_str.startswith("Failed doctest test for "):
299.81 - # From doctest.py:
299.82 - #return ('Failed doctest test for %s\n'
299.83 - # ' File "%s", line %s, in %s\n\n%s'
299.84 - # % (test.name, test.filename, lineno, lname, err)
299.85 -
299.86 - m = re.match('Failed doctest test for (.*)\n'
299.87 - ' File "(.*)", line (.*), in (.*)\n\n(.*)', message_str)
299.88 - print "Match was " + str(m)
299.89 - if m:
299.90 - test_name = m.group(1)
299.91 - filename = m.group(2)
299.92 - lineno = m.group(3)
299.93 - lname = m.group(4)
299.94 - err = m.group(5)
299.95 -
299.96 - print "test_name = " + test_name
299.97 - print "filename = " + filename
299.98 - print "lineno = " + lineno
299.99 - print "lname = " + lname
299.100 -# print "err = " + err
299.101 -
299.102 - # From output_difference() in doctest
299.103 -----------------------------------------------------------------------
299.104 -File "/Users/tor/Downloads/diveintopython-5.4/py/roman/stage9/pythontest.py", line 20, in pythontest.factorial
299.105 -Failed example:
299.106 - factorial(30L)
299.107 -Expected:
299.108 - 265252859812191058636308480000000L
299.109 -Got:
299.110 - 132626429906095529318154240000000L
299.111 -
299.112 -
299.113 - if want and got:
299.114 - return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
299.115 - elif want:
299.116 - return 'Expected:\n%sGot nothing\n' % _indent(want)
299.117 - elif got:
299.118 - return 'Expected nothing\nGot:\n%s' % _indent(got)
299.119 - else:
299.120 - return 'Expected nothing\nGot nothing\n'
299.121 -
299.122 -
299.123 - # Modify stack and message
299.124 - message = message_str[m.start(5):]
299.125 - stackstr = test_name + "() in " + filename + ":" + lineno + "%BR%"
299.126 -
299.127 - return (message, stackstr)
299.128 -
299.129 - def addError(self, test, err):
299.130 - time_taken = time.time() - self._start_time
299.131 - TestResult.addError(self, test, err)
299.132 - (error, message, tb) = err
299.133 - stackstr = self._generate_stack(tb)
299.134 - self.stream.writeln("%%TEST_ERROR%% time=%.6f testname=%s message=%s location=%s" %
299.135 - (time_taken, self.getDescription(test), str(message).replace('\n', '%BR%'), stackstr))
299.136 -
299.137 - def addFailure(self, test, err):
299.138 - time_taken = time.time() - self._start_time
299.139 - TestResult.addFailure(self, test, err)
299.140 -
299.141 - (error, message, tb) = err
299.142 - stackstr = self._generate_stack(tb)
299.143 - (message, stackstr) = self._handle_doctest(message, stackstr)
299.144 - self.stream.writeln("%%TEST_FAILED%% time=%.6f testname=%s message=%s location=%s" %
299.145 - (time_taken, self.getDescription(test), str(message).replace('\n', '%BR%'), stackstr))
299.146 -
299.147 - def printErrors(self):
299.148 - pass
299.149 -
299.150 - def printErrorList(self, flavour, errors):
299.151 - pass
299.152 -
299.153 -
299.154 -class _NetBeansTestRunner:
299.155 - """A test runner class that displays results in textual form.
299.156 -
299.157 - It prints out the names of tests as they are run, errors as they
299.158 - occur, and a summary of the results at the end of the test run.
299.159 - """
299.160 - def __init__(self, stream=sys.stdout):
299.161 - self.stream = _NbWritelnDecorator(stream)
299.162 -
299.163 -
299.164 - def _makeResult(self):
299.165 - return _NbTextTestResult(self.stream)
299.166 -
299.167 - def _get_suite_name(self, test):
299.168 - if (hasattr(test, "_tests")):
299.169 - name_set = set()
299.170 - for o in test._tests:
299.171 - for s in o._tests:
299.172 - name_set.add(s.__class__)
299.173 - name = ""
299.174 - for s in name_set:
299.175 - if (len(name) > 0):
299.176 - name += ","
299.177 - #name += s.__module__ + '.' + s.__name__
299.178 - name += s.__name__
299.179 - return name;
299.180 - else:
299.181 - class_ = test.__class__
299.182 - classname = class_.__module__ + "." + class_.__name__
299.183 - return classname
299.184 -
299.185 - def run(self, test):
299.186 - "Run the given test case or test suite."
299.187 - suite_name = self._get_suite_name(test)
299.188 - self.stream.writeln("%%SUITE_STARTING%% %s" % suite_name)
299.189 - result = self._makeResult()
299.190 - startTime = time.time()
299.191 - test(result)
299.192 - stopTime = time.time()
299.193 - timeTaken = stopTime - startTime
299.194 - result.printErrors()
299.195 - if not result.wasSuccessful():
299.196 - failed, errored = map(len, (result.failures, result.errors))
299.197 - if failed:
299.198 - self.stream.writeln("%%SUITE_FAILURES%% %d" % failed)
299.199 - if errored:
299.200 - self.stream.writeln("%%SUITE_ERRORS%% %d" % errored)
299.201 - else:
299.202 - print "%SUITE_SUCCESS%"
299.203 - self.stream.writeln("%%SUITE_FINISHED%% time=%.4f" % timeTaken)
299.204 - return result
299.205 -
299.206 -##############################################################################
299.207 -# Driver for running tests from NetBeans
299.208 -##############################################################################
299.209 -if __name__ == '__main__':
299.210 - import unittest
299.211 - import doctest
299.212 -
299.213 - parser = OptionParser(usage="%prog <[--method <name> ]--file|--directory> <files/directories...>", version="%prog 1.0")
299.214 - parser.add_option("-f", "--file",
299.215 - action="store_true", dest="filename",
299.216 - help="Test the given file")
299.217 - parser.add_option("-m", "--method",
299.218 - action="store", type="string", dest="method",
299.219 - help="Test the given method")
299.220 - parser.add_option("-d", "--directory",
299.221 - action="store_true", dest="directory",
299.222 - help="Test the given directory")
299.223 - (options, args) = parser.parse_args()
299.224 - if len(args) == 0:
299.225 - parser.error("Don't forget to specify files/directories")
299.226 - if (options.method and not options.filename):
299.227 - parser.error("must specify --file if you specify --method")
299.228 - if (options.filename and options.directory):
299.229 - parser.error("--directory and --file are mutually exclusive")
299.230 - if (not options.filename and not options.directory):
299.231 - parser.error("You must specify at least one of --file, --method and --directory")
299.232 -
299.233 - if options.filename or options.method:
299.234 - if len(args) > 1:
299.235 - parser.error("You can only specify one file with --file")
299.236 - file_name = args[0]
299.237 - module_name = os.path.splitext(file_name)[0:-1][0]
299.238 - module = __import__(module_name, globals(), locals(), module_name)
299.239 - if (options.method):
299.240 - suite = unittest.TestLoader().loadTestsFromName(options.method, module)
299.241 - else:
299.242 - suite = unittest.TestLoader().loadTestsFromModule(module)
299.243 - # Doctest
299.244 - suite.addTest(doctest.DocTestSuite(module))
299.245 -
299.246 - else:
299.247 - assert options.directory;
299.248 - test_modules = []
299.249 - for dir in args:
299.250 - file_list = os.listdir(dir)
299.251 - for file_name in file_list:
299.252 - extension = os.path.splitext(file_name)[-1]
299.253 - if extension == '.py':
299.254 - test_module_name = os.path.splitext(file_name)[0:-1][0]
299.255 - try:
299.256 - module = __import__(test_module_name, globals(), locals(), test_module_name)
299.257 - test_modules.append(module)
299.258 - except:
299.259 - # No complaints - just test the files we can (user may have run
299.260 - # test project on an unfinished project where not all files are valid)
299.261 - pass
299.262 - suite = unittest.TestSuite(map(unittest.defaultTestLoader.loadTestsFromModule, test_modules))
299.263 - # Doctest
299.264 - for module in test_modules:
299.265 - suite.addTest(doctest.DocTestSuite(module))
299.266 -
299.267 - # Run all the tests
299.268 - _NetBeansTestRunner().run(suite)
300.1 --- a/python.editor/test/unit/data/testfiles/exceptas.py Sun Jan 04 13:11:53 2015 -0600
300.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
300.3 @@ -1,32 +0,0 @@
300.4 -import sys
300.5 -print "Hello from " + sys.version
300.6 -def foo():
300.7 - pass
300.8 -def bar():
300.9 - pass
300.10 -
300.11 -try:
300.12 - foo()
300.13 -except Foo as x:
300.14 - bar()
300.15 -finally:
300.16 - pass
300.17 -
300.18 -class MyError(Exception):
300.19 - def extra(self):
300.20 - pass
300.21 -
300.22 -def test1():
300.23 - try:
300.24 - pass
300.25 - except EOFError:
300.26 - print "No var"
300.27 - except MyError, ex:
300.28 - print "Got error with %" % ex.e
300.29 -
300.30 -def test2():
300.31 - try:
300.32 - pass
300.33 - except MyError as ex2:
300.34 - print "Got error with %" % ex2.e
300.35 -
301.1 --- a/python.editor/test/unit/data/testfiles/extract1.py Sun Jan 04 13:11:53 2015 -0600
301.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
301.3 @@ -1,25 +0,0 @@
301.4 -class ExtractTest:
301.5 - def extract_test1(self, param_read_in_block, param_read_after_block, default_param=4):
301.6 - local1 = 1
301.7 - local2 = local1
301.8 - not_used_in_block = 1
301.9 - reassigned_in_block_before_read = 2
301.10 - read_in_block_only = 3
301.11 - read_after_block_only = 4
301.12 -
301.13 - # Beginning of extraction segment
301.14 - read_after_block = 5
301.15 - reassigned_after_block = 6
301.16 - reassigned_in_block_before_read = 7
301.17 - print reassigned_in_block_before_read
301.18 - print read_in_block_only
301.19 - print param_read_in_block
301.20 - # End of extraction segment
301.21 -
301.22 - print local1
301.23 - print read_after_block
301.24 - reassigned_after_block = 7
301.25 - print reassigned_after_block
301.26 - print not_used_in_block
301.27 - print param_read_after_block
301.28 -
302.1 --- a/python.editor/test/unit/data/testfiles/extract1.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
302.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
302.3 @@ -1,31 +0,0 @@
302.4 -class ExtractTest:
302.5 - def extract_test1(self, param_read_in_block, param_read_after_block, default_param=4):
302.6 - local1 = 1
302.7 - local2 = local1
302.8 - not_used_in_block = 1
302.9 - reassigned_in_block_before_read = 2
302.10 - read_in_block_only = 3
302.11 - read_after_block_only = 4
302.12 -
302.13 - read_after_block = |>new_name<|(self, param_read_in_block, read_in_block_only)
302.14 -
302.15 - print local1
302.16 - print read_after_block
302.17 - reassigned_after_block = 7
302.18 - print reassigned_after_block
302.19 - print not_used_in_block
302.20 - print param_read_after_block
302.21 -
302.22 - def |>^new_name<|(self, param_read_in_block, read_in_block_only):
302.23 - # Beginning of extraction segment
302.24 - read_after_block = 5
302.25 - reassigned_after_block = 6
302.26 - reassigned_in_block_before_read = 7
302.27 - print reassigned_in_block_before_read
302.28 - print read_in_block_only
302.29 - print param_read_in_block
302.30 - # End of extraction segment
302.31 -
302.32 - return read_after_block
302.33 -
302.34 -
303.1 --- a/python.editor/test/unit/data/testfiles/extract1.py.testFix1b.fixed Sun Jan 04 13:11:53 2015 -0600
303.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
303.3 @@ -1,31 +0,0 @@
303.4 -class ExtractTest:
303.5 - def extract_test1(self, param_read_in_block, param_read_after_block, default_param=4):
303.6 - local1 = 1
303.7 - local2 = local1
303.8 - not_used_in_block = 1
303.9 - reassigned_in_block_before_read = 2
303.10 - read_in_block_only = 3
303.11 - read_after_block_only = 4
303.12 -
303.13 - read_after_block = |>new_name<|(self, param_read_in_block, read_in_block_only)
303.14 -
303.15 - print local1
303.16 - print read_after_block
303.17 - reassigned_after_block = 7
303.18 - print reassigned_after_block
303.19 - print not_used_in_block
303.20 - print param_read_after_block
303.21 -
303.22 - def |>^new_name<|(self, param_read_in_block, read_in_block_only):
303.23 - # Beginning of extraction segment
303.24 - read_after_block = 5
303.25 - reassigned_after_block = 6
303.26 - reassigned_in_block_before_read = 7
303.27 - print reassigned_in_block_before_read
303.28 - print read_in_block_only
303.29 - print param_read_in_block
303.30 - # End of extraction segment
303.31 -
303.32 - return read_after_block
303.33 -
303.34 -
304.1 --- a/python.editor/test/unit/data/testfiles/extract1.py.testFix7.fixed Sun Jan 04 13:11:53 2015 -0600
304.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
304.3 @@ -1,31 +0,0 @@
304.4 -class ExtractTest:
304.5 - def extract_test1(self, param_read_in_block, param_read_after_block, default_param=4):
304.6 - local1 = 1
304.7 - local2 = local1
304.8 - not_used_in_block,read_in_block_only = |>new_name<|(self)
304.9 -
304.10 - # Beginning of extraction segment
304.11 - read_after_block = 5
304.12 - reassigned_after_block = 6
304.13 - reassigned_in_block_before_read = 7
304.14 - print reassigned_in_block_before_read
304.15 - print read_in_block_only
304.16 - print param_read_in_block
304.17 - # End of extraction segment
304.18 -
304.19 - print local1
304.20 - print read_after_block
304.21 - reassigned_after_block = 7
304.22 - print reassigned_after_block
304.23 - print not_used_in_block
304.24 - print param_read_after_block
304.25 -
304.26 - def |>^new_name<|(self):
304.27 - not_used_in_block = 1
304.28 - reassigned_in_block_before_read = 2
304.29 - read_in_block_only = 3
304.30 - read_after_block_only = 4
304.31 -
304.32 - return not_used_in_block,read_in_block_only
304.33 -
304.34 -
305.1 --- a/python.editor/test/unit/data/testfiles/extract1.py.testHint1.hints Sun Jan 04 13:11:53 2015 -0600
305.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
305.3 @@ -1,5 +0,0 @@
305.4 - # Beginning of extraction segment
305.5 -
305.6 -HINT:Extract Code
305.7 -FIX:Extract Method
305.8 - # End of extraction segment^
306.1 --- a/python.editor/test/unit/data/testfiles/extract2.py Sun Jan 04 13:11:53 2015 -0600
306.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
306.3 @@ -1,5 +0,0 @@
306.4 -not_used = 1
306.5 -simple_code = 1
306.6 -simple_code = simple_code+1
306.7 -print simple_code + not_used
306.8 -
307.1 --- a/python.editor/test/unit/data/testfiles/extract2.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
307.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
307.3 @@ -1,11 +0,0 @@
307.4 -not_used = 1
307.5 -
307.6 -def |>^new_name<|():
307.7 - simple_code = 1
307.8 - simple_code = simple_code+1
307.9 -
307.10 - return simple_code
307.11 -
307.12 -simple_code = |>new_name<|()
307.13 -print simple_code + not_used
307.14 -
308.1 --- a/python.editor/test/unit/data/testfiles/extract2.py.testFix3.fixed Sun Jan 04 13:11:53 2015 -0600
308.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
308.3 @@ -1,9 +0,0 @@
308.4 -
308.5 -def |>^new_name<|():
308.6 - not_used = 1
308.7 - simple_code = 1
308.8 - simple_code = simple_code+1
308.9 - print simple_code + not_used
308.10 -
308.11 -|>new_name<|()
308.12 -
309.1 --- a/python.editor/test/unit/data/testfiles/extract3.py Sun Jan 04 13:11:53 2015 -0600
309.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
309.3 @@ -1,10 +0,0 @@
309.4 -
309.5 -__author__="tor"
309.6 -__date__ ="$Oct 12, 2008 7:19:09 PM$"
309.7 -
309.8 -if __name__ == "__main__":
309.9 - print "Hello";
309.10 - preprocess(foo, source, output_file, macros, include_dirs, extra_preargs, extra_postargs);
309.11 - get_preprocess(self, source, output_file, macros, include_dirs, extra_preargs, extra_postargs)
309.12 -
309.13 -
310.1 --- a/python.editor/test/unit/data/testfiles/extract4.py Sun Jan 04 13:11:53 2015 -0600
310.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
310.3 @@ -1,10 +0,0 @@
310.4 -
310.5 -__author__="tor"
310.6 -__date__ ="$Oct 22, 2008 2:06:12 PM$"
310.7 -
310.8 -if __name__ == "__main__":
310.9 - if _a >a:
310.10 - c = a
310.11 - else
310.12 - c = b
310.13 -
311.1 --- a/python.editor/test/unit/data/testfiles/extract4.py.testFix5.fixed Sun Jan 04 13:11:53 2015 -0600
311.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
311.3 @@ -1,14 +0,0 @@
311.4 -
311.5 -__author__="tor"
311.6 -__date__ ="$Oct 22, 2008 2:06:12 PM$"
311.7 -
311.8 -
311.9 -def |>^new_name<|(_a, a, b):
311.10 - if _a >a:
311.11 - c = a
311.12 - else
311.13 - c = b
311.14 -
311.15 -if __name__ == "__main__":
311.16 - |>new_name<|(_a, a, b)
311.17 -
312.1 --- a/python.editor/test/unit/data/testfiles/extract5.py Sun Jan 04 13:11:53 2015 -0600
312.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
312.3 @@ -1,4 +0,0 @@
312.4 -if _a >a:
312.5 - c = a
312.6 -else
312.7 - c = b
313.1 --- a/python.editor/test/unit/data/testfiles/extract5.py.testFix6.fixed Sun Jan 04 13:11:53 2015 -0600
313.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
313.3 @@ -1,8 +0,0 @@
313.4 -
313.5 -def |>^new_name<|(_a, a, b):
313.6 - if _a >a:
313.7 - c = a
313.8 - else
313.9 - c = b
313.10 -
313.11 -|>new_name<|(_a, a, b)
314.1 --- a/python.editor/test/unit/data/testfiles/formatting.py Sun Jan 04 13:11:53 2015 -0600
314.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
314.3 @@ -1,40 +0,0 @@
314.4 -def func( args , without , commas, arg=3,arg = 4):
314.5 - if pos!=-1 and optval[ pos-1 ].isspace():
314.6 - pass
314.7 -def func2( aargs ):
314.8 - pass
314.9 -
314.10 -def func3( arrrrgs, arg2 ):
314.11 - pass
314.12 -
314.13 -x+=1
314.14 -y+=2
314.15 -z=3
314.16 -d = 4
314.17 -if d==4:
314.18 - pass
314.19 -x = `foo`
314.20 -
314.21 -class Test:
314.22 - @property
314.23 - def scheme(self):
314.24 - return self[ 0 ]
314.25 -
314.26 -x = ((500+30)*(470))
314.27 -# x=1,y=2
314.28 -modeDict = { 'r' : 'rb', 'w' : 'wb', 'a': 'r+b' }
314.29 -modeDict2 = {'r':'rb', 'w':'wb', 'a': 'r+b'}
314.30 -x = 2 ; y=3 ; z = 5
314.31 -
314.32 -if d==5:
314.33 - pass
314.34 -
314.35 -output=`dmesg | grep hda`
314.36 -
314.37 -SECTCRE = re.compile(
314.38 - r'\[' # [
314.39 - r'(?P<header>[^]]+)' # very permissive!
314.40 - r'\]' # ]
314.41 - )
314.42 -
314.43 -
315.1 --- a/python.editor/test/unit/data/testfiles/formatting.py.formatted Sun Jan 04 13:11:53 2015 -0600
315.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
315.3 @@ -1,40 +0,0 @@
315.4 -def func(args, without, commas, arg=3, arg=4):
315.5 - if pos != -1 and optval[pos-1].isspace():
315.6 - pass
315.7 -def func2(aargs):
315.8 - pass
315.9 -
315.10 -def func3(arrrrgs, arg2):
315.11 - pass
315.12 -
315.13 -x += 1
315.14 -y += 2
315.15 -z = 3
315.16 -d = 4
315.17 -if d == 4:
315.18 - pass
315.19 -x = `foo`
315.20 -
315.21 -class Test:
315.22 - @property
315.23 - def scheme(self):
315.24 - return self[0]
315.25 -
315.26 -x = ((500 + 30) * (470))
315.27 -# x=1,y=2
315.28 -modeDict = {'r': 'rb', 'w': 'wb', 'a': 'r+b'}
315.29 -modeDict2 = {'r':'rb', 'w':'wb', 'a': 'r+b'}
315.30 -x = 2; y = 3; z = 5
315.31 -
315.32 -if d == 5:
315.33 - pass
315.34 -
315.35 -output = `dmesg | grep hda`
315.36 -
315.37 -SECTCRE = re.compile(
315.38 - r'\[' # [
315.39 - r'(?P<header>[^]]+)' # very permissive!
315.40 - r'\]' # ]
315.41 - )
315.42 -
315.43 -
316.1 --- a/python.editor/test/unit/data/testfiles/formatting.py.scopes Sun Jan 04 13:11:53 2015 -0600
316.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
316.3 @@ -1,46 +0,0 @@
316.4 -=============================================
316.5 -<file-top>: Module : OffsetRange[0,691>
316.6 -SECTCRE [bound][data][node=Name]
316.7 -Test [bound][class][def][node=ClassDef]
316.8 -d [bound][data][read][node=Name]
316.9 -dmesg [read][UNRESOLVED][node=Name]
316.10 -foo [read][UNRESOLVED][node=Name]
316.11 -func [bound][function][def][node=FunctionDef]
316.12 -func2 [bound][function][def][node=FunctionDef]
316.13 -func3 [bound][function][def][node=FunctionDef]
316.14 -grep [read][UNRESOLVED][node=Name]
316.15 -modeDict [bound][data][node=Name]
316.16 -modeDict2 [bound][data][node=Name]
316.17 -output [bound][data][node=Name]
316.18 -re [read][UNRESOLVED][node=Name]
316.19 -x [bound][data][node=Name]
316.20 -y [bound][data][node=Name]
316.21 -z [bound][data][node=Name]
316.22 -
316.23 - =============================================
316.24 - func: FunctionDef : OffsetRange[0,119>
316.25 - arg [bound][param][data][unused][node=Name]
316.26 - args [bound][param][data][unused][node=Name]
316.27 - commas [bound][param][data][unused][node=Name]
316.28 - optval [free][read][node=Name]
316.29 - pos [free][read][node=Name]
316.30 - without [bound][param][data][unused][node=Name]
316.31 -
316.32 - =============================================
316.33 - func2: FunctionDef : OffsetRange[119,149>
316.34 - aargs [bound][param][data][unused][node=Name]
316.35 -
316.36 - =============================================
316.37 - func3: FunctionDef : OffsetRange[149,190>
316.38 - arg2 [bound][param][data][unused][node=Name]
316.39 - arrrrgs [bound][param][data][unused][node=Name]
316.40 -
316.41 - =============================================
316.42 - class Test: ClassDef : OffsetRange[243,317>
316.43 - property [free][read][node=Name]
316.44 - scheme [bound][function][def][node=FunctionDef]
316.45 -
316.46 - =============================================
316.47 - scheme: FunctionDef : OffsetRange[259,317>
316.48 - self [bound][param][data][read][node=Name]
316.49 -
317.1 --- a/python.editor/test/unit/data/testfiles/fromimports.py Sun Jan 04 13:11:53 2015 -0600
317.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
317.3 @@ -1,3 +0,0 @@
317.4 -from distutils import core
317.5 -core.g
317.6 -
318.1 --- a/python.editor/test/unit/data/testfiles/fromimports.py.testFromImports.completion Sun Jan 04 13:11:53 2015 -0600
318.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
318.3 @@ -1,17 +0,0 @@
318.4 -Code completion result for source line:
318.5 -core.|g
318.6 -(QueryType=COMPLETION, NameKind=PREFIX)
318.7 -MODULE Command
318.8 -MODULE DEBUG
318.9 -MODULE Distribution
318.10 -MODULE Extension
318.11 -MODULE grok_environment_error
318.12 -MODULE os
318.13 -MODULE sys
318.14 -METHOD gen_usage(script_name)
318.15 -METHOD run_setup(script_name, script_
318.16 -METHOD setup(attrs)
318.17 -VARIABLE USAGE
318.18 -VARIABLE __revision__
318.19 -VARIABLE extension_keywords
318.20 -VARIABLE setup_keywords
319.1 --- a/python.editor/test/unit/data/testfiles/futureimport.py Sun Jan 04 13:11:53 2015 -0600
319.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
319.3 @@ -1,4 +0,0 @@
319.4 -# Ensure that the future imports here aren't shown as unused or imported symbols for code completion
319.5 -from __future__ import absolute_imports, with_statement
319.6 -with_stateme # Call
319.7 -
320.1 --- a/python.editor/test/unit/data/testfiles/futureimport.py.testFutureImport1.completion Sun Jan 04 13:11:53 2015 -0600
320.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
320.3 @@ -1,3 +0,0 @@
320.4 -Code completion result for source line:
320.5 -from __future__ import |absolute_imports, with_statement
320.6 -(QueryType=COMPLETION, NameKind=PREFIX)
321.1 --- a/python.editor/test/unit/data/testfiles/getopt.py Sun Jan 04 13:11:53 2015 -0600
321.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
321.3 @@ -1,211 +0,0 @@
321.4 -# -*- coding: iso-8859-1 -*-
321.5 -"""Parser for command line options.
321.6 -
321.7 -This module helps scripts to parse the command line arguments in
321.8 -sys.argv. It supports the same conventions as the Unix getopt()
321.9 -function (including the special meanings of arguments of the form `-'
321.10 -and `--'). Long options similar to those supported by GNU software
321.11 -may be used as well via an optional third argument. This module
321.12 -provides two functions and an exception:
321.13 -
321.14 -getopt() -- Parse command line options
321.15 -gnu_getopt() -- Like getopt(), but allow option and non-option arguments
321.16 -to be intermixed.
321.17 -GetoptError -- exception (class) raised with 'opt' attribute, which is the
321.18 -option involved with the exception.
321.19 -"""
321.20 -
321.21 -# Long option support added by Lars Wirzenius <liw@iki.fi>.
321.22 -#
321.23 -# Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
321.24 -# to class-based exceptions.
321.25 -#
321.26 -# Peter Åstrand <astrand@lysator.liu.se> added gnu_getopt().
321.27 -#
321.28 -# TODO for gnu_getopt():
321.29 -#
321.30 -# - GNU getopt_long_only mechanism
321.31 -# - allow the caller to specify ordering
321.32 -# - RETURN_IN_ORDER option
321.33 -# - GNU extension with '-' as first character of option string
321.34 -# - optional arguments, specified by double colons
321.35 -# - a option string with a W followed by semicolon should
321.36 -# treat "-W foo" as "--foo"
321.37 -
321.38 -__all__ = ["GetoptError","error","getopt","gnu_getopt"]
321.39 -
321.40 -import os
321.41 -
321.42 -class GetoptError(Exception):
321.43 - opt = ''
321.44 - msg = ''
321.45 - def __init__(self, msg, opt=''):
321.46 - self.msg = msg
321.47 - self.opt = opt
321.48 - Exception.__init__(self, msg, opt)
321.49 -
321.50 - def __str__(self):
321.51 - return self.msg
321.52 -
321.53 -error = GetoptError # backward compatibility
321.54 -
321.55 -def getopt(args, shortopts, longopts = []):
321.56 - """getopt(args, options[, long_options]) -> opts, args
321.57 -
321.58 - Parses command line options and parameter list. args is the
321.59 - argument list to be parsed, without the leading reference to the
321.60 - running program. Typically, this means "sys.argv[1:]". shortopts
321.61 - is the string of option letters that the script wants to
321.62 - recognize, with options that require an argument followed by a
321.63 - colon (i.e., the same format that Unix getopt() uses). If
321.64 - specified, longopts is a list of strings with the names of the
321.65 - long options which should be supported. The leading '--'
321.66 - characters should not be included in the option name. Options
321.67 - which require an argument should be followed by an equal sign
321.68 - ('=').
321.69 -
321.70 - The return value consists of two elements: the first is a list of
321.71 - (option, value) pairs; the second is the list of program arguments
321.72 - left after the option list was stripped (this is a trailing slice
321.73 - of the first argument). Each option-and-value pair returned has
321.74 - the option as its first element, prefixed with a hyphen (e.g.,
321.75 - '-x'), and the option argument as its second element, or an empty
321.76 - string if the option has no argument. The options occur in the
321.77 - list in the same order in which they were found, thus allowing
321.78 - multiple occurrences. Long and short options may be mixed.
321.79 -
321.80 - """
321.81 -
321.82 - opts = []
321.83 - if type(longopts) == type(""):
321.84 - longopts = [longopts]
321.85 - else:
321.86 - longopts = list(longopts)
321.87 - while args and args[0].startswith('-') and args[0] != '-':
321.88 - if args[0] == '--':
321.89 - args = args[1:]
321.90 - break
321.91 - if args[0].startswith('--'):
321.92 - opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
321.93 - else:
321.94 - opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
321.95 -
321.96 - return opts, args
321.97 -
321.98 -def gnu_getopt(args, shortopts, longopts = []):
321.99 - """getopt(args, options[, long_options]) -> opts, args
321.100 -
321.101 - This function works like getopt(), except that GNU style scanning
321.102 - mode is used by default. This means that option and non-option
321.103 - arguments may be intermixed. The getopt() function stops
321.104 - processing options as soon as a non-option argument is
321.105 - encountered.
321.106 -
321.107 - If the first character of the option string is `+', or if the
321.108 - environment variable POSIXLY_CORRECT is set, then option
321.109 - processing stops as soon as a non-option argument is encountered.
321.110 -
321.111 - """
321.112 -
321.113 - opts = []
321.114 - prog_args = []
321.115 - if isinstance(longopts, str):
321.116 - longopts = [longopts]
321.117 - else:
321.118 - longopts = list(longopts)
321.119 -
321.120 - # Allow options after non-option arguments?
321.121 - if shortopts.startswith('+'):
321.122 - shortopts = shortopts[1:]
321.123 - all_options_first = True
321.124 - elif os.environ.get("POSIXLY_CORRECT"):
321.125 - all_options_first = True
321.126 - else:
321.127 - all_options_first = False
321.128 -
321.129 - while args:
321.130 - if args[0] == '--':
321.131 - prog_args += args[1:]
321.132 - break
321.133 -
321.134 - if args[0][:2] == '--':
321.135 - opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
321.136 - elif args[0][:1] == '-':
321.137 - opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
321.138 - else:
321.139 - if all_options_first:
321.140 - prog_args += args
321.141 - break
321.142 - else:
321.143 - prog_args.append(args[0])
321.144 - args = args[1:]
321.145 -
321.146 - return opts, prog_args
321.147 -
321.148 -def do_longs(opts, opt, longopts, args):
321.149 - try:
321.150 - i = opt.index('=')
321.151 - except ValueError:
321.152 - optarg = None
321.153 - else:
321.154 - opt, optarg = opt[:i], opt[i+1:]
321.155 -
321.156 - has_arg, opt = long_has_args(opt, longopts)
321.157 - if has_arg:
321.158 - if optarg is None:
321.159 - if not args:
321.160 - raise GetoptError('option --%s requires argument' % opt, opt)
321.161 - optarg, args = args[0], args[1:]
321.162 - elif optarg:
321.163 - raise GetoptError('option --%s must not have an argument' % opt, opt)
321.164 - opts.append(('--' + opt, optarg or ''))
321.165 - return opts, args
321.166 -
321.167 -# Return:
321.168 -# has_arg?
321.169 -# full option name
321.170 -def long_has_args(opt, longopts):
321.171 - possibilities = [o for o in longopts if o.startswith(opt)]
321.172 - if not possibilities:
321.173 - raise GetoptError('option --%s not recognized' % opt, opt)
321.174 - # Is there an exact match?
321.175 - if opt in possibilities:
321.176 - return False, opt
321.177 - elif opt + '=' in possibilities:
321.178 - return True, opt
321.179 - # No exact match, so better be unique.
321.180 - if len(possibilities) > 1:
321.181 - # XXX since possibilities contains all valid continuations, might be
321.182 - # nice to work them into the error msg
321.183 - raise GetoptError('option --%s not a unique prefix' % opt, opt)
321.184 - assert len(possibilities) == 1
321.185 - unique_match = possibilities[0]
321.186 - has_arg = unique_match.endswith('=')
321.187 - if has_arg:
321.188 - unique_match = unique_match[:-1]
321.189 - return has_arg, unique_match
321.190 -
321.191 -def do_shorts(opts, optstring, shortopts, args):
321.192 - while optstring != '':
321.193 - opt, optstring = optstring[0], optstring[1:]
321.194 - if short_has_arg(opt, shortopts):
321.195 - if optstring == '':
321.196 - if not args:
321.197 - raise GetoptError('option -%s requires argument' % opt,
321.198 - opt)
321.199 - optstring, args = args[0], args[1:]
321.200 - optarg, optstring = optstring, ''
321.201 - else:
321.202 - optarg = ''
321.203 - opts.append(('-' + opt, optarg))
321.204 - return opts, args
321.205 -
321.206 -def short_has_arg(opt, shortopts):
321.207 - for i in range(len(shortopts)):
321.208 - if opt == shortopts[i] != ':':
321.209 - return shortopts.startswith(':', i+1)
321.210 - raise GetoptError('option -%s not recognized' % opt, opt)
321.211 -
321.212 -if __name__ == '__main__':
321.213 - import sys
321.214 - print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])
322.1 --- a/python.editor/test/unit/data/testfiles/getopt.py.folds Sun Jan 04 13:11:53 2015 -0600
322.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
322.3 @@ -1,212 +0,0 @@
322.4 - # -*- coding: iso-8859-1 -*-
322.5 -+ """Parser for command line options.
322.6 -|
322.7 -| This module helps scripts to parse the command line arguments in
322.8 -| sys.argv. It supports the same conventions as the Unix getopt()
322.9 -| function (including the special meanings of arguments of the form `-'
322.10 -| and `--'). Long options similar to those supported by GNU software
322.11 -| may be used as well via an optional third argument. This module
322.12 -| provides two functions and an exception:
322.13 -|
322.14 -| getopt() -- Parse command line options
322.15 -| gnu_getopt() -- Like getopt(), but allow option and non-option arguments
322.16 -| to be intermixed.
322.17 -| GetoptError -- exception (class) raised with 'opt' attribute, which is the
322.18 -| option involved with the exception.
322.19 -- """
322.20 -
322.21 - # Long option support added by Lars Wirzenius <liw@iki.fi>.
322.22 - #
322.23 - # Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
322.24 - # to class-based exceptions.
322.25 - #
322.26 - # Peter Åstrand <astrand@lysator.liu.se> added gnu_getopt().
322.27 - #
322.28 - # TODO for gnu_getopt():
322.29 - #
322.30 - # - GNU getopt_long_only mechanism
322.31 - # - allow the caller to specify ordering
322.32 - # - RETURN_IN_ORDER option
322.33 - # - GNU extension with '-' as first character of option string
322.34 - # - optional arguments, specified by double colons
322.35 - # - a option string with a W followed by semicolon should
322.36 - # treat "-W foo" as "--foo"
322.37 -
322.38 - __all__ = ["GetoptError","error","getopt","gnu_getopt"]
322.39 -
322.40 - import os
322.41 -
322.42 -+ class GetoptError(Exception):
322.43 -| opt = ''
322.44 -| msg = ''
322.45 -+ def __init__(self, msg, opt=''):
322.46 -| self.msg = msg
322.47 -| self.opt = opt
322.48 -| Exception.__init__(self, msg, opt)
322.49 --
322.50 -+ def __str__(self):
322.51 -| return self.msg
322.52 --
322.53 - error = GetoptError # backward compatibility
322.54 -
322.55 -+ def getopt(args, shortopts, longopts = []):
322.56 -+ """getopt(args, options[, long_options]) -> opts, args
322.57 -|
322.58 -| Parses command line options and parameter list. args is the
322.59 -| argument list to be parsed, without the leading reference to the
322.60 -| running program. Typically, this means "sys.argv[1:]". shortopts
322.61 -| is the string of option letters that the script wants to
322.62 -| recognize, with options that require an argument followed by a
322.63 -| colon (i.e., the same format that Unix getopt() uses). If
322.64 -| specified, longopts is a list of strings with the names of the
322.65 -| long options which should be supported. The leading '--'
322.66 -| characters should not be included in the option name. Options
322.67 -| which require an argument should be followed by an equal sign
322.68 -| ('=').
322.69 -|
322.70 -| The return value consists of two elements: the first is a list of
322.71 -| (option, value) pairs; the second is the list of program arguments
322.72 -| left after the option list was stripped (this is a trailing slice
322.73 -| of the first argument). Each option-and-value pair returned has
322.74 -| the option as its first element, prefixed with a hyphen (e.g.,
322.75 -| '-x'), and the option argument as its second element, or an empty
322.76 -| string if the option has no argument. The options occur in the
322.77 -| list in the same order in which they were found, thus allowing
322.78 -| multiple occurrences. Long and short options may be mixed.
322.79 -|
322.80 -- """
322.81 -|
322.82 -| opts = []
322.83 -| if type(longopts) == type(""):
322.84 -| longopts = [longopts]
322.85 -| else:
322.86 -| longopts = list(longopts)
322.87 -| while args and args[0].startswith('-') and args[0] != '-':
322.88 -| if args[0] == '--':
322.89 -| args = args[1:]
322.90 -| break
322.91 -| if args[0].startswith('--'):
322.92 -| opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
322.93 -| else:
322.94 -| opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
322.95 -|
322.96 -| return opts, args
322.97 --
322.98 -+ def gnu_getopt(args, shortopts, longopts = []):
322.99 -+ """getopt(args, options[, long_options]) -> opts, args
322.100 -|
322.101 -| This function works like getopt(), except that GNU style scanning
322.102 -| mode is used by default. This means that option and non-option
322.103 -| arguments may be intermixed. The getopt() function stops
322.104 -| processing options as soon as a non-option argument is
322.105 -| encountered.
322.106 -|
322.107 -| If the first character of the option string is `+', or if the
322.108 -| environment variable POSIXLY_CORRECT is set, then option
322.109 -| processing stops as soon as a non-option argument is encountered.
322.110 -|
322.111 -- """
322.112 -|
322.113 -| opts = []
322.114 -| prog_args = []
322.115 -| if isinstance(longopts, str):
322.116 -| longopts = [longopts]
322.117 -| else:
322.118 -| longopts = list(longopts)
322.119 -|
322.120 -| # Allow options after non-option arguments?
322.121 -| if shortopts.startswith('+'):
322.122 -| shortopts = shortopts[1:]
322.123 -| all_options_first = True
322.124 -| elif os.environ.get("POSIXLY_CORRECT"):
322.125 -| all_options_first = True
322.126 -| else:
322.127 -| all_options_first = False
322.128 -|
322.129 -| while args:
322.130 -| if args[0] == '--':
322.131 -| prog_args += args[1:]
322.132 -| break
322.133 -|
322.134 -| if args[0][:2] == '--':
322.135 -| opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
322.136 -| elif args[0][:1] == '-':
322.137 -| opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
322.138 -| else:
322.139 -| if all_options_first:
322.140 -| prog_args += args
322.141 -| break
322.142 -| else:
322.143 -| prog_args.append(args[0])
322.144 -| args = args[1:]
322.145 -|
322.146 -| return opts, prog_args
322.147 --
322.148 -+ def do_longs(opts, opt, longopts, args):
322.149 -| try:
322.150 -| i = opt.index('=')
322.151 -| except ValueError:
322.152 -| optarg = None
322.153 -| else:
322.154 -| opt, optarg = opt[:i], opt[i+1:]
322.155 -|
322.156 -| has_arg, opt = long_has_args(opt, longopts)
322.157 -| if has_arg:
322.158 -| if optarg is None:
322.159 -| if not args:
322.160 -| raise GetoptError('option --%s requires argument' % opt, opt)
322.161 -| optarg, args = args[0], args[1:]
322.162 -| elif optarg:
322.163 -| raise GetoptError('option --%s must not have an argument' % opt, opt)
322.164 -| opts.append(('--' + opt, optarg or ''))
322.165 -| return opts, args
322.166 -|
322.167 -| # Return:
322.168 -| # has_arg?
322.169 -- # full option name
322.170 -+ def long_has_args(opt, longopts):
322.171 -| possibilities = [o for o in longopts if o.startswith(opt)]
322.172 -| if not possibilities:
322.173 -| raise GetoptError('option --%s not recognized' % opt, opt)
322.174 -| # Is there an exact match?
322.175 -| if opt in possibilities:
322.176 -| return False, opt
322.177 -| elif opt + '=' in possibilities:
322.178 -| return True, opt
322.179 -| # No exact match, so better be unique.
322.180 -| if len(possibilities) > 1:
322.181 -| # XXX since possibilities contains all valid continuations, might be
322.182 -| # nice to work them into the error msg
322.183 -| raise GetoptError('option --%s not a unique prefix' % opt, opt)
322.184 -| assert len(possibilities) == 1
322.185 -| unique_match = possibilities[0]
322.186 -| has_arg = unique_match.endswith('=')
322.187 -| if has_arg:
322.188 -| unique_match = unique_match[:-1]
322.189 -| return has_arg, unique_match
322.190 --
322.191 -+ def do_shorts(opts, optstring, shortopts, args):
322.192 -| while optstring != '':
322.193 -| opt, optstring = optstring[0], optstring[1:]
322.194 -| if short_has_arg(opt, shortopts):
322.195 -| if optstring == '':
322.196 -| if not args:
322.197 -| raise GetoptError('option -%s requires argument' % opt,
322.198 -| opt)
322.199 -| optstring, args = args[0], args[1:]
322.200 -| optarg, optstring = optstring, ''
322.201 -| else:
322.202 -| optarg = ''
322.203 -| opts.append(('-' + opt, optarg))
322.204 -| return opts, args
322.205 --
322.206 -+ def short_has_arg(opt, shortopts):
322.207 -| for i in range(len(shortopts)):
322.208 -| if opt == shortopts[i] != ':':
322.209 -| return shortopts.startswith(':', i+1)
322.210 -| raise GetoptError('option -%s not recognized' % opt, opt)
322.211 --
322.212 - if __name__ == '__main__':
322.213 - import sys
322.214 - print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])
322.215 -
323.1 --- a/python.editor/test/unit/data/testfiles/getopt.py.nameoffsets Sun Jan 04 13:11:53 2015 -0600
323.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
323.3 @@ -1,212 +0,0 @@
323.4 -
323.5 -# -*- coding: iso-8859-1 -*-
323.6 -"""Parser for command line options.
323.7 -
323.8 -This module helps scripts to parse the command line arguments in
323.9 -sys.argv. It supports the same conventions as the Unix getopt()
323.10 -function (including the special meanings of arguments of the form `-'
323.11 -and `--'). Long options similar to those supported by GNU software
323.12 -may be used as well via an optional third argument. This module
323.13 -provides two functions and an exception:
323.14 -
323.15 -getopt() -- Parse command line options
323.16 -gnu_getopt() -- Like getopt(), but allow option and non-option arguments
323.17 -to be intermixed.
323.18 -GetoptError -- exception (class) raised with 'opt' attribute, which is the
323.19 -option involved with the exception.
323.20 -"""
323.21 -
323.22 -# Long option support added by Lars Wirzenius <liw@iki.fi>.
323.23 -#
323.24 -# Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
323.25 -# to class-based exceptions.
323.26 -#
323.27 -# Peter Åstrand <astrand@lysator.liu.se> added gnu_getopt().
323.28 -#
323.29 -# TODO for gnu_getopt():
323.30 -#
323.31 -# - GNU getopt_long_only mechanism
323.32 -# - allow the caller to specify ordering
323.33 -# - RETURN_IN_ORDER option
323.34 -# - GNU extension with '-' as first character of option string
323.35 -# - optional arguments, specified by double colons
323.36 -# - a option string with a W followed by semicolon should
323.37 -# treat "-W foo" as "--foo"
323.38 -
323.39 -<Name>__all__</Name> = ["GetoptError","error","getopt","gnu_getopt"]
323.40 -
323.41 -import os
323.42 -
323.43 -class <ClassDef>GetoptError</ClassDef>(<Name>Exception</Name>):
323.44 - <Name>opt</Name> = ''
323.45 - <Name>msg</Name> = ''
323.46 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>msg</Name>, <Name>opt</Name>=''):
323.47 - <Attribute><Name>self</Name></Attribute>.msg = <Name>msg</Name>
323.48 - <Attribute><Name>self</Name></Attribute>.opt = <Name>opt</Name>
323.49 - <Attribute><Name>Exception</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, <Name>msg</Name>, <Name>opt</Name>)
323.50 -
323.51 - def <FunctionDef>__str__</FunctionDef>(<Name>self</Name>):
323.52 - return <Attribute><Name>self</Name></Attribute>.msg
323.53 -
323.54 -<Name>error</Name> = <Name>GetoptError</Name> # backward compatibility
323.55 -
323.56 -def <FunctionDef>getopt</FunctionDef>(<Name>args</Name>, <Name>shortopts</Name>, <Name>longopts</Name> = []):
323.57 - """getopt(args, options[, long_options]) -> opts, args
323.58 -
323.59 - Parses command line options and parameter list. args is the
323.60 - argument list to be parsed, without the leading reference to the
323.61 - running program. Typically, this means "sys.argv[1:]". shortopts
323.62 - is the string of option letters that the script wants to
323.63 - recognize, with options that require an argument followed by a
323.64 - colon (i.e., the same format that Unix getopt() uses). If
323.65 - specified, longopts is a list of strings with the names of the
323.66 - long options which should be supported. The leading '--'
323.67 - characters should not be included in the option name. Options
323.68 - which require an argument should be followed by an equal sign
323.69 - ('=').
323.70 -
323.71 - The return value consists of two elements: the first is a list of
323.72 - (option, value) pairs; the second is the list of program arguments
323.73 - left after the option list was stripped (this is a trailing slice
323.74 - of the first argument). Each option-and-value pair returned has
323.75 - the option as its first element, prefixed with a hyphen (e.g.,
323.76 - '-x'), and the option argument as its second element, or an empty
323.77 - string if the option has no argument. The options occur in the
323.78 - list in the same order in which they were found, thus allowing
323.79 - multiple occurrences. Long and short options may be mixed.
323.80 -
323.81 - """
323.82 -
323.83 - <Name>opts</Name> = []
323.84 - if <Call><Name>type</Name></Call>(<Name>longopts</Name>) == <Call><Name>type</Name></Call>(""):
323.85 - <Name>longopts</Name> = [<Name>longopts</Name>]
323.86 - else:
323.87 - <Name>longopts</Name> = <Call><Name>list</Name></Call>(<Name>longopts</Name>)
323.88 - while <Name>args</Name> and <Name>args</Name><Attribute>[0]</Attribute>.<Call>startswith</Call>('-') and <Name>args</Name>[0] != '-':
323.89 - if <Name>args</Name>[0] == '--':
323.90 - <Name>args</Name> = <Name>args</Name>[1:]
323.91 - break
323.92 - if <Name>args</Name><Attribute>[0]</Attribute>.<Call>startswith</Call>('--'):
323.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:])
323.94 - else:
323.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:])
323.96 -
323.97 - return <Name>opts</Name>, <Name>args</Name>
323.98 -
323.99 -def <FunctionDef>gnu_getopt</FunctionDef>(<Name>args</Name>, <Name>shortopts</Name>, <Name>longopts</Name> = []):
323.100 - """getopt(args, options[, long_options]) -> opts, args
323.101 -
323.102 - This function works like getopt(), except that GNU style scanning
323.103 - mode is used by default. This means that option and non-option
323.104 - arguments may be intermixed. The getopt() function stops
323.105 - processing options as soon as a non-option argument is
323.106 - encountered.
323.107 -
323.108 - If the first character of the option string is `+', or if the
323.109 - environment variable POSIXLY_CORRECT is set, then option
323.110 - processing stops as soon as a non-option argument is encountered.
323.111 -
323.112 - """
323.113 -
323.114 - <Name>opts</Name> = []
323.115 - <Name>prog_args</Name> = []
323.116 - if <Call><Name>isinstance</Name></Call>(<Name>longopts</Name>, <Name>str</Name>):
323.117 - <Name>longopts</Name> = [<Name>longopts</Name>]
323.118 - else:
323.119 - <Name>longopts</Name> = <Call><Name>list</Name></Call>(<Name>longopts</Name>)
323.120 -
323.121 - # Allow options after non-option arguments?
323.122 - if <Attribute><Name>shortopts</Name></Attribute>.<Call>startswith</Call>('+'):
323.123 - <Name>shortopts</Name> = <Name>shortopts</Name>[1:]
323.124 - <Name>all_options_first</Name> = <Name>True</Name>
323.125 - elif <Attribute><Attribute><Name>os</Name></Attribute></Attribute>.environ.<Call>get</Call>("POSIXLY_CORRECT"):
323.126 - <Name>all_options_first</Name> = <Name>True</Name>
323.127 - else:
323.128 - <Name>all_options_first</Name> = <Name>False</Name>
323.129 -
323.130 - while <Name>args</Name>:
323.131 - if <Name>args</Name>[0] == '--':
323.132 - <Name>prog_args</Name> += <Name>args</Name>[1:]
323.133 - break
323.134 -
323.135 - if <Name>args</Name>[0][:2] == '--':
323.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:])
323.137 - elif <Name>args</Name>[0][:1] == '-':
323.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:])
323.139 - else:
323.140 - if <Name>all_options_first</Name>:
323.141 - <Name>prog_args</Name> += <Name>args</Name>
323.142 - break
323.143 - else:
323.144 - <Attribute><Name>prog_args</Name></Attribute>.<Call>append</Call>(<Name>args</Name>[0])
323.145 - <Name>args</Name> = <Name>args</Name>[1:]
323.146 -
323.147 - return <Name>opts</Name>, <Name>prog_args</Name>
323.148 -
323.149 -def <FunctionDef>do_longs</FunctionDef>(<Name>opts</Name>, <Name>opt</Name>, <Name>longopts</Name>, <Name>args</Name>):
323.150 - try:
323.151 - <Name>i</Name> = <Attribute><Name>opt</Name></Attribute>.<Call>index</Call>('=')
323.152 - except <Name>ValueError</Name>:
323.153 - <Name>optarg</Name> = <Name>None</Name>
323.154 - else:
323.155 - <Name>opt</Name>, <Name>optarg</Name> = <Name>opt</Name>[:<Name>i</Name>], <Name>opt</Name>[<Name>i</Name>+1:]
323.156 -
323.157 - <Name>has_arg</Name>, <Name>opt</Name> = <Call><Name>long_has_args</Name></Call>(<Name>opt</Name>, <Name>longopts</Name>)
323.158 - if <Name>has_arg</Name>:
323.159 - if <Name>optarg</Name> is <Name>None</Name>:
323.160 - if not <Name>args</Name>:
323.161 - raise <Call><Name>GetoptError</Name></Call>('option --%s requires argument' % <Name>opt</Name>, <Name>opt</Name>)
323.162 - <Name>optarg</Name>, <Name>args</Name> = <Name>args</Name>[0], <Name>args</Name>[1:]
323.163 - elif <Name>optarg</Name>:
323.164 - raise <Call><Name>GetoptError</Name></Call>('option --%s must not have an argument' % <Name>opt</Name>, <Name>opt</Name>)
323.165 - <Attribute><Name>opts</Name></Attribute>.<Call>append</Call>(('--' + <Name>opt</Name>, <Name>optarg</Name> or ''))
323.166 - return <Name>opts</Name>, <Name>args</Name>
323.167 -
323.168 -# Return:
323.169 -# has_arg?
323.170 -# full option name
323.171 -def <FunctionDef>long_has_args</FunctionDef>(<Name>opt</Name>, <Name>longopts</Name>):
323.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>)]
323.173 - if not <Name>possibilities</Name>:
323.174 - raise <Call><Name>GetoptError</Name></Call>('option --%s not recognized' % <Name>opt</Name>, <Name>opt</Name>)
323.175 - # Is there an exact match?
323.176 - if <Name>opt</Name> in <Name>possibilities</Name>:
323.177 - return <Name>False</Name>, <Name>opt</Name>
323.178 - elif <Name>opt</Name> + '=' in <Name>possibilities</Name>:
323.179 - return <Name>True</Name>, <Name>opt</Name>
323.180 - # No exact match, so better be unique.
323.181 - if <Call><Name>len</Name></Call>(<Name>possibilities</Name>) > 1:
323.182 - # XXX since possibilities contains all valid continuations, might be
323.183 - # nice to work them into the error msg
323.184 - raise <Call><Name>GetoptError</Name></Call>('option --%s not a unique prefix' % <Name>opt</Name>, <Name>opt</Name>)
323.185 - assert <Call><Name>len</Name></Call>(<Name>possibilities</Name>) == 1
323.186 - <Name>unique_match</Name> = <Name>possibilities</Name>[0]
323.187 - <Name>has_arg</Name> = <Attribute><Name>unique_match</Name></Attribute>.<Call>endswith</Call>('=')
323.188 - if <Name>has_arg</Name>:
323.189 - <Name>unique_match</Name> = <Name>unique_match</Name>[:-1]
323.190 - return <Name>has_arg</Name>, <Name>unique_match</Name>
323.191 -
323.192 -def <FunctionDef>do_shorts</FunctionDef>(<Name>opts</Name>, <Name>optstring</Name>, <Name>shortopts</Name>, <Name>args</Name>):
323.193 - while <Name>optstring</Name> != '':
323.194 - <Name>opt</Name>, <Name>optstring</Name> = <Name>optstring</Name>[0], <Name>optstring</Name>[1:]
323.195 - if <Call><Name>short_has_arg</Name></Call>(<Name>opt</Name>, <Name>shortopts</Name>):
323.196 - if <Name>optstring</Name> == '':
323.197 - if not <Name>args</Name>:
323.198 - raise <Call><Name>GetoptError</Name></Call>('option -%s requires argument' % <Name>opt</Name>,
323.199 - <Name>opt</Name>)
323.200 - <Name>optstring</Name>, <Name>args</Name> = <Name>args</Name>[0], <Name>args</Name>[1:]
323.201 - <Name>optarg</Name>, <Name>optstring</Name> = <Name>optstring</Name>, ''
323.202 - else:
323.203 - <Name>optarg</Name> = ''
323.204 - <Attribute><Name>opts</Name></Attribute>.<Call>append</Call>(('-' + <Name>opt</Name>, <Name>optarg</Name>))
323.205 - return <Name>opts</Name>, <Name>args</Name>
323.206 -
323.207 -def <FunctionDef>short_has_arg</FunctionDef>(<Name>opt</Name>, <Name>shortopts</Name>):
323.208 - for <Name>i</Name> in <Call><Name>range</Name></Call>(<Call><Name>len</Name></Call>(<Name>shortopts</Name>)):
323.209 - if <Name>opt</Name> == <Name>shortopts</Name>[<Name>i</Name>] != ':':
323.210 - return <Attribute><Name>shortopts</Name></Attribute>.<Call>startswith</Call>(':', <Name>i</Name>+1)
323.211 - raise <Call><Name>GetoptError</Name></Call>('option -%s not recognized' % <Name>opt</Name>, <Name>opt</Name>)
323.212 -
323.213 -if <Name>__name__</Name> == '__main__':
323.214 - import sys
323.215 - print <Call><Name>getopt</Name></Call>(<Attribute><Name>sys</Name></Attribute>.argv[1:], "a:b", ["alpha=", "beta"])
324.1 --- a/python.editor/test/unit/data/testfiles/getopt.py.offsets Sun Jan 04 13:11:53 2015 -0600
324.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
324.3 @@ -1,212 +0,0 @@
324.4 -
324.5 -# -*- coding: iso-8859-1 -*-
324.6 -<Module><Expr><Str>"""Parser for command line options.
324.7 -
324.8 -This module helps scripts to parse the command line arguments in
324.9 -sys.argv. It supports the same conventions as the Unix getopt()
324.10 -function (including the special meanings of arguments of the form `-'
324.11 -and `--'). Long options similar to those supported by GNU software
324.12 -may be used as well via an optional third argument. This module
324.13 -provides two functions and an exception:
324.14 -
324.15 -getopt() -- Parse command line options
324.16 -gnu_getopt() -- Like getopt(), but allow option and non-option arguments
324.17 -to be intermixed.
324.18 -GetoptError -- exception (class) raised with 'opt' attribute, which is the
324.19 -option involved with the exception.
324.20 -"""</Str></Expr>
324.21 -
324.22 -# Long option support added by Lars Wirzenius <liw@iki.fi>.
324.23 -#
324.24 -# Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
324.25 -# to class-based exceptions.
324.26 -#
324.27 -# Peter Åstrand <astrand@lysator.liu.se> added gnu_getopt().
324.28 -#
324.29 -# TODO for gnu_getopt():
324.30 -#
324.31 -# - GNU getopt_long_only mechanism
324.32 -# - allow the caller to specify ordering
324.33 -# - RETURN_IN_ORDER option
324.34 -# - GNU extension with '-' as first character of option string
324.35 -# - optional arguments, specified by double colons
324.36 -# - a option string with a W followed by semicolon should
324.37 -# treat "-W foo" as "--foo"
324.38 -
324.39 -<Assign><Name>__all__</Name> = <List>[<Str>"GetoptError"</Str>,<Str>"error"</Str>,<Str>"getopt"</Str>,<Str>"gnu_getopt"</Str>]</List></Assign>
324.40 -
324.41 -<Import>import os</Import>
324.42 -
324.43 -<ClassDef>class GetoptError(<Name>Exception</Name>):
324.44 - <Assign><Name>opt</Name> = <Str>''</Str></Assign>
324.45 - <Assign><Name>msg</Name> = <Str>''</Str></Assign>
324.46 - <FunctionDef>def __init__(<Name>self</Name>, <Name>msg</Name>, <Name>opt</Name>=<Str>''</Str>):
324.47 - <Assign><Attribute><Name>self</Name>.msg</Attribute> = <Name>msg</Name></Assign>
324.48 - <Assign><Attribute><Name>self</Name>.opt</Attribute> = <Name>opt</Name></Assign>
324.49 - <Expr><Call><Attribute><Name>Exception</Name>.__init__</Attribute>(<Name>self</Name>, <Name>msg</Name>, <Name>opt</Name>)</Call></Expr>
324.50 -
324.51 - </FunctionDef> <FunctionDef>def __str__(<Name>self</Name>):
324.52 - <Return>return <Attribute><Name>self</Name>.msg</Attribute></Return>
324.53 -
324.54 -</FunctionDef></ClassDef><Assign><Name>error</Name> = <Name>GetoptError</Name></Assign> # backward compatibility
324.55 -
324.56 -<FunctionDef>def getopt(<Name>args</Name>, <Name>shortopts</Name>, <Name>longopts</Name> = <List>[]</List>):
324.57 - <Expr><Str>"""getopt(args, options[, long_options]) -> opts, args
324.58 -
324.59 - Parses command line options and parameter list. args is the
324.60 - argument list to be parsed, without the leading reference to the
324.61 - running program. Typically, this means "sys.argv[1:]". shortopts
324.62 - is the string of option letters that the script wants to
324.63 - recognize, with options that require an argument followed by a
324.64 - colon (i.e., the same format that Unix getopt() uses). If
324.65 - specified, longopts is a list of strings with the names of the
324.66 - long options which should be supported. The leading '--'
324.67 - characters should not be included in the option name. Options
324.68 - which require an argument should be followed by an equal sign
324.69 - ('=').
324.70 -
324.71 - The return value consists of two elements: the first is a list of
324.72 - (option, value) pairs; the second is the list of program arguments
324.73 - left after the option list was stripped (this is a trailing slice
324.74 - of the first argument). Each option-and-value pair returned has
324.75 - the option as its first element, prefixed with a hyphen (e.g.,
324.76 - '-x'), and the option argument as its second element, or an empty
324.77 - string if the option has no argument. The options occur in the
324.78 - list in the same order in which they were found, thus allowing
324.79 - multiple occurrences. Long and short options may be mixed.
324.80 -
324.81 - """</Str></Expr>
324.82 -
324.83 - <Assign><Name>opts</Name> = <List>[]</List></Assign>
324.84 - <If>if <Compare><Call><Name>type</Name>(<Name>longopts</Name>)</Call> == <Call><Name>type</Name>(<Str>""</Str>)</Call></Compare>:
324.85 - <Assign><Name>longopts</Name> = <List>[<Name>longopts</Name>]</List></Assign>
324.86 - else:
324.87 - <Assign><Name>longopts</Name> = <Call><Name>list</Name>(<Name>longopts</Name>)</Call></Assign>
324.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>:
324.89 - <If>if <Compare><Subscript><Name>args</Name>[<Index><Num>0</Num></Index>]</Subscript> == <Str>'--'</Str></Compare>:
324.90 - <Assign><Name>args</Name> = <Subscript><Name>args</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript></Assign>
324.91 - <Break>break</Break>
324.92 - </If> <If>if <Call><Name>args</Name><Attribute><Subscript>[<Index><Num>0</Num></Index>]</Subscript>.startswith</Attribute>(<Str>'--'</Str>)</Call>:
324.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>
324.94 - else:
324.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>
324.96 -
324.97 - </If></While> <Return>return <Tuple><Name>opts</Name>, <Name>args</Name></Tuple></Return>
324.98 -
324.99 -</FunctionDef><FunctionDef>def gnu_getopt(<Name>args</Name>, <Name>shortopts</Name>, <Name>longopts</Name> = <List>[]</List>):
324.100 - <Expr><Str>"""getopt(args, options[, long_options]) -> opts, args
324.101 -
324.102 - This function works like getopt(), except that GNU style scanning
324.103 - mode is used by default. This means that option and non-option
324.104 - arguments may be intermixed. The getopt() function stops
324.105 - processing options as soon as a non-option argument is
324.106 - encountered.
324.107 -
324.108 - If the first character of the option string is `+', or if the
324.109 - environment variable POSIXLY_CORRECT is set, then option
324.110 - processing stops as soon as a non-option argument is encountered.
324.111 -
324.112 - """</Str></Expr>
324.113 -
324.114 - <Assign><Name>opts</Name> = <List>[]</List></Assign>
324.115 - <Assign><Name>prog_args</Name> = <List>[]</List></Assign>
324.116 - <If>if <Call><Name>isinstance</Name>(<Name>longopts</Name>, <Name>str</Name>)</Call>:
324.117 - <Assign><Name>longopts</Name> = <List>[<Name>longopts</Name>]</List></Assign>
324.118 - else:
324.119 - <Assign><Name>longopts</Name> = <Call><Name>list</Name>(<Name>longopts</Name>)</Call></Assign>
324.120 -
324.121 - # Allow options after non-option arguments?
324.122 - </If> <If>if <Call><Attribute><Name>shortopts</Name>.startswith</Attribute>(<Str>'+'</Str>)</Call>:
324.123 - <Assign><Name>shortopts</Name> = <Subscript><Name>shortopts</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript></Assign>
324.124 - <Assign><Name>all_options_first</Name> = <Name>True</Name></Assign>
324.125 - <If>elif <Call><Attribute><Attribute><Name>os</Name>.environ</Attribute>.get</Attribute>(<Str>"POSIXLY_CORRECT"</Str>)</Call>:
324.126 - <Assign><Name>all_options_first</Name> = <Name>True</Name></Assign>
324.127 - else:
324.128 - <Assign><Name>all_options_first</Name> = <Name>False</Name></Assign>
324.129 -
324.130 - </If></If> <While>while <Name>args</Name>:
324.131 - <If>if <Compare><Subscript><Name>args</Name>[<Index><Num>0</Num></Index>]</Subscript> == <Str>'--'</Str></Compare>:
324.132 - <AugAssign><Name>prog_args</Name> += <Subscript><Name>args</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript></AugAssign>
324.133 - <Break>break</Break>
324.134 -
324.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>:
324.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>
324.137 - <If>elif <Compare><Subscript><Name>args</Name><Subscript>[<Index><Num>0</Num></Index>]</Subscript>[<Slice>:<Num>1</Num></Slice>]</Subscript> == <Str>'-'</Str></Compare>:
324.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>
324.139 - else:
324.140 - <If>if <Name>all_options_first</Name>:
324.141 - <AugAssign><Name>prog_args</Name> += <Name>args</Name></AugAssign>
324.142 - <Break>break</Break>
324.143 - else:
324.144 - <Expr><Call><Attribute><Name>prog_args</Name>.append</Attribute>(<Subscript><Name>args</Name>[<Index><Num>0</Num></Index>]</Subscript>)</Call></Expr>
324.145 - <Assign><Name>args</Name> = <Subscript><Name>args</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript></Assign>
324.146 -
324.147 - </If></If></If></While> <Return>return <Tuple><Name>opts</Name>, <Name>prog_args</Name></Tuple></Return>
324.148 -
324.149 -</FunctionDef><FunctionDef>def do_longs(<Name>opts</Name>, <Name>opt</Name>, <Name>longopts</Name>, <Name>args</Name>):
324.150 - <TryExcept>try:
324.151 - <Assign><Name>i</Name> = <Call><Attribute><Name>opt</Name>.index</Attribute>(<Str>'='</Str>)</Call></Assign>
324.152 - <ExceptHandler>except <Name>ValueError</Name>:
324.153 - <Assign><Name>optarg</Name> = <Name>None</Name></Assign>
324.154 - </ExceptHandler> else:
324.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>
324.156 -
324.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>
324.158 - <If>if <Name>has_arg</Name>:
324.159 - <If>if <Compare><Name>optarg</Name> is <Name>None</Name></Compare>:
324.160 - <If>if <UnaryOp>not <Name>args</Name></UnaryOp>:
324.161 - <Raise>raise <Call><Name>GetoptError</Name>(<BinOp><Str>'option --%s requires argument'</Str> % <Name>opt</Name></BinOp>, <Name>opt</Name>)</Call></Raise>
324.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>
324.163 - </If> <If>elif <Name>optarg</Name>:
324.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>
324.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>
324.166 - <Return>return <Tuple><Name>opts</Name>, <Name>args</Name></Tuple></Return>
324.167 -
324.168 -# Return:
324.169 -# has_arg?
324.170 -# full option name
324.171 -</FunctionDef><FunctionDef>def long_has_args(<Name>opt</Name>, <Name>longopts</Name>):
324.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>
324.173 - <If>if <UnaryOp>not <Name>possibilities</Name></UnaryOp>:
324.174 - <Raise>raise <Call><Name>GetoptError</Name>(<BinOp><Str>'option --%s not recognized'</Str> % <Name>opt</Name></BinOp>, <Name>opt</Name>)</Call></Raise>
324.175 - # Is there an exact match?
324.176 - </If> <If>if <Compare><Name>opt</Name> in <Name>possibilities</Name></Compare>:
324.177 - <Return>return <Tuple><Name>False</Name>, <Name>opt</Name></Tuple></Return>
324.178 - <If>elif <Compare><BinOp><Name>opt</Name> + <Str>'='</Str></BinOp> in <Name>possibilities</Name></Compare>:
324.179 - <Return>return <Tuple><Name>True</Name>, <Name>opt</Name></Tuple></Return>
324.180 - # No exact match, so better be unique.
324.181 - </If></If> <If>if <Compare><Call><Name>len</Name>(<Name>possibilities</Name>)</Call> > <Num>1</Num></Compare>:
324.182 - # XXX since possibilities contains all valid continuations, might be
324.183 - # nice to work them into the error msg
324.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>
324.185 - </If> <Assert>assert <Compare><Call><Name>len</Name>(<Name>possibilities</Name>)</Call> == <Num>1</Num></Compare></Assert>
324.186 - <Assign><Name>unique_match</Name> = <Subscript><Name>possibilities</Name>[<Index><Num>0</Num></Index>]</Subscript></Assign>
324.187 - <Assign><Name>has_arg</Name> = <Call><Attribute><Name>unique_match</Name>.endswith</Attribute>(<Str>'='</Str>)</Call></Assign>
324.188 - <If>if <Name>has_arg</Name>:
324.189 - <Assign><Name>unique_match</Name> = <Subscript><Name>unique_match</Name>[<Slice>:<Num>-1</Num></Slice>]</Subscript></Assign>
324.190 - </If> <Return>return <Tuple><Name>has_arg</Name>, <Name>unique_match</Name></Tuple></Return>
324.191 -
324.192 -</FunctionDef><FunctionDef>def do_shorts(<Name>opts</Name>, <Name>optstring</Name>, <Name>shortopts</Name>, <Name>args</Name>):
324.193 - <While>while <Compare><Name>optstring</Name> != <Str>''</Str></Compare>:
324.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>
324.195 - <If>if <Call><Name>short_has_arg</Name>(<Name>opt</Name>, <Name>shortopts</Name>)</Call>:
324.196 - <If>if <Compare><Name>optstring</Name> == <Str>''</Str></Compare>:
324.197 - <If>if <UnaryOp>not <Name>args</Name></UnaryOp>:
324.198 - <Raise>raise <Call><Name>GetoptError</Name>(<BinOp><Str>'option -%s requires argument'</Str> % <Name>opt</Name></BinOp>,
324.199 - <Name>opt</Name>)</Call></Raise>
324.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>
324.201 - </If> <Assign><Tuple><Name>optarg</Name>, <Name>optstring</Name></Tuple> = <Tuple><Name>optstring</Name>, <Str>''</Str></Tuple></Assign>
324.202 - else:
324.203 - <Assign><Name>optarg</Name> = <Str>''</Str></Assign>
324.204 - </If> <Expr><Call><Attribute><Name>opts</Name>.append</Attribute>(<Tuple>(<BinOp><Str>'-'</Str> + <Name>opt</Name></BinOp>, <Name>optarg</Name>)</Tuple>)</Call></Expr>
324.205 - </While> <Return>return <Tuple><Name>opts</Name>, <Name>args</Name></Tuple></Return>
324.206 -
324.207 -</FunctionDef><FunctionDef>def short_has_arg(<Name>opt</Name>, <Name>shortopts</Name>):
324.208 - <For>for <Name>i</Name> in <Call><Name>range</Name>(<Call><Name>len</Name>(<Name>shortopts</Name>)</Call>)</Call>:
324.209 - <If>if <Compare><Name>opt</Name> == <Subscript><Name>shortopts</Name>[<Index><Name>i</Name></Index>]</Subscript> != <Str>':'</Str></Compare>:
324.210 - <Return>return <Call><Attribute><Name>shortopts</Name>.startswith</Attribute>(<Str>':'</Str>, <BinOp><Name>i</Name>+<Num>1</Num></BinOp>)</Call></Return>
324.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>
324.212 -
324.213 -</FunctionDef><If>if <Compare><Name>__name__</Name> == <Str>'__main__'</Str></Compare>:
324.214 - <Import>import sys</Import>
324.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>
325.1 --- a/python.editor/test/unit/data/testfiles/getopt.py.semantic Sun Jan 04 13:11:53 2015 -0600
325.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
325.3 @@ -1,211 +0,0 @@
325.4 -# -*- coding: iso-8859-1 -*-
325.5 -"""Parser for command line options.
325.6 -
325.7 -This module helps scripts to parse the command line arguments in
325.8 -sys.argv. It supports the same conventions as the Unix getopt()
325.9 -function (including the special meanings of arguments of the form `-'
325.10 -and `--'). Long options similar to those supported by GNU software
325.11 -may be used as well via an optional third argument. This module
325.12 -provides two functions and an exception:
325.13 -
325.14 -getopt() -- Parse command line options
325.15 -gnu_getopt() -- Like getopt(), but allow option and non-option arguments
325.16 -to be intermixed.
325.17 -GetoptError -- exception (class) raised with 'opt' attribute, which is the
325.18 -option involved with the exception.
325.19 -"""
325.20 -
325.21 -# Long option support added by Lars Wirzenius <liw@iki.fi>.
325.22 -#
325.23 -# Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
325.24 -# to class-based exceptions.
325.25 -#
325.26 -# Peter Åstrand <astrand@lysator.liu.se> added gnu_getopt().
325.27 -#
325.28 -# TODO for gnu_getopt():
325.29 -#
325.30 -# - GNU getopt_long_only mechanism
325.31 -# - allow the caller to specify ordering
325.32 -# - RETURN_IN_ORDER option
325.33 -# - GNU extension with '-' as first character of option string
325.34 -# - optional arguments, specified by double colons
325.35 -# - a option string with a W followed by semicolon should
325.36 -# treat "-W foo" as "--foo"
325.37 -
325.38 -__all__ = ["GetoptError","error","getopt","gnu_getopt"]
325.39 -
325.40 -import os
325.41 -
325.42 -class GetoptError(Exception):
325.43 - opt = ''
325.44 - msg = ''
325.45 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:msg<|, |>PARAMETER:opt<|=''):
325.46 - |>PARAMETER:self<|.msg = |>PARAMETER:msg<|
325.47 - |>PARAMETER:self<|.opt = |>PARAMETER:opt<|
325.48 - Exception.__init__(|>PARAMETER:self<|, |>PARAMETER:msg<|, |>PARAMETER:opt<|)
325.49 -
325.50 - def |>METHOD:__str__<|(|>PARAMETER:self<|):
325.51 - return |>PARAMETER:self<|.msg
325.52 -
325.53 -error = GetoptError # backward compatibility
325.54 -
325.55 -def |>METHOD:getopt<|(|>PARAMETER:args<|, |>PARAMETER:shortopts<|, |>PARAMETER:longopts<| = []):
325.56 - """getopt(args, options[, long_options]) -> opts, args
325.57 -
325.58 - Parses command line options and parameter list. args is the
325.59 - argument list to be parsed, without the leading reference to the
325.60 - running program. Typically, this means "sys.argv[1:]". shortopts
325.61 - is the string of option letters that the script wants to
325.62 - recognize, with options that require an argument followed by a
325.63 - colon (i.e., the same format that Unix getopt() uses). If
325.64 - specified, longopts is a list of strings with the names of the
325.65 - long options which should be supported. The leading '--'
325.66 - characters should not be included in the option name. Options
325.67 - which require an argument should be followed by an equal sign
325.68 - ('=').
325.69 -
325.70 - The return value consists of two elements: the first is a list of
325.71 - (option, value) pairs; the second is the list of program arguments
325.72 - left after the option list was stripped (this is a trailing slice
325.73 - of the first argument). Each option-and-value pair returned has
325.74 - the option as its first element, prefixed with a hyphen (e.g.,
325.75 - '-x'), and the option argument as its second element, or an empty
325.76 - string if the option has no argument. The options occur in the
325.77 - list in the same order in which they were found, thus allowing
325.78 - multiple occurrences. Long and short options may be mixed.
325.79 -
325.80 - """
325.81 -
325.82 - opts = []
325.83 - if type(|>PARAMETER:longopts<|) == type(""):
325.84 - |>PARAMETER:longopts<| = [|>PARAMETER:longopts<|]
325.85 - else:
325.86 - |>PARAMETER:longopts<| = list(|>PARAMETER:longopts<|)
325.87 - while |>PARAMETER:args<| and |>PARAMETER:args<|[0].startswith('-') and |>PARAMETER:args<|[0] != '-':
325.88 - if |>PARAMETER:args<|[0] == '--':
325.89 - |>PARAMETER:args<| = |>PARAMETER:args<|[1:]
325.90 - break
325.91 - if |>PARAMETER:args<|[0].startswith('--'):
325.92 - opts, |>PARAMETER:args<| = do_longs(opts, |>PARAMETER:args<|[0][2:], |>PARAMETER:longopts<|, |>PARAMETER:args<|[1:])
325.93 - else:
325.94 - opts, |>PARAMETER:args<| = do_shorts(opts, |>PARAMETER:args<|[0][1:], |>PARAMETER:shortopts<|, |>PARAMETER:args<|[1:])
325.95 -
325.96 - return opts, |>PARAMETER:args<|
325.97 -
325.98 -def |>METHOD:gnu_getopt<|(|>PARAMETER:args<|, |>PARAMETER:shortopts<|, |>PARAMETER:longopts<| = []):
325.99 - """getopt(args, options[, long_options]) -> opts, args
325.100 -
325.101 - This function works like getopt(), except that GNU style scanning
325.102 - mode is used by default. This means that option and non-option
325.103 - arguments may be intermixed. The getopt() function stops
325.104 - processing options as soon as a non-option argument is
325.105 - encountered.
325.106 -
325.107 - If the first character of the option string is `+', or if the
325.108 - environment variable POSIXLY_CORRECT is set, then option
325.109 - processing stops as soon as a non-option argument is encountered.
325.110 -
325.111 - """
325.112 -
325.113 - opts = []
325.114 - prog_args = []
325.115 - if isinstance(|>PARAMETER:longopts<|, str):
325.116 - |>PARAMETER:longopts<| = [|>PARAMETER:longopts<|]
325.117 - else:
325.118 - |>PARAMETER:longopts<| = list(|>PARAMETER:longopts<|)
325.119 -
325.120 - # Allow options after non-option arguments?
325.121 - if |>PARAMETER:shortopts<|.startswith('+'):
325.122 - |>PARAMETER:shortopts<| = |>PARAMETER:shortopts<|[1:]
325.123 - all_options_first = True
325.124 - elif os.environ.get("POSIXLY_CORRECT"):
325.125 - all_options_first = True
325.126 - else:
325.127 - all_options_first = False
325.128 -
325.129 - while |>PARAMETER:args<|:
325.130 - if |>PARAMETER:args<|[0] == '--':
325.131 - prog_args += |>PARAMETER:args<|[1:]
325.132 - break
325.133 -
325.134 - if |>PARAMETER:args<|[0][:2] == '--':
325.135 - opts, |>PARAMETER:args<| = do_longs(opts, |>PARAMETER:args<|[0][2:], |>PARAMETER:longopts<|, |>PARAMETER:args<|[1:])
325.136 - elif |>PARAMETER:args<|[0][:1] == '-':
325.137 - opts, |>PARAMETER:args<| = do_shorts(opts, |>PARAMETER:args<|[0][1:], |>PARAMETER:shortopts<|, |>PARAMETER:args<|[1:])
325.138 - else:
325.139 - if all_options_first:
325.140 - prog_args += |>PARAMETER:args<|
325.141 - break
325.142 - else:
325.143 - prog_args.append(|>PARAMETER:args<|[0])
325.144 - |>PARAMETER:args<| = |>PARAMETER:args<|[1:]
325.145 -
325.146 - return opts, prog_args
325.147 -
325.148 -def |>METHOD:do_longs<|(|>PARAMETER:opts<|, |>PARAMETER:opt<|, |>PARAMETER:longopts<|, |>PARAMETER:args<|):
325.149 - try:
325.150 - i = |>PARAMETER:opt<|.index('=')
325.151 - except ValueError:
325.152 - optarg = None
325.153 - else:
325.154 - |>PARAMETER:opt<|, optarg = |>PARAMETER:opt<|[:i], |>PARAMETER:opt<|[i+1:]
325.155 -
325.156 - has_arg, |>PARAMETER:opt<| = long_has_args(|>PARAMETER:opt<|, |>PARAMETER:longopts<|)
325.157 - if has_arg:
325.158 - if optarg is None:
325.159 - if not |>PARAMETER:args<|:
325.160 - raise GetoptError('option --%s requires argument' % |>PARAMETER:opt<|, |>PARAMETER:opt<|)
325.161 - optarg, |>PARAMETER:args<| = |>PARAMETER:args<|[0], |>PARAMETER:args<|[1:]
325.162 - elif optarg:
325.163 - raise GetoptError('option --%s must not have an argument' % |>PARAMETER:opt<|, |>PARAMETER:opt<|)
325.164 - |>PARAMETER:opts<|.append(('--' + |>PARAMETER:opt<|, optarg or ''))
325.165 - return |>PARAMETER:opts<|, |>PARAMETER:args<|
325.166 -
325.167 -# Return:
325.168 -# has_arg?
325.169 -# full option name
325.170 -def |>METHOD:long_has_args<|(|>PARAMETER:opt<|, |>PARAMETER:longopts<|):
325.171 - possibilities = [o for o in |>PARAMETER:longopts<| if o.startswith(|>PARAMETER:opt<|)]
325.172 - if not possibilities:
325.173 - raise GetoptError('option --%s not recognized' % |>PARAMETER:opt<|, |>PARAMETER:opt<|)
325.174 - # Is there an exact match?
325.175 - if |>PARAMETER:opt<| in possibilities:
325.176 - return False, |>PARAMETER:opt<|
325.177 - elif |>PARAMETER:opt<| + '=' in possibilities:
325.178 - return True, |>PARAMETER:opt<|
325.179 - # No exact match, so better be unique.
325.180 - if len(possibilities) > 1:
325.181 - # XXX since possibilities contains all valid continuations, might be
325.182 - # nice to work them into the error msg
325.183 - raise GetoptError('option --%s not a unique prefix' % |>PARAMETER:opt<|, |>PARAMETER:opt<|)
325.184 - assert len(possibilities) == 1
325.185 - unique_match = possibilities[0]
325.186 - has_arg = unique_match.endswith('=')
325.187 - if has_arg:
325.188 - unique_match = unique_match[:-1]
325.189 - return has_arg, unique_match
325.190 -
325.191 -def |>METHOD:do_shorts<|(|>PARAMETER:opts<|, |>PARAMETER:optstring<|, |>PARAMETER:shortopts<|, |>PARAMETER:args<|):
325.192 - while |>PARAMETER:optstring<| != '':
325.193 - opt, |>PARAMETER:optstring<| = |>PARAMETER:optstring<|[0], |>PARAMETER:optstring<|[1:]
325.194 - if short_has_arg(opt, |>PARAMETER:shortopts<|):
325.195 - if |>PARAMETER:optstring<| == '':
325.196 - if not |>PARAMETER:args<|:
325.197 - raise GetoptError('option -%s requires argument' % opt,
325.198 - opt)
325.199 - |>PARAMETER:optstring<|, |>PARAMETER:args<| = |>PARAMETER:args<|[0], |>PARAMETER:args<|[1:]
325.200 - optarg, |>PARAMETER:optstring<| = |>PARAMETER:optstring<|, ''
325.201 - else:
325.202 - optarg = ''
325.203 - |>PARAMETER:opts<|.append(('-' + opt, optarg))
325.204 - return |>PARAMETER:opts<|, |>PARAMETER:args<|
325.205 -
325.206 -def |>METHOD:short_has_arg<|(|>PARAMETER:opt<|, |>PARAMETER:shortopts<|):
325.207 - for i in range(len(|>PARAMETER:shortopts<|)):
325.208 - if |>PARAMETER:opt<| == |>PARAMETER:shortopts<|[i] != ':':
325.209 - return |>PARAMETER:shortopts<|.startswith(':', i+1)
325.210 - raise GetoptError('option -%s not recognized' % |>PARAMETER:opt<|, |>PARAMETER:opt<|)
325.211 -
325.212 -if __name__ == '__main__':
325.213 - import sys
325.214 - print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])
326.1 --- a/python.editor/test/unit/data/testfiles/getopt.py.structure Sun Jan 04 13:11:53 2015 -0600
326.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
326.3 @@ -1,11 +0,0 @@
326.4 -GetoptError:CLASS:[]:ESCAPED{GetoptError}:
326.5 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{msg}ESCAPED{,}ESCAPED{opt}}):
326.6 - __str__:METHOD:[]:ESCAPED{__str__}(PARAMETERS{ESCAPED{self}}):
326.7 - msg:ATTRIBUTE:[]:ESCAPED{msg}:
326.8 - opt:ATTRIBUTE:[]:ESCAPED{opt}:
326.9 -getopt:METHOD:[]:ESCAPED{getopt}(PARAMETERS{ESCAPED{args}ESCAPED{,}ESCAPED{shortopts}ESCAPED{,}ESCAPED{longopts}}):
326.10 -gnu_getopt:METHOD:[]:ESCAPED{gnu_getopt}(PARAMETERS{ESCAPED{args}ESCAPED{,}ESCAPED{shortopts}ESCAPED{,}ESCAPED{longopts}}):
326.11 -do_longs:METHOD:[PRIVATE]:ESCAPED{do_longs}(PARAMETERS{ESCAPED{opts}ESCAPED{,}ESCAPED{opt}ESCAPED{,}ESCAPED{longopts}ESCAPED{,}ESCAPED{args}}):
326.12 -long_has_args:METHOD:[PRIVATE]:ESCAPED{long_has_args}(PARAMETERS{ESCAPED{opt}ESCAPED{,}ESCAPED{longopts}}):
326.13 -do_shorts:METHOD:[PRIVATE]:ESCAPED{do_shorts}(PARAMETERS{ESCAPED{opts}ESCAPED{,}ESCAPED{optstring}ESCAPED{,}ESCAPED{shortopts}ESCAPED{,}ESCAPED{args}}):
326.14 -short_has_arg:METHOD:[PRIVATE]:ESCAPED{short_has_arg}(PARAMETERS{ESCAPED{opt}ESCAPED{,}ESCAPED{shortopts}}):
327.1 --- a/python.editor/test/unit/data/testfiles/gotolocal.py Sun Jan 04 13:11:53 2015 -0600
327.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
327.3 @@ -1,3 +0,0 @@
327.4 -def ggg(name):
327.5 - print name;
327.6 -
328.1 --- a/python.editor/test/unit/data/testfiles/hanging_indent.py Sun Jan 04 13:11:53 2015 -0600
328.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
328.3 @@ -1,8 +0,0 @@
328.4 -class LSimpleXMLRPCServer(LSimpleXMLRPCDispatcher, SimpleXMLRPCServer):
328.5 - def __init__(self, addr, requestHandler=LSimpleXMLRPCRequestHandler,
328.6 - logRequests=1, allow_none=0):
328.7 - SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests)
328.8 - LSimpleXMLRPCDispatcher.__init__(self)
328.9 -
328.10 - self.allow_none = allow_none
328.11 -
329.1 --- a/python.editor/test/unit/data/testfiles/hanging_indent.py.formatted 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 -class LSimpleXMLRPCServer(LSimpleXMLRPCDispatcher, SimpleXMLRPCServer):
329.5 - def __init__(self, addr, requestHandler=LSimpleXMLRPCRequestHandler,
329.6 - logRequests=1, allow_none=0):
329.7 - SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests)
329.8 - LSimpleXMLRPCDispatcher.__init__(self)
329.9 -
329.10 - self.allow_none = allow_none
329.11 -
330.1 --- a/python.editor/test/unit/data/testfiles/hanging_indent2.py Sun Jan 04 13:11:53 2015 -0600
330.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
330.3 @@ -1,15 +0,0 @@
330.4 -class Rectangle(Blob):
330.5 -
330.6 - def __init__(self, width, height,
330.7 - color='black', emphasis=None, highlight=0):
330.8 - if width == 0 and height == 0 and \
330.9 - color == 'red' and emphasis == 'strong' or \
330.10 - highlight > 100:
330.11 - raise ValueError("sorry, you lose")
330.12 - if width == 0 and height == 0 and (color == 'red' or
330.13 - emphasis is None):
330.14 - raise ValueError("I don't think so -- values are %s, %s" %
330.15 - (width, height))
330.16 - Blob.__init__(self, width, height,
330.17 - color, emphasis, highlight)
330.18 -
331.1 --- a/python.editor/test/unit/data/testfiles/hanging_indent2.py.formatted Sun Jan 04 13:11:53 2015 -0600
331.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
331.3 @@ -1,15 +0,0 @@
331.4 -class Rectangle(Blob):
331.5 -
331.6 - def __init__(self, width, height,
331.7 - color='black', emphasis=None, highlight=0):
331.8 - if width == 0 and height == 0 and \
331.9 - color == 'red' and emphasis == 'strong' or \
331.10 - highlight > 100:
331.11 - raise ValueError("sorry, you lose")
331.12 - if width == 0 and height == 0 and (color == 'red' or
331.13 - emphasis is None):
331.14 - raise ValueError("I don't think so -- values are %s, %s" %
331.15 - (width, height))
331.16 - Blob.__init__(self, width, height,
331.17 - color, emphasis, highlight)
331.18 -
332.1 --- a/python.editor/test/unit/data/testfiles/httplib.py Sun Jan 04 13:11:53 2015 -0600
332.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
332.3 @@ -1,1432 +0,0 @@
332.4 -"""HTTP/1.1 client library
332.5 -
332.6 -<intro stuff goes here>
332.7 -<other stuff, too>
332.8 -
332.9 -HTTPConnection goes through a number of "states", which define when a client
332.10 -may legally make another request or fetch the response for a particular
332.11 -request. This diagram details these state transitions:
332.12 -
332.13 - (null)
332.14 - |
332.15 - | HTTPConnection()
332.16 - v
332.17 - Idle
332.18 - |
332.19 - | putrequest()
332.20 - v
332.21 - Request-started
332.22 - |
332.23 - | ( putheader() )* endheaders()
332.24 - v
332.25 - Request-sent
332.26 - |
332.27 - | response = getresponse()
332.28 - v
332.29 - Unread-response [Response-headers-read]
332.30 - |\____________________
332.31 - | |
332.32 - | response.read() | putrequest()
332.33 - v v
332.34 - Idle Req-started-unread-response
332.35 - ______/|
332.36 - / |
332.37 - response.read() | | ( putheader() )* endheaders()
332.38 - v v
332.39 - Request-started Req-sent-unread-response
332.40 - |
332.41 - | response.read()
332.42 - v
332.43 - Request-sent
332.44 -
332.45 -This diagram presents the following rules:
332.46 - -- a second request may not be started until {response-headers-read}
332.47 - -- a response [object] cannot be retrieved until {request-sent}
332.48 - -- there is no differentiation between an unread response body and a
332.49 - partially read response body
332.50 -
332.51 -Note: this enforcement is applied by the HTTPConnection class. The
332.52 - HTTPResponse class does not enforce this state machine, which
332.53 - implies sophisticated clients may accelerate the request/response
332.54 - pipeline. Caution should be taken, though: accelerating the states
332.55 - beyond the above pattern may imply knowledge of the server's
332.56 - connection-close behavior for certain requests. For example, it
332.57 - is impossible to tell whether the server will close the connection
332.58 - UNTIL the response headers have been read; this means that further
332.59 - requests cannot be placed into the pipeline until it is known that
332.60 - the server will NOT be closing the connection.
332.61 -
332.62 -Logical State __state __response
332.63 -------------- ------- ----------
332.64 -Idle _CS_IDLE None
332.65 -Request-started _CS_REQ_STARTED None
332.66 -Request-sent _CS_REQ_SENT None
332.67 -Unread-response _CS_IDLE <response_class>
332.68 -Req-started-unread-response _CS_REQ_STARTED <response_class>
332.69 -Req-sent-unread-response _CS_REQ_SENT <response_class>
332.70 -"""
332.71 -
332.72 -import errno
332.73 -import mimetools
332.74 -import socket
332.75 -from urlparse import urlsplit
332.76 -
332.77 -try:
332.78 - from cStringIO import StringIO
332.79 -except ImportError:
332.80 - from StringIO import StringIO
332.81 -
332.82 -__all__ = ["HTTP", "HTTPResponse", "HTTPConnection", "HTTPSConnection",
332.83 - "HTTPException", "NotConnected", "UnknownProtocol",
332.84 - "UnknownTransferEncoding", "UnimplementedFileMode",
332.85 - "IncompleteRead", "InvalidURL", "ImproperConnectionState",
332.86 - "CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
332.87 - "BadStatusLine", "error", "responses"]
332.88 -
332.89 -HTTP_PORT = 80
332.90 -HTTPS_PORT = 443
332.91 -
332.92 -_UNKNOWN = 'UNKNOWN'
332.93 -
332.94 -# connection states
332.95 -_CS_IDLE = 'Idle'
332.96 -_CS_REQ_STARTED = 'Request-started'
332.97 -_CS_REQ_SENT = 'Request-sent'
332.98 -
332.99 -# status codes
332.100 -# informational
332.101 -CONTINUE = 100
332.102 -SWITCHING_PROTOCOLS = 101
332.103 -PROCESSING = 102
332.104 -
332.105 -# successful
332.106 -OK = 200
332.107 -CREATED = 201
332.108 -ACCEPTED = 202
332.109 -NON_AUTHORITATIVE_INFORMATION = 203
332.110 -NO_CONTENT = 204
332.111 -RESET_CONTENT = 205
332.112 -PARTIAL_CONTENT = 206
332.113 -MULTI_STATUS = 207
332.114 -IM_USED = 226
332.115 -
332.116 -# redirection
332.117 -MULTIPLE_CHOICES = 300
332.118 -MOVED_PERMANENTLY = 301
332.119 -FOUND = 302
332.120 -SEE_OTHER = 303
332.121 -NOT_MODIFIED = 304
332.122 -USE_PROXY = 305
332.123 -TEMPORARY_REDIRECT = 307
332.124 -
332.125 -# client error
332.126 -BAD_REQUEST = 400
332.127 -UNAUTHORIZED = 401
332.128 -PAYMENT_REQUIRED = 402
332.129 -FORBIDDEN = 403
332.130 -NOT_FOUND = 404
332.131 -METHOD_NOT_ALLOWED = 405
332.132 -NOT_ACCEPTABLE = 406
332.133 -PROXY_AUTHENTICATION_REQUIRED = 407
332.134 -REQUEST_TIMEOUT = 408
332.135 -CONFLICT = 409
332.136 -GONE = 410
332.137 -LENGTH_REQUIRED = 411
332.138 -PRECONDITION_FAILED = 412
332.139 -REQUEST_ENTITY_TOO_LARGE = 413
332.140 -REQUEST_URI_TOO_LONG = 414
332.141 -UNSUPPORTED_MEDIA_TYPE = 415
332.142 -REQUESTED_RANGE_NOT_SATISFIABLE = 416
332.143 -EXPECTATION_FAILED = 417
332.144 -UNPROCESSABLE_ENTITY = 422
332.145 -LOCKED = 423
332.146 -FAILED_DEPENDENCY = 424
332.147 -UPGRADE_REQUIRED = 426
332.148 -
332.149 -# server error
332.150 -INTERNAL_SERVER_ERROR = 500
332.151 -NOT_IMPLEMENTED = 501
332.152 -BAD_GATEWAY = 502
332.153 -SERVICE_UNAVAILABLE = 503
332.154 -GATEWAY_TIMEOUT = 504
332.155 -HTTP_VERSION_NOT_SUPPORTED = 505
332.156 -INSUFFICIENT_STORAGE = 507
332.157 -NOT_EXTENDED = 510
332.158 -
332.159 -# Mapping status codes to official W3C names
332.160 -responses = {
332.161 - 100: 'Continue',
332.162 - 101: 'Switching Protocols',
332.163 -
332.164 - 200: 'OK',
332.165 - 201: 'Created',
332.166 - 202: 'Accepted',
332.167 - 203: 'Non-Authoritative Information',
332.168 - 204: 'No Content',
332.169 - 205: 'Reset Content',
332.170 - 206: 'Partial Content',
332.171 -
332.172 - 300: 'Multiple Choices',
332.173 - 301: 'Moved Permanently',
332.174 - 302: 'Found',
332.175 - 303: 'See Other',
332.176 - 304: 'Not Modified',
332.177 - 305: 'Use Proxy',
332.178 - 306: '(Unused)',
332.179 - 307: 'Temporary Redirect',
332.180 -
332.181 - 400: 'Bad Request',
332.182 - 401: 'Unauthorized',
332.183 - 402: 'Payment Required',
332.184 - 403: 'Forbidden',
332.185 - 404: 'Not Found',
332.186 - 405: 'Method Not Allowed',
332.187 - 406: 'Not Acceptable',
332.188 - 407: 'Proxy Authentication Required',
332.189 - 408: 'Request Timeout',
332.190 - 409: 'Conflict',
332.191 - 410: 'Gone',
332.192 - 411: 'Length Required',
332.193 - 412: 'Precondition Failed',
332.194 - 413: 'Request Entity Too Large',
332.195 - 414: 'Request-URI Too Long',
332.196 - 415: 'Unsupported Media Type',
332.197 - 416: 'Requested Range Not Satisfiable',
332.198 - 417: 'Expectation Failed',
332.199 -
332.200 - 500: 'Internal Server Error',
332.201 - 501: 'Not Implemented',
332.202 - 502: 'Bad Gateway',
332.203 - 503: 'Service Unavailable',
332.204 - 504: 'Gateway Timeout',
332.205 - 505: 'HTTP Version Not Supported',
332.206 -}
332.207 -
332.208 -# maximal amount of data to read at one time in _safe_read
332.209 -MAXAMOUNT = 1048576
332.210 -
332.211 -class HTTPMessage(mimetools.Message):
332.212 -
332.213 - def addheader(self, key, value):
332.214 - """Add header for field key handling repeats."""
332.215 - prev = self.dict.get(key)
332.216 - if prev is None:
332.217 - self.dict[key] = value
332.218 - else:
332.219 - combined = ", ".join((prev, value))
332.220 - self.dict[key] = combined
332.221 -
332.222 - def addcontinue(self, key, more):
332.223 - """Add more field data from a continuation line."""
332.224 - prev = self.dict[key]
332.225 - self.dict[key] = prev + "\n " + more
332.226 -
332.227 - def readheaders(self):
332.228 - """Read header lines.
332.229 -
332.230 - Read header lines up to the entirely blank line that terminates them.
332.231 - The (normally blank) line that ends the headers is skipped, but not
332.232 - included in the returned list. If a non-header line ends the headers,
332.233 - (which is an error), an attempt is made to backspace over it; it is
332.234 - never included in the returned list.
332.235 -
332.236 - The variable self.status is set to the empty string if all went well,
332.237 - otherwise it is an error message. The variable self.headers is a
332.238 - completely uninterpreted list of lines contained in the header (so
332.239 - printing them will reproduce the header exactly as it appears in the
332.240 - file).
332.241 -
332.242 - If multiple header fields with the same name occur, they are combined
332.243 - according to the rules in RFC 2616 sec 4.2:
332.244 -
332.245 - Appending each subsequent field-value to the first, each separated
332.246 - by a comma. The order in which header fields with the same field-name
332.247 - are received is significant to the interpretation of the combined
332.248 - field value.
332.249 - """
332.250 - # XXX The implementation overrides the readheaders() method of
332.251 - # rfc822.Message. The base class design isn't amenable to
332.252 - # customized behavior here so the method here is a copy of the
332.253 - # base class code with a few small changes.
332.254 -
332.255 - self.dict = {}
332.256 - self.unixfrom = ''
332.257 - self.headers = hlist = []
332.258 - self.status = ''
332.259 - headerseen = ""
332.260 - firstline = 1
332.261 - startofline = unread = tell = None
332.262 - if hasattr(self.fp, 'unread'):
332.263 - unread = self.fp.unread
332.264 - elif self.seekable:
332.265 - tell = self.fp.tell
332.266 - while True:
332.267 - if tell:
332.268 - try:
332.269 - startofline = tell()
332.270 - except IOError:
332.271 - startofline = tell = None
332.272 - self.seekable = 0
332.273 - line = self.fp.readline()
332.274 - if not line:
332.275 - self.status = 'EOF in headers'
332.276 - break
332.277 - # Skip unix From name time lines
332.278 - if firstline and line.startswith('From '):
332.279 - self.unixfrom = self.unixfrom + line
332.280 - continue
332.281 - firstline = 0
332.282 - if headerseen and line[0] in ' \t':
332.283 - # XXX Not sure if continuation lines are handled properly
332.284 - # for http and/or for repeating headers
332.285 - # It's a continuation line.
332.286 - hlist.append(line)
332.287 - self.addcontinue(headerseen, line.strip())
332.288 - continue
332.289 - elif self.iscomment(line):
332.290 - # It's a comment. Ignore it.
332.291 - continue
332.292 - elif self.islast(line):
332.293 - # Note! No pushback here! The delimiter line gets eaten.
332.294 - break
332.295 - headerseen = self.isheader(line)
332.296 - if headerseen:
332.297 - # It's a legal header line, save it.
332.298 - hlist.append(line)
332.299 - self.addheader(headerseen, line[len(headerseen)+1:].strip())
332.300 - continue
332.301 - else:
332.302 - # It's not a header line; throw it back and stop here.
332.303 - if not self.dict:
332.304 - self.status = 'No headers'
332.305 - else:
332.306 - self.status = 'Non-header line where header expected'
332.307 - # Try to undo the read.
332.308 - if unread:
332.309 - unread(line)
332.310 - elif tell:
332.311 - self.fp.seek(startofline)
332.312 - else:
332.313 - self.status = self.status + '; bad seek'
332.314 - break
332.315 -
332.316 -class HTTPResponse:
332.317 -
332.318 - # strict: If true, raise BadStatusLine if the status line can't be
332.319 - # parsed as a valid HTTP/1.0 or 1.1 status line. By default it is
332.320 - # false because it prevents clients from talking to HTTP/0.9
332.321 - # servers. Note that a response with a sufficiently corrupted
332.322 - # status line will look like an HTTP/0.9 response.
332.323 -
332.324 - # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
332.325 -
332.326 - def __init__(self, sock, debuglevel=0, strict=0, method=None):
332.327 - self.fp = sock.makefile('rb', 0)
332.328 - self.debuglevel = debuglevel
332.329 - self.strict = strict
332.330 - self._method = method
332.331 -
332.332 - self.msg = None
332.333 -
332.334 - # from the Status-Line of the response
332.335 - self.version = _UNKNOWN # HTTP-Version
332.336 - self.status = _UNKNOWN # Status-Code
332.337 - self.reason = _UNKNOWN # Reason-Phrase
332.338 -
332.339 - self.chunked = _UNKNOWN # is "chunked" being used?
332.340 - self.chunk_left = _UNKNOWN # bytes left to read in current chunk
332.341 - self.length = _UNKNOWN # number of bytes left in response
332.342 - self.will_close = _UNKNOWN # conn will close at end of response
332.343 -
332.344 - def _read_status(self):
332.345 - # Initialize with Simple-Response defaults
332.346 - line = self.fp.readline()
332.347 - if self.debuglevel > 0:
332.348 - print "reply:", repr(line)
332.349 - if not line:
332.350 - # Presumably, the server closed the connection before
332.351 - # sending a valid response.
332.352 - raise BadStatusLine(line)
332.353 - try:
332.354 - [version, status, reason] = line.split(None, 2)
332.355 - except ValueError:
332.356 - try:
332.357 - [version, status] = line.split(None, 1)
332.358 - reason = ""
332.359 - except ValueError:
332.360 - # empty version will cause next test to fail and status
332.361 - # will be treated as 0.9 response.
332.362 - version = ""
332.363 - if not version.startswith('HTTP/'):
332.364 - if self.strict:
332.365 - self.close()
332.366 - raise BadStatusLine(line)
332.367 - else:
332.368 - # assume it's a Simple-Response from an 0.9 server
332.369 - self.fp = LineAndFileWrapper(line, self.fp)
332.370 - return "HTTP/0.9", 200, ""
332.371 -
332.372 - # The status code is a three-digit number
332.373 - try:
332.374 - status = int(status)
332.375 - if status < 100 or status > 999:
332.376 - raise BadStatusLine(line)
332.377 - except ValueError:
332.378 - raise BadStatusLine(line)
332.379 - return version, status, reason
332.380 -
332.381 - def begin(self):
332.382 - if self.msg is not None:
332.383 - # we've already started reading the response
332.384 - return
332.385 -
332.386 - # read until we get a non-100 response
332.387 - while True:
332.388 - version, status, reason = self._read_status()
332.389 - if status != CONTINUE:
332.390 - break
332.391 - # skip the header from the 100 response
332.392 - while True:
332.393 - skip = self.fp.readline().strip()
332.394 - if not skip:
332.395 - break
332.396 - if self.debuglevel > 0:
332.397 - print "header:", skip
332.398 -
332.399 - self.status = status
332.400 - self.reason = reason.strip()
332.401 - if version == 'HTTP/1.0':
332.402 - self.version = 10
332.403 - elif version.startswith('HTTP/1.'):
332.404 - self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
332.405 - elif version == 'HTTP/0.9':
332.406 - self.version = 9
332.407 - else:
332.408 - raise UnknownProtocol(version)
332.409 -
332.410 - if self.version == 9:
332.411 - self.length = None
332.412 - self.chunked = 0
332.413 - self.will_close = 1
332.414 - self.msg = HTTPMessage(StringIO())
332.415 - return
332.416 -
332.417 - self.msg = HTTPMessage(self.fp, 0)
332.418 - if self.debuglevel > 0:
332.419 - for hdr in self.msg.headers:
332.420 - print "header:", hdr,
332.421 -
332.422 - # don't let the msg keep an fp
332.423 - self.msg.fp = None
332.424 -
332.425 - # are we using the chunked-style of transfer encoding?
332.426 - tr_enc = self.msg.getheader('transfer-encoding')
332.427 - if tr_enc and tr_enc.lower() == "chunked":
332.428 - self.chunked = 1
332.429 - self.chunk_left = None
332.430 - else:
332.431 - self.chunked = 0
332.432 -
332.433 - # will the connection close at the end of the response?
332.434 - self.will_close = self._check_close()
332.435 -
332.436 - # do we have a Content-Length?
332.437 - # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
332.438 - length = self.msg.getheader('content-length')
332.439 - if length and not self.chunked:
332.440 - try:
332.441 - self.length = int(length)
332.442 - except ValueError:
332.443 - self.length = None
332.444 - else:
332.445 - self.length = None
332.446 -
332.447 - # does the body have a fixed length? (of zero)
332.448 - if (status == NO_CONTENT or status == NOT_MODIFIED or
332.449 - 100 <= status < 200 or # 1xx codes
332.450 - self._method == 'HEAD'):
332.451 - self.length = 0
332.452 -
332.453 - # if the connection remains open, and we aren't using chunked, and
332.454 - # a content-length was not provided, then assume that the connection
332.455 - # WILL close.
332.456 - if not self.will_close and \
332.457 - not self.chunked and \
332.458 - self.length is None:
332.459 - self.will_close = 1
332.460 -
332.461 - def _check_close(self):
332.462 - conn = self.msg.getheader('connection')
332.463 - if self.version == 11:
332.464 - # An HTTP/1.1 proxy is assumed to stay open unless
332.465 - # explicitly closed.
332.466 - conn = self.msg.getheader('connection')
332.467 - if conn and "close" in conn.lower():
332.468 - return True
332.469 - return False
332.470 -
332.471 - # Some HTTP/1.0 implementations have support for persistent
332.472 - # connections, using rules different than HTTP/1.1.
332.473 -
332.474 - # For older HTTP, Keep-Alive indiciates persistent connection.
332.475 - if self.msg.getheader('keep-alive'):
332.476 - return False
332.477 -
332.478 - # At least Akamai returns a "Connection: Keep-Alive" header,
332.479 - # which was supposed to be sent by the client.
332.480 - if conn and "keep-alive" in conn.lower():
332.481 - return False
332.482 -
332.483 - # Proxy-Connection is a netscape hack.
332.484 - pconn = self.msg.getheader('proxy-connection')
332.485 - if pconn and "keep-alive" in pconn.lower():
332.486 - return False
332.487 -
332.488 - # otherwise, assume it will close
332.489 - return True
332.490 -
332.491 - def close(self):
332.492 - if self.fp:
332.493 - self.fp.close()
332.494 - self.fp = None
332.495 -
332.496 - def isclosed(self):
332.497 - # NOTE: it is possible that we will not ever call self.close(). This
332.498 - # case occurs when will_close is TRUE, length is None, and we
332.499 - # read up to the last byte, but NOT past it.
332.500 - #
332.501 - # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
332.502 - # called, meaning self.isclosed() is meaningful.
332.503 - return self.fp is None
332.504 -
332.505 - # XXX It would be nice to have readline and __iter__ for this, too.
332.506 -
332.507 - def read(self, amt=None):
332.508 - if self.fp is None:
332.509 - return ''
332.510 -
332.511 - if self.chunked:
332.512 - return self._read_chunked(amt)
332.513 -
332.514 - if amt is None:
332.515 - # unbounded read
332.516 - if self.length is None:
332.517 - s = self.fp.read()
332.518 - else:
332.519 - s = self._safe_read(self.length)
332.520 - self.length = 0
332.521 - self.close() # we read everything
332.522 - return s
332.523 -
332.524 - if self.length is not None:
332.525 - if amt > self.length:
332.526 - # clip the read to the "end of response"
332.527 - amt = self.length
332.528 -
332.529 - # we do not use _safe_read() here because this may be a .will_close
332.530 - # connection, and the user is reading more bytes than will be provided
332.531 - # (for example, reading in 1k chunks)
332.532 - s = self.fp.read(amt)
332.533 - if self.length is not None:
332.534 - self.length -= len(s)
332.535 -
332.536 - return s
332.537 -
332.538 - def _read_chunked(self, amt):
332.539 - assert self.chunked != _UNKNOWN
332.540 - chunk_left = self.chunk_left
332.541 - value = ''
332.542 -
332.543 - # XXX This accumulates chunks by repeated string concatenation,
332.544 - # which is not efficient as the number or size of chunks gets big.
332.545 - while True:
332.546 - if chunk_left is None:
332.547 - line = self.fp.readline()
332.548 - i = line.find(';')
332.549 - if i >= 0:
332.550 - line = line[:i] # strip chunk-extensions
332.551 - chunk_left = int(line, 16)
332.552 - if chunk_left == 0:
332.553 - break
332.554 - if amt is None:
332.555 - value += self._safe_read(chunk_left)
332.556 - elif amt < chunk_left:
332.557 - value += self._safe_read(amt)
332.558 - self.chunk_left = chunk_left - amt
332.559 - return value
332.560 - elif amt == chunk_left:
332.561 - value += self._safe_read(amt)
332.562 - self._safe_read(2) # toss the CRLF at the end of the chunk
332.563 - self.chunk_left = None
332.564 - return value
332.565 - else:
332.566 - value += self._safe_read(chunk_left)
332.567 - amt -= chunk_left
332.568 -
332.569 - # we read the whole chunk, get another
332.570 - self._safe_read(2) # toss the CRLF at the end of the chunk
332.571 - chunk_left = None
332.572 -
332.573 - # read and discard trailer up to the CRLF terminator
332.574 - ### note: we shouldn't have any trailers!
332.575 - while True:
332.576 - line = self.fp.readline()
332.577 - if not line:
332.578 - # a vanishingly small number of sites EOF without
332.579 - # sending the trailer
332.580 - break
332.581 - if line == '\r\n':
332.582 - break
332.583 -
332.584 - # we read everything; close the "file"
332.585 - self.close()
332.586 -
332.587 - return value
332.588 -
332.589 - def _safe_read(self, amt):
332.590 - """Read the number of bytes requested, compensating for partial reads.
332.591 -
332.592 - Normally, we have a blocking socket, but a read() can be interrupted
332.593 - by a signal (resulting in a partial read).
332.594 -
332.595 - Note that we cannot distinguish between EOF and an interrupt when zero
332.596 - bytes have been read. IncompleteRead() will be raised in this
332.597 - situation.
332.598 -
332.599 - This function should be used when <amt> bytes "should" be present for
332.600 - reading. If the bytes are truly not available (due to EOF), then the
332.601 - IncompleteRead exception can be used to detect the problem.
332.602 - """
332.603 - s = []
332.604 - while amt > 0:
332.605 - chunk = self.fp.read(min(amt, MAXAMOUNT))
332.606 - if not chunk:
332.607 - raise IncompleteRead(s)
332.608 - s.append(chunk)
332.609 - amt -= len(chunk)
332.610 - return ''.join(s)
332.611 -
332.612 - def getheader(self, name, default=None):
332.613 - if self.msg is None:
332.614 - raise ResponseNotReady()
332.615 - return self.msg.getheader(name, default)
332.616 -
332.617 - def getheaders(self):
332.618 - """Return list of (header, value) tuples."""
332.619 - if self.msg is None:
332.620 - raise ResponseNotReady()
332.621 - return self.msg.items()
332.622 -
332.623 -
332.624 -class HTTPConnection:
332.625 -
332.626 - _http_vsn = 11
332.627 - _http_vsn_str = 'HTTP/1.1'
332.628 -
332.629 - response_class = HTTPResponse
332.630 - default_port = HTTP_PORT
332.631 - auto_open = 1
332.632 - debuglevel = 0
332.633 - strict = 0
332.634 -
332.635 - def __init__(self, host, port=None, strict=None):
332.636 - self.sock = None
332.637 - self._buffer = []
332.638 - self.__response = None
332.639 - self.__state = _CS_IDLE
332.640 - self._method = None
332.641 -
332.642 - self._set_hostport(host, port)
332.643 - if strict is not None:
332.644 - self.strict = strict
332.645 -
332.646 - def _set_hostport(self, host, port):
332.647 - if port is None:
332.648 - i = host.rfind(':')
332.649 - j = host.rfind(']') # ipv6 addresses have [...]
332.650 - if i > j:
332.651 - try:
332.652 - port = int(host[i+1:])
332.653 - except ValueError:
332.654 - raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
332.655 - host = host[:i]
332.656 - else:
332.657 - port = self.default_port
332.658 - if host and host[0] == '[' and host[-1] == ']':
332.659 - host = host[1:-1]
332.660 - self.host = host
332.661 - self.port = port
332.662 -
332.663 - def set_debuglevel(self, level):
332.664 - self.debuglevel = level
332.665 -
332.666 - def connect(self):
332.667 - """Connect to the host and port specified in __init__."""
332.668 - msg = "getaddrinfo returns an empty list"
332.669 - for res in socket.getaddrinfo(self.host, self.port, 0,
332.670 - socket.SOCK_STREAM):
332.671 - af, socktype, proto, canonname, sa = res
332.672 - try:
332.673 - self.sock = socket.socket(af, socktype, proto)
332.674 - if self.debuglevel > 0:
332.675 - print "connect: (%s, %s)" % (self.host, self.port)
332.676 - self.sock.connect(sa)
332.677 - except socket.error, msg:
332.678 - if self.debuglevel > 0:
332.679 - print 'connect fail:', (self.host, self.port)
332.680 - if self.sock:
332.681 - self.sock.close()
332.682 - self.sock = None
332.683 - continue
332.684 - break
332.685 - if not self.sock:
332.686 - raise socket.error, msg
332.687 -
332.688 - def close(self):
332.689 - """Close the connection to the HTTP server."""
332.690 - if self.sock:
332.691 - self.sock.close() # close it manually... there may be other refs
332.692 - self.sock = None
332.693 - if self.__response:
332.694 - self.__response.close()
332.695 - self.__response = None
332.696 - self.__state = _CS_IDLE
332.697 -
332.698 - def send(self, str):
332.699 - """Send `str' to the server."""
332.700 - if self.sock is None:
332.701 - if self.auto_open:
332.702 - self.connect()
332.703 - else:
332.704 - raise NotConnected()
332.705 -
332.706 - # send the data to the server. if we get a broken pipe, then close
332.707 - # the socket. we want to reconnect when somebody tries to send again.
332.708 - #
332.709 - # NOTE: we DO propagate the error, though, because we cannot simply
332.710 - # ignore the error... the caller will know if they can retry.
332.711 - if self.debuglevel > 0:
332.712 - print "send:", repr(str)
332.713 - try:
332.714 - self.sock.sendall(str)
332.715 - except socket.error, v:
332.716 - if v[0] == 32: # Broken pipe
332.717 - self.close()
332.718 - raise
332.719 -
332.720 - def _output(self, s):
332.721 - """Add a line of output to the current request buffer.
332.722 -
332.723 - Assumes that the line does *not* end with \\r\\n.
332.724 - """
332.725 - self._buffer.append(s)
332.726 -
332.727 - def _send_output(self):
332.728 - """Send the currently buffered request and clear the buffer.
332.729 -
332.730 - Appends an extra \\r\\n to the buffer.
332.731 - """
332.732 - self._buffer.extend(("", ""))
332.733 - msg = "\r\n".join(self._buffer)
332.734 - del self._buffer[:]
332.735 - self.send(msg)
332.736 -
332.737 - def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
332.738 - """Send a request to the server.
332.739 -
332.740 - `method' specifies an HTTP request method, e.g. 'GET'.
332.741 - `url' specifies the object being requested, e.g. '/index.html'.
332.742 - `skip_host' if True does not add automatically a 'Host:' header
332.743 - `skip_accept_encoding' if True does not add automatically an
332.744 - 'Accept-Encoding:' header
332.745 - """
332.746 -
332.747 - # if a prior response has been completed, then forget about it.
332.748 - if self.__response and self.__response.isclosed():
332.749 - self.__response = None
332.750 -
332.751 -
332.752 - # in certain cases, we cannot issue another request on this connection.
332.753 - # this occurs when:
332.754 - # 1) we are in the process of sending a request. (_CS_REQ_STARTED)
332.755 - # 2) a response to a previous request has signalled that it is going
332.756 - # to close the connection upon completion.
332.757 - # 3) the headers for the previous response have not been read, thus
332.758 - # we cannot determine whether point (2) is true. (_CS_REQ_SENT)
332.759 - #
332.760 - # if there is no prior response, then we can request at will.
332.761 - #
332.762 - # if point (2) is true, then we will have passed the socket to the
332.763 - # response (effectively meaning, "there is no prior response"), and
332.764 - # will open a new one when a new request is made.
332.765 - #
332.766 - # Note: if a prior response exists, then we *can* start a new request.
332.767 - # We are not allowed to begin fetching the response to this new
332.768 - # request, however, until that prior response is complete.
332.769 - #
332.770 - if self.__state == _CS_IDLE:
332.771 - self.__state = _CS_REQ_STARTED
332.772 - else:
332.773 - raise CannotSendRequest()
332.774 -
332.775 - # Save the method we use, we need it later in the response phase
332.776 - self._method = method
332.777 - if not url:
332.778 - url = '/'
332.779 - str = '%s %s %s' % (method, url, self._http_vsn_str)
332.780 -
332.781 - self._output(str)
332.782 -
332.783 - if self._http_vsn == 11:
332.784 - # Issue some standard headers for better HTTP/1.1 compliance
332.785 -
332.786 - if not skip_host:
332.787 - # this header is issued *only* for HTTP/1.1
332.788 - # connections. more specifically, this means it is
332.789 - # only issued when the client uses the new
332.790 - # HTTPConnection() class. backwards-compat clients
332.791 - # will be using HTTP/1.0 and those clients may be
332.792 - # issuing this header themselves. we should NOT issue
332.793 - # it twice; some web servers (such as Apache) barf
332.794 - # when they see two Host: headers
332.795 -
332.796 - # If we need a non-standard port,include it in the
332.797 - # header. If the request is going through a proxy,
332.798 - # but the host of the actual URL, not the host of the
332.799 - # proxy.
332.800 -
332.801 - netloc = ''
332.802 - if url.startswith('http'):
332.803 - nil, netloc, nil, nil, nil = urlsplit(url)
332.804 -
332.805 - if netloc:
332.806 - try:
332.807 - netloc_enc = netloc.encode("ascii")
332.808 - except UnicodeEncodeError:
332.809 - netloc_enc = netloc.encode("idna")
332.810 - self.putheader('Host', netloc_enc)
332.811 - else:
332.812 - try:
332.813 - host_enc = self.host.encode("ascii")
332.814 - except UnicodeEncodeError:
332.815 - host_enc = self.host.encode("idna")
332.816 - if self.port == HTTP_PORT:
332.817 - self.putheader('Host', host_enc)
332.818 - else:
332.819 - self.putheader('Host', "%s:%s" % (host_enc, self.port))
332.820 -
332.821 - # note: we are assuming that clients will not attempt to set these
332.822 - # headers since *this* library must deal with the
332.823 - # consequences. this also means that when the supporting
332.824 - # libraries are updated to recognize other forms, then this
332.825 - # code should be changed (removed or updated).
332.826 -
332.827 - # we only want a Content-Encoding of "identity" since we don't
332.828 - # support encodings such as x-gzip or x-deflate.
332.829 - if not skip_accept_encoding:
332.830 - self.putheader('Accept-Encoding', 'identity')
332.831 -
332.832 - # we can accept "chunked" Transfer-Encodings, but no others
332.833 - # NOTE: no TE header implies *only* "chunked"
332.834 - #self.putheader('TE', 'chunked')
332.835 -
332.836 - # if TE is supplied in the header, then it must appear in a
332.837 - # Connection header.
332.838 - #self.putheader('Connection', 'TE')
332.839 -
332.840 - else:
332.841 - # For HTTP/1.0, the server will assume "not chunked"
332.842 - pass
332.843 -
332.844 - def putheader(self, header, value):
332.845 - """Send a request header line to the server.
332.846 -
332.847 - For example: h.putheader('Accept', 'text/html')
332.848 - """
332.849 - if self.__state != _CS_REQ_STARTED:
332.850 - raise CannotSendHeader()
332.851 -
332.852 - str = '%s: %s' % (header, value)
332.853 - self._output(str)
332.854 -
332.855 - def endheaders(self):
332.856 - """Indicate that the last header line has been sent to the server."""
332.857 -
332.858 - if self.__state == _CS_REQ_STARTED:
332.859 - self.__state = _CS_REQ_SENT
332.860 - else:
332.861 - raise CannotSendHeader()
332.862 -
332.863 - self._send_output()
332.864 -
332.865 - def request(self, method, url, body=None, headers={}):
332.866 - """Send a complete request to the server."""
332.867 -
332.868 - try:
332.869 - self._send_request(method, url, body, headers)
332.870 - except socket.error, v:
332.871 - # trap 'Broken pipe' if we're allowed to automatically reconnect
332.872 - if v[0] != 32 or not self.auto_open:
332.873 - raise
332.874 - # try one more time
332.875 - self._send_request(method, url, body, headers)
332.876 -
332.877 - def _send_request(self, method, url, body, headers):
332.878 - # honour explicitly requested Host: and Accept-Encoding headers
332.879 - header_names = dict.fromkeys([k.lower() for k in headers])
332.880 - skips = {}
332.881 - if 'host' in header_names:
332.882 - skips['skip_host'] = 1
332.883 - if 'accept-encoding' in header_names:
332.884 - skips['skip_accept_encoding'] = 1
332.885 -
332.886 - self.putrequest(method, url, **skips)
332.887 -
332.888 - if body and ('content-length' not in header_names):
332.889 - self.putheader('Content-Length', str(len(body)))
332.890 - for hdr, value in headers.iteritems():
332.891 - self.putheader(hdr, value)
332.892 - self.endheaders()
332.893 -
332.894 - if body:
332.895 - self.send(body)
332.896 -
332.897 - def getresponse(self):
332.898 - "Get the response from the server."
332.899 -
332.900 - # if a prior response has been completed, then forget about it.
332.901 - if self.__response and self.__response.isclosed():
332.902 - self.__response = None
332.903 -
332.904 - #
332.905 - # if a prior response exists, then it must be completed (otherwise, we
332.906 - # cannot read this response's header to determine the connection-close
332.907 - # behavior)
332.908 - #
332.909 - # note: if a prior response existed, but was connection-close, then the
332.910 - # socket and response were made independent of this HTTPConnection
332.911 - # object since a new request requires that we open a whole new
332.912 - # connection
332.913 - #
332.914 - # this means the prior response had one of two states:
332.915 - # 1) will_close: this connection was reset and the prior socket and
332.916 - # response operate independently
332.917 - # 2) persistent: the response was retained and we await its
332.918 - # isclosed() status to become true.
332.919 - #
332.920 - if self.__state != _CS_REQ_SENT or self.__response:
332.921 - raise ResponseNotReady()
332.922 -
332.923 - if self.debuglevel > 0:
332.924 - response = self.response_class(self.sock, self.debuglevel,
332.925 - strict=self.strict,
332.926 - method=self._method)
332.927 - else:
332.928 - response = self.response_class(self.sock, strict=self.strict,
332.929 - method=self._method)
332.930 -
332.931 - response.begin()
332.932 - assert response.will_close != _UNKNOWN
332.933 - self.__state = _CS_IDLE
332.934 -
332.935 - if response.will_close:
332.936 - # this effectively passes the connection to the response
332.937 - self.close()
332.938 - else:
332.939 - # remember this, so we can tell when it is complete
332.940 - self.__response = response
332.941 -
332.942 - return response
332.943 -
332.944 -# The next several classes are used to define FakeSocket, a socket-like
332.945 -# interface to an SSL connection.
332.946 -
332.947 -# The primary complexity comes from faking a makefile() method. The
332.948 -# standard socket makefile() implementation calls dup() on the socket
332.949 -# file descriptor. As a consequence, clients can call close() on the
332.950 -# parent socket and its makefile children in any order. The underlying
332.951 -# socket isn't closed until they are all closed.
332.952 -
332.953 -# The implementation uses reference counting to keep the socket open
332.954 -# until the last client calls close(). SharedSocket keeps track of
332.955 -# the reference counting and SharedSocketClient provides an constructor
332.956 -# and close() method that call incref() and decref() correctly.
332.957 -
332.958 -class SharedSocket:
332.959 -
332.960 - def __init__(self, sock):
332.961 - self.sock = sock
332.962 - self._refcnt = 0
332.963 -
332.964 - def incref(self):
332.965 - self._refcnt += 1
332.966 -
332.967 - def decref(self):
332.968 - self._refcnt -= 1
332.969 - assert self._refcnt >= 0
332.970 - if self._refcnt == 0:
332.971 - self.sock.close()
332.972 -
332.973 - def __del__(self):
332.974 - self.sock.close()
332.975 -
332.976 -class SharedSocketClient:
332.977 -
332.978 - def __init__(self, shared):
332.979 - self._closed = 0
332.980 - self._shared = shared
332.981 - self._shared.incref()
332.982 - self._sock = shared.sock
332.983 -
332.984 - def close(self):
332.985 - if not self._closed:
332.986 - self._shared.decref()
332.987 - self._closed = 1
332.988 - self._shared = None
332.989 -
332.990 -class SSLFile(SharedSocketClient):
332.991 - """File-like object wrapping an SSL socket."""
332.992 -
332.993 - BUFSIZE = 8192
332.994 -
332.995 - def __init__(self, sock, ssl, bufsize=None):
332.996 - SharedSocketClient.__init__(self, sock)
332.997 - self._ssl = ssl
332.998 - self._buf = ''
332.999 - self._bufsize = bufsize or self.__class__.BUFSIZE
332.1000 -
332.1001 - def _read(self):
332.1002 - buf = ''
332.1003 - # put in a loop so that we retry on transient errors
332.1004 - while True:
332.1005 - try:
332.1006 - buf = self._ssl.read(self._bufsize)
332.1007 - except socket.sslerror, err:
332.1008 - if (err[0] == socket.SSL_ERROR_WANT_READ
332.1009 - or err[0] == socket.SSL_ERROR_WANT_WRITE):
332.1010 - continue
332.1011 - if (err[0] == socket.SSL_ERROR_ZERO_RETURN
332.1012 - or err[0] == socket.SSL_ERROR_EOF):
332.1013 - break
332.1014 - raise
332.1015 - except socket.error, err:
332.1016 - if err[0] == errno.EINTR:
332.1017 - continue
332.1018 - if err[0] == errno.EBADF:
332.1019 - # XXX socket was closed?
332.1020 - break
332.1021 - raise
332.1022 - else:
332.1023 - break
332.1024 - return buf
332.1025 -
332.1026 - def read(self, size=None):
332.1027 - L = [self._buf]
332.1028 - avail = len(self._buf)
332.1029 - while size is None or avail < size:
332.1030 - s = self._read()
332.1031 - if s == '':
332.1032 - break
332.1033 - L.append(s)
332.1034 - avail += len(s)
332.1035 - all = "".join(L)
332.1036 - if size is None:
332.1037 - self._buf = ''
332.1038 - return all
332.1039 - else:
332.1040 - self._buf = all[size:]
332.1041 - return all[:size]
332.1042 -
332.1043 - def readline(self):
332.1044 - L = [self._buf]
332.1045 - self._buf = ''
332.1046 - while 1:
332.1047 - i = L[-1].find("\n")
332.1048 - if i >= 0:
332.1049 - break
332.1050 - s = self._read()
332.1051 - if s == '':
332.1052 - break
332.1053 - L.append(s)
332.1054 - if i == -1:
332.1055 - # loop exited because there is no more data
332.1056 - return "".join(L)
332.1057 - else:
332.1058 - all = "".join(L)
332.1059 - # XXX could do enough bookkeeping not to do a 2nd search
332.1060 - i = all.find("\n") + 1
332.1061 - line = all[:i]
332.1062 - self._buf = all[i:]
332.1063 - return line
332.1064 -
332.1065 - def readlines(self, sizehint=0):
332.1066 - total = 0
332.1067 - list = []
332.1068 - while True:
332.1069 - line = self.readline()
332.1070 - if not line:
332.1071 - break
332.1072 - list.append(line)
332.1073 - total += len(line)
332.1074 - if sizehint and total >= sizehint:
332.1075 - break
332.1076 - return list
332.1077 -
332.1078 - def fileno(self):
332.1079 - return self._sock.fileno()
332.1080 -
332.1081 - def __iter__(self):
332.1082 - return self
332.1083 -
332.1084 - def next(self):
332.1085 - line = self.readline()
332.1086 - if not line:
332.1087 - raise StopIteration
332.1088 - return line
332.1089 -
332.1090 -class FakeSocket(SharedSocketClient):
332.1091 -
332.1092 - class _closedsocket:
332.1093 - def __getattr__(self, name):
332.1094 - raise error(9, 'Bad file descriptor')
332.1095 -
332.1096 - def __init__(self, sock, ssl):
332.1097 - sock = SharedSocket(sock)
332.1098 - SharedSocketClient.__init__(self, sock)
332.1099 - self._ssl = ssl
332.1100 -
332.1101 - def close(self):
332.1102 - SharedSocketClient.close(self)
332.1103 - self._sock = self.__class__._closedsocket()
332.1104 -
332.1105 - def makefile(self, mode, bufsize=None):
332.1106 - if mode != 'r' and mode != 'rb':
332.1107 - raise UnimplementedFileMode()
332.1108 - return SSLFile(self._shared, self._ssl, bufsize)
332.1109 -
332.1110 - def send(self, stuff, flags = 0):
332.1111 - return self._ssl.write(stuff)
332.1112 -
332.1113 - sendall = send
332.1114 -
332.1115 - def recv(self, len = 1024, flags = 0):
332.1116 - return self._ssl.read(len)
332.1117 -
332.1118 - def __getattr__(self, attr):
332.1119 - return getattr(self._sock, attr)
332.1120 -
332.1121 -
332.1122 -class HTTPSConnection(HTTPConnection):
332.1123 - "This class allows communication via SSL."
332.1124 -
332.1125 - default_port = HTTPS_PORT
332.1126 -
332.1127 - def __init__(self, host, port=None, key_file=None, cert_file=None,
332.1128 - strict=None):
332.1129 - HTTPConnection.__init__(self, host, port, strict)
332.1130 - self.key_file = key_file
332.1131 - self.cert_file = cert_file
332.1132 -
332.1133 - def connect(self):
332.1134 - "Connect to a host on a given (SSL) port."
332.1135 -
332.1136 - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
332.1137 - sock.connect((self.host, self.port))
332.1138 - ssl = socket.ssl(sock, self.key_file, self.cert_file)
332.1139 - self.sock = FakeSocket(sock, ssl)
332.1140 -
332.1141 -
332.1142 -class HTTP:
332.1143 - "Compatibility class with httplib.py from 1.5."
332.1144 -
332.1145 - _http_vsn = 10
332.1146 - _http_vsn_str = 'HTTP/1.0'
332.1147 -
332.1148 - debuglevel = 0
332.1149 -
332.1150 - _connection_class = HTTPConnection
332.1151 -
332.1152 - def __init__(self, host='', port=None, strict=None):
332.1153 - "Provide a default host, since the superclass requires one."
332.1154 -
332.1155 - # some joker passed 0 explicitly, meaning default port
332.1156 - if port == 0:
332.1157 - port = None
332.1158 -
332.1159 - # Note that we may pass an empty string as the host; this will throw
332.1160 - # an error when we attempt to connect. Presumably, the client code
332.1161 - # will call connect before then, with a proper host.
332.1162 - self._setup(self._connection_class(host, port, strict))
332.1163 -
332.1164 - def _setup(self, conn):
332.1165 - self._conn = conn
332.1166 -
332.1167 - # set up delegation to flesh out interface
332.1168 - self.send = conn.send
332.1169 - self.putrequest = conn.putrequest
332.1170 - self.endheaders = conn.endheaders
332.1171 - self.set_debuglevel = conn.set_debuglevel
332.1172 -
332.1173 - conn._http_vsn = self._http_vsn
332.1174 - conn._http_vsn_str = self._http_vsn_str
332.1175 -
332.1176 - self.file = None
332.1177 -
332.1178 - def connect(self, host=None, port=None):
332.1179 - "Accept arguments to set the host/port, since the superclass doesn't."
332.1180 -
332.1181 - if host is not None:
332.1182 - self._conn._set_hostport(host, port)
332.1183 - self._conn.connect()
332.1184 -
332.1185 - def getfile(self):
332.1186 - "Provide a getfile, since the superclass' does not use this concept."
332.1187 - return self.file
332.1188 -
332.1189 - def putheader(self, header, *values):
332.1190 - "The superclass allows only one value argument."
332.1191 - self._conn.putheader(header, '\r\n\t'.join(values))
332.1192 -
332.1193 - def getreply(self):
332.1194 - """Compat definition since superclass does not define it.
332.1195 -
332.1196 - Returns a tuple consisting of:
332.1197 - - server status code (e.g. '200' if all goes well)
332.1198 - - server "reason" corresponding to status code
332.1199 - - any RFC822 headers in the response from the server
332.1200 - """
332.1201 - try:
332.1202 - response = self._conn.getresponse()
332.1203 - except BadStatusLine, e:
332.1204 - ### hmm. if getresponse() ever closes the socket on a bad request,
332.1205 - ### then we are going to have problems with self.sock
332.1206 -
332.1207 - ### should we keep this behavior? do people use it?
332.1208 - # keep the socket open (as a file), and return it
332.1209 - self.file = self._conn.sock.makefile('rb', 0)
332.1210 -
332.1211 - # close our socket -- we want to restart after any protocol error
332.1212 - self.close()
332.1213 -
332.1214 - self.headers = None
332.1215 - return -1, e.line, None
332.1216 -
332.1217 - self.headers = response.msg
332.1218 - self.file = response.fp
332.1219 - return response.status, response.reason, response.msg
332.1220 -
332.1221 - def close(self):
332.1222 - self._conn.close()
332.1223 -
332.1224 - # note that self.file == response.fp, which gets closed by the
332.1225 - # superclass. just clear the object ref here.
332.1226 - ### hmm. messy. if status==-1, then self.file is owned by us.
332.1227 - ### well... we aren't explicitly closing, but losing this ref will
332.1228 - ### do it
332.1229 - self.file = None
332.1230 -
332.1231 -if hasattr(socket, 'ssl'):
332.1232 - class HTTPS(HTTP):
332.1233 - """Compatibility with 1.5 httplib interface
332.1234 -
332.1235 - Python 1.5.2 did not have an HTTPS class, but it defined an
332.1236 - interface for sending http requests that is also useful for
332.1237 - https.
332.1238 - """
332.1239 -
332.1240 - _connection_class = HTTPSConnection
332.1241 -
332.1242 - def __init__(self, host='', port=None, key_file=None, cert_file=None,
332.1243 - strict=None):
332.1244 - # provide a default host, pass the X509 cert info
332.1245 -
332.1246 - # urf. compensate for bad input.
332.1247 - if port == 0:
332.1248 - port = None
332.1249 - self._setup(self._connection_class(host, port, key_file,
332.1250 - cert_file, strict))
332.1251 -
332.1252 - # we never actually use these for anything, but we keep them
332.1253 - # here for compatibility with post-1.5.2 CVS.
332.1254 - self.key_file = key_file
332.1255 - self.cert_file = cert_file
332.1256 -
332.1257 -
332.1258 -class HTTPException(Exception):
332.1259 - # Subclasses that define an __init__ must call Exception.__init__
332.1260 - # or define self.args. Otherwise, str() will fail.
332.1261 - pass
332.1262 -
332.1263 -class NotConnected(HTTPException):
332.1264 - pass
332.1265 -
332.1266 -class InvalidURL(HTTPException):
332.1267 - pass
332.1268 -
332.1269 -class UnknownProtocol(HTTPException):
332.1270 - def __init__(self, version):
332.1271 - self.args = version,
332.1272 - self.version = version
332.1273 -
332.1274 -class UnknownTransferEncoding(HTTPException):
332.1275 - pass
332.1276 -
332.1277 -class UnimplementedFileMode(HTTPException):
332.1278 - pass
332.1279 -
332.1280 -class IncompleteRead(HTTPException):
332.1281 - def __init__(self, partial):
332.1282 - self.args = partial,
332.1283 - self.partial = partial
332.1284 -
332.1285 -class ImproperConnectionState(HTTPException):
332.1286 - pass
332.1287 -
332.1288 -class CannotSendRequest(ImproperConnectionState):
332.1289 - pass
332.1290 -
332.1291 -class CannotSendHeader(ImproperConnectionState):
332.1292 - pass
332.1293 -
332.1294 -class ResponseNotReady(ImproperConnectionState):
332.1295 - pass
332.1296 -
332.1297 -class BadStatusLine(HTTPException):
332.1298 - def __init__(self, line):
332.1299 - self.args = line,
332.1300 - self.line = line
332.1301 -
332.1302 -# for backwards compatibility
332.1303 -error = HTTPException
332.1304 -
332.1305 -class LineAndFileWrapper:
332.1306 - """A limited file-like object for HTTP/0.9 responses."""
332.1307 -
332.1308 - # The status-line parsing code calls readline(), which normally
332.1309 - # get the HTTP status line. For a 0.9 response, however, this is
332.1310 - # actually the first line of the body! Clients need to get a
332.1311 - # readable file object that contains that line.
332.1312 -
332.1313 - def __init__(self, line, file):
332.1314 - self._line = line
332.1315 - self._file = file
332.1316 - self._line_consumed = 0
332.1317 - self._line_offset = 0
332.1318 - self._line_left = len(line)
332.1319 -
332.1320 - def __getattr__(self, attr):
332.1321 - return getattr(self._file, attr)
332.1322 -
332.1323 - def _done(self):
332.1324 - # called when the last byte is read from the line. After the
332.1325 - # call, all read methods are delegated to the underlying file
332.1326 - # object.
332.1327 - self._line_consumed = 1
332.1328 - self.read = self._file.read
332.1329 - self.readline = self._file.readline
332.1330 - self.readlines = self._file.readlines
332.1331 -
332.1332 - def read(self, amt=None):
332.1333 - if self._line_consumed:
332.1334 - return self._file.read(amt)
332.1335 - assert self._line_left
332.1336 - if amt is None or amt > self._line_left:
332.1337 - s = self._line[self._line_offset:]
332.1338 - self._done()
332.1339 - if amt is None:
332.1340 - return s + self._file.read()
332.1341 - else:
332.1342 - return s + self._file.read(amt - len(s))
332.1343 - else:
332.1344 - assert amt <= self._line_left
332.1345 - i = self._line_offset
332.1346 - j = i + amt
332.1347 - s = self._line[i:j]
332.1348 - self._line_offset = j
332.1349 - self._line_left -= amt
332.1350 - if self._line_left == 0:
332.1351 - self._done()
332.1352 - return s
332.1353 -
332.1354 - def readline(self):
332.1355 - if self._line_consumed:
332.1356 - return self._file.readline()
332.1357 - assert self._line_left
332.1358 - s = self._line[self._line_offset:]
332.1359 - self._done()
332.1360 - return s
332.1361 -
332.1362 - def readlines(self, size=None):
332.1363 - if self._line_consumed:
332.1364 - return self._file.readlines(size)
332.1365 - assert self._line_left
332.1366 - L = [self._line[self._line_offset:]]
332.1367 - self._done()
332.1368 - if size is None:
332.1369 - return L + self._file.readlines()
332.1370 - else:
332.1371 - return L + self._file.readlines(size)
332.1372 -
332.1373 -def test():
332.1374 - """Test this module.
332.1375 -
332.1376 - A hodge podge of tests collected here, because they have too many
332.1377 - external dependencies for the regular test suite.
332.1378 - """
332.1379 -
332.1380 - import sys
332.1381 - import getopt
332.1382 - opts, args = getopt.getopt(sys.argv[1:], 'd')
332.1383 - dl = 0
332.1384 - for o, a in opts:
332.1385 - if o == '-d': dl = dl + 1
332.1386 - host = 'www.python.org'
332.1387 - selector = '/'
332.1388 - if args[0:]: host = args[0]
332.1389 - if args[1:]: selector = args[1]
332.1390 - h = HTTP()
332.1391 - h.set_debuglevel(dl)
332.1392 - h.connect(host)
332.1393 - h.putrequest('GET', selector)
332.1394 - h.endheaders()
332.1395 - status, reason, headers = h.getreply()
332.1396 - print 'status =', status
332.1397 - print 'reason =', reason
332.1398 - print "read", len(h.getfile().read())
332.1399 - print
332.1400 - if headers:
332.1401 - for header in headers.headers: print header.strip()
332.1402 - print
332.1403 -
332.1404 - # minimal test that code to extract host from url works
332.1405 - class HTTP11(HTTP):
332.1406 - _http_vsn = 11
332.1407 - _http_vsn_str = 'HTTP/1.1'
332.1408 -
332.1409 - h = HTTP11('www.python.org')
332.1410 - h.putrequest('GET', 'http://www.python.org/~jeremy/')
332.1411 - h.endheaders()
332.1412 - h.getreply()
332.1413 - h.close()
332.1414 -
332.1415 - if hasattr(socket, 'ssl'):
332.1416 -
332.1417 - for host, selector in (('sourceforge.net', '/projects/python'),
332.1418 - ):
332.1419 - print "https://%s%s" % (host, selector)
332.1420 - hs = HTTPS()
332.1421 - hs.set_debuglevel(dl)
332.1422 - hs.connect(host)
332.1423 - hs.putrequest('GET', selector)
332.1424 - hs.endheaders()
332.1425 - status, reason, headers = hs.getreply()
332.1426 - print 'status =', status
332.1427 - print 'reason =', reason
332.1428 - print "read", len(hs.getfile().read())
332.1429 - print
332.1430 - if headers:
332.1431 - for header in headers.headers: print header.strip()
332.1432 - print
332.1433 -
332.1434 -if __name__ == '__main__':
332.1435 - test()
333.1 --- a/python.editor/test/unit/data/testfiles/httplib.py.indexed Sun Jan 04 13:11:53 2015 -0600
333.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
333.3 @@ -1,481 +0,0 @@
333.4 -
333.5 -
333.6 -Document 0
333.7 -Searchable Keys:
333.8 - class : BadStatusLine
333.9 - class-ig : badstatusline
333.10 - extends : HTTPException
333.11 - in : httplib
333.12 - member : __init__;c;|CONSTRUCTOR|;self,line;
333.13 - member : args;D;;
333.14 - member : line;D;;
333.15 -
333.16 -Not Searchable Keys:
333.17 -
333.18 -
333.19 -Document 1
333.20 -Searchable Keys:
333.21 - class : CannotSendHeader
333.22 - class-ig : cannotsendheader
333.23 - extends : ImproperConnectionState
333.24 - in : httplib
333.25 -
333.26 -Not Searchable Keys:
333.27 -
333.28 -
333.29 -Document 2
333.30 -Searchable Keys:
333.31 - class : CannotSendRequest
333.32 - class-ig : cannotsendrequest
333.33 - extends : ImproperConnectionState
333.34 - in : httplib
333.35 -
333.36 -Not Searchable Keys:
333.37 -
333.38 -
333.39 -Document 3
333.40 -Searchable Keys:
333.41 - class : FakeSocket
333.42 - class-ig : fakesocket
333.43 - extends : SharedSocketClient
333.44 - in : httplib
333.45 - item : _closedsocket;C;|PRIVATE|;
333.46 - member : __getattr__;F;|PRIVATE|;self,attr;
333.47 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,sock,ssl;
333.48 - member : _sock;D;|PRIVATE|;
333.49 - member : _ssl;D;|PRIVATE|;
333.50 - member : close;F;|PRIVATE|;self;
333.51 - member : makefile;F;|PRIVATE|;self,mode,bufsize;
333.52 - member : recv;F;|PRIVATE|;self,len,flags;
333.53 - member : send;F;|PRIVATE|;self,stuff,flags;
333.54 - member : sendall;F;|PRIVATE|;self,stuff,flags;
333.55 -
333.56 -Not Searchable Keys:
333.57 - clzattrs : ;|PRIVATE|;
333.58 -
333.59 -
333.60 -Document 4
333.61 -Searchable Keys:
333.62 - class : HTTP
333.63 - class-ig : http
333.64 - in : httplib
333.65 - member : __init__;c;|CONSTRUCTOR|;self,host,port,strict;
333.66 - member : _conn;D;|PRIVATE|;
333.67 - member : _connection_class;D;|PRIVATE|;
333.68 - member : _http_vsn;D;|PRIVATE|;
333.69 - member : _http_vsn_str;D;|PRIVATE|;
333.70 - member : _setup;F;|PRIVATE|;self,conn;
333.71 - member : close;F;;self;
333.72 - member : connect;F;;self,host,port;
333.73 - member : debuglevel;D;;
333.74 - member : endheaders;D;;
333.75 - member : file;D;;
333.76 - member : getfile;F;;self;
333.77 - member : getreply;F;;self;
333.78 - member : headers;D;;
333.79 - member : putheader;F;;self,header,values;
333.80 - member : putrequest;D;;
333.81 - member : send;D;;
333.82 - member : set_debuglevel;D;;
333.83 -
333.84 -Not Searchable Keys:
333.85 -
333.86 -
333.87 -Document 5
333.88 -Searchable Keys:
333.89 - class : HTTPConnection
333.90 - class-ig : httpconnection
333.91 - in : httplib
333.92 - member : __init__;c;|CONSTRUCTOR|;self,host,port,strict;
333.93 - member : __response;D;|PRIVATE|;
333.94 - member : __state;D;|PRIVATE|;
333.95 - member : _buffer;D;|PRIVATE|;
333.96 - member : _http_vsn;D;|PRIVATE|;
333.97 - member : _http_vsn_str;D;|PRIVATE|;
333.98 - member : _method;D;|PRIVATE|;
333.99 - member : _output;F;|PRIVATE|;self,s;
333.100 - member : _send_output;F;|PRIVATE|;self;
333.101 - member : _send_request;F;|PRIVATE|;self,method,url,body,headers;
333.102 - member : _set_hostport;F;|PRIVATE|;self,host,port;
333.103 - member : auto_open;D;;
333.104 - member : close;F;;self;
333.105 - member : connect;F;;self;
333.106 - member : debuglevel;D;;
333.107 - member : debuglevel;D;;
333.108 - member : default_port;D;;
333.109 - member : endheaders;F;;self;
333.110 - member : getresponse;F;;self;
333.111 - member : host;D;;
333.112 - member : port;D;;
333.113 - member : putheader;F;;self,header,value;
333.114 - member : putrequest;F;;self,method,url,skip_host,skip_accept_encoding;
333.115 - member : request;F;;self,method,url,body,headers;
333.116 - member : response_class;D;;
333.117 - member : send;F;;self,str;
333.118 - member : set_debuglevel;F;;self,level;
333.119 - member : sock;D;;
333.120 - member : strict;D;;
333.121 - member : strict;D;;
333.122 -
333.123 -Not Searchable Keys:
333.124 -
333.125 -
333.126 -Document 6
333.127 -Searchable Keys:
333.128 - class : HTTPException
333.129 - class-ig : httpexception
333.130 - extends : Exception
333.131 - in : httplib
333.132 -
333.133 -Not Searchable Keys:
333.134 -
333.135 -
333.136 -Document 7
333.137 -Searchable Keys:
333.138 - class : HTTPMessage
333.139 - class-ig : httpmessage
333.140 - extends : Message
333.141 - in : httplib
333.142 - member : addcontinue;F;|PRIVATE|;self,key,more;
333.143 - member : addheader;F;|PRIVATE|;self,key,value;
333.144 - member : dict;D;;
333.145 - member : headers;D;;
333.146 - member : readheaders;F;|PRIVATE|;self;
333.147 - member : seekable;D;;
333.148 - member : status;D;;
333.149 - member : unixfrom;D;;
333.150 -
333.151 -Not Searchable Keys:
333.152 - clzattrs : ;|PRIVATE|;
333.153 -
333.154 -
333.155 -Document 8
333.156 -Searchable Keys:
333.157 - class : HTTPResponse
333.158 - class-ig : httpresponse
333.159 - in : httplib
333.160 - member : __init__;c;|CONSTRUCTOR|;self,sock,debuglevel,strict,method;
333.161 - member : _check_close;F;|PRIVATE|;self;
333.162 - member : _method;D;|PRIVATE|;
333.163 - member : _read_chunked;F;|PRIVATE|;self,amt;
333.164 - member : _read_status;F;|PRIVATE|;self;
333.165 - member : _safe_read;F;|PRIVATE|;self,amt;
333.166 - member : begin;F;;self;
333.167 - member : chunk_left;D;;
333.168 - member : chunked;D;;
333.169 - member : close;F;;self;
333.170 - member : debuglevel;D;;
333.171 - member : fp;D;;
333.172 - member : getheader;F;;self,name,default;
333.173 - member : getheaders;F;;self;
333.174 - member : isclosed;F;;self;
333.175 - member : length;D;;
333.176 - member : msg;D;;
333.177 - member : read;F;;self,amt;
333.178 - member : reason;D;;
333.179 - member : status;D;;
333.180 - member : strict;D;;
333.181 - member : version;D;;
333.182 - member : will_close;D;;
333.183 -
333.184 -Not Searchable Keys:
333.185 -
333.186 -
333.187 -Document 9
333.188 -Searchable Keys:
333.189 - class : HTTPS
333.190 - class-ig : https
333.191 - extends : HTTP
333.192 - in : httplib
333.193 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,host,port,key_file,cert_file,strict;
333.194 - member : _connection_class;D;|PRIVATE|;
333.195 - member : cert_file;D;;
333.196 - member : key_file;D;;
333.197 -
333.198 -Not Searchable Keys:
333.199 - clzattrs : ;|PRIVATE|;
333.200 -
333.201 -
333.202 -Document 10
333.203 -Searchable Keys:
333.204 - class : HTTPSConnection
333.205 - class-ig : httpsconnection
333.206 - extends : HTTPConnection
333.207 - in : httplib
333.208 - member : __init__;c;|CONSTRUCTOR|;self,host,port,key_file,cert_file,strict;
333.209 - member : cert_file;D;;
333.210 - member : connect;F;;self;
333.211 - member : default_port;D;;
333.212 - member : key_file;D;;
333.213 - member : sock;D;;
333.214 -
333.215 -Not Searchable Keys:
333.216 -
333.217 -
333.218 -Document 11
333.219 -Searchable Keys:
333.220 - class : ImproperConnectionState
333.221 - class-ig : improperconnectionstate
333.222 - extends : HTTPException
333.223 - in : httplib
333.224 -
333.225 -Not Searchable Keys:
333.226 -
333.227 -
333.228 -Document 12
333.229 -Searchable Keys:
333.230 - class : IncompleteRead
333.231 - class-ig : incompleteread
333.232 - extends : HTTPException
333.233 - in : httplib
333.234 - member : __init__;c;|CONSTRUCTOR|;self,partial;
333.235 - member : args;D;;
333.236 - member : partial;D;;
333.237 -
333.238 -Not Searchable Keys:
333.239 -
333.240 -
333.241 -Document 13
333.242 -Searchable Keys:
333.243 - class : InvalidURL
333.244 - class-ig : invalidurl
333.245 - extends : HTTPException
333.246 - in : httplib
333.247 -
333.248 -Not Searchable Keys:
333.249 -
333.250 -
333.251 -Document 14
333.252 -Searchable Keys:
333.253 - class : LineAndFileWrapper
333.254 - class-ig : lineandfilewrapper
333.255 - in : httplib
333.256 - member : __getattr__;F;|PRIVATE|;self,attr;
333.257 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,line,file;
333.258 - member : _done;F;|PRIVATE|;self;
333.259 - member : _file;D;|PRIVATE|;
333.260 - member : _line;D;|PRIVATE|;
333.261 - member : _line_consumed;D;|PRIVATE|;
333.262 - member : _line_left;D;|PRIVATE|;
333.263 - member : _line_offset;D;|PRIVATE|;
333.264 - member : read;D;;
333.265 - member : read;F;|PRIVATE|;self,amt;
333.266 - member : readline;D;;
333.267 - member : readline;F;|PRIVATE|;self;
333.268 - member : readlines;D;;
333.269 - member : readlines;F;|PRIVATE|;self,size;
333.270 -
333.271 -Not Searchable Keys:
333.272 - clzattrs : ;|PRIVATE|;
333.273 -
333.274 -
333.275 -Document 15
333.276 -Searchable Keys:
333.277 - class : NotConnected
333.278 - class-ig : notconnected
333.279 - extends : HTTPException
333.280 - in : httplib
333.281 -
333.282 -Not Searchable Keys:
333.283 -
333.284 -
333.285 -Document 16
333.286 -Searchable Keys:
333.287 - class : ResponseNotReady
333.288 - class-ig : responsenotready
333.289 - extends : ImproperConnectionState
333.290 - in : httplib
333.291 -
333.292 -Not Searchable Keys:
333.293 -
333.294 -
333.295 -Document 17
333.296 -Searchable Keys:
333.297 - class : SSLFile
333.298 - class-ig : sslfile
333.299 - extends : SharedSocketClient
333.300 - in : httplib
333.301 - member : BUFSIZE;D;|PRIVATE|;
333.302 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,sock,ssl,bufsize;
333.303 - member : __iter__;F;|PRIVATE|;self;
333.304 - member : _buf;D;|PRIVATE|;
333.305 - member : _bufsize;D;|PRIVATE|;
333.306 - member : _read;F;|PRIVATE|;self;
333.307 - member : _ssl;D;|PRIVATE|;
333.308 - member : fileno;F;|PRIVATE|;self;
333.309 - member : next;F;|PRIVATE|;self;
333.310 - member : read;F;|PRIVATE|;self,size;
333.311 - member : readline;F;|PRIVATE|;self;
333.312 - member : readlines;F;|PRIVATE|;self,sizehint;
333.313 -
333.314 -Not Searchable Keys:
333.315 - clzattrs : ;|PRIVATE|;
333.316 -
333.317 -
333.318 -Document 18
333.319 -Searchable Keys:
333.320 - class : SharedSocket
333.321 - class-ig : sharedsocket
333.322 - in : httplib
333.323 - member : __del__;F;|PRIVATE|;self;
333.324 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,sock;
333.325 - member : _refcnt;D;|PRIVATE|;
333.326 - member : decref;F;|PRIVATE|;self;
333.327 - member : incref;F;|PRIVATE|;self;
333.328 - member : sock;D;;
333.329 -
333.330 -Not Searchable Keys:
333.331 - clzattrs : ;|PRIVATE|;
333.332 -
333.333 -
333.334 -Document 19
333.335 -Searchable Keys:
333.336 - class : SharedSocketClient
333.337 - class-ig : sharedsocketclient
333.338 - in : httplib
333.339 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,shared;
333.340 - member : _closed;D;|PRIVATE|;
333.341 - member : _shared;D;|PRIVATE|;
333.342 - member : _sock;D;|PRIVATE|;
333.343 - member : close;F;|PRIVATE|;self;
333.344 -
333.345 -Not Searchable Keys:
333.346 - clzattrs : ;|PRIVATE|;
333.347 -
333.348 -
333.349 -Document 20
333.350 -Searchable Keys:
333.351 - class : UnimplementedFileMode
333.352 - class-ig : unimplementedfilemode
333.353 - extends : HTTPException
333.354 - in : httplib
333.355 -
333.356 -Not Searchable Keys:
333.357 -
333.358 -
333.359 -Document 21
333.360 -Searchable Keys:
333.361 - class : UnknownProtocol
333.362 - class-ig : unknownprotocol
333.363 - extends : HTTPException
333.364 - in : httplib
333.365 - member : __init__;c;|CONSTRUCTOR|;self,version;
333.366 - member : args;D;;
333.367 - member : version;D;;
333.368 -
333.369 -Not Searchable Keys:
333.370 -
333.371 -
333.372 -Document 22
333.373 -Searchable Keys:
333.374 - class : UnknownTransferEncoding
333.375 - class-ig : unknowntransferencoding
333.376 - extends : HTTPException
333.377 - in : httplib
333.378 -
333.379 -Not Searchable Keys:
333.380 -
333.381 -
333.382 -Document 23
333.383 -Searchable Keys:
333.384 - class : error
333.385 - class-ig : error
333.386 - extends : Exception
333.387 - in : httplib
333.388 -
333.389 -Not Searchable Keys:
333.390 -
333.391 -
333.392 -Document 24
333.393 -Searchable Keys:
333.394 - item : ACCEPTED;D;|PRIVATE|;
333.395 - item : BAD_GATEWAY;D;|PRIVATE|;
333.396 - item : BAD_REQUEST;D;|PRIVATE|;
333.397 - item : BadStatusLine;C;;
333.398 - item : CONFLICT;D;|PRIVATE|;
333.399 - item : CONTINUE;D;|PRIVATE|;
333.400 - item : CREATED;D;|PRIVATE|;
333.401 - item : CannotSendHeader;C;;
333.402 - item : CannotSendRequest;C;;
333.403 - item : EXPECTATION_FAILED;D;|PRIVATE|;
333.404 - item : FAILED_DEPENDENCY;D;|PRIVATE|;
333.405 - item : FORBIDDEN;D;|PRIVATE|;
333.406 - item : FOUND;D;|PRIVATE|;
333.407 - item : FakeSocket;C;|PRIVATE|;
333.408 - item : GATEWAY_TIMEOUT;D;|PRIVATE|;
333.409 - item : GONE;D;|PRIVATE|;
333.410 - item : HTTP;C;;
333.411 - item : HTTPConnection;C;;
333.412 - item : HTTPException;C;;
333.413 - item : HTTPMessage;C;|PRIVATE|;
333.414 - item : HTTPResponse;C;;
333.415 - item : HTTPS;C;|PRIVATE|;
333.416 - item : HTTPSConnection;C;;
333.417 - item : HTTPS_PORT;D;|PRIVATE|;
333.418 - item : HTTP_PORT;D;|PRIVATE|;
333.419 - item : HTTP_VERSION_NOT_SUPPORTED;D;|PRIVATE|;
333.420 - item : IM_USED;D;|PRIVATE|;
333.421 - item : INSUFFICIENT_STORAGE;D;|PRIVATE|;
333.422 - item : INTERNAL_SERVER_ERROR;D;|PRIVATE|;
333.423 - item : ImproperConnectionState;C;;
333.424 - item : IncompleteRead;C;;
333.425 - item : InvalidURL;C;;
333.426 - item : LENGTH_REQUIRED;D;|PRIVATE|;
333.427 - item : LOCKED;D;|PRIVATE|;
333.428 - item : LineAndFileWrapper;C;|PRIVATE|;
333.429 - item : MAXAMOUNT;D;|PRIVATE|;
333.430 - item : METHOD_NOT_ALLOWED;D;|PRIVATE|;
333.431 - item : MOVED_PERMANENTLY;D;|PRIVATE|;
333.432 - item : MULTIPLE_CHOICES;D;|PRIVATE|;
333.433 - item : MULTI_STATUS;D;|PRIVATE|;
333.434 - item : NON_AUTHORITATIVE_INFORMATION;D;|PRIVATE|;
333.435 - item : NOT_ACCEPTABLE;D;|PRIVATE|;
333.436 - item : NOT_EXTENDED;D;|PRIVATE|;
333.437 - item : NOT_FOUND;D;|PRIVATE|;
333.438 - item : NOT_IMPLEMENTED;D;|PRIVATE|;
333.439 - item : NOT_MODIFIED;D;|PRIVATE|;
333.440 - item : NO_CONTENT;D;|PRIVATE|;
333.441 - item : NotConnected;C;;
333.442 - item : OK;D;|PRIVATE|;
333.443 - item : PARTIAL_CONTENT;D;|PRIVATE|;
333.444 - item : PAYMENT_REQUIRED;D;|PRIVATE|;
333.445 - item : PRECONDITION_FAILED;D;|PRIVATE|;
333.446 - item : PROCESSING;D;|PRIVATE|;
333.447 - item : PROXY_AUTHENTICATION_REQUIRED;D;|PRIVATE|;
333.448 - item : REQUESTED_RANGE_NOT_SATISFIABLE;D;|PRIVATE|;
333.449 - item : REQUEST_ENTITY_TOO_LARGE;D;|PRIVATE|;
333.450 - item : REQUEST_TIMEOUT;D;|PRIVATE|;
333.451 - item : REQUEST_URI_TOO_LONG;D;|PRIVATE|;
333.452 - item : RESET_CONTENT;D;|PRIVATE|;
333.453 - item : ResponseNotReady;C;;
333.454 - item : SEE_OTHER;D;|PRIVATE|;
333.455 - item : SERVICE_UNAVAILABLE;D;|PRIVATE|;
333.456 - item : SSLFile;C;|PRIVATE|;
333.457 - item : SWITCHING_PROTOCOLS;D;|PRIVATE|;
333.458 - item : SharedSocket;C;|PRIVATE|;
333.459 - item : SharedSocketClient;C;|PRIVATE|;
333.460 - item : StringIO;I;|PRIVATE|;
333.461 - item : TEMPORARY_REDIRECT;D;|PRIVATE|;
333.462 - item : UNAUTHORIZED;D;|PRIVATE|;
333.463 - item : UNPROCESSABLE_ENTITY;D;|PRIVATE|;
333.464 - item : UNSUPPORTED_MEDIA_TYPE;D;|PRIVATE|;
333.465 - item : UPGRADE_REQUIRED;D;|PRIVATE|;
333.466 - item : USE_PROXY;D;|PRIVATE|;
333.467 - item : UnimplementedFileMode;C;;
333.468 - item : UnknownProtocol;C;;
333.469 - item : UnknownTransferEncoding;C;;
333.470 - item : _CS_IDLE;D;|PRIVATE|;
333.471 - item : _CS_REQ_SENT;D;|PRIVATE|;
333.472 - item : _CS_REQ_STARTED;D;|PRIVATE|;
333.473 - item : _UNKNOWN;D;|PRIVATE|;
333.474 - item : __all__;D;;
333.475 - item : errno;I;|PRIVATE|;
333.476 - item : error;C;;
333.477 - item : mimetools;I;|PRIVATE|;
333.478 - item : responses;D;;
333.479 - item : socket;I;|PRIVATE|;
333.480 - item : test;F;|PRIVATE|;;
333.481 - item : urlsplit;I;|PRIVATE|;
333.482 - module : httplib
333.483 -
333.484 -Not Searchable Keys:
334.1 --- a/python.editor/test/unit/data/testfiles/imports/__init__.py Sun Jan 04 13:11:53 2015 -0600
334.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
334.3 @@ -1,5 +0,0 @@
334.4 -import efl
334.5 -import cocoa
334.6 -import console
334.7 -import curses
334.8 -
335.1 --- a/python.editor/test/unit/data/testfiles/imports/__init__.py.testFixInit2.imported Sun Jan 04 13:11:53 2015 -0600
335.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
335.3 @@ -1,6 +0,0 @@
335.4 -import curses
335.5 -
335.6 -import cocoa
335.7 -import console
335.8 -import efl
335.9 -
336.1 --- a/python.editor/test/unit/data/testfiles/imports/definitions.py Sun Jan 04 13:11:53 2015 -0600
336.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
336.3 @@ -1,9 +0,0 @@
336.4 -class DecimalException:
336.5 - def methodInClass(self):
336.6 - print foo
336.7 -
336.8 -
336.9 -class OtherClass:
336.10 - def otherMethodInClass(self,foo):
336.11 - print bar
336.12 -
337.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates1.py Sun Jan 04 13:11:53 2015 -0600
337.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
337.3 @@ -1,9 +0,0 @@
337.4 -"""My module"""
337.5 -import definitions
337.6 -import definitions
337.7 -import definitions
337.8 -import unused1
337.9 -import definitions
337.10 -
337.11 -x.otherMethodInClass()
337.12 -
338.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates1.py.imports Sun Jan 04 13:11:53 2015 -0600
338.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
338.3 @@ -1,5 +0,0 @@
338.4 -Requires user interaction: No
338.5 -Unused imports:
338.6 - unused1
338.7 -Duplicate imports:
338.8 - definitions
339.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates2.py Sun Jan 04 13:11:53 2015 -0600
339.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
339.3 @@ -1,9 +0,0 @@
339.4 -"""My module"""
339.5 -import definitions
339.6 -import definitions
339.7 -from definitions import Foo
339.8 -import unused1
339.9 -import definitions
339.10 -
339.11 -x.otherMethodInClass()
339.12 -
340.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates2.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,6 +0,0 @@
340.4 -Requires user interaction: No
340.5 -Unused imports:
340.6 - definitions:Foo
340.7 - unused1
340.8 -Duplicate imports:
340.9 - definitions
341.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates2.py.testFixDuplicates2b.imported Sun Jan 04 13:11:53 2015 -0600
341.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
341.3 @@ -1,7 +0,0 @@
341.4 -"""My module"""
341.5 -import definitions
341.6 -#from definitions import Foo
341.7 -#import unused1
341.8 -
341.9 -x.otherMethodInClass()
341.10 -
342.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates3.py Sun Jan 04 13:11:53 2015 -0600
342.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
342.3 @@ -1,9 +0,0 @@
342.4 -"""My module"""
342.5 -from definitions import Foo
342.6 -import definitions
342.7 -import definitions
342.8 -import unused1
342.9 -import definitions
342.10 -
342.11 -x.otherMethodInClass()
342.12 -
343.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates3.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 - definitions:Foo
343.7 - unused1
343.8 -Duplicate imports:
343.9 - definitions
344.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates3.py.testFixDuplicates3b.imported Sun Jan 04 13:11:53 2015 -0600
344.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
344.3 @@ -1,7 +0,0 @@
344.4 -"""My module"""
344.5 -import definitions
344.6 -#from definitions import Foo
344.7 -#import unused1
344.8 -
344.9 -x.otherMethodInClass()
344.10 -
345.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates4.py Sun Jan 04 13:11:53 2015 -0600
345.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
345.3 @@ -1,9 +0,0 @@
345.4 -"""My module"""
345.5 -import unused1
345.6 -from definitions import Foo
345.7 -from definitions import Bar
345.8 -from definitions import Foo
345.9 -from definitions import Bar
345.10 -
345.11 -x.otherMethodInClass()
345.12 -
346.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates4.py.imports Sun Jan 04 13:11:53 2015 -0600
346.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
346.3 @@ -1,11 +0,0 @@
346.4 -Requires user interaction: No
346.5 -Unused imports:
346.6 - definitions:Bar
346.7 - definitions:Foo
346.8 - unused1
346.9 -Duplicate imports:
346.10 - definitions:Bar
346.11 - definitions:Foo
346.12 -Unresolved Symbols:
346.13 - otherMethodInClass
346.14 - *definitions
347.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates4.py.testFixDuplicates4b.imported Sun Jan 04 13:11:53 2015 -0600
347.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
347.3 @@ -1,8 +0,0 @@
347.4 -"""My module"""
347.5 -import definitions
347.6 -#from definitions import Bar
347.7 -#from definitions import Foo
347.8 -#import unused1
347.9 -
347.10 -x.otherMethodInClass()
347.11 -
348.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates5.py Sun Jan 04 13:11:53 2015 -0600
348.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
348.3 @@ -1,9 +0,0 @@
348.4 -"""My module"""
348.5 -import unused1
348.6 -from definitions import DecimalException
348.7 -from definitions import OtherClass, DecimalException
348.8 -
348.9 -x.otherMethodInClass()
348.10 -x = DecimalException();
348.11 -y = OtherClass();
348.12 -
349.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates5.py.imports Sun Jan 04 13:11:53 2015 -0600
349.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
349.3 @@ -1,8 +0,0 @@
349.4 -Requires user interaction: No
349.5 -Unused imports:
349.6 - unused1
349.7 -Duplicate imports:
349.8 - definitions:DecimalException
349.9 -Unresolved Symbols:
349.10 - otherMethodInClass
349.11 - *definitions
350.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates5.py.testFixDuplicates5b.imported Sun Jan 04 13:11:53 2015 -0600
350.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
350.3 @@ -1,10 +0,0 @@
350.4 -"""My module"""
350.5 -import definitions
350.6 -from definitions import DecimalException
350.7 -from definitions import OtherClass
350.8 -#import unused1
350.9 -
350.10 -x.otherMethodInClass()
350.11 -x = DecimalException();
350.12 -y = OtherClass();
350.13 -
351.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates6.py Sun Jan 04 13:11:53 2015 -0600
351.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
351.3 @@ -1,8 +0,0 @@
351.4 -"""My module"""
351.5 -import unused1
351.6 -from definitions import DecimalException
351.7 -from definitions import OtherClass, DecimalException
351.8 -
351.9 -x = DecimalException();
351.10 -y = OtherClass();
351.11 -
352.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates6.py.imports Sun Jan 04 13:11:53 2015 -0600
352.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
352.3 @@ -1,5 +0,0 @@
352.4 -Requires user interaction: No
352.5 -Unused imports:
352.6 - unused1
352.7 -Duplicate imports:
352.8 - definitions:DecimalException
353.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates6.py.testFixDuplicates6b.imported Sun Jan 04 13:11:53 2015 -0600
353.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
353.3 @@ -1,8 +0,0 @@
353.4 -"""My module"""
353.5 -from definitions import DecimalException
353.6 -from definitions import OtherClass
353.7 -#import unused1
353.8 -
353.9 -x = DecimalException();
353.10 -y = OtherClass();
353.11 -
354.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates7.py Sun Jan 04 13:11:53 2015 -0600
354.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
354.3 @@ -1,4 +0,0 @@
354.4 -import unused1
354.5 -from definitions import DecimalException, Unused
354.6 -
354.7 -x = DecimalException();
355.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates7.py.testFixDuplicates7.imported Sun Jan 04 13:11:53 2015 -0600
355.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
355.3 @@ -1,5 +0,0 @@
355.4 -from definitions import DecimalException
355.5 -#from definitions import Unused
355.6 -#import unused1
355.7 -
355.8 -x = DecimalException();
356.1 --- a/python.editor/test/unit/data/testfiles/imports/futures.py Sun Jan 04 13:11:53 2015 -0600
356.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
356.3 @@ -1,8 +0,0 @@
356.4 -# Ensure that the future imports here aren't shown as unused or imported symbols for code completion
356.5 -import ghi
356.6 -from abc import whatever
356.7 -from __future__ import with_statement, absolute_imports
356.8 -from __future__ import with_statement
356.9 -from def import whatever
356.10 -import jkl
356.11 -
357.1 --- a/python.editor/test/unit/data/testfiles/imports/futures.py.testSortFutureImports.imported Sun Jan 04 13:11:53 2015 -0600
357.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
357.3 @@ -1,8 +0,0 @@
357.4 -# Ensure that the future imports here aren't shown as unused or imported symbols for code completion
357.5 -from __future__ import absolute_imports
357.6 -from __future__ import with_statement
357.7 -import ghi
357.8 -from abc import whatever
357.9 -from def import whatever
357.10 -import jkl
357.11 -
358.1 --- a/python.editor/test/unit/data/testfiles/imports/imports1.py Sun Jan 04 13:11:53 2015 -0600
358.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
358.3 @@ -1,6 +0,0 @@
358.4 -import foo
358.5 -import bar as BAR
358.6 -import module1, module2, module3
358.7 -from module4 import Class1
358.8 -from module5 import Class2 as Class3
358.9 -
359.1 --- a/python.editor/test/unit/data/testfiles/imports/imports1.py.imports Sun Jan 04 13:11:53 2015 -0600
359.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
359.3 @@ -1,9 +0,0 @@
359.4 -Requires user interaction: No
359.5 -Unused imports:
359.6 - bar
359.7 - foo
359.8 - module1
359.9 - module2
359.10 - module3
359.11 - module4:Class1
359.12 - module5:Class2:Class3
360.1 --- a/python.editor/test/unit/data/testfiles/imports/imports1.py.testFixImports1.imported Sun Jan 04 13:11:53 2015 -0600
360.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
360.3 @@ -1,3 +0,0 @@
360.4 -import module2
360.5 -import module3
360.6 -
361.1 --- a/python.editor/test/unit/data/testfiles/imports/imports1.py.testFixImports2.imported Sun Jan 04 13:11:53 2015 -0600
361.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
361.3 @@ -1,8 +0,0 @@
361.4 -import module2
361.5 -import module3
361.6 -#import bar as BAR
361.7 -#import foo
361.8 -#import module1
361.9 -#from module4 import Class1
361.10 -#from module5 import Class2 as Class3
361.11 -
362.1 --- a/python.editor/test/unit/data/testfiles/imports/imports1.py.testFixOrganize6.imported Sun Jan 04 13:11:53 2015 -0600
362.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
362.3 @@ -1,8 +0,0 @@
362.4 -import bar as BAR
362.5 -import foo
362.6 -import module1
362.7 -import module2
362.8 -import module3
362.9 -from module4 import Class1
362.10 -from module5 import Class2 as Class3
362.11 -
363.1 --- a/python.editor/test/unit/data/testfiles/imports/imports2.py Sun Jan 04 13:11:53 2015 -0600
363.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
363.3 @@ -1,4 +0,0 @@
363.4 -"""My module"""
363.5 -
363.6 -x = DecimalException();
363.7 -
364.1 --- a/python.editor/test/unit/data/testfiles/imports/imports2.py.imports Sun Jan 04 13:11:53 2015 -0600
364.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
364.3 @@ -1,4 +0,0 @@
364.4 -Requires user interaction: No
364.5 -Unresolved Symbols:
364.6 - DecimalException
364.7 - *definitions
365.1 --- a/python.editor/test/unit/data/testfiles/imports/imports2.py.testFixImports3.imported Sun Jan 04 13:11:53 2015 -0600
365.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
365.3 @@ -1,4 +0,0 @@
365.4 -"""My module"""
365.5 -import decimal
365.6 -x = DecimalException();
365.7 -
366.1 --- a/python.editor/test/unit/data/testfiles/imports/imports3.py Sun Jan 04 13:11:53 2015 -0600
366.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
366.3 @@ -1,5 +0,0 @@
366.4 -"""My module"""
366.5 -import unused1
366.6 -
366.7 -x.otherMethodInClass()
366.8 -
367.1 --- a/python.editor/test/unit/data/testfiles/imports/imports3.py.imports Sun Jan 04 13:11:53 2015 -0600
367.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
367.3 @@ -1,6 +0,0 @@
367.4 -Requires user interaction: No
367.5 -Unused imports:
367.6 - unused1
367.7 -Unresolved Symbols:
367.8 - otherMethodInClass
367.9 - *definitions
368.1 --- a/python.editor/test/unit/data/testfiles/imports/imports3.py.testFixImports4.imported Sun Jan 04 13:11:53 2015 -0600
368.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
368.3 @@ -1,6 +0,0 @@
368.4 -"""My module"""
368.5 -import definitions
368.6 -#import unused1
368.7 -
368.8 -x.otherMethodInClass()
368.9 -
369.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py Sun Jan 04 13:11:53 2015 -0600
369.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
369.3 @@ -1,30 +0,0 @@
369.4 -# Copyright 2008
369.5 -# Here we are
369.6 -"""Docs here"""
369.7 -
369.8 -__author__ = 'Tor Norbye'
369.9 -
369.10 -
369.11 -import sys
369.12 -import wsgiref.handlers
369.13 -from google.appengine.ext.webapp.util import run_wsgi_app
369.14 -from google.appengine.ext import webapp
369.15 -from google.appengine.ext import db
369.16 -import os
369.17 -from google.appengine.api import users
369.18 -from google.appengine.api import users
369.19 -from google.appengine.api import users
369.20 -import string
369.21 -from google.appengine.ext.webapp import template
369.22 -from google.appengine.ext.webapp.util import login_required
369.23 -import random
369.24 -import datetime
369.25 -
369.26 -def codehere():
369.27 - print "some code"
369.28 -
369.29 -if (true):
369.30 - import dont_touch_me
369.31 -
369.32 -
369.33 -
370.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.formatted Sun Jan 04 13:11:53 2015 -0600
370.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
370.3 @@ -1,29 +0,0 @@
370.4 -# Copyright 2008
370.5 -# Here we are
370.6 -"""Docs here"""
370.7 -
370.8 -__author__ = 'Tor Norbye'
370.9 -
370.10 -
370.11 -import datetime
370.12 -import os
370.13 -import random
370.14 -import string
370.15 -import sys
370.16 -import wsgiref.handlers
370.17 -
370.18 -from google.appengine.api import users
370.19 -from google.appengine.ext import db
370.20 -from google.appengine.ext import webapp
370.21 -from google.appengine.ext.webapp import template
370.22 -from google.appengine.ext.webapp.util import login_required
370.23 -from google.appengine.ext.webapp.util import run_wsgi_app
370.24 -
370.25 -def codehere():
370.26 - print "some code"
370.27 -
370.28 -if (true):
370.29 - import dont_touch_me
370.30 -
370.31 -
370.32 -
371.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.testFixOrganize1.imported Sun Jan 04 13:11:53 2015 -0600
371.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
371.3 @@ -1,29 +0,0 @@
371.4 -# Copyright 2008
371.5 -# Here we are
371.6 -"""Docs here"""
371.7 -
371.8 -__author__ = 'Tor Norbye'
371.9 -
371.10 -
371.11 -import datetime
371.12 -import os
371.13 -import random
371.14 -import string
371.15 -import sys
371.16 -import wsgiref.handlers
371.17 -
371.18 -from google.appengine.api import users
371.19 -from google.appengine.ext import db
371.20 -from google.appengine.ext import webapp
371.21 -from google.appengine.ext.webapp import template
371.22 -from google.appengine.ext.webapp.util import login_required
371.23 -from google.appengine.ext.webapp.util import run_wsgi_app
371.24 -
371.25 -def codehere():
371.26 - print "some code"
371.27 -
371.28 -if (true):
371.29 - import dont_touch_me
371.30 -
371.31 -
371.32 -
372.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.testFixOrganize2.imported Sun Jan 04 13:11:53 2015 -0600
372.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
372.3 @@ -1,27 +0,0 @@
372.4 -# Copyright 2008
372.5 -# Here we are
372.6 -"""Docs here"""
372.7 -
372.8 -__author__ = 'Tor Norbye'
372.9 -
372.10 -
372.11 -import datetime
372.12 -import os
372.13 -import random
372.14 -import string
372.15 -import sys
372.16 -import wsgiref.handlers
372.17 -
372.18 -from google.appengine.api import users
372.19 -from google.appengine.ext import db, webapp
372.20 -from google.appengine.ext.webapp import template
372.21 -from google.appengine.ext.webapp.util import login_required, run_wsgi_app
372.22 -
372.23 -def codehere():
372.24 - print "some code"
372.25 -
372.26 -if (true):
372.27 - import dont_touch_me
372.28 -
372.29 -
372.30 -
373.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.testFixOrganize3.imported Sun Jan 04 13:11:53 2015 -0600
373.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
373.3 @@ -1,29 +0,0 @@
373.4 -# Copyright 2008
373.5 -# Here we are
373.6 -"""Docs here"""
373.7 -
373.8 -__author__ = 'Tor Norbye'
373.9 -
373.10 -
373.11 -import datetime
373.12 -import os
373.13 -import random
373.14 -import string
373.15 -import sys
373.16 -import wsgiref.handlers
373.17 -
373.18 -from google.appengine.api import users
373.19 -from google.appengine.ext import db
373.20 -from google.appengine.ext import webapp
373.21 -from google.appengine.ext.webapp import template
373.22 -from google.appengine.ext.webapp.util import login_required
373.23 -from google.appengine.ext.webapp.util import run_wsgi_app
373.24 -
373.25 -def codehere():
373.26 - print "some code"
373.27 -
373.28 -if (true):
373.29 - import dont_touch_me
373.30 -
373.31 -
373.32 -
374.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.testFixOrganize4.imported Sun Jan 04 13:11:53 2015 -0600
374.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
374.3 @@ -1,28 +0,0 @@
374.4 -# Copyright 2008
374.5 -# Here we are
374.6 -"""Docs here"""
374.7 -
374.8 -__author__ = 'Tor Norbye'
374.9 -
374.10 -
374.11 -import datetime
374.12 -from google.appengine.api import users
374.13 -from google.appengine.ext import db
374.14 -from google.appengine.ext import webapp
374.15 -from google.appengine.ext.webapp import template
374.16 -from google.appengine.ext.webapp.util import login_required
374.17 -from google.appengine.ext.webapp.util import run_wsgi_app
374.18 -import os
374.19 -import random
374.20 -import string
374.21 -import sys
374.22 -import wsgiref.handlers
374.23 -
374.24 -def codehere():
374.25 - print "some code"
374.26 -
374.27 -if (true):
374.28 - import dont_touch_me
374.29 -
374.30 -
374.31 -
375.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.testFixOrganize5.imported Sun Jan 04 13:11:53 2015 -0600
375.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
375.3 @@ -1,27 +0,0 @@
375.4 -# Copyright 2008
375.5 -# Here we are
375.6 -"""Docs here"""
375.7 -
375.8 -__author__ = 'Tor Norbye'
375.9 -
375.10 -
375.11 -import datetime
375.12 -import os
375.13 -import random
375.14 -import string
375.15 -import sys
375.16 -import wsgiref.handlers
375.17 -
375.18 -from google.appengine.api import users
375.19 -from google.appengine.ext import db, webapp
375.20 -from google.appengine.ext.webapp import template
375.21 -from google.appengine.ext.webapp.util import login_required, run_wsgi_app
375.22 -
375.23 -def codehere():
375.24 - print "some code"
375.25 -
375.26 -if (true):
375.27 - import dont_touch_me
375.28 -
375.29 -
375.30 -
376.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.testFixOrganize7.imported Sun Jan 04 13:11:53 2015 -0600
376.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
376.3 @@ -1,29 +0,0 @@
376.4 -# Copyright 2008
376.5 -# Here we are
376.6 -"""Docs here"""
376.7 -
376.8 -__author__ = 'Tor Norbye'
376.9 -
376.10 -
376.11 -import sys
376.12 -import wsgiref.handlers
376.13 -import os
376.14 -import string
376.15 -import random
376.16 -import datetime
376.17 -
376.18 -from google.appengine.ext.webapp.util import run_wsgi_app
376.19 -from google.appengine.ext import webapp
376.20 -from google.appengine.ext import db
376.21 -from google.appengine.api import users
376.22 -from google.appengine.ext.webapp import template
376.23 -from google.appengine.ext.webapp.util import login_required
376.24 -
376.25 -def codehere():
376.26 - print "some code"
376.27 -
376.28 -if (true):
376.29 - import dont_touch_me
376.30 -
376.31 -
376.32 -
377.1 --- a/python.editor/test/unit/data/testfiles/imports/organize2.py Sun Jan 04 13:11:53 2015 -0600
377.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
377.3 @@ -1,5 +0,0 @@
377.4 -
377.5 -from bar import *
377.6 -from foo import *
377.7 -
377.8 -print "Hello"
378.1 --- a/python.editor/test/unit/data/testfiles/imports/organize2.py.testFixOrganize8.imported Sun Jan 04 13:11:53 2015 -0600
378.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
378.3 @@ -1,5 +0,0 @@
378.4 -
378.5 -from bar import *
378.6 -from foo import *
378.7 -
378.8 -print "Hello"
379.1 --- a/python.editor/test/unit/data/testfiles/imports/toplevel.py Sun Jan 04 13:11:53 2015 -0600
379.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
379.3 @@ -1,6 +0,0 @@
379.4 -try:
379.5 - import cStringIO as StringIO
379.6 -except ImportError:
379.7 - import StringIO
379.8 -
379.9 -
380.1 --- a/python.editor/test/unit/data/testfiles/imports3.py Sun Jan 04 13:11:53 2015 -0600
380.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
380.3 @@ -1,1 +0,0 @@
380.4 -import
381.1 --- a/python.editor/test/unit/data/testfiles/imports3.py.testImports3.completion Sun Jan 04 13:11:53 2015 -0600
381.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
381.3 @@ -1,634 +0,0 @@
381.4 -Code completion result for source line:
381.5 -import |
381.6 -(QueryType=COMPLETION, NameKind=PREFIX)
381.7 -------------------------------------
381.8 -KEYWORD BaseHTTPServer
381.9 -KEYWORD ---Bastion ---
381.10 -KEYWORD CGIHTTPServer
381.11 -KEYWORD ---Carbon.AE ---
381.12 -KEYWORD ---Carbon.AH ---
381.13 -KEYWORD ---Carbon.App ---
381.14 -KEYWORD ---Carbon.CF ---
381.15 -KEYWORD ---Carbon.CG ---
381.16 -KEYWORD ---Carbon.CarbonEvt ---
381.17 -KEYWORD ---Carbon.Cm ---
381.18 -KEYWORD ---Carbon.Ctl ---
381.19 -KEYWORD ---Carbon.Dlg ---
381.20 -KEYWORD ---Carbon.Evt ---
381.21 -KEYWORD ---Carbon.Fm ---
381.22 -KEYWORD ---Carbon.Folder ---
381.23 -KEYWORD ---Carbon.Help ---
381.24 -KEYWORD ---Carbon.List ---
381.25 -KEYWORD ---Carbon.Menu ---
381.26 -KEYWORD ---Carbon.Mlte ---
381.27 -KEYWORD ---Carbon.Qd ---
381.28 -KEYWORD ---Carbon.Qdoffs ---
381.29 -KEYWORD ---Carbon.Qt ---
381.30 -KEYWORD ---Carbon.Res ---
381.31 -KEYWORD ---Carbon.Scrap ---
381.32 -KEYWORD ---Carbon.Snd ---
381.33 -KEYWORD ---Carbon.TE ---
381.34 -KEYWORD ---Carbon.Win ---
381.35 -KEYWORD ---ColorPicker ---
381.36 -KEYWORD ConfigParser
381.37 -KEYWORD Cookie
381.38 -KEYWORD DocXMLRPCServer
381.39 -KEYWORD ---EasyDialogs ---
381.40 -KEYWORD ---FrameWork ---
381.41 -KEYWORD HTMLParser
381.42 -KEYWORD ---MacOS ---
381.43 -KEYWORD ---MimeWriter ---
381.44 -KEYWORD MiniAEFrame
381.45 -KEYWORD ---Nav ---
381.46 -KEYWORD ---PixMapWrapper ---
381.47 -KEYWORD Queue
381.48 -KEYWORD ScrolledText
381.49 -KEYWORD SimpleHTTPServer
381.50 -KEYWORD SimpleXMLRPCServer
381.51 -KEYWORD SocketServer
381.52 -KEYWORD StringIO
381.53 -KEYWORD Tix
381.54 -KEYWORD Tkinter
381.55 -KEYWORD UserDict
381.56 -KEYWORD UserList
381.57 -KEYWORD UserString
381.58 -KEYWORD ---W ---
381.59 -KEYWORD _LWPCookieJar
381.60 -KEYWORD _MozillaCookieJar
381.61 -KEYWORD __builtin__
381.62 -KEYWORD __future__
381.63 -KEYWORD __main__
381.64 -KEYWORD _ast
381.65 -KEYWORD _rawffi
381.66 -KEYWORD _strptime
381.67 -KEYWORD _threading_local
381.68 -KEYWORD _winreg
381.69 -KEYWORD abc
381.70 -KEYWORD ---aepack ---
381.71 -KEYWORD ---aetools ---
381.72 -KEYWORD ---aetypes ---
381.73 -KEYWORD aifc
381.74 -KEYWORD anydbm
381.75 -KEYWORD ---applesingle ---
381.76 -KEYWORD array
381.77 -KEYWORD ast
381.78 -KEYWORD asynchat
381.79 -KEYWORD asyncore
381.80 -KEYWORD atexit
381.81 -KEYWORD audioop
381.82 -KEYWORD ---autoGIL ---
381.83 -KEYWORD base64
381.84 -KEYWORD bdb
381.85 -KEYWORD binascii
381.86 -KEYWORD binhex
381.87 -KEYWORD bisect
381.88 -KEYWORD bsddb
381.89 -KEYWORD ---buildtools ---
381.90 -KEYWORD bz2
381.91 -KEYWORD calendar
381.92 -KEYWORD ---cfmfile ---
381.93 -KEYWORD cgi
381.94 -KEYWORD cgitb
381.95 -KEYWORD chunk
381.96 -KEYWORD cmath
381.97 -KEYWORD cmd
381.98 -KEYWORD code
381.99 -KEYWORD codecs
381.100 -KEYWORD codeop
381.101 -KEYWORD collections
381.102 -KEYWORD colorsys
381.103 -KEYWORD commands
381.104 -KEYWORD compileall
381.105 -KEYWORD compiler
381.106 -KEYWORD compiler.ast
381.107 -KEYWORD compiler.consts
381.108 -KEYWORD compiler.future
381.109 -KEYWORD compiler.misc
381.110 -KEYWORD compiler.pyassem
381.111 -KEYWORD compiler.pycodegen
381.112 -KEYWORD compiler.symbols
381.113 -KEYWORD compiler.syntax
381.114 -KEYWORD compiler.transformer
381.115 -KEYWORD compiler.visitor
381.116 -KEYWORD compl
381.117 -KEYWORD compl2
381.118 -KEYWORD compl3
381.119 -KEYWORD compl4
381.120 -KEYWORD compl5
381.121 -KEYWORD constants
381.122 -KEYWORD contextlib
381.123 -KEYWORD cookielib
381.124 -KEYWORD copy
381.125 -KEYWORD copy_reg
381.126 -KEYWORD crypt
381.127 -KEYWORD csv
381.128 -KEYWORD ctypes
381.129 -KEYWORD curses
381.130 -KEYWORD curses.ascii
381.131 -KEYWORD curses.panel
381.132 -KEYWORD curses.textpad
381.133 -KEYWORD curses.wrapper
381.134 -KEYWORD datetime
381.135 -KEYWORD dbexts
381.136 -KEYWORD dbhash
381.137 -KEYWORD dbm
381.138 -KEYWORD decimal
381.139 -KEYWORD difflib
381.140 -KEYWORD dircache
381.141 -KEYWORD dis
381.142 -KEYWORD distutils
381.143 -KEYWORD distutils.archive_util
381.144 -KEYWORD distutils.bcppcompiler
381.145 -KEYWORD distutils.ccompiler
381.146 -KEYWORD distutils.cmd
381.147 -KEYWORD distutils.command
381.148 -KEYWORD distutils.command.bdist
381.149 -KEYWORD distutils.command.bdist_dumb
381.150 -KEYWORD distutils.command.bdist_msi
381.151 -KEYWORD distutils.command.bdist_rpm
381.152 -KEYWORD distutils.command.bdist_winins
381.153 -KEYWORD distutils.command.build
381.154 -KEYWORD distutils.command.build_clib
381.155 -KEYWORD distutils.command.build_ext
381.156 -KEYWORD distutils.command.build_py
381.157 -KEYWORD distutils.command.build_script
381.158 -KEYWORD distutils.command.clean
381.159 -KEYWORD distutils.command.config
381.160 -KEYWORD distutils.command.install
381.161 -KEYWORD distutils.command.install_data
381.162 -KEYWORD distutils.command.install_egg_
381.163 -KEYWORD distutils.command.install_head
381.164 -KEYWORD distutils.command.install_lib
381.165 -KEYWORD distutils.command.install_scri
381.166 -KEYWORD distutils.command.register
381.167 -KEYWORD distutils.command.sdist
381.168 -KEYWORD distutils.command.upload
381.169 -KEYWORD distutils.core
381.170 -KEYWORD distutils.cygwinccompiler
381.171 -KEYWORD distutils.debug
381.172 -KEYWORD distutils.dep_util
381.173 -KEYWORD distutils.dir_util
381.174 -KEYWORD distutils.dist
381.175 -KEYWORD distutils.emxccompiler
381.176 -KEYWORD distutils.errors
381.177 -KEYWORD distutils.extension
381.178 -KEYWORD distutils.fancy_getopt
381.179 -KEYWORD distutils.file_util
381.180 -KEYWORD distutils.filelist
381.181 -KEYWORD distutils.jythoncompiler
381.182 -KEYWORD distutils.log
381.183 -KEYWORD distutils.msvccompiler
381.184 -KEYWORD distutils.mwerkscompiler
381.185 -KEYWORD distutils.spawn
381.186 -KEYWORD distutils.sysconfig
381.187 -KEYWORD distutils.tests
381.188 -KEYWORD distutils.tests.support
381.189 -KEYWORD distutils.tests.test_build_py
381.190 -KEYWORD distutils.tests.test_build_scr
381.191 -KEYWORD distutils.tests.test_dist
381.192 -KEYWORD distutils.tests.test_install
381.193 -KEYWORD distutils.tests.test_install_s
381.194 -KEYWORD distutils.tests.test_versionpr
381.195 -KEYWORD distutils.text_file
381.196 -KEYWORD distutils.unixccompiler
381.197 -KEYWORD distutils.util
381.198 -KEYWORD distutils.version
381.199 -KEYWORD distutils.versionpredicate
381.200 -KEYWORD ---dl ---
381.201 -KEYWORD doctest
381.202 -KEYWORD dumbdbm
381.203 -KEYWORD dummy_thread
381.204 -KEYWORD dummy_threading
381.205 -KEYWORD email
381.206 -KEYWORD email._parseaddr
381.207 -KEYWORD email.base64mime
381.208 -KEYWORD email.charset
381.209 -KEYWORD email.encoders
381.210 -KEYWORD email.errors
381.211 -KEYWORD email.feedparser
381.212 -KEYWORD email.generator
381.213 -KEYWORD email.header
381.214 -KEYWORD email.iterators
381.215 -KEYWORD email.message
381.216 -KEYWORD email.mime
381.217 -KEYWORD email.mime.application
381.218 -KEYWORD email.mime.audio
381.219 -KEYWORD email.mime.base
381.220 -KEYWORD email.mime.image
381.221 -KEYWORD email.mime.message
381.222 -KEYWORD email.mime.multipart
381.223 -KEYWORD email.mime.nonmultipart
381.224 -KEYWORD email.mime.text
381.225 -KEYWORD email.parser
381.226 -KEYWORD email.quoprimime
381.227 -KEYWORD email.test.test_email_torture
381.228 -KEYWORD email.utils
381.229 -KEYWORD encodings
381.230 -KEYWORD encodings.aliases
381.231 -KEYWORD encodings.ascii
381.232 -KEYWORD encodings.base64_codec
381.233 -KEYWORD encodings.big5
381.234 -KEYWORD encodings.big5hkscs
381.235 -KEYWORD encodings.bz2_codec
381.236 -KEYWORD encodings.charmap
381.237 -KEYWORD encodings.cp037
381.238 -KEYWORD encodings.cp1006
381.239 -KEYWORD encodings.cp1026
381.240 -KEYWORD encodings.cp1140
381.241 -KEYWORD encodings.cp1250
381.242 -KEYWORD encodings.cp1251
381.243 -KEYWORD encodings.cp1252
381.244 -KEYWORD encodings.cp1253
381.245 -KEYWORD encodings.cp1254
381.246 -KEYWORD encodings.cp1255
381.247 -KEYWORD encodings.cp1256
381.248 -KEYWORD encodings.cp1257
381.249 -KEYWORD encodings.cp1258
381.250 -KEYWORD encodings.cp424
381.251 -KEYWORD encodings.cp437
381.252 -KEYWORD encodings.cp500
381.253 -KEYWORD encodings.cp737
381.254 -KEYWORD encodings.cp775
381.255 -KEYWORD encodings.cp850
381.256 -KEYWORD encodings.cp852
381.257 -KEYWORD encodings.cp855
381.258 -KEYWORD encodings.cp856
381.259 -KEYWORD encodings.cp857
381.260 -KEYWORD encodings.cp860
381.261 -KEYWORD encodings.cp861
381.262 -KEYWORD encodings.cp862
381.263 -KEYWORD encodings.cp863
381.264 -KEYWORD encodings.cp864
381.265 -KEYWORD encodings.cp865
381.266 -KEYWORD encodings.cp866
381.267 -KEYWORD encodings.cp869
381.268 -KEYWORD encodings.cp874
381.269 -KEYWORD encodings.cp875
381.270 -KEYWORD encodings.cp932
381.271 -KEYWORD encodings.cp949
381.272 -KEYWORD encodings.cp950
381.273 -KEYWORD encodings.euc_jis_2004
381.274 -KEYWORD encodings.euc_jisx0213
381.275 -KEYWORD encodings.euc_jp
381.276 -KEYWORD encodings.euc_kr
381.277 -KEYWORD encodings.gb18030
381.278 -KEYWORD encodings.gb2312
381.279 -KEYWORD encodings.gbk
381.280 -KEYWORD encodings.hex_codec
381.281 -KEYWORD encodings.hp_roman8
381.282 -KEYWORD encodings.hz
381.283 -KEYWORD encodings.idna
381.284 -KEYWORD encodings.iso2022_jp
381.285 -KEYWORD encodings.iso2022_jp_1
381.286 -KEYWORD encodings.iso2022_jp_2
381.287 -KEYWORD encodings.iso2022_jp_2004
381.288 -KEYWORD encodings.iso2022_jp_3
381.289 -KEYWORD encodings.iso2022_jp_ext
381.290 -KEYWORD encodings.iso2022_kr
381.291 -KEYWORD encodings.iso8859_1
381.292 -KEYWORD encodings.iso8859_10
381.293 -KEYWORD encodings.iso8859_11
381.294 -KEYWORD encodings.iso8859_13
381.295 -KEYWORD encodings.iso8859_14
381.296 -KEYWORD encodings.iso8859_15
381.297 -KEYWORD encodings.iso8859_16
381.298 -KEYWORD encodings.iso8859_2
381.299 -KEYWORD encodings.iso8859_3
381.300 -KEYWORD encodings.iso8859_4
381.301 -KEYWORD encodings.iso8859_5
381.302 -KEYWORD encodings.iso8859_6
381.303 -KEYWORD encodings.iso8859_7
381.304 -KEYWORD encodings.iso8859_8
381.305 -KEYWORD encodings.iso8859_9
381.306 -KEYWORD encodings.johab
381.307 -KEYWORD encodings.koi8_r
381.308 -KEYWORD encodings.koi8_u
381.309 -KEYWORD encodings.latin_1
381.310 -KEYWORD encodings.mac_arabic
381.311 -KEYWORD encodings.mac_centeuro
381.312 -KEYWORD encodings.mac_croatian
381.313 -KEYWORD encodings.mac_cyrillic
381.314 -KEYWORD encodings.mac_farsi
381.315 -KEYWORD encodings.mac_greek
381.316 -KEYWORD encodings.mac_iceland
381.317 -KEYWORD encodings.mac_latin2
381.318 -KEYWORD encodings.mac_roman
381.319 -KEYWORD encodings.mac_romanian
381.320 -KEYWORD encodings.mac_turkish
381.321 -KEYWORD encodings.mbcs
381.322 -KEYWORD encodings.palmos
381.323 -KEYWORD encodings.ptcp154
381.324 -KEYWORD encodings.punycode
381.325 -KEYWORD encodings.quopri_codec
381.326 -KEYWORD encodings.raw_unicode_escape
381.327 -KEYWORD encodings.rot_13
381.328 -KEYWORD encodings.shift_jis
381.329 -KEYWORD encodings.shift_jis_2004
381.330 -KEYWORD encodings.shift_jisx0213
381.331 -KEYWORD encodings.string_escape
381.332 -KEYWORD encodings.tis_620
381.333 -KEYWORD encodings.undefined
381.334 -KEYWORD encodings.unicode_escape
381.335 -KEYWORD encodings.unicode_internal
381.336 -KEYWORD encodings.utf_16
381.337 -KEYWORD encodings.utf_16_be
381.338 -KEYWORD encodings.utf_16_le
381.339 -KEYWORD encodings.utf_7
381.340 -KEYWORD encodings.utf_8
381.341 -KEYWORD encodings.utf_8_sig
381.342 -KEYWORD encodings.uu_codec
381.343 -KEYWORD encodings.zlib_codec
381.344 -KEYWORD errno
381.345 -KEYWORD exceptions
381.346 -KEYWORD fcntl
381.347 -KEYWORD filecmp
381.348 -KEYWORD fileinput
381.349 -KEYWORD findertools
381.350 -KEYWORD fnmatch
381.351 -KEYWORD formatter
381.352 -KEYWORD fpectl
381.353 -KEYWORD fpformat
381.354 -KEYWORD fractions
381.355 -KEYWORD ftplib
381.356 -KEYWORD functions
381.357 -KEYWORD functools
381.358 -KEYWORD future_builtins
381.359 -KEYWORD gc
381.360 -KEYWORD gdbm
381.361 -KEYWORD gensuitemodule
381.362 -KEYWORD getopt
381.363 -KEYWORD getpass
381.364 -KEYWORD gettext
381.365 -KEYWORD glob
381.366 -KEYWORD ---gopherlib ---
381.367 -KEYWORD grp
381.368 -KEYWORD gzip
381.369 -KEYWORD hashlib
381.370 -KEYWORD heapq
381.371 -KEYWORD hmac
381.372 -KEYWORD hotshot
381.373 -KEYWORD hotshot.stats
381.374 -KEYWORD htmlentitydefs
381.375 -KEYWORD htmllib
381.376 -KEYWORD httplib
381.377 -KEYWORD ---ic ---
381.378 -KEYWORD ---icopen ---
381.379 -KEYWORD ihooks
381.380 -KEYWORD ---imageop ---
381.381 -KEYWORD imaplib
381.382 -KEYWORD imghdr
381.383 -KEYWORD imp
381.384 -KEYWORD imports3
381.385 -KEYWORD imports7
381.386 -KEYWORD imports8
381.387 -KEYWORD imports9
381.388 -KEYWORD ---imputil ---
381.389 -KEYWORD inspect
381.390 -KEYWORD io
381.391 -KEYWORD isql
381.392 -KEYWORD itertools
381.393 -KEYWORD javapath
381.394 -KEYWORD javashell
381.395 -KEYWORD jreload
381.396 -KEYWORD json
381.397 -KEYWORD keyword
381.398 -KEYWORD lib2to3
381.399 -KEYWORD linecache
381.400 -KEYWORD locale
381.401 -KEYWORD logging
381.402 -KEYWORD logging.config
381.403 -KEYWORD logging.handlers
381.404 -KEYWORD ---macerrors ---
381.405 -KEYWORD ---macostools ---
381.406 -KEYWORD macpath
381.407 -KEYWORD ---macresource ---
381.408 -KEYWORD macurl2path
381.409 -KEYWORD mailbox
381.410 -KEYWORD mailcap
381.411 -KEYWORD markupbase
381.412 -KEYWORD marshal
381.413 -KEYWORD math
381.414 -KEYWORD ---md5 ---
381.415 -KEYWORD mhlib
381.416 -KEYWORD ---mimetools ---
381.417 -KEYWORD mimetypes
381.418 -KEYWORD ---mimify ---
381.419 -KEYWORD mmap
381.420 -KEYWORD modulefinder
381.421 -KEYWORD msilib
381.422 -KEYWORD msvcrt
381.423 -KEYWORD ---multifile ---
381.424 -KEYWORD multiprocessing
381.425 -KEYWORD multiprocessing.connection
381.426 -KEYWORD multiprocessing.dummy
381.427 -KEYWORD multiprocessing.managers
381.428 -KEYWORD multiprocessing.pool
381.429 -KEYWORD multiprocessing.sharedctypes
381.430 -KEYWORD mutex
381.431 -KEYWORD netrc
381.432 -KEYWORD new
381.433 -KEYWORD nis
381.434 -KEYWORD nntplib
381.435 -KEYWORD ntpath
381.436 -KEYWORD nturl2path
381.437 -KEYWORD numbers
381.438 -KEYWORD occurrences2
381.439 -KEYWORD opcode
381.440 -KEYWORD operator
381.441 -KEYWORD optparse
381.442 -KEYWORD os
381.443 -KEYWORD os.path
381.444 -KEYWORD ossaudiodev
381.445 -KEYWORD parser
381.446 -KEYWORD pawt
381.447 -KEYWORD pawt.colors
381.448 -KEYWORD pawt.swing
381.449 -KEYWORD pdb
381.450 -KEYWORD pickle
381.451 -KEYWORD pickletools
381.452 -KEYWORD pipes
381.453 -KEYWORD pkgutil
381.454 -KEYWORD platform
381.455 -KEYWORD plistlib
381.456 -KEYWORD popen2
381.457 -KEYWORD poplib
381.458 -KEYWORD posix
381.459 -KEYWORD ---posixfile ---
381.460 -KEYWORD posixpath
381.461 -KEYWORD pprint
381.462 -KEYWORD profile
381.463 -KEYWORD pstats
381.464 -KEYWORD pty
381.465 -KEYWORD pwd
381.466 -KEYWORD py_compile
381.467 -KEYWORD pyclbr
381.468 -KEYWORD pydoc
381.469 -KEYWORD quopri
381.470 -KEYWORD random
381.471 -KEYWORD re
381.472 -KEYWORD readline
381.473 -KEYWORD repr
381.474 -KEYWORD resource
381.475 -KEYWORD ---rexec ---
381.476 -KEYWORD ---rfc822 ---
381.477 -KEYWORD rlcompleter
381.478 -KEYWORD robotparser
381.479 -KEYWORD runpy
381.480 -KEYWORD sched
381.481 -KEYWORD select
381.482 -KEYWORD ---sets ---
381.483 -KEYWORD sgmllib
381.484 -KEYWORD ---sha ---
381.485 -KEYWORD shelve
381.486 -KEYWORD shlex
381.487 -KEYWORD shutil
381.488 -KEYWORD signal
381.489 -KEYWORD site
381.490 -KEYWORD smtpd
381.491 -KEYWORD smtplib
381.492 -KEYWORD sndhdr
381.493 -KEYWORD socket
381.494 -KEYWORD spwd
381.495 -KEYWORD sqlite3
381.496 -KEYWORD sre
381.497 -KEYWORD sre_compile
381.498 -KEYWORD sre_constants
381.499 -KEYWORD sre_parse
381.500 -KEYWORD ssl
381.501 -KEYWORD stat
381.502 -KEYWORD ---statvfs ---
381.503 -KEYWORD stdtypes
381.504 -KEYWORD string
381.505 -KEYWORD ---stringprep ---
381.506 -KEYWORD struct
381.507 -KEYWORD subprocess
381.508 -KEYWORD symbol
381.509 -KEYWORD symtable
381.510 -KEYWORD sys
381.511 -KEYWORD syslog
381.512 -KEYWORD tabnanny
381.513 -KEYWORD tarfile
381.514 -KEYWORD telnetlib
381.515 -KEYWORD tempfile
381.516 -KEYWORD termios
381.517 -KEYWORD test.bugs.bugs100
381.518 -KEYWORD test.bugs.bugs101
381.519 -KEYWORD test.bugs.jdkbugs
381.520 -KEYWORD test.bugs.pr101
381.521 -KEYWORD test.bugs.pr104
381.522 -KEYWORD test.bugs.pr112
381.523 -KEYWORD test.bugs.pr119
381.524 -KEYWORD test.bugs.pr127
381.525 -KEYWORD test.bugs.pr133
381.526 -KEYWORD test.bugs.pr133.test
381.527 -KEYWORD test.bugs.pr134
381.528 -KEYWORD test.bugs.pr139
381.529 -KEYWORD test.bugs.pr142
381.530 -KEYWORD test.bugs.pr144
381.531 -KEYWORD test.bugs.pr148
381.532 -KEYWORD test.bugs.pr149
381.533 -KEYWORD test.bugs.pr155
381.534 -KEYWORD test.bugs.pr170
381.535 -KEYWORD test.bugs.pr171
381.536 -KEYWORD test.bugs.pr174
381.537 -KEYWORD test.bugs.pr178
381.538 -KEYWORD test.bugs.pr183
381.539 -KEYWORD test.bugs.pr186
381.540 -KEYWORD test.bugs.pr191
381.541 -KEYWORD test.bugs.pr192
381.542 -KEYWORD test.bugs.pr195
381.543 -KEYWORD test.bugs.pr208
381.544 -KEYWORD test.bugs.pr233
381.545 -KEYWORD test.bugs.pr234
381.546 -KEYWORD test.bugs.pr235
381.547 -KEYWORD test.bugs.pr239
381.548 -KEYWORD test.bugs.pr241
381.549 -KEYWORD test.bugs.pr242
381.550 -KEYWORD test.crashers.bogus_code_obj
381.551 -KEYWORD test.crashers.borrowed_ref_1
381.552 -KEYWORD test.crashers.borrowed_ref_2
381.553 -KEYWORD test.crashers.gc_inspection
381.554 -KEYWORD test.crashers.infinite_rec_1
381.555 -KEYWORD test.crashers.infinite_rec_2
381.556 -KEYWORD test.crashers.infinite_rec_4
381.557 -KEYWORD test.crashers.infinite_rec_5
381.558 -KEYWORD test.crashers.loosing_dict_ref
381.559 -KEYWORD test.crashers.nasty_eq_vs_dict
381.560 -KEYWORD test.crashers.recursion_limit_
381.561 -KEYWORD test.crashers.recursive_call
381.562 -KEYWORD test.leakers
381.563 -KEYWORD test.leakers.test_ctypes
381.564 -KEYWORD test.leakers.test_gestalt
381.565 -KEYWORD test.leakers.test_selftype
381.566 -KEYWORD test.test_metaclass_support
381.567 -KEYWORD test.test_metaclass_support.me
381.568 -KEYWORD test.test_metaclass_support.si
381.569 -KEYWORD test.xmltests
381.570 -KEYWORD test.zxjdbc.dbextstest
381.571 -KEYWORD test.zxjdbc.jndi
381.572 -KEYWORD test.zxjdbc.runner
381.573 -KEYWORD test.zxjdbc.sptest
381.574 -KEYWORD test.zxjdbc.test_zxjdbc_dbapi2
381.575 -KEYWORD test.zxjdbc.zxtest
381.576 -KEYWORD textwrap
381.577 -KEYWORD this
381.578 -KEYWORD thread
381.579 -KEYWORD threading
381.580 -KEYWORD time
381.581 -KEYWORD timeit
381.582 -KEYWORD token
381.583 -KEYWORD tokenize
381.584 -KEYWORD trace
381.585 -KEYWORD traceback
381.586 -KEYWORD tty
381.587 -KEYWORD turtle
381.588 -KEYWORD types
381.589 -KEYWORD unicodedata
381.590 -KEYWORD unittest
381.591 -KEYWORD urllib
381.592 -KEYWORD urllib2
381.593 -KEYWORD urlparse
381.594 -KEYWORD user
381.595 -KEYWORD uu
381.596 -KEYWORD uuid
381.597 -KEYWORD ---videoreader ---
381.598 -KEYWORD warnings
381.599 -KEYWORD wave
381.600 -KEYWORD weakref
381.601 -KEYWORD webbrowser
381.602 -KEYWORD whichdb
381.603 -KEYWORD winsound
381.604 -KEYWORD wsgiref
381.605 -KEYWORD wsgiref.handlers
381.606 -KEYWORD wsgiref.headers
381.607 -KEYWORD wsgiref.simple_server
381.608 -KEYWORD wsgiref.util
381.609 -KEYWORD wsgiref.validate
381.610 -KEYWORD xdrlib
381.611 -KEYWORD xml
381.612 -KEYWORD xml.FtCore
381.613 -KEYWORD xml.Uri
381.614 -KEYWORD xml.dom
381.615 -KEYWORD xml.dom.MessageSource
381.616 -KEYWORD xml.dom.NodeFilter
381.617 -KEYWORD xml.dom.domreg
381.618 -KEYWORD xml.dom.minicompat
381.619 -KEYWORD xml.dom.minidom
381.620 -KEYWORD xml.dom.pulldom
381.621 -KEYWORD xml.dom.xmlbuilder
381.622 -KEYWORD xml.etree
381.623 -KEYWORD xml.etree.ElementTree
381.624 -KEYWORD xml.parsers.expat
381.625 -KEYWORD xml.sax
381.626 -KEYWORD xml.sax._exceptions
381.627 -KEYWORD xml.sax.drivers2
381.628 -KEYWORD xml.sax.drivers2.drv_javasax
381.629 -KEYWORD xml.sax.handler
381.630 -KEYWORD xml.sax.saxlib
381.631 -KEYWORD xml.sax.saxutils
381.632 -KEYWORD xml.sax.xmlreader
381.633 -KEYWORD xmllib
381.634 -KEYWORD xmlrpclib
381.635 -KEYWORD zipfile
381.636 -KEYWORD zipimport
381.637 -KEYWORD zlib
382.1 --- a/python.editor/test/unit/data/testfiles/imports4.py Sun Jan 04 13:11:53 2015 -0600
382.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
382.3 @@ -1,4 +0,0 @@
382.4 -import
382.5 -
382.6 -
382.7 -
383.1 --- a/python.editor/test/unit/data/testfiles/imports4.py.testImports4.completion Sun Jan 04 13:11:53 2015 -0600
383.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
383.3 @@ -1,635 +0,0 @@
383.4 -Code completion result for source line:
383.5 -import |
383.6 -(QueryType=COMPLETION, NameKind=PREFIX)
383.7 -------------------------------------
383.8 -KEYWORD BaseHTTPServer
383.9 -KEYWORD ---Bastion ---
383.10 -KEYWORD CGIHTTPServer
383.11 -KEYWORD ---Carbon.AE ---
383.12 -KEYWORD ---Carbon.AH ---
383.13 -KEYWORD ---Carbon.App ---
383.14 -KEYWORD ---Carbon.CF ---
383.15 -KEYWORD ---Carbon.CG ---
383.16 -KEYWORD ---Carbon.CarbonEvt ---
383.17 -KEYWORD ---Carbon.Cm ---
383.18 -KEYWORD ---Carbon.Ctl ---
383.19 -KEYWORD ---Carbon.Dlg ---
383.20 -KEYWORD ---Carbon.Evt ---
383.21 -KEYWORD ---Carbon.Fm ---
383.22 -KEYWORD ---Carbon.Folder ---
383.23 -KEYWORD ---Carbon.Help ---
383.24 -KEYWORD ---Carbon.List ---
383.25 -KEYWORD ---Carbon.Menu ---
383.26 -KEYWORD ---Carbon.Mlte ---
383.27 -KEYWORD ---Carbon.Qd ---
383.28 -KEYWORD ---Carbon.Qdoffs ---
383.29 -KEYWORD ---Carbon.Qt ---
383.30 -KEYWORD ---Carbon.Res ---
383.31 -KEYWORD ---Carbon.Scrap ---
383.32 -KEYWORD ---Carbon.Snd ---
383.33 -KEYWORD ---Carbon.TE ---
383.34 -KEYWORD ---Carbon.Win ---
383.35 -KEYWORD ---ColorPicker ---
383.36 -KEYWORD ConfigParser
383.37 -KEYWORD Cookie
383.38 -KEYWORD DocXMLRPCServer
383.39 -KEYWORD ---EasyDialogs ---
383.40 -KEYWORD ---FrameWork ---
383.41 -KEYWORD HTMLParser
383.42 -KEYWORD ---MacOS ---
383.43 -KEYWORD ---MimeWriter ---
383.44 -KEYWORD MiniAEFrame
383.45 -KEYWORD ---Nav ---
383.46 -KEYWORD ---PixMapWrapper ---
383.47 -KEYWORD Queue
383.48 -KEYWORD ScrolledText
383.49 -KEYWORD SimpleHTTPServer
383.50 -KEYWORD SimpleXMLRPCServer
383.51 -KEYWORD SocketServer
383.52 -KEYWORD StringIO
383.53 -KEYWORD Tix
383.54 -KEYWORD Tkinter
383.55 -KEYWORD UserDict
383.56 -KEYWORD UserList
383.57 -KEYWORD UserString
383.58 -KEYWORD ---W ---
383.59 -KEYWORD _LWPCookieJar
383.60 -KEYWORD _MozillaCookieJar
383.61 -KEYWORD __builtin__
383.62 -KEYWORD __future__
383.63 -KEYWORD __main__
383.64 -KEYWORD _ast
383.65 -KEYWORD _rawffi
383.66 -KEYWORD _strptime
383.67 -KEYWORD _threading_local
383.68 -KEYWORD _winreg
383.69 -KEYWORD abc
383.70 -KEYWORD ---aepack ---
383.71 -KEYWORD ---aetools ---
383.72 -KEYWORD ---aetypes ---
383.73 -KEYWORD aifc
383.74 -KEYWORD anydbm
383.75 -KEYWORD ---applesingle ---
383.76 -KEYWORD array
383.77 -KEYWORD ast
383.78 -KEYWORD asynchat
383.79 -KEYWORD asyncore
383.80 -KEYWORD atexit
383.81 -KEYWORD audioop
383.82 -KEYWORD ---autoGIL ---
383.83 -KEYWORD base64
383.84 -KEYWORD bdb
383.85 -KEYWORD binascii
383.86 -KEYWORD binhex
383.87 -KEYWORD bisect
383.88 -KEYWORD bsddb
383.89 -KEYWORD ---buildtools ---
383.90 -KEYWORD bz2
383.91 -KEYWORD calendar
383.92 -KEYWORD ---cfmfile ---
383.93 -KEYWORD cgi
383.94 -KEYWORD cgitb
383.95 -KEYWORD chunk
383.96 -KEYWORD cmath
383.97 -KEYWORD cmd
383.98 -KEYWORD code
383.99 -KEYWORD codecs
383.100 -KEYWORD codeop
383.101 -KEYWORD collections
383.102 -KEYWORD colorsys
383.103 -KEYWORD commands
383.104 -KEYWORD compileall
383.105 -KEYWORD compiler
383.106 -KEYWORD compiler.ast
383.107 -KEYWORD compiler.consts
383.108 -KEYWORD compiler.future
383.109 -KEYWORD compiler.misc
383.110 -KEYWORD compiler.pyassem
383.111 -KEYWORD compiler.pycodegen
383.112 -KEYWORD compiler.symbols
383.113 -KEYWORD compiler.syntax
383.114 -KEYWORD compiler.transformer
383.115 -KEYWORD compiler.visitor
383.116 -KEYWORD compl
383.117 -KEYWORD compl2
383.118 -KEYWORD compl3
383.119 -KEYWORD compl4
383.120 -KEYWORD compl5
383.121 -KEYWORD constants
383.122 -KEYWORD contextlib
383.123 -KEYWORD cookielib
383.124 -KEYWORD copy
383.125 -KEYWORD copy_reg
383.126 -KEYWORD crypt
383.127 -KEYWORD csv
383.128 -KEYWORD ctypes
383.129 -KEYWORD curses
383.130 -KEYWORD curses.ascii
383.131 -KEYWORD curses.panel
383.132 -KEYWORD curses.textpad
383.133 -KEYWORD curses.wrapper
383.134 -KEYWORD datetime
383.135 -KEYWORD dbexts
383.136 -KEYWORD dbhash
383.137 -KEYWORD dbm
383.138 -KEYWORD decimal
383.139 -KEYWORD difflib
383.140 -KEYWORD dircache
383.141 -KEYWORD dis
383.142 -KEYWORD distutils
383.143 -KEYWORD distutils.archive_util
383.144 -KEYWORD distutils.bcppcompiler
383.145 -KEYWORD distutils.ccompiler
383.146 -KEYWORD distutils.cmd
383.147 -KEYWORD distutils.command
383.148 -KEYWORD distutils.command.bdist
383.149 -KEYWORD distutils.command.bdist_dumb
383.150 -KEYWORD distutils.command.bdist_msi
383.151 -KEYWORD distutils.command.bdist_rpm
383.152 -KEYWORD distutils.command.bdist_winins
383.153 -KEYWORD distutils.command.build
383.154 -KEYWORD distutils.command.build_clib
383.155 -KEYWORD distutils.command.build_ext
383.156 -KEYWORD distutils.command.build_py
383.157 -KEYWORD distutils.command.build_script
383.158 -KEYWORD distutils.command.clean
383.159 -KEYWORD distutils.command.config
383.160 -KEYWORD distutils.command.install
383.161 -KEYWORD distutils.command.install_data
383.162 -KEYWORD distutils.command.install_egg_
383.163 -KEYWORD distutils.command.install_head
383.164 -KEYWORD distutils.command.install_lib
383.165 -KEYWORD distutils.command.install_scri
383.166 -KEYWORD distutils.command.register
383.167 -KEYWORD distutils.command.sdist
383.168 -KEYWORD distutils.command.upload
383.169 -KEYWORD distutils.core
383.170 -KEYWORD distutils.cygwinccompiler
383.171 -KEYWORD distutils.debug
383.172 -KEYWORD distutils.dep_util
383.173 -KEYWORD distutils.dir_util
383.174 -KEYWORD distutils.dist
383.175 -KEYWORD distutils.emxccompiler
383.176 -KEYWORD distutils.errors
383.177 -KEYWORD distutils.extension
383.178 -KEYWORD distutils.fancy_getopt
383.179 -KEYWORD distutils.file_util
383.180 -KEYWORD distutils.filelist
383.181 -KEYWORD distutils.jythoncompiler
383.182 -KEYWORD distutils.log
383.183 -KEYWORD distutils.msvccompiler
383.184 -KEYWORD distutils.mwerkscompiler
383.185 -KEYWORD distutils.spawn
383.186 -KEYWORD distutils.sysconfig
383.187 -KEYWORD distutils.tests
383.188 -KEYWORD distutils.tests.support
383.189 -KEYWORD distutils.tests.test_build_py
383.190 -KEYWORD distutils.tests.test_build_scr
383.191 -KEYWORD distutils.tests.test_dist
383.192 -KEYWORD distutils.tests.test_install
383.193 -KEYWORD distutils.tests.test_install_s
383.194 -KEYWORD distutils.tests.test_versionpr
383.195 -KEYWORD distutils.text_file
383.196 -KEYWORD distutils.unixccompiler
383.197 -KEYWORD distutils.util
383.198 -KEYWORD distutils.version
383.199 -KEYWORD distutils.versionpredicate
383.200 -KEYWORD ---dl ---
383.201 -KEYWORD doctest
383.202 -KEYWORD dumbdbm
383.203 -KEYWORD dummy_thread
383.204 -KEYWORD dummy_threading
383.205 -KEYWORD email
383.206 -KEYWORD email._parseaddr
383.207 -KEYWORD email.base64mime
383.208 -KEYWORD email.charset
383.209 -KEYWORD email.encoders
383.210 -KEYWORD email.errors
383.211 -KEYWORD email.feedparser
383.212 -KEYWORD email.generator
383.213 -KEYWORD email.header
383.214 -KEYWORD email.iterators
383.215 -KEYWORD email.message
383.216 -KEYWORD email.mime
383.217 -KEYWORD email.mime.application
383.218 -KEYWORD email.mime.audio
383.219 -KEYWORD email.mime.base
383.220 -KEYWORD email.mime.image
383.221 -KEYWORD email.mime.message
383.222 -KEYWORD email.mime.multipart
383.223 -KEYWORD email.mime.nonmultipart
383.224 -KEYWORD email.mime.text
383.225 -KEYWORD email.parser
383.226 -KEYWORD email.quoprimime
383.227 -KEYWORD email.test.test_email_torture
383.228 -KEYWORD email.utils
383.229 -KEYWORD encodings
383.230 -KEYWORD encodings.aliases
383.231 -KEYWORD encodings.ascii
383.232 -KEYWORD encodings.base64_codec
383.233 -KEYWORD encodings.big5
383.234 -KEYWORD encodings.big5hkscs
383.235 -KEYWORD encodings.bz2_codec
383.236 -KEYWORD encodings.charmap
383.237 -KEYWORD encodings.cp037
383.238 -KEYWORD encodings.cp1006
383.239 -KEYWORD encodings.cp1026
383.240 -KEYWORD encodings.cp1140
383.241 -KEYWORD encodings.cp1250
383.242 -KEYWORD encodings.cp1251
383.243 -KEYWORD encodings.cp1252
383.244 -KEYWORD encodings.cp1253
383.245 -KEYWORD encodings.cp1254
383.246 -KEYWORD encodings.cp1255
383.247 -KEYWORD encodings.cp1256
383.248 -KEYWORD encodings.cp1257
383.249 -KEYWORD encodings.cp1258
383.250 -KEYWORD encodings.cp424
383.251 -KEYWORD encodings.cp437
383.252 -KEYWORD encodings.cp500
383.253 -KEYWORD encodings.cp737
383.254 -KEYWORD encodings.cp775
383.255 -KEYWORD encodings.cp850
383.256 -KEYWORD encodings.cp852
383.257 -KEYWORD encodings.cp855
383.258 -KEYWORD encodings.cp856
383.259 -KEYWORD encodings.cp857
383.260 -KEYWORD encodings.cp860
383.261 -KEYWORD encodings.cp861
383.262 -KEYWORD encodings.cp862
383.263 -KEYWORD encodings.cp863
383.264 -KEYWORD encodings.cp864
383.265 -KEYWORD encodings.cp865
383.266 -KEYWORD encodings.cp866
383.267 -KEYWORD encodings.cp869
383.268 -KEYWORD encodings.cp874
383.269 -KEYWORD encodings.cp875
383.270 -KEYWORD encodings.cp932
383.271 -KEYWORD encodings.cp949
383.272 -KEYWORD encodings.cp950
383.273 -KEYWORD encodings.euc_jis_2004
383.274 -KEYWORD encodings.euc_jisx0213
383.275 -KEYWORD encodings.euc_jp
383.276 -KEYWORD encodings.euc_kr
383.277 -KEYWORD encodings.gb18030
383.278 -KEYWORD encodings.gb2312
383.279 -KEYWORD encodings.gbk
383.280 -KEYWORD encodings.hex_codec
383.281 -KEYWORD encodings.hp_roman8
383.282 -KEYWORD encodings.hz
383.283 -KEYWORD encodings.idna
383.284 -KEYWORD encodings.iso2022_jp
383.285 -KEYWORD encodings.iso2022_jp_1
383.286 -KEYWORD encodings.iso2022_jp_2
383.287 -KEYWORD encodings.iso2022_jp_2004
383.288 -KEYWORD encodings.iso2022_jp_3
383.289 -KEYWORD encodings.iso2022_jp_ext
383.290 -KEYWORD encodings.iso2022_kr
383.291 -KEYWORD encodings.iso8859_1
383.292 -KEYWORD encodings.iso8859_10
383.293 -KEYWORD encodings.iso8859_11
383.294 -KEYWORD encodings.iso8859_13
383.295 -KEYWORD encodings.iso8859_14
383.296 -KEYWORD encodings.iso8859_15
383.297 -KEYWORD encodings.iso8859_16
383.298 -KEYWORD encodings.iso8859_2
383.299 -KEYWORD encodings.iso8859_3
383.300 -KEYWORD encodings.iso8859_4
383.301 -KEYWORD encodings.iso8859_5
383.302 -KEYWORD encodings.iso8859_6
383.303 -KEYWORD encodings.iso8859_7
383.304 -KEYWORD encodings.iso8859_8
383.305 -KEYWORD encodings.iso8859_9
383.306 -KEYWORD encodings.johab
383.307 -KEYWORD encodings.koi8_r
383.308 -KEYWORD encodings.koi8_u
383.309 -KEYWORD encodings.latin_1
383.310 -KEYWORD encodings.mac_arabic
383.311 -KEYWORD encodings.mac_centeuro
383.312 -KEYWORD encodings.mac_croatian
383.313 -KEYWORD encodings.mac_cyrillic
383.314 -KEYWORD encodings.mac_farsi
383.315 -KEYWORD encodings.mac_greek
383.316 -KEYWORD encodings.mac_iceland
383.317 -KEYWORD encodings.mac_latin2
383.318 -KEYWORD encodings.mac_roman
383.319 -KEYWORD encodings.mac_romanian
383.320 -KEYWORD encodings.mac_turkish
383.321 -KEYWORD encodings.mbcs
383.322 -KEYWORD encodings.palmos
383.323 -KEYWORD encodings.ptcp154
383.324 -KEYWORD encodings.punycode
383.325 -KEYWORD encodings.quopri_codec
383.326 -KEYWORD encodings.raw_unicode_escape
383.327 -KEYWORD encodings.rot_13
383.328 -KEYWORD encodings.shift_jis
383.329 -KEYWORD encodings.shift_jis_2004
383.330 -KEYWORD encodings.shift_jisx0213
383.331 -KEYWORD encodings.string_escape
383.332 -KEYWORD encodings.tis_620
383.333 -KEYWORD encodings.undefined
383.334 -KEYWORD encodings.unicode_escape
383.335 -KEYWORD encodings.unicode_internal
383.336 -KEYWORD encodings.utf_16
383.337 -KEYWORD encodings.utf_16_be
383.338 -KEYWORD encodings.utf_16_le
383.339 -KEYWORD encodings.utf_7
383.340 -KEYWORD encodings.utf_8
383.341 -KEYWORD encodings.utf_8_sig
383.342 -KEYWORD encodings.uu_codec
383.343 -KEYWORD encodings.zlib_codec
383.344 -KEYWORD errno
383.345 -KEYWORD exceptions
383.346 -KEYWORD fcntl
383.347 -KEYWORD filecmp
383.348 -KEYWORD fileinput
383.349 -KEYWORD findertools
383.350 -KEYWORD fnmatch
383.351 -KEYWORD formatter
383.352 -KEYWORD fpectl
383.353 -KEYWORD fpformat
383.354 -KEYWORD fractions
383.355 -KEYWORD ftplib
383.356 -KEYWORD functions
383.357 -KEYWORD functools
383.358 -KEYWORD future_builtins
383.359 -KEYWORD gc
383.360 -KEYWORD gdbm
383.361 -KEYWORD gensuitemodule
383.362 -KEYWORD getopt
383.363 -KEYWORD getpass
383.364 -KEYWORD gettext
383.365 -KEYWORD glob
383.366 -KEYWORD ---gopherlib ---
383.367 -KEYWORD grp
383.368 -KEYWORD gzip
383.369 -KEYWORD hashlib
383.370 -KEYWORD heapq
383.371 -KEYWORD hmac
383.372 -KEYWORD hotshot
383.373 -KEYWORD hotshot.stats
383.374 -KEYWORD htmlentitydefs
383.375 -KEYWORD htmllib
383.376 -KEYWORD httplib
383.377 -KEYWORD ---ic ---
383.378 -KEYWORD ---icopen ---
383.379 -KEYWORD ihooks
383.380 -KEYWORD ---imageop ---
383.381 -KEYWORD imaplib
383.382 -KEYWORD imghdr
383.383 -KEYWORD imp
383.384 -KEYWORD imports3
383.385 -KEYWORD imports4
383.386 -KEYWORD imports7
383.387 -KEYWORD imports8
383.388 -KEYWORD imports9
383.389 -KEYWORD ---imputil ---
383.390 -KEYWORD inspect
383.391 -KEYWORD io
383.392 -KEYWORD isql
383.393 -KEYWORD itertools
383.394 -KEYWORD javapath
383.395 -KEYWORD javashell
383.396 -KEYWORD jreload
383.397 -KEYWORD json
383.398 -KEYWORD keyword
383.399 -KEYWORD lib2to3
383.400 -KEYWORD linecache
383.401 -KEYWORD locale
383.402 -KEYWORD logging
383.403 -KEYWORD logging.config
383.404 -KEYWORD logging.handlers
383.405 -KEYWORD ---macerrors ---
383.406 -KEYWORD ---macostools ---
383.407 -KEYWORD macpath
383.408 -KEYWORD ---macresource ---
383.409 -KEYWORD macurl2path
383.410 -KEYWORD mailbox
383.411 -KEYWORD mailcap
383.412 -KEYWORD markupbase
383.413 -KEYWORD marshal
383.414 -KEYWORD math
383.415 -KEYWORD ---md5 ---
383.416 -KEYWORD mhlib
383.417 -KEYWORD ---mimetools ---
383.418 -KEYWORD mimetypes
383.419 -KEYWORD ---mimify ---
383.420 -KEYWORD mmap
383.421 -KEYWORD modulefinder
383.422 -KEYWORD msilib
383.423 -KEYWORD msvcrt
383.424 -KEYWORD ---multifile ---
383.425 -KEYWORD multiprocessing
383.426 -KEYWORD multiprocessing.connection
383.427 -KEYWORD multiprocessing.dummy
383.428 -KEYWORD multiprocessing.managers
383.429 -KEYWORD multiprocessing.pool
383.430 -KEYWORD multiprocessing.sharedctypes
383.431 -KEYWORD mutex
383.432 -KEYWORD netrc
383.433 -KEYWORD new
383.434 -KEYWORD nis
383.435 -KEYWORD nntplib
383.436 -KEYWORD ntpath
383.437 -KEYWORD nturl2path
383.438 -KEYWORD numbers
383.439 -KEYWORD occurrences2
383.440 -KEYWORD opcode
383.441 -KEYWORD operator
383.442 -KEYWORD optparse
383.443 -KEYWORD os
383.444 -KEYWORD os.path
383.445 -KEYWORD ossaudiodev
383.446 -KEYWORD parser
383.447 -KEYWORD pawt
383.448 -KEYWORD pawt.colors
383.449 -KEYWORD pawt.swing
383.450 -KEYWORD pdb
383.451 -KEYWORD pickle
383.452 -KEYWORD pickletools
383.453 -KEYWORD pipes
383.454 -KEYWORD pkgutil
383.455 -KEYWORD platform
383.456 -KEYWORD plistlib
383.457 -KEYWORD popen2
383.458 -KEYWORD poplib
383.459 -KEYWORD posix
383.460 -KEYWORD ---posixfile ---
383.461 -KEYWORD posixpath
383.462 -KEYWORD pprint
383.463 -KEYWORD profile
383.464 -KEYWORD pstats
383.465 -KEYWORD pty
383.466 -KEYWORD pwd
383.467 -KEYWORD py_compile
383.468 -KEYWORD pyclbr
383.469 -KEYWORD pydoc
383.470 -KEYWORD quopri
383.471 -KEYWORD random
383.472 -KEYWORD re
383.473 -KEYWORD readline
383.474 -KEYWORD repr
383.475 -KEYWORD resource
383.476 -KEYWORD ---rexec ---
383.477 -KEYWORD ---rfc822 ---
383.478 -KEYWORD rlcompleter
383.479 -KEYWORD robotparser
383.480 -KEYWORD runpy
383.481 -KEYWORD sched
383.482 -KEYWORD select
383.483 -KEYWORD ---sets ---
383.484 -KEYWORD sgmllib
383.485 -KEYWORD ---sha ---
383.486 -KEYWORD shelve
383.487 -KEYWORD shlex
383.488 -KEYWORD shutil
383.489 -KEYWORD signal
383.490 -KEYWORD site
383.491 -KEYWORD smtpd
383.492 -KEYWORD smtplib
383.493 -KEYWORD sndhdr
383.494 -KEYWORD socket
383.495 -KEYWORD spwd
383.496 -KEYWORD sqlite3
383.497 -KEYWORD sre
383.498 -KEYWORD sre_compile
383.499 -KEYWORD sre_constants
383.500 -KEYWORD sre_parse
383.501 -KEYWORD ssl
383.502 -KEYWORD stat
383.503 -KEYWORD ---statvfs ---
383.504 -KEYWORD stdtypes
383.505 -KEYWORD string
383.506 -KEYWORD ---stringprep ---
383.507 -KEYWORD struct
383.508 -KEYWORD subprocess
383.509 -KEYWORD symbol
383.510 -KEYWORD symtable
383.511 -KEYWORD sys
383.512 -KEYWORD syslog
383.513 -KEYWORD tabnanny
383.514 -KEYWORD tarfile
383.515 -KEYWORD telnetlib
383.516 -KEYWORD tempfile
383.517 -KEYWORD termios
383.518 -KEYWORD test.bugs.bugs100
383.519 -KEYWORD test.bugs.bugs101
383.520 -KEYWORD test.bugs.jdkbugs
383.521 -KEYWORD test.bugs.pr101
383.522 -KEYWORD test.bugs.pr104
383.523 -KEYWORD test.bugs.pr112
383.524 -KEYWORD test.bugs.pr119
383.525 -KEYWORD test.bugs.pr127
383.526 -KEYWORD test.bugs.pr133
383.527 -KEYWORD test.bugs.pr133.test
383.528 -KEYWORD test.bugs.pr134
383.529 -KEYWORD test.bugs.pr139
383.530 -KEYWORD test.bugs.pr142
383.531 -KEYWORD test.bugs.pr144
383.532 -KEYWORD test.bugs.pr148
383.533 -KEYWORD test.bugs.pr149
383.534 -KEYWORD test.bugs.pr155
383.535 -KEYWORD test.bugs.pr170
383.536 -KEYWORD test.bugs.pr171
383.537 -KEYWORD test.bugs.pr174
383.538 -KEYWORD test.bugs.pr178
383.539 -KEYWORD test.bugs.pr183
383.540 -KEYWORD test.bugs.pr186
383.541 -KEYWORD test.bugs.pr191
383.542 -KEYWORD test.bugs.pr192
383.543 -KEYWORD test.bugs.pr195
383.544 -KEYWORD test.bugs.pr208
383.545 -KEYWORD test.bugs.pr233
383.546 -KEYWORD test.bugs.pr234
383.547 -KEYWORD test.bugs.pr235
383.548 -KEYWORD test.bugs.pr239
383.549 -KEYWORD test.bugs.pr241
383.550 -KEYWORD test.bugs.pr242
383.551 -KEYWORD test.crashers.bogus_code_obj
383.552 -KEYWORD test.crashers.borrowed_ref_1
383.553 -KEYWORD test.crashers.borrowed_ref_2
383.554 -KEYWORD test.crashers.gc_inspection
383.555 -KEYWORD test.crashers.infinite_rec_1
383.556 -KEYWORD test.crashers.infinite_rec_2
383.557 -KEYWORD test.crashers.infinite_rec_4
383.558 -KEYWORD test.crashers.infinite_rec_5
383.559 -KEYWORD test.crashers.loosing_dict_ref
383.560 -KEYWORD test.crashers.nasty_eq_vs_dict
383.561 -KEYWORD test.crashers.recursion_limit_
383.562 -KEYWORD test.crashers.recursive_call
383.563 -KEYWORD test.leakers
383.564 -KEYWORD test.leakers.test_ctypes
383.565 -KEYWORD test.leakers.test_gestalt
383.566 -KEYWORD test.leakers.test_selftype
383.567 -KEYWORD test.test_metaclass_support
383.568 -KEYWORD test.test_metaclass_support.me
383.569 -KEYWORD test.test_metaclass_support.si
383.570 -KEYWORD test.xmltests
383.571 -KEYWORD test.zxjdbc.dbextstest
383.572 -KEYWORD test.zxjdbc.jndi
383.573 -KEYWORD test.zxjdbc.runner
383.574 -KEYWORD test.zxjdbc.sptest
383.575 -KEYWORD test.zxjdbc.test_zxjdbc_dbapi2
383.576 -KEYWORD test.zxjdbc.zxtest
383.577 -KEYWORD textwrap
383.578 -KEYWORD this
383.579 -KEYWORD thread
383.580 -KEYWORD threading
383.581 -KEYWORD time
383.582 -KEYWORD timeit
383.583 -KEYWORD token
383.584 -KEYWORD tokenize
383.585 -KEYWORD trace
383.586 -KEYWORD traceback
383.587 -KEYWORD tty
383.588 -KEYWORD turtle
383.589 -KEYWORD types
383.590 -KEYWORD unicodedata
383.591 -KEYWORD unittest
383.592 -KEYWORD urllib
383.593 -KEYWORD urllib2
383.594 -KEYWORD urlparse
383.595 -KEYWORD user
383.596 -KEYWORD uu
383.597 -KEYWORD uuid
383.598 -KEYWORD ---videoreader ---
383.599 -KEYWORD warnings
383.600 -KEYWORD wave
383.601 -KEYWORD weakref
383.602 -KEYWORD webbrowser
383.603 -KEYWORD whichdb
383.604 -KEYWORD winsound
383.605 -KEYWORD wsgiref
383.606 -KEYWORD wsgiref.handlers
383.607 -KEYWORD wsgiref.headers
383.608 -KEYWORD wsgiref.simple_server
383.609 -KEYWORD wsgiref.util
383.610 -KEYWORD wsgiref.validate
383.611 -KEYWORD xdrlib
383.612 -KEYWORD xml
383.613 -KEYWORD xml.FtCore
383.614 -KEYWORD xml.Uri
383.615 -KEYWORD xml.dom
383.616 -KEYWORD xml.dom.MessageSource
383.617 -KEYWORD xml.dom.NodeFilter
383.618 -KEYWORD xml.dom.domreg
383.619 -KEYWORD xml.dom.minicompat
383.620 -KEYWORD xml.dom.minidom
383.621 -KEYWORD xml.dom.pulldom
383.622 -KEYWORD xml.dom.xmlbuilder
383.623 -KEYWORD xml.etree
383.624 -KEYWORD xml.etree.ElementTree
383.625 -KEYWORD xml.parsers.expat
383.626 -KEYWORD xml.sax
383.627 -KEYWORD xml.sax._exceptions
383.628 -KEYWORD xml.sax.drivers2
383.629 -KEYWORD xml.sax.drivers2.drv_javasax
383.630 -KEYWORD xml.sax.handler
383.631 -KEYWORD xml.sax.saxlib
383.632 -KEYWORD xml.sax.saxutils
383.633 -KEYWORD xml.sax.xmlreader
383.634 -KEYWORD xmllib
383.635 -KEYWORD xmlrpclib
383.636 -KEYWORD zipfile
383.637 -KEYWORD zipimport
383.638 -KEYWORD zlib
384.1 --- a/python.editor/test/unit/data/testfiles/imports5.py Sun Jan 04 13:11:53 2015 -0600
384.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
384.3 @@ -1,1 +0,0 @@
384.4 -import im
385.1 --- a/python.editor/test/unit/data/testfiles/imports5.py.testImports5.completion Sun Jan 04 13:11:53 2015 -0600
385.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
385.3 @@ -1,22 +0,0 @@
385.4 -Code completion result for source line:
385.5 -import i|m
385.6 -(QueryType=COMPLETION, NameKind=PREFIX)
385.7 -------------------------------------
385.8 -KEYWORD ---ic ---
385.9 -KEYWORD ---icopen ---
385.10 -KEYWORD ihooks
385.11 -KEYWORD ---imageop ---
385.12 -KEYWORD imaplib
385.13 -KEYWORD imghdr
385.14 -KEYWORD imp
385.15 -KEYWORD imports3
385.16 -KEYWORD imports4
385.17 -KEYWORD imports5
385.18 -KEYWORD imports7
385.19 -KEYWORD imports8
385.20 -KEYWORD imports9
385.21 -KEYWORD ---imputil ---
385.22 -KEYWORD inspect
385.23 -KEYWORD io
385.24 -KEYWORD isql
385.25 -KEYWORD itertools
386.1 --- a/python.editor/test/unit/data/testfiles/imports6.py Sun Jan 04 13:11:53 2015 -0600
386.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
386.3 @@ -1,1 +0,0 @@
386.4 -from i
387.1 --- a/python.editor/test/unit/data/testfiles/imports6.py.testImports6.completion Sun Jan 04 13:11:53 2015 -0600
387.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
387.3 @@ -1,637 +0,0 @@
387.4 -Code completion result for source line:
387.5 -from |i
387.6 -(QueryType=COMPLETION, NameKind=PREFIX)
387.7 -------------------------------------
387.8 -KEYWORD BaseHTTPServer
387.9 -KEYWORD ---Bastion ---
387.10 -KEYWORD CGIHTTPServer
387.11 -KEYWORD ---Carbon.AE ---
387.12 -KEYWORD ---Carbon.AH ---
387.13 -KEYWORD ---Carbon.App ---
387.14 -KEYWORD ---Carbon.CF ---
387.15 -KEYWORD ---Carbon.CG ---
387.16 -KEYWORD ---Carbon.CarbonEvt ---
387.17 -KEYWORD ---Carbon.Cm ---
387.18 -KEYWORD ---Carbon.Ctl ---
387.19 -KEYWORD ---Carbon.Dlg ---
387.20 -KEYWORD ---Carbon.Evt ---
387.21 -KEYWORD ---Carbon.Fm ---
387.22 -KEYWORD ---Carbon.Folder ---
387.23 -KEYWORD ---Carbon.Help ---
387.24 -KEYWORD ---Carbon.List ---
387.25 -KEYWORD ---Carbon.Menu ---
387.26 -KEYWORD ---Carbon.Mlte ---
387.27 -KEYWORD ---Carbon.Qd ---
387.28 -KEYWORD ---Carbon.Qdoffs ---
387.29 -KEYWORD ---Carbon.Qt ---
387.30 -KEYWORD ---Carbon.Res ---
387.31 -KEYWORD ---Carbon.Scrap ---
387.32 -KEYWORD ---Carbon.Snd ---
387.33 -KEYWORD ---Carbon.TE ---
387.34 -KEYWORD ---Carbon.Win ---
387.35 -KEYWORD ---ColorPicker ---
387.36 -KEYWORD ConfigParser
387.37 -KEYWORD Cookie
387.38 -KEYWORD DocXMLRPCServer
387.39 -KEYWORD ---EasyDialogs ---
387.40 -KEYWORD ---FrameWork ---
387.41 -KEYWORD HTMLParser
387.42 -KEYWORD ---MacOS ---
387.43 -KEYWORD ---MimeWriter ---
387.44 -KEYWORD MiniAEFrame
387.45 -KEYWORD ---Nav ---
387.46 -KEYWORD ---PixMapWrapper ---
387.47 -KEYWORD Queue
387.48 -KEYWORD ScrolledText
387.49 -KEYWORD SimpleHTTPServer
387.50 -KEYWORD SimpleXMLRPCServer
387.51 -KEYWORD SocketServer
387.52 -KEYWORD StringIO
387.53 -KEYWORD Tix
387.54 -KEYWORD Tkinter
387.55 -KEYWORD UserDict
387.56 -KEYWORD UserList
387.57 -KEYWORD UserString
387.58 -KEYWORD ---W ---
387.59 -KEYWORD _LWPCookieJar
387.60 -KEYWORD _MozillaCookieJar
387.61 -KEYWORD __builtin__
387.62 -KEYWORD __future__
387.63 -KEYWORD __main__
387.64 -KEYWORD _ast
387.65 -KEYWORD _rawffi
387.66 -KEYWORD _strptime
387.67 -KEYWORD _threading_local
387.68 -KEYWORD _winreg
387.69 -KEYWORD abc
387.70 -KEYWORD ---aepack ---
387.71 -KEYWORD ---aetools ---
387.72 -KEYWORD ---aetypes ---
387.73 -KEYWORD aifc
387.74 -KEYWORD anydbm
387.75 -KEYWORD ---applesingle ---
387.76 -KEYWORD array
387.77 -KEYWORD ast
387.78 -KEYWORD asynchat
387.79 -KEYWORD asyncore
387.80 -KEYWORD atexit
387.81 -KEYWORD audioop
387.82 -KEYWORD ---autoGIL ---
387.83 -KEYWORD base64
387.84 -KEYWORD bdb
387.85 -KEYWORD binascii
387.86 -KEYWORD binhex
387.87 -KEYWORD bisect
387.88 -KEYWORD bsddb
387.89 -KEYWORD ---buildtools ---
387.90 -KEYWORD bz2
387.91 -KEYWORD calendar
387.92 -KEYWORD ---cfmfile ---
387.93 -KEYWORD cgi
387.94 -KEYWORD cgitb
387.95 -KEYWORD chunk
387.96 -KEYWORD cmath
387.97 -KEYWORD cmd
387.98 -KEYWORD code
387.99 -KEYWORD codecs
387.100 -KEYWORD codeop
387.101 -KEYWORD collections
387.102 -KEYWORD colorsys
387.103 -KEYWORD commands
387.104 -KEYWORD compileall
387.105 -KEYWORD compiler
387.106 -KEYWORD compiler.ast
387.107 -KEYWORD compiler.consts
387.108 -KEYWORD compiler.future
387.109 -KEYWORD compiler.misc
387.110 -KEYWORD compiler.pyassem
387.111 -KEYWORD compiler.pycodegen
387.112 -KEYWORD compiler.symbols
387.113 -KEYWORD compiler.syntax
387.114 -KEYWORD compiler.transformer
387.115 -KEYWORD compiler.visitor
387.116 -KEYWORD compl
387.117 -KEYWORD compl2
387.118 -KEYWORD compl3
387.119 -KEYWORD compl4
387.120 -KEYWORD compl5
387.121 -KEYWORD constants
387.122 -KEYWORD contextlib
387.123 -KEYWORD cookielib
387.124 -KEYWORD copy
387.125 -KEYWORD copy_reg
387.126 -KEYWORD crypt
387.127 -KEYWORD csv
387.128 -KEYWORD ctypes
387.129 -KEYWORD curses
387.130 -KEYWORD curses.ascii
387.131 -KEYWORD curses.panel
387.132 -KEYWORD curses.textpad
387.133 -KEYWORD curses.wrapper
387.134 -KEYWORD datetime
387.135 -KEYWORD dbexts
387.136 -KEYWORD dbhash
387.137 -KEYWORD dbm
387.138 -KEYWORD decimal
387.139 -KEYWORD difflib
387.140 -KEYWORD dircache
387.141 -KEYWORD dis
387.142 -KEYWORD distutils
387.143 -KEYWORD distutils.archive_util
387.144 -KEYWORD distutils.bcppcompiler
387.145 -KEYWORD distutils.ccompiler
387.146 -KEYWORD distutils.cmd
387.147 -KEYWORD distutils.command
387.148 -KEYWORD distutils.command.bdist
387.149 -KEYWORD distutils.command.bdist_dumb
387.150 -KEYWORD distutils.command.bdist_msi
387.151 -KEYWORD distutils.command.bdist_rpm
387.152 -KEYWORD distutils.command.bdist_winins
387.153 -KEYWORD distutils.command.build
387.154 -KEYWORD distutils.command.build_clib
387.155 -KEYWORD distutils.command.build_ext
387.156 -KEYWORD distutils.command.build_py
387.157 -KEYWORD distutils.command.build_script
387.158 -KEYWORD distutils.command.clean
387.159 -KEYWORD distutils.command.config
387.160 -KEYWORD distutils.command.install
387.161 -KEYWORD distutils.command.install_data
387.162 -KEYWORD distutils.command.install_egg_
387.163 -KEYWORD distutils.command.install_head
387.164 -KEYWORD distutils.command.install_lib
387.165 -KEYWORD distutils.command.install_scri
387.166 -KEYWORD distutils.command.register
387.167 -KEYWORD distutils.command.sdist
387.168 -KEYWORD distutils.command.upload
387.169 -KEYWORD distutils.core
387.170 -KEYWORD distutils.cygwinccompiler
387.171 -KEYWORD distutils.debug
387.172 -KEYWORD distutils.dep_util
387.173 -KEYWORD distutils.dir_util
387.174 -KEYWORD distutils.dist
387.175 -KEYWORD distutils.emxccompiler
387.176 -KEYWORD distutils.errors
387.177 -KEYWORD distutils.extension
387.178 -KEYWORD distutils.fancy_getopt
387.179 -KEYWORD distutils.file_util
387.180 -KEYWORD distutils.filelist
387.181 -KEYWORD distutils.jythoncompiler
387.182 -KEYWORD distutils.log
387.183 -KEYWORD distutils.msvccompiler
387.184 -KEYWORD distutils.mwerkscompiler
387.185 -KEYWORD distutils.spawn
387.186 -KEYWORD distutils.sysconfig
387.187 -KEYWORD distutils.tests
387.188 -KEYWORD distutils.tests.support
387.189 -KEYWORD distutils.tests.test_build_py
387.190 -KEYWORD distutils.tests.test_build_scr
387.191 -KEYWORD distutils.tests.test_dist
387.192 -KEYWORD distutils.tests.test_install
387.193 -KEYWORD distutils.tests.test_install_s
387.194 -KEYWORD distutils.tests.test_versionpr
387.195 -KEYWORD distutils.text_file
387.196 -KEYWORD distutils.unixccompiler
387.197 -KEYWORD distutils.util
387.198 -KEYWORD distutils.version
387.199 -KEYWORD distutils.versionpredicate
387.200 -KEYWORD ---dl ---
387.201 -KEYWORD doctest
387.202 -KEYWORD dumbdbm
387.203 -KEYWORD dummy_thread
387.204 -KEYWORD dummy_threading
387.205 -KEYWORD email
387.206 -KEYWORD email._parseaddr
387.207 -KEYWORD email.base64mime
387.208 -KEYWORD email.charset
387.209 -KEYWORD email.encoders
387.210 -KEYWORD email.errors
387.211 -KEYWORD email.feedparser
387.212 -KEYWORD email.generator
387.213 -KEYWORD email.header
387.214 -KEYWORD email.iterators
387.215 -KEYWORD email.message
387.216 -KEYWORD email.mime
387.217 -KEYWORD email.mime.application
387.218 -KEYWORD email.mime.audio
387.219 -KEYWORD email.mime.base
387.220 -KEYWORD email.mime.image
387.221 -KEYWORD email.mime.message
387.222 -KEYWORD email.mime.multipart
387.223 -KEYWORD email.mime.nonmultipart
387.224 -KEYWORD email.mime.text
387.225 -KEYWORD email.parser
387.226 -KEYWORD email.quoprimime
387.227 -KEYWORD email.test.test_email_torture
387.228 -KEYWORD email.utils
387.229 -KEYWORD encodings
387.230 -KEYWORD encodings.aliases
387.231 -KEYWORD encodings.ascii
387.232 -KEYWORD encodings.base64_codec
387.233 -KEYWORD encodings.big5
387.234 -KEYWORD encodings.big5hkscs
387.235 -KEYWORD encodings.bz2_codec
387.236 -KEYWORD encodings.charmap
387.237 -KEYWORD encodings.cp037
387.238 -KEYWORD encodings.cp1006
387.239 -KEYWORD encodings.cp1026
387.240 -KEYWORD encodings.cp1140
387.241 -KEYWORD encodings.cp1250
387.242 -KEYWORD encodings.cp1251
387.243 -KEYWORD encodings.cp1252
387.244 -KEYWORD encodings.cp1253
387.245 -KEYWORD encodings.cp1254
387.246 -KEYWORD encodings.cp1255
387.247 -KEYWORD encodings.cp1256
387.248 -KEYWORD encodings.cp1257
387.249 -KEYWORD encodings.cp1258
387.250 -KEYWORD encodings.cp424
387.251 -KEYWORD encodings.cp437
387.252 -KEYWORD encodings.cp500
387.253 -KEYWORD encodings.cp737
387.254 -KEYWORD encodings.cp775
387.255 -KEYWORD encodings.cp850
387.256 -KEYWORD encodings.cp852
387.257 -KEYWORD encodings.cp855
387.258 -KEYWORD encodings.cp856
387.259 -KEYWORD encodings.cp857
387.260 -KEYWORD encodings.cp860
387.261 -KEYWORD encodings.cp861
387.262 -KEYWORD encodings.cp862
387.263 -KEYWORD encodings.cp863
387.264 -KEYWORD encodings.cp864
387.265 -KEYWORD encodings.cp865
387.266 -KEYWORD encodings.cp866
387.267 -KEYWORD encodings.cp869
387.268 -KEYWORD encodings.cp874
387.269 -KEYWORD encodings.cp875
387.270 -KEYWORD encodings.cp932
387.271 -KEYWORD encodings.cp949
387.272 -KEYWORD encodings.cp950
387.273 -KEYWORD encodings.euc_jis_2004
387.274 -KEYWORD encodings.euc_jisx0213
387.275 -KEYWORD encodings.euc_jp
387.276 -KEYWORD encodings.euc_kr
387.277 -KEYWORD encodings.gb18030
387.278 -KEYWORD encodings.gb2312
387.279 -KEYWORD encodings.gbk
387.280 -KEYWORD encodings.hex_codec
387.281 -KEYWORD encodings.hp_roman8
387.282 -KEYWORD encodings.hz
387.283 -KEYWORD encodings.idna
387.284 -KEYWORD encodings.iso2022_jp
387.285 -KEYWORD encodings.iso2022_jp_1
387.286 -KEYWORD encodings.iso2022_jp_2
387.287 -KEYWORD encodings.iso2022_jp_2004
387.288 -KEYWORD encodings.iso2022_jp_3
387.289 -KEYWORD encodings.iso2022_jp_ext
387.290 -KEYWORD encodings.iso2022_kr
387.291 -KEYWORD encodings.iso8859_1
387.292 -KEYWORD encodings.iso8859_10
387.293 -KEYWORD encodings.iso8859_11
387.294 -KEYWORD encodings.iso8859_13
387.295 -KEYWORD encodings.iso8859_14
387.296 -KEYWORD encodings.iso8859_15
387.297 -KEYWORD encodings.iso8859_16
387.298 -KEYWORD encodings.iso8859_2
387.299 -KEYWORD encodings.iso8859_3
387.300 -KEYWORD encodings.iso8859_4
387.301 -KEYWORD encodings.iso8859_5
387.302 -KEYWORD encodings.iso8859_6
387.303 -KEYWORD encodings.iso8859_7
387.304 -KEYWORD encodings.iso8859_8
387.305 -KEYWORD encodings.iso8859_9
387.306 -KEYWORD encodings.johab
387.307 -KEYWORD encodings.koi8_r
387.308 -KEYWORD encodings.koi8_u
387.309 -KEYWORD encodings.latin_1
387.310 -KEYWORD encodings.mac_arabic
387.311 -KEYWORD encodings.mac_centeuro
387.312 -KEYWORD encodings.mac_croatian
387.313 -KEYWORD encodings.mac_cyrillic
387.314 -KEYWORD encodings.mac_farsi
387.315 -KEYWORD encodings.mac_greek
387.316 -KEYWORD encodings.mac_iceland
387.317 -KEYWORD encodings.mac_latin2
387.318 -KEYWORD encodings.mac_roman
387.319 -KEYWORD encodings.mac_romanian
387.320 -KEYWORD encodings.mac_turkish
387.321 -KEYWORD encodings.mbcs
387.322 -KEYWORD encodings.palmos
387.323 -KEYWORD encodings.ptcp154
387.324 -KEYWORD encodings.punycode
387.325 -KEYWORD encodings.quopri_codec
387.326 -KEYWORD encodings.raw_unicode_escape
387.327 -KEYWORD encodings.rot_13
387.328 -KEYWORD encodings.shift_jis
387.329 -KEYWORD encodings.shift_jis_2004
387.330 -KEYWORD encodings.shift_jisx0213
387.331 -KEYWORD encodings.string_escape
387.332 -KEYWORD encodings.tis_620
387.333 -KEYWORD encodings.undefined
387.334 -KEYWORD encodings.unicode_escape
387.335 -KEYWORD encodings.unicode_internal
387.336 -KEYWORD encodings.utf_16
387.337 -KEYWORD encodings.utf_16_be
387.338 -KEYWORD encodings.utf_16_le
387.339 -KEYWORD encodings.utf_7
387.340 -KEYWORD encodings.utf_8
387.341 -KEYWORD encodings.utf_8_sig
387.342 -KEYWORD encodings.uu_codec
387.343 -KEYWORD encodings.zlib_codec
387.344 -KEYWORD errno
387.345 -KEYWORD exceptions
387.346 -KEYWORD fcntl
387.347 -KEYWORD filecmp
387.348 -KEYWORD fileinput
387.349 -KEYWORD findertools
387.350 -KEYWORD fnmatch
387.351 -KEYWORD formatter
387.352 -KEYWORD fpectl
387.353 -KEYWORD fpformat
387.354 -KEYWORD fractions
387.355 -KEYWORD ftplib
387.356 -KEYWORD functions
387.357 -KEYWORD functools
387.358 -KEYWORD future_builtins
387.359 -KEYWORD gc
387.360 -KEYWORD gdbm
387.361 -KEYWORD gensuitemodule
387.362 -KEYWORD getopt
387.363 -KEYWORD getpass
387.364 -KEYWORD gettext
387.365 -KEYWORD glob
387.366 -KEYWORD ---gopherlib ---
387.367 -KEYWORD grp
387.368 -KEYWORD gzip
387.369 -KEYWORD hashlib
387.370 -KEYWORD heapq
387.371 -KEYWORD hmac
387.372 -KEYWORD hotshot
387.373 -KEYWORD hotshot.stats
387.374 -KEYWORD htmlentitydefs
387.375 -KEYWORD htmllib
387.376 -KEYWORD httplib
387.377 -KEYWORD ---ic ---
387.378 -KEYWORD ---icopen ---
387.379 -KEYWORD ihooks
387.380 -KEYWORD ---imageop ---
387.381 -KEYWORD imaplib
387.382 -KEYWORD imghdr
387.383 -KEYWORD imp
387.384 -KEYWORD imports3
387.385 -KEYWORD imports4
387.386 -KEYWORD imports5
387.387 -KEYWORD imports6
387.388 -KEYWORD imports7
387.389 -KEYWORD imports8
387.390 -KEYWORD imports9
387.391 -KEYWORD ---imputil ---
387.392 -KEYWORD inspect
387.393 -KEYWORD io
387.394 -KEYWORD isql
387.395 -KEYWORD itertools
387.396 -KEYWORD javapath
387.397 -KEYWORD javashell
387.398 -KEYWORD jreload
387.399 -KEYWORD json
387.400 -KEYWORD keyword
387.401 -KEYWORD lib2to3
387.402 -KEYWORD linecache
387.403 -KEYWORD locale
387.404 -KEYWORD logging
387.405 -KEYWORD logging.config
387.406 -KEYWORD logging.handlers
387.407 -KEYWORD ---macerrors ---
387.408 -KEYWORD ---macostools ---
387.409 -KEYWORD macpath
387.410 -KEYWORD ---macresource ---
387.411 -KEYWORD macurl2path
387.412 -KEYWORD mailbox
387.413 -KEYWORD mailcap
387.414 -KEYWORD markupbase
387.415 -KEYWORD marshal
387.416 -KEYWORD math
387.417 -KEYWORD ---md5 ---
387.418 -KEYWORD mhlib
387.419 -KEYWORD ---mimetools ---
387.420 -KEYWORD mimetypes
387.421 -KEYWORD ---mimify ---
387.422 -KEYWORD mmap
387.423 -KEYWORD modulefinder
387.424 -KEYWORD msilib
387.425 -KEYWORD msvcrt
387.426 -KEYWORD ---multifile ---
387.427 -KEYWORD multiprocessing
387.428 -KEYWORD multiprocessing.connection
387.429 -KEYWORD multiprocessing.dummy
387.430 -KEYWORD multiprocessing.managers
387.431 -KEYWORD multiprocessing.pool
387.432 -KEYWORD multiprocessing.sharedctypes
387.433 -KEYWORD mutex
387.434 -KEYWORD netrc
387.435 -KEYWORD new
387.436 -KEYWORD nis
387.437 -KEYWORD nntplib
387.438 -KEYWORD ntpath
387.439 -KEYWORD nturl2path
387.440 -KEYWORD numbers
387.441 -KEYWORD occurrences2
387.442 -KEYWORD opcode
387.443 -KEYWORD operator
387.444 -KEYWORD optparse
387.445 -KEYWORD os
387.446 -KEYWORD os.path
387.447 -KEYWORD ossaudiodev
387.448 -KEYWORD parser
387.449 -KEYWORD pawt
387.450 -KEYWORD pawt.colors
387.451 -KEYWORD pawt.swing
387.452 -KEYWORD pdb
387.453 -KEYWORD pickle
387.454 -KEYWORD pickletools
387.455 -KEYWORD pipes
387.456 -KEYWORD pkgutil
387.457 -KEYWORD platform
387.458 -KEYWORD plistlib
387.459 -KEYWORD popen2
387.460 -KEYWORD poplib
387.461 -KEYWORD posix
387.462 -KEYWORD ---posixfile ---
387.463 -KEYWORD posixpath
387.464 -KEYWORD pprint
387.465 -KEYWORD profile
387.466 -KEYWORD pstats
387.467 -KEYWORD pty
387.468 -KEYWORD pwd
387.469 -KEYWORD py_compile
387.470 -KEYWORD pyclbr
387.471 -KEYWORD pydoc
387.472 -KEYWORD quopri
387.473 -KEYWORD random
387.474 -KEYWORD re
387.475 -KEYWORD readline
387.476 -KEYWORD repr
387.477 -KEYWORD resource
387.478 -KEYWORD ---rexec ---
387.479 -KEYWORD ---rfc822 ---
387.480 -KEYWORD rlcompleter
387.481 -KEYWORD robotparser
387.482 -KEYWORD runpy
387.483 -KEYWORD sched
387.484 -KEYWORD select
387.485 -KEYWORD ---sets ---
387.486 -KEYWORD sgmllib
387.487 -KEYWORD ---sha ---
387.488 -KEYWORD shelve
387.489 -KEYWORD shlex
387.490 -KEYWORD shutil
387.491 -KEYWORD signal
387.492 -KEYWORD site
387.493 -KEYWORD smtpd
387.494 -KEYWORD smtplib
387.495 -KEYWORD sndhdr
387.496 -KEYWORD socket
387.497 -KEYWORD spwd
387.498 -KEYWORD sqlite3
387.499 -KEYWORD sre
387.500 -KEYWORD sre_compile
387.501 -KEYWORD sre_constants
387.502 -KEYWORD sre_parse
387.503 -KEYWORD ssl
387.504 -KEYWORD stat
387.505 -KEYWORD ---statvfs ---
387.506 -KEYWORD stdtypes
387.507 -KEYWORD string
387.508 -KEYWORD ---stringprep ---
387.509 -KEYWORD struct
387.510 -KEYWORD subprocess
387.511 -KEYWORD symbol
387.512 -KEYWORD symtable
387.513 -KEYWORD sys
387.514 -KEYWORD syslog
387.515 -KEYWORD tabnanny
387.516 -KEYWORD tarfile
387.517 -KEYWORD telnetlib
387.518 -KEYWORD tempfile
387.519 -KEYWORD termios
387.520 -KEYWORD test.bugs.bugs100
387.521 -KEYWORD test.bugs.bugs101
387.522 -KEYWORD test.bugs.jdkbugs
387.523 -KEYWORD test.bugs.pr101
387.524 -KEYWORD test.bugs.pr104
387.525 -KEYWORD test.bugs.pr112
387.526 -KEYWORD test.bugs.pr119
387.527 -KEYWORD test.bugs.pr127
387.528 -KEYWORD test.bugs.pr133
387.529 -KEYWORD test.bugs.pr133.test
387.530 -KEYWORD test.bugs.pr134
387.531 -KEYWORD test.bugs.pr139
387.532 -KEYWORD test.bugs.pr142
387.533 -KEYWORD test.bugs.pr144
387.534 -KEYWORD test.bugs.pr148
387.535 -KEYWORD test.bugs.pr149
387.536 -KEYWORD test.bugs.pr155
387.537 -KEYWORD test.bugs.pr170
387.538 -KEYWORD test.bugs.pr171
387.539 -KEYWORD test.bugs.pr174
387.540 -KEYWORD test.bugs.pr178
387.541 -KEYWORD test.bugs.pr183
387.542 -KEYWORD test.bugs.pr186
387.543 -KEYWORD test.bugs.pr191
387.544 -KEYWORD test.bugs.pr192
387.545 -KEYWORD test.bugs.pr195
387.546 -KEYWORD test.bugs.pr208
387.547 -KEYWORD test.bugs.pr233
387.548 -KEYWORD test.bugs.pr234
387.549 -KEYWORD test.bugs.pr235
387.550 -KEYWORD test.bugs.pr239
387.551 -KEYWORD test.bugs.pr241
387.552 -KEYWORD test.bugs.pr242
387.553 -KEYWORD test.crashers.bogus_code_obj
387.554 -KEYWORD test.crashers.borrowed_ref_1
387.555 -KEYWORD test.crashers.borrowed_ref_2
387.556 -KEYWORD test.crashers.gc_inspection
387.557 -KEYWORD test.crashers.infinite_rec_1
387.558 -KEYWORD test.crashers.infinite_rec_2
387.559 -KEYWORD test.crashers.infinite_rec_4
387.560 -KEYWORD test.crashers.infinite_rec_5
387.561 -KEYWORD test.crashers.loosing_dict_ref
387.562 -KEYWORD test.crashers.nasty_eq_vs_dict
387.563 -KEYWORD test.crashers.recursion_limit_
387.564 -KEYWORD test.crashers.recursive_call
387.565 -KEYWORD test.leakers
387.566 -KEYWORD test.leakers.test_ctypes
387.567 -KEYWORD test.leakers.test_gestalt
387.568 -KEYWORD test.leakers.test_selftype
387.569 -KEYWORD test.test_metaclass_support
387.570 -KEYWORD test.test_metaclass_support.me
387.571 -KEYWORD test.test_metaclass_support.si
387.572 -KEYWORD test.xmltests
387.573 -KEYWORD test.zxjdbc.dbextstest
387.574 -KEYWORD test.zxjdbc.jndi
387.575 -KEYWORD test.zxjdbc.runner
387.576 -KEYWORD test.zxjdbc.sptest
387.577 -KEYWORD test.zxjdbc.test_zxjdbc_dbapi2
387.578 -KEYWORD test.zxjdbc.zxtest
387.579 -KEYWORD textwrap
387.580 -KEYWORD this
387.581 -KEYWORD thread
387.582 -KEYWORD threading
387.583 -KEYWORD time
387.584 -KEYWORD timeit
387.585 -KEYWORD token
387.586 -KEYWORD tokenize
387.587 -KEYWORD trace
387.588 -KEYWORD traceback
387.589 -KEYWORD tty
387.590 -KEYWORD turtle
387.591 -KEYWORD types
387.592 -KEYWORD unicodedata
387.593 -KEYWORD unittest
387.594 -KEYWORD urllib
387.595 -KEYWORD urllib2
387.596 -KEYWORD urlparse
387.597 -KEYWORD user
387.598 -KEYWORD uu
387.599 -KEYWORD uuid
387.600 -KEYWORD ---videoreader ---
387.601 -KEYWORD warnings
387.602 -KEYWORD wave
387.603 -KEYWORD weakref
387.604 -KEYWORD webbrowser
387.605 -KEYWORD whichdb
387.606 -KEYWORD winsound
387.607 -KEYWORD wsgiref
387.608 -KEYWORD wsgiref.handlers
387.609 -KEYWORD wsgiref.headers
387.610 -KEYWORD wsgiref.simple_server
387.611 -KEYWORD wsgiref.util
387.612 -KEYWORD wsgiref.validate
387.613 -KEYWORD xdrlib
387.614 -KEYWORD xml
387.615 -KEYWORD xml.FtCore
387.616 -KEYWORD xml.Uri
387.617 -KEYWORD xml.dom
387.618 -KEYWORD xml.dom.MessageSource
387.619 -KEYWORD xml.dom.NodeFilter
387.620 -KEYWORD xml.dom.domreg
387.621 -KEYWORD xml.dom.minicompat
387.622 -KEYWORD xml.dom.minidom
387.623 -KEYWORD xml.dom.pulldom
387.624 -KEYWORD xml.dom.xmlbuilder
387.625 -KEYWORD xml.etree
387.626 -KEYWORD xml.etree.ElementTree
387.627 -KEYWORD xml.parsers.expat
387.628 -KEYWORD xml.sax
387.629 -KEYWORD xml.sax._exceptions
387.630 -KEYWORD xml.sax.drivers2
387.631 -KEYWORD xml.sax.drivers2.drv_javasax
387.632 -KEYWORD xml.sax.handler
387.633 -KEYWORD xml.sax.saxlib
387.634 -KEYWORD xml.sax.saxutils
387.635 -KEYWORD xml.sax.xmlreader
387.636 -KEYWORD xmllib
387.637 -KEYWORD xmlrpclib
387.638 -KEYWORD zipfile
387.639 -KEYWORD zipimport
387.640 -KEYWORD zlib
388.1 --- a/python.editor/test/unit/data/testfiles/imports6.py.testImports6b.completion Sun Jan 04 13:11:53 2015 -0600
388.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
388.3 @@ -1,23 +0,0 @@
388.4 -Code completion result for source line:
388.5 -from i|
388.6 -(QueryType=COMPLETION, NameKind=PREFIX)
388.7 -------------------------------------
388.8 -KEYWORD ---ic ---
388.9 -KEYWORD ---icopen ---
388.10 -KEYWORD ihooks
388.11 -KEYWORD ---imageop ---
388.12 -KEYWORD imaplib
388.13 -KEYWORD imghdr
388.14 -KEYWORD imp
388.15 -KEYWORD imports3
388.16 -KEYWORD imports4
388.17 -KEYWORD imports5
388.18 -KEYWORD imports6
388.19 -KEYWORD imports7
388.20 -KEYWORD imports8
388.21 -KEYWORD imports9
388.22 -KEYWORD ---imputil ---
388.23 -KEYWORD inspect
388.24 -KEYWORD io
388.25 -KEYWORD isql
388.26 -KEYWORD itertools
389.1 --- a/python.editor/test/unit/data/testfiles/imports7.py Sun Jan 04 13:11:53 2015 -0600
389.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
389.3 @@ -1,2 +0,0 @@
389.4 -from sys import r
389.5 -
390.1 --- a/python.editor/test/unit/data/testfiles/imports7.py.testImports7.completion Sun Jan 04 13:11:53 2015 -0600
390.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
390.3 @@ -1,60 +0,0 @@
390.4 -Code completion result for source line:
390.5 -from sys import |r
390.6 -(QueryType=COMPLETION, NameKind=PREFIX)
390.7 -METHOD displayhook(value)
390.8 -METHOD exc_clear()
390.9 -METHOD exc_info()
390.10 -METHOD excepthook(type, value, traceb
390.11 -METHOD exit(arg)
390.12 -METHOD getcheckinterval()
390.13 -METHOD getdefaultencoding()
390.14 -METHOD getdlopenflags()
390.15 -METHOD getfilesystemencoding()
390.16 -METHOD getprofile()
390.17 -METHOD getrecursionlimit()
390.18 -METHOD getrefcount(object)
390.19 -METHOD getsizeof(object, default)
390.20 -METHOD gettrace()
390.21 -METHOD getwindowsversion()
390.22 -METHOD setcheckinterval(interval)
390.23 -METHOD setdefaultencoding(name)
390.24 -METHOD setdlopenflags(n)
390.25 -METHOD setprofile(profilefunc)
390.26 -METHOD setrecursionlimit(limit)
390.27 -METHOD settrace(tracefunc)
390.28 -METHOD settscdump(on_flag)
390.29 -VARIABLE __displayhook__
390.30 -VARIABLE __stdin__
390.31 -VARIABLE api_version
390.32 -VARIABLE argv
390.33 -VARIABLE builtin_module_names
390.34 -VARIABLE byteorder
390.35 -VARIABLE copyright
390.36 -VARIABLE dllhandle
390.37 -VARIABLE dont_write_bytecode
390.38 -VARIABLE ---exc_type ---
390.39 -VARIABLE exec_prefix
390.40 -VARIABLE executable
390.41 -VARIABLE ---exitfunc ---
390.42 -VARIABLE flags
390.43 -VARIABLE float_info
390.44 -VARIABLE hexversion
390.45 -VARIABLE last_type
390.46 -VARIABLE maxint
390.47 -VARIABLE maxsize
390.48 -VARIABLE maxunicode
390.49 -VARIABLE modules
390.50 -VARIABLE path
390.51 -VARIABLE platform
390.52 -VARIABLE prefix
390.53 -VARIABLE ps1
390.54 -VARIABLE py3kwarning
390.55 -VARIABLE stdin
390.56 -VARIABLE subversion
390.57 -VARIABLE tracebacklimit
390.58 -VARIABLE version
390.59 -VARIABLE version_info
390.60 -VARIABLE warnoptions
390.61 -VARIABLE winver
390.62 -------------------------------------
390.63 -KEYWORD * Import All Exported Symbols
391.1 --- a/python.editor/test/unit/data/testfiles/imports8.py Sun Jan 04 13:11:53 2015 -0600
391.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
391.3 @@ -1,2 +0,0 @@
391.4 -import distutils.command
391.5 -
392.1 --- a/python.editor/test/unit/data/testfiles/imports8.py.testImports8.completion Sun Jan 04 13:11:53 2015 -0600
392.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
392.3 @@ -1,26 +0,0 @@
392.4 -Code completion result for source line:
392.5 -import distutils.com|mand
392.6 -(QueryType=COMPLETION, NameKind=PREFIX)
392.7 -------------------------------------
392.8 -KEYWORD distutils.command
392.9 -KEYWORD distutils.command.bdist
392.10 -KEYWORD distutils.command.bdist_dumb
392.11 -KEYWORD distutils.command.bdist_msi
392.12 -KEYWORD distutils.command.bdist_rpm
392.13 -KEYWORD distutils.command.bdist_winins
392.14 -KEYWORD distutils.command.build
392.15 -KEYWORD distutils.command.build_clib
392.16 -KEYWORD distutils.command.build_ext
392.17 -KEYWORD distutils.command.build_py
392.18 -KEYWORD distutils.command.build_script
392.19 -KEYWORD distutils.command.clean
392.20 -KEYWORD distutils.command.config
392.21 -KEYWORD distutils.command.install
392.22 -KEYWORD distutils.command.install_data
392.23 -KEYWORD distutils.command.install_egg_
392.24 -KEYWORD distutils.command.install_head
392.25 -KEYWORD distutils.command.install_lib
392.26 -KEYWORD distutils.command.install_scri
392.27 -KEYWORD distutils.command.register
392.28 -KEYWORD distutils.command.sdist
392.29 -KEYWORD distutils.command.upload
393.1 --- a/python.editor/test/unit/data/testfiles/imports9.py Sun Jan 04 13:11:53 2015 -0600
393.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
393.3 @@ -1,2 +0,0 @@
393.4 -from difflib import c
393.5 -
394.1 --- a/python.editor/test/unit/data/testfiles/imports9.py.testImports9.completion Sun Jan 04 13:11:53 2015 -0600
394.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
394.3 @@ -1,16 +0,0 @@
394.4 -Code completion result for source line:
394.5 -from difflib import |c
394.6 -(QueryType=COMPLETION, NameKind=PREFIX)
394.7 -CLASS Differ
394.8 -CLASS HtmlDiff
394.9 -CLASS SequenceMatcher
394.10 -METHOD IS_CHARACTER_JUNK(ch, ws)
394.11 -METHOD IS_LINE_JUNK(line, pat)
394.12 -METHOD context_diff(a, b, fromfile, t
394.13 -METHOD get_close_matches(word, possib
394.14 -METHOD ndiff(a, b, linejunk, charjunk
394.15 -METHOD restore(delta, which)
394.16 -METHOD unified_diff(a, b, fromfile, t
394.17 -VARIABLE __all__
394.18 -------------------------------------
394.19 -KEYWORD * Import All Exported Symbols
395.1 --- a/python.editor/test/unit/data/testfiles/issue149618.py Sun Jan 04 13:11:53 2015 -0600
395.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
395.3 @@ -1,5 +0,0 @@
395.4 -def loadstable(name,theglobals=None,thelocals=None,fromlist=None,level=-1):
395.5 - if name.split('.')[0]!="tools"
395.6 - print "Python"
395.7 -
395.8 -
396.1 --- a/python.editor/test/unit/data/testfiles/issue149618.py.offsets Sun Jan 04 13:11:53 2015 -0600
396.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
396.3 @@ -1,6 +0,0 @@
396.4 -
396.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>):
396.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>
396.7 - <Print>print <Str>"Python"</Str></Print>
396.8 -
396.9 -</If></FunctionDef></Module>
397.1 --- a/python.editor/test/unit/data/testfiles/jreload.py Sun Jan 04 13:11:53 2015 -0600
397.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
397.3 @@ -1,119 +0,0 @@
397.4 -# java classes reload support (experimental)
397.5 -# Copyright 2000 Samuele Pedroni
397.6 -
397.7 -# ?? could have problem with import pkg.jclass.inner (this should not be used in any case)
397.8 -# ?? using import * with a load-set together with reloading can be confusing
397.9 -# cannot be fixed => anyway import * is not for production code
397.10 -
397.11 -__version__ = "0.3"
397.12 -
397.13 -import sys
397.14 -from org.python.core import imp,PyJavaPackage,PyJavaClass
397.15 -from _jython import is_lazy as _is_lazy
397.16 -
397.17 -import jxxload_help
397.18 -
397.19 -
397.20 -class _LoaderFactory(jxxload_help.JavaLoaderFactory):
397.21 - def __init__(self,path):
397.22 - vfs = jxxload_help.PathVFS()
397.23 - for fname in path:
397.24 - vfs.addVFS(fname)
397.25 - self.vfs = vfs
397.26 -
397.27 - def makeLoader(self):
397.28 - return jxxload_help.PathVFSJavaLoader(self.vfs,imp.getSyspathJavaLoader())
397.29 -
397.30 -class _Unload:
397.31 -
397.32 - def __init__(self,ls):
397.33 - self.ls = ls
397.34 - self.ls_name = ls._name
397.35 - self.loader = ls._mgr.loader
397.36 -
397.37 - def do_unload(self,pkg):
397.38 - for n in pkg.__dict__.keys():
397.39 - e = pkg.__dict__[n]
397.40 - if isinstance(e,PyJavaClass):
397.41 - if _is_lazy(e): continue
397.42 - if e.classLoader is self.loader:
397.43 - del pkg.__dict__[n]
397.44 - if pkg.__name__:
397.45 - n = self.ls_name + '.' + pkg.__name__ + '.' +n
397.46 - else:
397.47 - n = self.ls_name + '.' + n
397.48 - if sys.modules.has_key(n): del sys.modules[n]
397.49 -
397.50 - elif isinstance(e,PyJavaPackage):
397.51 - self.do_unload(e)
397.52 -
397.53 - def __call__(self):
397.54 - if self.loader:
397.55 - if self.ls._mgr.checkLoader() is self.loader:
397.56 - self.do_unload(self.ls._top)
397.57 - self.ls._mgr.resetLoader()
397.58 - loader = self.loader
397.59 - jxxload_help.DiscardHelp.discard(loader,loader.interfaces)
397.60 - self.loader = None
397.61 -
397.62 -class LoadSet:
397.63 -# ?? for the moment from import * and dir do not work for LoadSet, but work for
397.64 -# contained pkgs
397.65 -# need java impl as PyObject
397.66 -
397.67 - def __init__(self,name,path):
397.68 - mgr = jxxload_help.PackageManager(path,_LoaderFactory(path))
397.69 - self._name = name
397.70 - self._mgr = mgr
397.71 - self._top = mgr.topLevelPackage
397.72 -
397.73 - def __getattr__(self,name):
397.74 - try:
397.75 - return getattr(self._top,name)
397.76 - except:
397.77 - if name == 'unload': return _Unload(self)
397.78 - raise
397.79 -
397.80 -
397.81 - def __repr__(self):
397.82 - return "<java load-set %s>" % self._name
397.83 -
397.84 -def unloadf(ls):
397.85 - if not isinstance(ls,LoadSet): raise TypeError,"unloadf(): arg is not a load-set"
397.86 - return _Unload(ls)
397.87 -
397.88 -def makeLoadSet(name,path):
397.89 - if sys.modules.has_key(name): return sys.modules[name]
397.90 - sys.modules[name] = ls = LoadSet(name,path)
397.91 - return ls
397.92 -
397.93 -_reload = reload
397.94 -
397.95 -def _do_reload(ls_name,mgr,pkg):
397.96 - pkg_name = pkg.__name__
397.97 - for n in pkg.__dict__.keys():
397.98 - e = pkg.__dict__[n]
397.99 - if isinstance(e,PyJavaClass):
397.100 - if _is_lazy(e): continue
397.101 - del pkg.__dict__[n]
397.102 - try :
397.103 - c = mgr.findClass(pkg_name,n);
397.104 - if c:
397.105 - pkg.__dict__[n] = c
397.106 - if pkg_name:
397.107 - n = ls_name + '.' + pkg_name + '.' + n
397.108 - else:
397.109 - n = ls_name + '.' + n
397.110 - if sys.modules.has_key(n): sys.modules[n] = c
397.111 - except:
397.112 - pass
397.113 - elif isinstance(e,PyJavaPackage):
397.114 - _do_reload(ls_name,mgr,e)
397.115 -
397.116 -def reload(ls):
397.117 - if isinstance(ls,LoadSet):
397.118 - ls._mgr.resetLoader()
397.119 - _do_reload(ls._name,ls._mgr,ls._top)
397.120 - return ls
397.121 - else:
397.122 - return _reload(ls)
398.1 --- a/python.editor/test/unit/data/testfiles/jreload.py.indexed Sun Jan 04 13:11:53 2015 -0600
398.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
398.3 @@ -1,67 +0,0 @@
398.4 -
398.5 -
398.6 -Document 0
398.7 -Searchable Keys:
398.8 - class : LoadSet
398.9 - class-ig : loadset
398.10 - in : jreload
398.11 - member : __getattr__;F;;self,name;
398.12 - member : __init__;c;|CONSTRUCTOR|;self,name,path;
398.13 - member : __repr__;F;;self;
398.14 - member : _mgr;D;|PRIVATE|;
398.15 - member : _name;D;|PRIVATE|;
398.16 - member : _top;D;|PRIVATE|;
398.17 -
398.18 -Not Searchable Keys:
398.19 -
398.20 -
398.21 -Document 1
398.22 -Searchable Keys:
398.23 - class : _LoaderFactory
398.24 - class-ig : _loaderfactory
398.25 - extends : JavaLoaderFactory
398.26 - in : jreload
398.27 - member : __init__;c;|CONSTRUCTOR|;self,path;
398.28 - member : makeLoader;F;;self;
398.29 - member : vfs;D;;
398.30 -
398.31 -Not Searchable Keys:
398.32 - clzattrs : ;|PRIVATE|;
398.33 -
398.34 -
398.35 -Document 2
398.36 -Searchable Keys:
398.37 - class : _Unload
398.38 - class-ig : _unload
398.39 - in : jreload
398.40 - member : __call__;F;;self;
398.41 - member : __init__;c;|CONSTRUCTOR|;self,ls;
398.42 - member : do_unload;F;;self,pkg;
398.43 - member : loader;D;;
398.44 - member : ls;D;;
398.45 - member : ls_name;D;;
398.46 -
398.47 -Not Searchable Keys:
398.48 - clzattrs : ;|PRIVATE|;
398.49 -
398.50 -
398.51 -Document 3
398.52 -Searchable Keys:
398.53 - item : LoadSet;C;;
398.54 - item : PyJavaClass;I;;
398.55 - item : PyJavaPackage;I;;
398.56 - item : _LoaderFactory;C;|PRIVATE|;
398.57 - item : _Unload;C;|PRIVATE|;
398.58 - item : __version__;D;;
398.59 - item : _do_reload;F;|PRIVATE|;ls_name,mgr,pkg;
398.60 - item : _is_lazy;I;|PRIVATE|;
398.61 - item : _reload;D;|PRIVATE|;
398.62 - item : imp;I;;
398.63 - item : jxxload_help;I;;
398.64 - item : makeLoadSet;F;;name,path;
398.65 - item : reload;F;;ls;
398.66 - item : sys;I;;
398.67 - item : unloadf;F;;ls;
398.68 - module : jreload
398.69 -
398.70 -Not Searchable Keys:
399.1 --- a/python.editor/test/unit/data/testfiles/lib-old/Para.py Sun Jan 04 13:11:53 2015 -0600
399.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
399.3 @@ -1,343 +0,0 @@
399.4 -# Text formatting abstractions
399.5 -# Note -- this module is obsolete, it's too slow anyway
399.6 -
399.7 -
399.8 -# Oft-used type object
399.9 -Int = type(0)
399.10 -
399.11 -
399.12 -# Represent a paragraph. This is a list of words with associated
399.13 -# font and size information, plus indents and justification for the
399.14 -# entire paragraph.
399.15 -# Once the words have been added to a paragraph, it can be laid out
399.16 -# for different line widths. Once laid out, it can be rendered at
399.17 -# different screen locations. Once rendered, it can be queried
399.18 -# for mouse hits, and parts of the text can be highlighted
399.19 -class Para:
399.20 - #
399.21 - def __init__(self):
399.22 - self.words = [] # The words
399.23 - self.just = 'l' # Justification: 'l', 'r', 'lr' or 'c'
399.24 - self.indent_left = self.indent_right = self.indent_hang = 0
399.25 - # Final lay-out parameters, may change
399.26 - self.left = self.top = self.right = self.bottom = \
399.27 - self.width = self.height = self.lines = None
399.28 - #
399.29 - # Add a word, computing size information for it.
399.30 - # Words may also be added manually by appending to self.words
399.31 - # Each word should be a 7-tuple:
399.32 - # (font, text, width, space, stretch, ascent, descent)
399.33 - def addword(self, d, font, text, space, stretch):
399.34 - if font is not None:
399.35 - d.setfont(font)
399.36 - width = d.textwidth(text)
399.37 - ascent = d.baseline()
399.38 - descent = d.lineheight() - ascent
399.39 - spw = d.textwidth(' ')
399.40 - space = space * spw
399.41 - stretch = stretch * spw
399.42 - tuple = (font, text, width, space, stretch, ascent, descent)
399.43 - self.words.append(tuple)
399.44 - #
399.45 - # Hooks to begin and end anchors -- insert numbers in the word list!
399.46 - def bgn_anchor(self, id):
399.47 - self.words.append(id)
399.48 - #
399.49 - def end_anchor(self, id):
399.50 - self.words.append(0)
399.51 - #
399.52 - # Return the total length (width) of the text added so far, in pixels
399.53 - def getlength(self):
399.54 - total = 0
399.55 - for word in self.words:
399.56 - if type(word) is not Int:
399.57 - total = total + word[2] + word[3]
399.58 - return total
399.59 - #
399.60 - # Tab to a given position (relative to the current left indent):
399.61 - # remove all stretch, add fixed space up to the new indent.
399.62 - # If the current position is already at the tab stop,
399.63 - # don't add any new space (but still remove the stretch)
399.64 - def tabto(self, tab):
399.65 - total = 0
399.66 - as, de = 1, 0
399.67 - for i in range(len(self.words)):
399.68 - word = self.words[i]
399.69 - if type(word) is Int: continue
399.70 - (fo, te, wi, sp, st, as, de) = word
399.71 - self.words[i] = (fo, te, wi, sp, 0, as, de)
399.72 - total = total + wi + sp
399.73 - if total < tab:
399.74 - self.words.append((None, '', 0, tab-total, 0, as, de))
399.75 - #
399.76 - # Make a hanging tag: tab to hang, increment indent_left by hang,
399.77 - # and reset indent_hang to -hang
399.78 - def makehangingtag(self, hang):
399.79 - self.tabto(hang)
399.80 - self.indent_left = self.indent_left + hang
399.81 - self.indent_hang = -hang
399.82 - #
399.83 - # Decide where the line breaks will be given some screen width
399.84 - def layout(self, linewidth):
399.85 - self.width = linewidth
399.86 - height = 0
399.87 - self.lines = lines = []
399.88 - avail1 = self.width - self.indent_left - self.indent_right
399.89 - avail = avail1 - self.indent_hang
399.90 - words = self.words
399.91 - i = 0
399.92 - n = len(words)
399.93 - lastfont = None
399.94 - while i < n:
399.95 - firstfont = lastfont
399.96 - charcount = 0
399.97 - width = 0
399.98 - stretch = 0
399.99 - ascent = 0
399.100 - descent = 0
399.101 - lsp = 0
399.102 - j = i
399.103 - while i < n:
399.104 - word = words[i]
399.105 - if type(word) is Int:
399.106 - if word > 0 and width >= avail:
399.107 - break
399.108 - i = i+1
399.109 - continue
399.110 - fo, te, wi, sp, st, as, de = word
399.111 - if width + wi > avail and width > 0 and wi > 0:
399.112 - break
399.113 - if fo is not None:
399.114 - lastfont = fo
399.115 - if width == 0:
399.116 - firstfont = fo
399.117 - charcount = charcount + len(te) + (sp > 0)
399.118 - width = width + wi + sp
399.119 - lsp = sp
399.120 - stretch = stretch + st
399.121 - lst = st
399.122 - ascent = max(ascent, as)
399.123 - descent = max(descent, de)
399.124 - i = i+1
399.125 - while i > j and type(words[i-1]) is Int and \
399.126 - words[i-1] > 0: i = i-1
399.127 - width = width - lsp
399.128 - if i < n:
399.129 - stretch = stretch - lst
399.130 - else:
399.131 - stretch = 0
399.132 - tuple = i-j, firstfont, charcount, width, stretch, \
399.133 - ascent, descent
399.134 - lines.append(tuple)
399.135 - height = height + ascent + descent
399.136 - avail = avail1
399.137 - self.height = height
399.138 - #
399.139 - # Call a function for all words in a line
399.140 - def visit(self, wordfunc, anchorfunc):
399.141 - avail1 = self.width - self.indent_left - self.indent_right
399.142 - avail = avail1 - self.indent_hang
399.143 - v = self.top
399.144 - i = 0
399.145 - for tuple in self.lines:
399.146 - wordcount, firstfont, charcount, width, stretch, \
399.147 - ascent, descent = tuple
399.148 - h = self.left + self.indent_left
399.149 - if i == 0: h = h + self.indent_hang
399.150 - extra = 0
399.151 - if self.just == 'r': h = h + avail - width
399.152 - elif self.just == 'c': h = h + (avail - width) / 2
399.153 - elif self.just == 'lr' and stretch > 0:
399.154 - extra = avail - width
399.155 - v2 = v + ascent + descent
399.156 - for j in range(i, i+wordcount):
399.157 - word = self.words[j]
399.158 - if type(word) is Int:
399.159 - ok = anchorfunc(self, tuple, word, \
399.160 - h, v)
399.161 - if ok is not None: return ok
399.162 - continue
399.163 - fo, te, wi, sp, st, as, de = word
399.164 - if extra > 0 and stretch > 0:
399.165 - ex = extra * st / stretch
399.166 - extra = extra - ex
399.167 - stretch = stretch - st
399.168 - else:
399.169 - ex = 0
399.170 - h2 = h + wi + sp + ex
399.171 - ok = wordfunc(self, tuple, word, h, v, \
399.172 - h2, v2, (j==i), (j==i+wordcount-1))
399.173 - if ok is not None: return ok
399.174 - h = h2
399.175 - v = v2
399.176 - i = i + wordcount
399.177 - avail = avail1
399.178 - #
399.179 - # Render a paragraph in "drawing object" d, using the rectangle
399.180 - # given by (left, top, right) with an unspecified bottom.
399.181 - # Return the computed bottom of the text.
399.182 - def render(self, d, left, top, right):
399.183 - if self.width != right-left:
399.184 - self.layout(right-left)
399.185 - self.left = left
399.186 - self.top = top
399.187 - self.right = right
399.188 - self.bottom = self.top + self.height
399.189 - self.anchorid = 0
399.190 - try:
399.191 - self.d = d
399.192 - self.visit(self.__class__._renderword, \
399.193 - self.__class__._renderanchor)
399.194 - finally:
399.195 - self.d = None
399.196 - return self.bottom
399.197 - #
399.198 - def _renderword(self, tuple, word, h, v, h2, v2, isfirst, islast):
399.199 - if word[0] is not None: self.d.setfont(word[0])
399.200 - baseline = v + tuple[5]
399.201 - self.d.text((h, baseline - word[5]), word[1])
399.202 - if self.anchorid > 0:
399.203 - self.d.line((h, baseline+2), (h2, baseline+2))
399.204 - #
399.205 - def _renderanchor(self, tuple, word, h, v):
399.206 - self.anchorid = word
399.207 - #
399.208 - # Return which anchor(s) was hit by the mouse
399.209 - def hitcheck(self, mouseh, mousev):
399.210 - self.mouseh = mouseh
399.211 - self.mousev = mousev
399.212 - self.anchorid = 0
399.213 - self.hits = []
399.214 - self.visit(self.__class__._hitcheckword, \
399.215 - self.__class__._hitcheckanchor)
399.216 - return self.hits
399.217 - #
399.218 - def _hitcheckword(self, tuple, word, h, v, h2, v2, isfirst, islast):
399.219 - if self.anchorid > 0 and h <= self.mouseh <= h2 and \
399.220 - v <= self.mousev <= v2:
399.221 - self.hits.append(self.anchorid)
399.222 - #
399.223 - def _hitcheckanchor(self, tuple, word, h, v):
399.224 - self.anchorid = word
399.225 - #
399.226 - # Return whether the given anchor id is present
399.227 - def hasanchor(self, id):
399.228 - return id in self.words or -id in self.words
399.229 - #
399.230 - # Extract the raw text from the word list, substituting one space
399.231 - # for non-empty inter-word space, and terminating with '\n'
399.232 - def extract(self):
399.233 - text = ''
399.234 - for w in self.words:
399.235 - if type(w) is not Int:
399.236 - word = w[1]
399.237 - if w[3]: word = word + ' '
399.238 - text = text + word
399.239 - return text + '\n'
399.240 - #
399.241 - # Return which character position was hit by the mouse, as
399.242 - # an offset in the entire text as returned by extract().
399.243 - # Return None if the mouse was not in this paragraph
399.244 - def whereis(self, d, mouseh, mousev):
399.245 - if mousev < self.top or mousev > self.bottom:
399.246 - return None
399.247 - self.mouseh = mouseh
399.248 - self.mousev = mousev
399.249 - self.lastfont = None
399.250 - self.charcount = 0
399.251 - try:
399.252 - self.d = d
399.253 - return self.visit(self.__class__._whereisword, \
399.254 - self.__class__._whereisanchor)
399.255 - finally:
399.256 - self.d = None
399.257 - #
399.258 - def _whereisword(self, tuple, word, h1, v1, h2, v2, isfirst, islast):
399.259 - fo, te, wi, sp, st, as, de = word
399.260 - if fo is not None: self.lastfont = fo
399.261 - h = h1
399.262 - if isfirst: h1 = 0
399.263 - if islast: h2 = 999999
399.264 - if not (v1 <= self.mousev <= v2 and h1 <= self.mouseh <= h2):
399.265 - self.charcount = self.charcount + len(te) + (sp > 0)
399.266 - return
399.267 - if self.lastfont is not None:
399.268 - self.d.setfont(self.lastfont)
399.269 - cc = 0
399.270 - for c in te:
399.271 - cw = self.d.textwidth(c)
399.272 - if self.mouseh <= h + cw/2:
399.273 - return self.charcount + cc
399.274 - cc = cc+1
399.275 - h = h+cw
399.276 - self.charcount = self.charcount + cc
399.277 - if self.mouseh <= (h+h2) / 2:
399.278 - return self.charcount
399.279 - else:
399.280 - return self.charcount + 1
399.281 - #
399.282 - def _whereisanchor(self, tuple, word, h, v):
399.283 - pass
399.284 - #
399.285 - # Return screen position corresponding to position in paragraph.
399.286 - # Return tuple (h, vtop, vbaseline, vbottom).
399.287 - # This is more or less the inverse of whereis()
399.288 - def screenpos(self, d, pos):
399.289 - if pos < 0:
399.290 - ascent, descent = self.lines[0][5:7]
399.291 - return self.left, self.top, self.top + ascent, \
399.292 - self.top + ascent + descent
399.293 - self.pos = pos
399.294 - self.lastfont = None
399.295 - try:
399.296 - self.d = d
399.297 - ok = self.visit(self.__class__._screenposword, \
399.298 - self.__class__._screenposanchor)
399.299 - finally:
399.300 - self.d = None
399.301 - if ok is None:
399.302 - ascent, descent = self.lines[-1][5:7]
399.303 - ok = self.right, self.bottom - ascent - descent, \
399.304 - self.bottom - descent, self.bottom
399.305 - return ok
399.306 - #
399.307 - def _screenposword(self, tuple, word, h1, v1, h2, v2, isfirst, islast):
399.308 - fo, te, wi, sp, st, as, de = word
399.309 - if fo is not None: self.lastfont = fo
399.310 - cc = len(te) + (sp > 0)
399.311 - if self.pos > cc:
399.312 - self.pos = self.pos - cc
399.313 - return
399.314 - if self.pos < cc:
399.315 - self.d.setfont(self.lastfont)
399.316 - h = h1 + self.d.textwidth(te[:self.pos])
399.317 - else:
399.318 - h = h2
399.319 - ascent, descent = tuple[5:7]
399.320 - return h, v1, v1+ascent, v2
399.321 - #
399.322 - def _screenposanchor(self, tuple, word, h, v):
399.323 - pass
399.324 - #
399.325 - # Invert the stretch of text between pos1 and pos2.
399.326 - # If pos1 is None, the beginning is implied;
399.327 - # if pos2 is None, the end is implied.
399.328 - # Undoes its own effect when called again with the same arguments
399.329 - def invert(self, d, pos1, pos2):
399.330 - if pos1 is None:
399.331 - pos1 = self.left, self.top, self.top, self.top
399.332 - else:
399.333 - pos1 = self.screenpos(d, pos1)
399.334 - if pos2 is None:
399.335 - pos2 = self.right, self.bottom,self.bottom,self.bottom
399.336 - else:
399.337 - pos2 = self.screenpos(d, pos2)
399.338 - h1, top1, baseline1, bottom1 = pos1
399.339 - h2, top2, baseline2, bottom2 = pos2
399.340 - if bottom1 <= top2:
399.341 - d.invert((h1, top1), (self.right, bottom1))
399.342 - h1 = self.left
399.343 - if bottom1 < top2:
399.344 - d.invert((h1, bottom1), (self.right, top2))
399.345 - top1, bottom1 = top2, bottom2
399.346 - d.invert((h1, top1), (h2, bottom2))
400.1 --- a/python.editor/test/unit/data/testfiles/md5.py Sun Jan 04 13:11:53 2015 -0600
400.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
400.3 @@ -1,10 +0,0 @@
400.4 -# $Id: md5.py 39316 2005-08-21 18:45:59Z greg $
400.5 -#
400.6 -# Copyright (C) 2005 Gregory P. Smith (greg@electricrain.com)
400.7 -# Licensed to PSF under a Contributor Agreement.
400.8 -
400.9 -from hashlib import md5
400.10 -new = md5
400.11 -
400.12 -blocksize = 1 # legacy value (wrong in any useful sense)
400.13 -digest_size = 16
401.1 --- a/python.editor/test/unit/data/testfiles/md5.py.indexed Sun Jan 04 13:11:53 2015 -0600
401.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
401.3 @@ -1,12 +0,0 @@
401.4 -
401.5 -
401.6 -Document 0
401.7 -Searchable Keys:
401.8 - item : blocksize;D;;
401.9 - item : digest_size;D;;
401.10 - item : md5;I;;
401.11 - item : new;D;;
401.12 - module : md5
401.13 -
401.14 -Not Searchable Keys:
401.15 - modattrs : D
402.1 --- a/python.editor/test/unit/data/testfiles/mimetypes.py Sun Jan 04 13:11:53 2015 -0600
402.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
402.3 @@ -1,533 +0,0 @@
402.4 -"""Guess the MIME type of a file.
402.5 -
402.6 -This module defines two useful functions:
402.7 -
402.8 -guess_type(url, strict=1) -- guess the MIME type and encoding of a URL.
402.9 -
402.10 -guess_extension(type, strict=1) -- guess the extension for a given MIME type.
402.11 -
402.12 -It also contains the following, for tuning the behavior:
402.13 -
402.14 -Data:
402.15 -
402.16 -knownfiles -- list of files to parse
402.17 -inited -- flag set when init() has been called
402.18 -suffix_map -- dictionary mapping suffixes to suffixes
402.19 -encodings_map -- dictionary mapping suffixes to encodings
402.20 -types_map -- dictionary mapping suffixes to types
402.21 -
402.22 -Functions:
402.23 -
402.24 -init([files]) -- parse a list of files, default knownfiles
402.25 -read_mime_types(file) -- parse one file, return a dictionary or None
402.26 -"""
402.27 -
402.28 -import os
402.29 -import posixpath
402.30 -import urllib
402.31 -
402.32 -__all__ = [
402.33 - "guess_type","guess_extension","guess_all_extensions",
402.34 - "add_type","read_mime_types","init"
402.35 -]
402.36 -
402.37 -knownfiles = [
402.38 - "/etc/mime.types",
402.39 - "/etc/httpd/mime.types", # Mac OS X
402.40 - "/etc/httpd/conf/mime.types", # Apache
402.41 - "/etc/apache/mime.types", # Apache 1
402.42 - "/etc/apache2/mime.types", # Apache 2
402.43 - "/usr/local/etc/httpd/conf/mime.types",
402.44 - "/usr/local/lib/netscape/mime.types",
402.45 - "/usr/local/etc/httpd/conf/mime.types", # Apache 1.2
402.46 - "/usr/local/etc/mime.types", # Apache 1.3
402.47 - ]
402.48 -
402.49 -inited = False
402.50 -
402.51 -
402.52 -class MimeTypes:
402.53 - """MIME-types datastore.
402.54 -
402.55 - This datastore can handle information from mime.types-style files
402.56 - and supports basic determination of MIME type from a filename or
402.57 - URL, and can guess a reasonable extension given a MIME type.
402.58 - """
402.59 -
402.60 - def __init__(self, filenames=(), strict=True):
402.61 - if not inited:
402.62 - init()
402.63 - self.encodings_map = encodings_map.copy()
402.64 - self.suffix_map = suffix_map.copy()
402.65 - self.types_map = ({}, {}) # dict for (non-strict, strict)
402.66 - self.types_map_inv = ({}, {})
402.67 - for (ext, type) in types_map.items():
402.68 - self.add_type(type, ext, True)
402.69 - for (ext, type) in common_types.items():
402.70 - self.add_type(type, ext, False)
402.71 - for name in filenames:
402.72 - self.read(name, strict)
402.73 -
402.74 - def add_type(self, type, ext, strict=True):
402.75 - """Add a mapping between a type and an extension.
402.76 -
402.77 - When the extension is already known, the new
402.78 - type will replace the old one. When the type
402.79 - is already known the extension will be added
402.80 - to the list of known extensions.
402.81 -
402.82 - If strict is true, information will be added to
402.83 - list of standard types, else to the list of non-standard
402.84 - types.
402.85 - """
402.86 - self.types_map[strict][ext] = type
402.87 - exts = self.types_map_inv[strict].setdefault(type, [])
402.88 - if ext not in exts:
402.89 - exts.append(ext)
402.90 -
402.91 - def guess_type(self, url, strict=True):
402.92 - """Guess the type of a file based on its URL.
402.93 -
402.94 - Return value is a tuple (type, encoding) where type is None if
402.95 - the type can't be guessed (no or unknown suffix) or a string
402.96 - of the form type/subtype, usable for a MIME Content-type
402.97 - header; and encoding is None for no encoding or the name of
402.98 - the program used to encode (e.g. compress or gzip). The
402.99 - mappings are table driven. Encoding suffixes are case
402.100 - sensitive; type suffixes are first tried case sensitive, then
402.101 - case insensitive.
402.102 -
402.103 - The suffixes .tgz, .taz and .tz (case sensitive!) are all
402.104 - mapped to '.tar.gz'. (This is table-driven too, using the
402.105 - dictionary suffix_map.)
402.106 -
402.107 - Optional `strict' argument when False adds a bunch of commonly found,
402.108 - but non-standard types.
402.109 - """
402.110 - scheme, url = urllib.splittype(url)
402.111 - if scheme == 'data':
402.112 - # syntax of data URLs:
402.113 - # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
402.114 - # mediatype := [ type "/" subtype ] *( ";" parameter )
402.115 - # data := *urlchar
402.116 - # parameter := attribute "=" value
402.117 - # type/subtype defaults to "text/plain"
402.118 - comma = url.find(',')
402.119 - if comma < 0:
402.120 - # bad data URL
402.121 - return None, None
402.122 - semi = url.find(';', 0, comma)
402.123 - if semi >= 0:
402.124 - type = url[:semi]
402.125 - else:
402.126 - type = url[:comma]
402.127 - if '=' in type or '/' not in type:
402.128 - type = 'text/plain'
402.129 - return type, None # never compressed, so encoding is None
402.130 - base, ext = posixpath.splitext(url)
402.131 - while ext in self.suffix_map:
402.132 - base, ext = posixpath.splitext(base + self.suffix_map[ext])
402.133 - if ext in self.encodings_map:
402.134 - encoding = self.encodings_map[ext]
402.135 - base, ext = posixpath.splitext(base)
402.136 - else:
402.137 - encoding = None
402.138 - types_map = self.types_map[True]
402.139 - if ext in types_map:
402.140 - return types_map[ext], encoding
402.141 - elif ext.lower() in types_map:
402.142 - return types_map[ext.lower()], encoding
402.143 - elif strict:
402.144 - return None, encoding
402.145 - types_map = self.types_map[False]
402.146 - if ext in types_map:
402.147 - return types_map[ext], encoding
402.148 - elif ext.lower() in types_map:
402.149 - return types_map[ext.lower()], encoding
402.150 - else:
402.151 - return None, encoding
402.152 -
402.153 - def guess_all_extensions(self, type, strict=True):
402.154 - """Guess the extensions for a file based on its MIME type.
402.155 -
402.156 - Return value is a list of strings giving the possible filename
402.157 - extensions, including the leading dot ('.'). The extension is not
402.158 - guaranteed to have been associated with any particular data stream,
402.159 - but would be mapped to the MIME type `type' by guess_type().
402.160 -
402.161 - Optional `strict' argument when false adds a bunch of commonly found,
402.162 - but non-standard types.
402.163 - """
402.164 - type = type.lower()
402.165 - extensions = self.types_map_inv[True].get(type, [])
402.166 - if not strict:
402.167 - for ext in self.types_map_inv[False].get(type, []):
402.168 - if ext not in extensions:
402.169 - extensions.append(ext)
402.170 - return extensions
402.171 -
402.172 - def guess_extension(self, type, strict=True):
402.173 - """Guess the extension for a file based on its MIME type.
402.174 -
402.175 - Return value is a string giving a filename extension,
402.176 - including the leading dot ('.'). The extension is not
402.177 - guaranteed to have been associated with any particular data
402.178 - stream, but would be mapped to the MIME type `type' by
402.179 - guess_type(). If no extension can be guessed for `type', None
402.180 - is returned.
402.181 -
402.182 - Optional `strict' argument when false adds a bunch of commonly found,
402.183 - but non-standard types.
402.184 - """
402.185 - extensions = self.guess_all_extensions(type, strict)
402.186 - if not extensions:
402.187 - return None
402.188 - return extensions[0]
402.189 -
402.190 - def read(self, filename, strict=True):
402.191 - """
402.192 - Read a single mime.types-format file, specified by pathname.
402.193 -
402.194 - If strict is true, information will be added to
402.195 - list of standard types, else to the list of non-standard
402.196 - types.
402.197 - """
402.198 - fp = open(filename)
402.199 - self.readfp(fp, strict)
402.200 - fp.close()
402.201 -
402.202 - def readfp(self, fp, strict=True):
402.203 - """
402.204 - Read a single mime.types-format file.
402.205 -
402.206 - If strict is true, information will be added to
402.207 - list of standard types, else to the list of non-standard
402.208 - types.
402.209 - """
402.210 - while 1:
402.211 - line = fp.readline()
402.212 - if not line:
402.213 - break
402.214 - words = line.split()
402.215 - for i in range(len(words)):
402.216 - if words[i][0] == '#':
402.217 - del words[i:]
402.218 - break
402.219 - if not words:
402.220 - continue
402.221 - type, suffixes = words[0], words[1:]
402.222 - for suff in suffixes:
402.223 - self.add_type(type, '.' + suff, strict)
402.224 -
402.225 -def guess_type(url, strict=True):
402.226 - """Guess the type of a file based on its URL.
402.227 -
402.228 - Return value is a tuple (type, encoding) where type is None if the
402.229 - type can't be guessed (no or unknown suffix) or a string of the
402.230 - form type/subtype, usable for a MIME Content-type header; and
402.231 - encoding is None for no encoding or the name of the program used
402.232 - to encode (e.g. compress or gzip). The mappings are table
402.233 - driven. Encoding suffixes are case sensitive; type suffixes are
402.234 - first tried case sensitive, then case insensitive.
402.235 -
402.236 - The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped
402.237 - to ".tar.gz". (This is table-driven too, using the dictionary
402.238 - suffix_map).
402.239 -
402.240 - Optional `strict' argument when false adds a bunch of commonly found, but
402.241 - non-standard types.
402.242 - """
402.243 - init()
402.244 - return guess_type(url, strict)
402.245 -
402.246 -
402.247 -def guess_all_extensions(type, strict=True):
402.248 - """Guess the extensions for a file based on its MIME type.
402.249 -
402.250 - Return value is a list of strings giving the possible filename
402.251 - extensions, including the leading dot ('.'). The extension is not
402.252 - guaranteed to have been associated with any particular data
402.253 - stream, but would be mapped to the MIME type `type' by
402.254 - guess_type(). If no extension can be guessed for `type', None
402.255 - is returned.
402.256 -
402.257 - Optional `strict' argument when false adds a bunch of commonly found,
402.258 - but non-standard types.
402.259 - """
402.260 - init()
402.261 - return guess_all_extensions(type, strict)
402.262 -
402.263 -def guess_extension(type, strict=True):
402.264 - """Guess the extension for a file based on its MIME type.
402.265 -
402.266 - Return value is a string giving a filename extension, including the
402.267 - leading dot ('.'). The extension is not guaranteed to have been
402.268 - associated with any particular data stream, but would be mapped to the
402.269 - MIME type `type' by guess_type(). If no extension can be guessed for
402.270 - `type', None is returned.
402.271 -
402.272 - Optional `strict' argument when false adds a bunch of commonly found,
402.273 - but non-standard types.
402.274 - """
402.275 - init()
402.276 - return guess_extension(type, strict)
402.277 -
402.278 -def add_type(type, ext, strict=True):
402.279 - """Add a mapping between a type and an extension.
402.280 -
402.281 - When the extension is already known, the new
402.282 - type will replace the old one. When the type
402.283 - is already known the extension will be added
402.284 - to the list of known extensions.
402.285 -
402.286 - If strict is true, information will be added to
402.287 - list of standard types, else to the list of non-standard
402.288 - types.
402.289 - """
402.290 - init()
402.291 - return add_type(type, ext, strict)
402.292 -
402.293 -
402.294 -def init(files=None):
402.295 - global guess_all_extensions, guess_extension, guess_type
402.296 - global suffix_map, types_map, encodings_map, common_types
402.297 - global add_type, inited
402.298 - inited = True
402.299 - db = MimeTypes()
402.300 - if files is None:
402.301 - files = knownfiles
402.302 - for file in files:
402.303 - if os.path.isfile(file):
402.304 - db.readfp(open(file))
402.305 - encodings_map = db.encodings_map
402.306 - suffix_map = db.suffix_map
402.307 - types_map = db.types_map[True]
402.308 - guess_all_extensions = db.guess_all_extensions
402.309 - guess_extension = db.guess_extension
402.310 - guess_type = db.guess_type
402.311 - add_type = db.add_type
402.312 - common_types = db.types_map[False]
402.313 -
402.314 -
402.315 -def read_mime_types(file):
402.316 - try:
402.317 - f = open(file)
402.318 - except IOError:
402.319 - return None
402.320 - db = MimeTypes()
402.321 - db.readfp(f, True)
402.322 - return db.types_map[True]
402.323 -
402.324 -
402.325 -def _default_mime_types():
402.326 - global suffix_map
402.327 - global encodings_map
402.328 - global types_map
402.329 - global common_types
402.330 -
402.331 - suffix_map = {
402.332 - '.tgz': '.tar.gz',
402.333 - '.taz': '.tar.gz',
402.334 - '.tz': '.tar.gz',
402.335 - }
402.336 -
402.337 - encodings_map = {
402.338 - '.gz': 'gzip',
402.339 - '.Z': 'compress',
402.340 - }
402.341 -
402.342 - # Before adding new types, make sure they are either registered with IANA,
402.343 - # at http://www.isi.edu/in-notes/iana/assignments/media-types
402.344 - # or extensions, i.e. using the x- prefix
402.345 -
402.346 - # If you add to these, please keep them sorted!
402.347 - types_map = {
402.348 - '.a' : 'application/octet-stream',
402.349 - '.ai' : 'application/postscript',
402.350 - '.aif' : 'audio/x-aiff',
402.351 - '.aifc' : 'audio/x-aiff',
402.352 - '.aiff' : 'audio/x-aiff',
402.353 - '.au' : 'audio/basic',
402.354 - '.avi' : 'video/x-msvideo',
402.355 - '.bat' : 'text/plain',
402.356 - '.bcpio' : 'application/x-bcpio',
402.357 - '.bin' : 'application/octet-stream',
402.358 - '.bmp' : 'image/x-ms-bmp',
402.359 - '.c' : 'text/plain',
402.360 - # Duplicates :(
402.361 - '.cdf' : 'application/x-cdf',
402.362 - '.cdf' : 'application/x-netcdf',
402.363 - '.cpio' : 'application/x-cpio',
402.364 - '.csh' : 'application/x-csh',
402.365 - '.css' : 'text/css',
402.366 - '.dll' : 'application/octet-stream',
402.367 - '.doc' : 'application/msword',
402.368 - '.dot' : 'application/msword',
402.369 - '.dvi' : 'application/x-dvi',
402.370 - '.eml' : 'message/rfc822',
402.371 - '.eps' : 'application/postscript',
402.372 - '.etx' : 'text/x-setext',
402.373 - '.exe' : 'application/octet-stream',
402.374 - '.gif' : 'image/gif',
402.375 - '.gtar' : 'application/x-gtar',
402.376 - '.h' : 'text/plain',
402.377 - '.hdf' : 'application/x-hdf',
402.378 - '.htm' : 'text/html',
402.379 - '.html' : 'text/html',
402.380 - '.ief' : 'image/ief',
402.381 - '.jpe' : 'image/jpeg',
402.382 - '.jpeg' : 'image/jpeg',
402.383 - '.jpg' : 'image/jpeg',
402.384 - '.js' : 'application/x-javascript',
402.385 - '.ksh' : 'text/plain',
402.386 - '.latex' : 'application/x-latex',
402.387 - '.m1v' : 'video/mpeg',
402.388 - '.man' : 'application/x-troff-man',
402.389 - '.me' : 'application/x-troff-me',
402.390 - '.mht' : 'message/rfc822',
402.391 - '.mhtml' : 'message/rfc822',
402.392 - '.mif' : 'application/x-mif',
402.393 - '.mov' : 'video/quicktime',
402.394 - '.movie' : 'video/x-sgi-movie',
402.395 - '.mp2' : 'audio/mpeg',
402.396 - '.mp3' : 'audio/mpeg',
402.397 - '.mpa' : 'video/mpeg',
402.398 - '.mpe' : 'video/mpeg',
402.399 - '.mpeg' : 'video/mpeg',
402.400 - '.mpg' : 'video/mpeg',
402.401 - '.ms' : 'application/x-troff-ms',
402.402 - '.nc' : 'application/x-netcdf',
402.403 - '.nws' : 'message/rfc822',
402.404 - '.o' : 'application/octet-stream',
402.405 - '.obj' : 'application/octet-stream',
402.406 - '.oda' : 'application/oda',
402.407 - '.p12' : 'application/x-pkcs12',
402.408 - '.p7c' : 'application/pkcs7-mime',
402.409 - '.pbm' : 'image/x-portable-bitmap',
402.410 - '.pdf' : 'application/pdf',
402.411 - '.pfx' : 'application/x-pkcs12',
402.412 - '.pgm' : 'image/x-portable-graymap',
402.413 - '.pl' : 'text/plain',
402.414 - '.png' : 'image/png',
402.415 - '.pnm' : 'image/x-portable-anymap',
402.416 - '.pot' : 'application/vnd.ms-powerpoint',
402.417 - '.ppa' : 'application/vnd.ms-powerpoint',
402.418 - '.ppm' : 'image/x-portable-pixmap',
402.419 - '.pps' : 'application/vnd.ms-powerpoint',
402.420 - '.ppt' : 'application/vnd.ms-powerpoint',
402.421 - '.ps' : 'application/postscript',
402.422 - '.pwz' : 'application/vnd.ms-powerpoint',
402.423 - '.py' : 'text/x-python',
402.424 - '.pyc' : 'application/x-python-code',
402.425 - '.pyo' : 'application/x-python-code',
402.426 - '.qt' : 'video/quicktime',
402.427 - '.ra' : 'audio/x-pn-realaudio',
402.428 - '.ram' : 'application/x-pn-realaudio',
402.429 - '.ras' : 'image/x-cmu-raster',
402.430 - '.rdf' : 'application/xml',
402.431 - '.rgb' : 'image/x-rgb',
402.432 - '.roff' : 'application/x-troff',
402.433 - '.rtx' : 'text/richtext',
402.434 - '.sgm' : 'text/x-sgml',
402.435 - '.sgml' : 'text/x-sgml',
402.436 - '.sh' : 'application/x-sh',
402.437 - '.shar' : 'application/x-shar',
402.438 - '.snd' : 'audio/basic',
402.439 - '.so' : 'application/octet-stream',
402.440 - '.src' : 'application/x-wais-source',
402.441 - '.sv4cpio': 'application/x-sv4cpio',
402.442 - '.sv4crc' : 'application/x-sv4crc',
402.443 - '.swf' : 'application/x-shockwave-flash',
402.444 - '.t' : 'application/x-troff',
402.445 - '.tar' : 'application/x-tar',
402.446 - '.tcl' : 'application/x-tcl',
402.447 - '.tex' : 'application/x-tex',
402.448 - '.texi' : 'application/x-texinfo',
402.449 - '.texinfo': 'application/x-texinfo',
402.450 - '.tif' : 'image/tiff',
402.451 - '.tiff' : 'image/tiff',
402.452 - '.tr' : 'application/x-troff',
402.453 - '.tsv' : 'text/tab-separated-values',
402.454 - '.txt' : 'text/plain',
402.455 - '.ustar' : 'application/x-ustar',
402.456 - '.vcf' : 'text/x-vcard',
402.457 - '.wav' : 'audio/x-wav',
402.458 - '.wiz' : 'application/msword',
402.459 - '.wsdl' : 'application/xml',
402.460 - '.xbm' : 'image/x-xbitmap',
402.461 - '.xlb' : 'application/vnd.ms-excel',
402.462 - # Duplicates :(
402.463 - '.xls' : 'application/excel',
402.464 - '.xls' : 'application/vnd.ms-excel',
402.465 - '.xml' : 'text/xml',
402.466 - '.xpdl' : 'application/xml',
402.467 - '.xpm' : 'image/x-xpixmap',
402.468 - '.xsl' : 'application/xml',
402.469 - '.xwd' : 'image/x-xwindowdump',
402.470 - '.zip' : 'application/zip',
402.471 - }
402.472 -
402.473 - # These are non-standard types, commonly found in the wild. They will
402.474 - # only match if strict=0 flag is given to the API methods.
402.475 -
402.476 - # Please sort these too
402.477 - common_types = {
402.478 - '.jpg' : 'image/jpg',
402.479 - '.mid' : 'audio/midi',
402.480 - '.midi': 'audio/midi',
402.481 - '.pct' : 'image/pict',
402.482 - '.pic' : 'image/pict',
402.483 - '.pict': 'image/pict',
402.484 - '.rtf' : 'application/rtf',
402.485 - '.xul' : 'text/xul'
402.486 - }
402.487 -
402.488 -
402.489 -_default_mime_types()
402.490 -
402.491 -
402.492 -if __name__ == '__main__':
402.493 - import sys
402.494 - import getopt
402.495 -
402.496 - USAGE = """\
402.497 -Usage: mimetypes.py [options] type
402.498 -
402.499 -Options:
402.500 - --help / -h -- print this message and exit
402.501 - --lenient / -l -- additionally search of some common, but non-standard
402.502 - types.
402.503 - --extension / -e -- guess extension instead of type
402.504 -
402.505 -More than one type argument may be given.
402.506 -"""
402.507 -
402.508 - def usage(code, msg=''):
402.509 - print USAGE
402.510 - if msg: print msg
402.511 - sys.exit(code)
402.512 -
402.513 - try:
402.514 - opts, args = getopt.getopt(sys.argv[1:], 'hle',
402.515 - ['help', 'lenient', 'extension'])
402.516 - except getopt.error, msg:
402.517 - usage(1, msg)
402.518 -
402.519 - strict = 1
402.520 - extension = 0
402.521 - for opt, arg in opts:
402.522 - if opt in ('-h', '--help'):
402.523 - usage(0)
402.524 - elif opt in ('-l', '--lenient'):
402.525 - strict = 0
402.526 - elif opt in ('-e', '--extension'):
402.527 - extension = 1
402.528 - for gtype in args:
402.529 - if extension:
402.530 - guess = guess_extension(gtype, strict)
402.531 - if not guess: print "I don't know anything about type", gtype
402.532 - else: print guess
402.533 - else:
402.534 - guess, encoding = guess_type(gtype, strict)
402.535 - if not guess: print "I don't know anything about type", gtype
402.536 - else: print 'type:', guess, 'encoding:', encoding
403.1 --- a/python.editor/test/unit/data/testfiles/mimetypes.py.scopes Sun Jan 04 13:11:53 2015 -0600
403.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
403.3 @@ -1,229 +0,0 @@
403.4 -=============================================
403.5 -<file-top>: Module : OffsetRange[0,18689>
403.6 -False [private][read][UNRESOLVED][node=Name]
403.7 -MimeTypes [bound][private][class][def][read][called][node=ClassDef]
403.8 -None [private][read][UNRESOLVED][node=Name]
403.9 -True [private][read][UNRESOLVED][node=Name]
403.10 -USAGE [bound][private][data][read][node=Name]
403.11 -__all__ [bound][data][node=Name]
403.12 -__name__ [private][read][UNRESOLVED][node=Name]
403.13 -_default_mime_types [bound][private][function][def][read][called][node=FunctionDef]
403.14 -add_type [bound][function][def][read][called][node=FunctionDef]
403.15 -arg [bound][private][data][node=Name]
403.16 -args [bound][private][data][read][node=Name]
403.17 -encoding [bound][private][data][read][node=Name]
403.18 -extension [bound][private][data][read][node=Name]
403.19 -getopt [bound][imported][private][data][read][node=Import]
403.20 -gtype [bound][private][data][read][node=Name]
403.21 -guess [bound][private][data][read][node=Name]
403.22 -guess_all_extensions [bound][function][def][read][called][node=FunctionDef]
403.23 -guess_extension [bound][function][def][read][called][node=FunctionDef]
403.24 -guess_type [bound][function][def][read][called][node=FunctionDef]
403.25 -init [bound][function][def][node=FunctionDef]
403.26 -inited [bound][private][data][read][node=Name]
403.27 -knownfiles [bound][private][data][read][node=Name]
403.28 -msg [bound][private][data][read][node=Name]
403.29 -opt [bound][private][data][read][node=Name]
403.30 -opts [bound][private][data][read][node=Name]
403.31 -os [bound][imported][private][data][read][node=Import]
403.32 -posixpath [bound][imported][private][data][read][node=Import]
403.33 -read_mime_types [bound][function][def][node=FunctionDef]
403.34 -strict [bound][private][data][read][node=Name]
403.35 -sys [bound][imported][private][data][read][node=Import]
403.36 -urllib [bound][imported][private][data][read][node=Import]
403.37 -usage [bound][private][function][def][read][called][node=FunctionDef]
403.38 -
403.39 - =============================================
403.40 - class MimeTypes: ClassDef : OffsetRange[1347,7937>
403.41 - True [free][private][read][node=Name]
403.42 - __init__ [bound][private][function][def][node=FunctionDef]
403.43 - add_type [bound][private][function][def][node=FunctionDef]
403.44 - guess_all_extensions [bound][private][function][def][node=FunctionDef]
403.45 - guess_extension [bound][private][function][def][node=FunctionDef]
403.46 - guess_type [bound][private][function][def][node=FunctionDef]
403.47 - read [bound][private][function][def][node=FunctionDef]
403.48 - readfp [bound][private][function][def][node=FunctionDef]
403.49 - ------ Attributes ---------------------------------------
403.50 - encodings_map : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
403.51 - suffix_map : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
403.52 - types_map : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
403.53 - types_map_inv : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
403.54 -
403.55 - =============================================
403.56 - __init__: FunctionDef : OffsetRange[1611,2151>
403.57 - False [free][private][read][node=Name]
403.58 - True [free][private][read][node=Name]
403.59 - common_types [free][private][read][node=Name]
403.60 - encodings_map [free][private][read][node=Name]
403.61 - ext [bound][private][data][read][node=Name]
403.62 - filenames [bound][param][private][data][read][node=Name]
403.63 - init [free][private][read][called][node=Name]
403.64 - inited [free][private][read][node=Name]
403.65 - name [bound][private][data][read][node=Name]
403.66 - self [bound][param][private][data][read][node=Name]
403.67 - strict [bound][param][private][data][read][node=Name]
403.68 - suffix_map [free][private][read][node=Name]
403.69 - type [bound][private][data][read][node=Name]
403.70 - types_map [free][private][read][node=Name]
403.71 - ------ Attributes ---------------------------------------
403.72 - add_type : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
403.73 - read : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
403.74 -
403.75 - =============================================
403.76 - add_type: FunctionDef : OffsetRange[2152,2771>
403.77 - ext [bound][param][private][data][read][node=Name]
403.78 - exts [bound][private][data][read][node=Name]
403.79 - self [bound][param][private][data][read][node=Name]
403.80 - strict [bound][param][private][data][read][node=Name]
403.81 - type [bound][param][private][data][read][node=Name]
403.82 - ------ Attributes ---------------------------------------
403.83 - types_map : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
403.84 - types_map_inv : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
403.85 -
403.86 - =============================================
403.87 - guess_type: FunctionDef : OffsetRange[2772,5327>
403.88 - False [free][private][read][node=Name]
403.89 - None [free][private][read][node=Name]
403.90 - True [free][private][read][node=Name]
403.91 - base [bound][private][data][read][node=Name]
403.92 - comma [bound][private][data][read][node=Name]
403.93 - encoding [bound][private][data][read][node=Name]
403.94 - ext [bound][private][data][read][node=Name]
403.95 - posixpath [free][private][read][node=Name]
403.96 - scheme [bound][private][data][read][node=Name]
403.97 - self [bound][param][private][data][read][node=Name]
403.98 - semi [bound][private][data][read][node=Name]
403.99 - strict [bound][param][private][data][read][node=Name]
403.100 - type [bound][private][data][read][node=Name]
403.101 - types_map [bound][private][data][read][node=Name]
403.102 - url [bound][param][private][data][read][node=Name]
403.103 - urllib [free][private][read][node=Name]
403.104 - ------ Attributes ---------------------------------------
403.105 - encodings_map : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
403.106 - suffix_map : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
403.107 - types_map : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
403.108 -
403.109 - =============================================
403.110 - guess_all_extensions: FunctionDef : OffsetRange[5328,6151>
403.111 - False [free][private][read][node=Name]
403.112 - True [free][private][read][node=Name]
403.113 - ext [bound][private][data][read][node=Name]
403.114 - extensions [bound][private][data][read][node=Name]
403.115 - self [bound][param][private][data][read][node=Name]
403.116 - strict [bound][param][private][data][read][node=Name]
403.117 - type [bound][param][private][data][read][node=Name]
403.118 - ------ Attributes ---------------------------------------
403.119 - types_map_inv : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
403.120 -
403.121 - =============================================
403.122 - guess_extension: FunctionDef : OffsetRange[6152,6881>
403.123 - None [free][private][read][node=Name]
403.124 - extensions [bound][private][data][read][node=Name]
403.125 - self [bound][param][private][data][read][node=Name]
403.126 - strict [bound][param][private][data][read][node=Name]
403.127 - type [bound][param][private][data][read][node=Name]
403.128 - ------ Attributes ---------------------------------------
403.129 - guess_all_extensions : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
403.130 -
403.131 - =============================================
403.132 - read: FunctionDef : OffsetRange[6882,7234>
403.133 - filename [bound][param][private][data][read][node=Name]
403.134 - fp [bound][private][data][read][node=Name]
403.135 - open [free][private][read][called][node=Name]
403.136 - self [bound][param][private][data][read][node=Name]
403.137 - strict [bound][param][private][data][read][node=Name]
403.138 - ------ Attributes ---------------------------------------
403.139 - readfp : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
403.140 -
403.141 - =============================================
403.142 - readfp: FunctionDef : OffsetRange[7235,7937>
403.143 - fp [bound][param][private][data][read][node=Name]
403.144 - i [bound][private][data][read][node=Name]
403.145 - len [free][private][read][called][node=Name]
403.146 - line [bound][private][data][read][node=Name]
403.147 - range [free][private][read][called][node=Name]
403.148 - self [bound][param][private][data][read][node=Name]
403.149 - strict [bound][param][private][data][read][node=Name]
403.150 - suff [bound][private][data][read][node=Name]
403.151 - suffixes [bound][private][data][read][node=Name]
403.152 - type [bound][private][data][read][node=Name]
403.153 - words [bound][private][data][read][node=Name]
403.154 - ------ Attributes ---------------------------------------
403.155 - add_type : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
403.156 -
403.157 - =============================================
403.158 - guess_type: FunctionDef : OffsetRange[7937,8796>
403.159 - guess_type [free][read][called][node=Name]
403.160 - init [free][read][called][node=Name]
403.161 - strict [bound][param][data][read][node=Name]
403.162 - url [bound][param][data][read][node=Name]
403.163 -
403.164 - =============================================
403.165 - guess_all_extensions: FunctionDef : OffsetRange[8796,9419>
403.166 - guess_all_extensions [free][read][called][node=Name]
403.167 - init [free][read][called][node=Name]
403.168 - strict [bound][param][data][read][node=Name]
403.169 - type [bound][param][data][read][node=Name]
403.170 -
403.171 - =============================================
403.172 - guess_extension: FunctionDef : OffsetRange[9419,10006>
403.173 - guess_extension [free][read][called][node=Name]
403.174 - init [free][read][called][node=Name]
403.175 - strict [bound][param][data][read][node=Name]
403.176 - type [bound][param][data][read][node=Name]
403.177 -
403.178 - =============================================
403.179 - add_type: FunctionDef : OffsetRange[10006,10468>
403.180 - add_type [free][read][called][node=Name]
403.181 - ext [bound][param][data][read][node=Name]
403.182 - init [free][read][called][node=Name]
403.183 - strict [bound][param][data][read][node=Name]
403.184 - type [bound][param][data][read][node=Name]
403.185 -
403.186 - =============================================
403.187 - init: FunctionDef : OffsetRange[10468,11113>
403.188 - False [free][read][node=Name]
403.189 - MimeTypes [free][read][called][node=Name]
403.190 - None [free][read][node=Name]
403.191 - True [free][read][node=Name]
403.192 - add_type [bound][func-global][data][unused][node=Global]
403.193 - common_types [bound][func-global][data][unused][node=Global]
403.194 - db [bound][data][read][node=Name]
403.195 - encodings_map [bound][func-global][data][unused][node=Global]
403.196 - file [bound][data][read][node=Name]
403.197 - files [bound][param][data][read][node=Name]
403.198 - guess_all_extensions [bound][func-global][data][unused][node=Global]
403.199 - guess_extension [bound][func-global][data][unused][node=Global]
403.200 - guess_type [bound][func-global][data][unused][node=Global]
403.201 - inited [bound][func-global][data][unused][node=Global]
403.202 - knownfiles [free][read][node=Name]
403.203 - open [free][read][called][node=Name]
403.204 - os [free][read][node=Name]
403.205 - suffix_map [bound][func-global][data][unused][node=Global]
403.206 - types_map [bound][func-global][data][unused][node=Global]
403.207 -
403.208 - =============================================
403.209 - read_mime_types: FunctionDef : OffsetRange[11113,11288>
403.210 - IOError [free][read][node=Name]
403.211 - MimeTypes [free][read][called][node=Name]
403.212 - None [free][read][node=Name]
403.213 - True [free][read][node=Name]
403.214 - db [bound][data][read][node=Name]
403.215 - f [bound][data][read][node=Name]
403.216 - file [bound][param][data][read][node=Name]
403.217 - open [free][read][called][node=Name]
403.218 -
403.219 - =============================================
403.220 - _default_mime_types: FunctionDef : OffsetRange[11288,17334>
403.221 - common_types [bound][func-global][private][data][unused][node=Global]
403.222 - encodings_map [bound][func-global][private][data][unused][node=Global]
403.223 - suffix_map [bound][func-global][private][data][unused][node=Global]
403.224 - types_map [bound][func-global][private][data][unused][node=Global]
403.225 -
403.226 - =============================================
403.227 - usage: FunctionDef : OffsetRange[17753,17851>
403.228 - USAGE [free][private][read][node=Name]
403.229 - code [bound][param][private][data][read][node=Name]
403.230 - msg [bound][param][private][data][read][node=Name]
403.231 - sys [free][private][read][node=Name]
403.232 -
404.1 --- a/python.editor/test/unit/data/testfiles/minicompat.py Sun Jan 04 13:11:53 2015 -0600
404.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
404.3 @@ -1,184 +0,0 @@
404.4 -"""Python version compatibility support for minidom."""
404.5 -
404.6 -# This module should only be imported using "import *".
404.7 -#
404.8 -# The following names are defined:
404.9 -#
404.10 -# isinstance -- version of the isinstance() function that accepts
404.11 -# tuples as the second parameter regardless of the
404.12 -# Python version
404.13 -#
404.14 -# NodeList -- lightest possible NodeList implementation
404.15 -#
404.16 -# EmptyNodeList -- lightest possible NodeList that is guarateed to
404.17 -# remain empty (immutable)
404.18 -#
404.19 -# StringTypes -- tuple of defined string types
404.20 -#
404.21 -# GetattrMagic -- base class used to make _get_<attr> be magically
404.22 -# invoked when available
404.23 -# defproperty -- function used in conjunction with GetattrMagic;
404.24 -# using these together is needed to make them work
404.25 -# as efficiently as possible in both Python 2.2+
404.26 -# and older versions. For example:
404.27 -#
404.28 -# class MyClass(GetattrMagic):
404.29 -# def _get_myattr(self):
404.30 -# return something
404.31 -#
404.32 -# defproperty(MyClass, "myattr",
404.33 -# "return some value")
404.34 -#
404.35 -# For Python 2.2 and newer, this will construct a
404.36 -# property object on the class, which avoids
404.37 -# needing to override __getattr__(). It will only
404.38 -# work for read-only attributes.
404.39 -#
404.40 -# For older versions of Python, inheriting from
404.41 -# GetattrMagic will use the traditional
404.42 -# __getattr__() hackery to achieve the same effect,
404.43 -# but less efficiently.
404.44 -#
404.45 -# defproperty() should be used for each version of
404.46 -# the relevant _get_<property>() function.
404.47 -#
404.48 -# NewStyle -- base class to cause __slots__ to be honored in
404.49 -# the new world
404.50 -#
404.51 -# True, False -- only for Python 2.2 and earlier
404.52 -
404.53 -__all__ = ["NodeList", "EmptyNodeList", "NewStyle",
404.54 - "StringTypes", "defproperty", "GetattrMagic"]
404.55 -
404.56 -import xml.dom
404.57 -
404.58 -try:
404.59 - unicode
404.60 -except NameError:
404.61 - StringTypes = type(''),
404.62 -else:
404.63 - StringTypes = type(''), type(unicode(''))
404.64 -
404.65 -
404.66 -# define True and False only if not defined as built-ins
404.67 -try:
404.68 - True
404.69 -except NameError:
404.70 - True = 1
404.71 - False = 0
404.72 - __all__.extend(["True", "False"])
404.73 -
404.74 -
404.75 -try:
404.76 - isinstance('', StringTypes)
404.77 -except TypeError:
404.78 - #
404.79 - # Wrap isinstance() to make it compatible with the version in
404.80 - # Python 2.2 and newer.
404.81 - #
404.82 - _isinstance = isinstance
404.83 - def isinstance(obj, type_or_seq):
404.84 - try:
404.85 - return _isinstance(obj, type_or_seq)
404.86 - except TypeError:
404.87 - for t in type_or_seq:
404.88 - if _isinstance(obj, t):
404.89 - return 1
404.90 - return 0
404.91 - __all__.append("isinstance")
404.92 -
404.93 -
404.94 -if list is type([]):
404.95 - class NodeList(list):
404.96 - __slots__ = ()
404.97 -
404.98 - def item(self, index):
404.99 - if 0 <= index < len(self):
404.100 - return self[index]
404.101 -
404.102 - def _get_length(self):
404.103 - return len(self)
404.104 -
404.105 - def _set_length(self, value):
404.106 - raise xml.dom.NoModificationAllowedErr(
404.107 - "attempt to modify read-only attribute 'length'")
404.108 -
404.109 - length = property(_get_length, _set_length,
404.110 - doc="The number of nodes in the NodeList.")
404.111 -
404.112 - def __getstate__(self):
404.113 - return list(self)
404.114 -
404.115 - def __setstate__(self, state):
404.116 - self[:] = state
404.117 -
404.118 - class EmptyNodeList(tuple):
404.119 - __slots__ = ()
404.120 -
404.121 - def __add__(self, other):
404.122 - NL = NodeList()
404.123 - NL.extend(other)
404.124 - return NL
404.125 -
404.126 - def __radd__(self, other):
404.127 - NL = NodeList()
404.128 - NL.extend(other)
404.129 - return NL
404.130 -
404.131 - def item(self, index):
404.132 - return None
404.133 -
404.134 - def _get_length(self):
404.135 - return 0
404.136 -
404.137 - def _set_length(self, value):
404.138 - raise xml.dom.NoModificationAllowedErr(
404.139 - "attempt to modify read-only attribute 'length'")
404.140 -
404.141 - length = property(_get_length, _set_length,
404.142 - doc="The number of nodes in the NodeList.")
404.143 -
404.144 -else:
404.145 - def NodeList():
404.146 - return []
404.147 -
404.148 - def EmptyNodeList():
404.149 - return []
404.150 -
404.151 -
404.152 -try:
404.153 - property
404.154 -except NameError:
404.155 - def defproperty(klass, name, doc):
404.156 - # taken care of by the base __getattr__()
404.157 - pass
404.158 -
404.159 - class GetattrMagic:
404.160 - def __getattr__(self, key):
404.161 - if key.startswith("_"):
404.162 - raise AttributeError, key
404.163 -
404.164 - try:
404.165 - get = getattr(self, "_get_" + key)
404.166 - except AttributeError:
404.167 - raise AttributeError, key
404.168 - return get()
404.169 -
404.170 - class NewStyle:
404.171 - pass
404.172 -
404.173 -else:
404.174 - def defproperty(klass, name, doc):
404.175 - get = getattr(klass, ("_get_" + name)).im_func
404.176 - def set(self, value, name=name):
404.177 - raise xml.dom.NoModificationAllowedErr(
404.178 - "attempt to modify read-only attribute " + repr(name))
404.179 - assert not hasattr(klass, "_set_" + name), \
404.180 - "expected not to find _set_" + name
404.181 - prop = property(get, set, doc=doc)
404.182 - setattr(klass, name, prop)
404.183 -
404.184 - class GetattrMagic:
404.185 - pass
404.186 -
404.187 - NewStyle = object
405.1 --- a/python.editor/test/unit/data/testfiles/minicompat.py.indexed Sun Jan 04 13:11:53 2015 -0600
405.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
405.3 @@ -1,37 +0,0 @@
405.4 -
405.5 -
405.6 -Document 0
405.7 -Searchable Keys:
405.8 - class : GetattrMagic
405.9 - class-ig : getattrmagic
405.10 - in : minicompat
405.11 -
405.12 -Not Searchable Keys:
405.13 -
405.14 -
405.15 -Document 1
405.16 -Searchable Keys:
405.17 - class : NewStyle
405.18 - class-ig : newstyle
405.19 - in : minicompat
405.20 -
405.21 -Not Searchable Keys:
405.22 -
405.23 -
405.24 -Document 2
405.25 -Searchable Keys:
405.26 - item : EmptyNodeList;C;;
405.27 - item : False;D;;
405.28 - item : GetattrMagic;C;;
405.29 - item : NewStyle;C;;
405.30 - item : NodeList;C;;
405.31 - item : StringTypes;D;;
405.32 - item : True;D;;
405.33 - item : __all__;D;;
405.34 - item : _isinstance;D;|PRIVATE|;
405.35 - item : defproperty;F;;klass,name,doc;
405.36 - item : isinstance;F;;obj,type_or_seq;
405.37 - item : xml;I;|PRIVATE|;
405.38 - module : minicompat
405.39 -
405.40 -Not Searchable Keys:
406.1 --- a/python.editor/test/unit/data/testfiles/modifiers.py Sun Jan 04 13:11:53 2015 -0600
406.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
406.3 @@ -1,12 +0,0 @@
406.4 -class ParsingError(Error):
406.5 - """Raised when a configuration file does not follow legal syntax."""
406.6 -
406.7 - def __init__(self, filename):
406.8 - Error.__init__(self, 'File contains parsing errors: %s' % filename)
406.9 - self.filename = filename
406.10 - self.errors = []
406.11 -
406.12 - def __i_am_private(self, lineno, line):
406.13 - self.errors.append((lineno, line))
406.14 - self.message += '\n\t[line %2d]: %s' % (lineno, line)
406.15 -
407.1 --- a/python.editor/test/unit/data/testfiles/modifiers.py.structure 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 -ParsingError:CLASS:[]:ESCAPED{ParsingError}:
407.5 - __i_am_private:METHOD:[PRIVATE]:ESCAPED{__i_am_private}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{lineno}ESCAPED{,}ESCAPED{line}}):
407.6 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{filename}}):
407.7 - errors:ATTRIBUTE:[]:ESCAPED{errors}:
407.8 - filename:ATTRIBUTE:[]:ESCAPED{filename}:
408.1 --- a/python.editor/test/unit/data/testfiles/names.py Sun Jan 04 13:11:53 2015 -0600
408.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
408.3 @@ -1,615 +0,0 @@
408.4 -"""Configuration file parser.
408.5 -
408.6 -A setup file consists of sections, lead by a "[section]" header,
408.7 -and followed by "name: value" entries, with continuations and such in
408.8 -the style of RFC 822.
408.9 -
408.10 - the same section, or values in a special [DEFAULT] section.
408.11 -
408.12 -For example:
408.13 -
408.14 - something: %(dir)s/whatever
408.15 -
408.16 -would resolve the "%(dir)s" to the value of dir. All reference
408.17 -expansions are done late, on demand.
408.18 -
408.19 -Intrinsic defaults can be specified by passing them into the
408.20 -ConfigParser constructor as a dictionary.
408.21 -
408.22 -class:
408.23 -
408.24 -ConfigParser -- responsible for parsing a list of
408.25 - configuration files, and managing the parsed database.
408.26 -
408.27 - methods:
408.28 -
408.29 - __init__(defaults=None)
408.30 - create the parser and specify a dictionary of intrinsic defaults. The
408.31 - keys must be strings, the values must be appropriate for %()s string
408.32 - interpolation. Note that `__name__' is always an intrinsic default;
408.33 - it's value is the section's name.
408.34 -
408.35 - sections()
408.36 - return all the configuration section names, sans DEFAULT
408.37 -
408.38 - has_section(section)
408.39 - return whether the given section exists
408.40 -
408.41 - has_option(section, option)
408.42 - return whether the given option exists in the given section
408.43 -
408.44 - options(section)
408.45 - return list of configuration options for the named section
408.46 -
408.47 - read(filenames)
408.48 - read and parse the list of named configuration files, given by
408.49 - name. A single filename is also allowed. Non-existing files
408.50 - are ignored.
408.51 -
408.52 - readfp(fp, filename=None)
408.53 - read and parse one configuration file, given as a file object.
408.54 - The filename defaults to fp.name; it is only used in error
408.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
408.56 -
408.57 - get(section, option, raw=False, vars=None)
408.58 - return a string value for the named option. All % interpolations are
408.59 - expanded in the return values, based on the defaults passed into the
408.60 - constructor and the DEFAULT section. Additional substitutions may be
408.61 - provided using the `vars' argument, which must be a dictionary whose
408.62 - contents override any pre-existing defaults.
408.63 -
408.64 - getint(section, options)
408.65 - like get(), but convert value to an integer
408.66 -
408.67 - getfloat(section, options)
408.68 - like get(), but convert value to a float
408.69 -
408.70 - getboolean(section, options)
408.71 - like get(), but convert value to a boolean (currently case
408.72 - insensitively defined as 0, false, no, off for False, and 1, true,
408.73 - yes, on for True). Returns False or True.
408.74 -
408.75 - items(section, raw=False, vars=None)
408.76 - return a list of tuples with (name, value) for each option
408.77 - in the section.
408.78 -
408.79 - remove_section(section)
408.80 - remove the given file section and all its options
408.81 -
408.82 - remove_option(section, option)
408.83 - remove the given option from the given section
408.84 -
408.85 - set(section, option, value)
408.86 - set the given option
408.87 -
408.88 - write(fp)
408.89 - write the configuration state in .ini format
408.90 -"""
408.91 -
408.92 -import re
408.93 -
408.94 -__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
408.95 - "InterpolationError", "InterpolationDepthError",
408.96 - "InterpolationSyntaxError", "ParsingError",
408.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
408.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
408.99 -
408.100 -DEFAULTSECT = "DEFAULT"
408.101 -
408.102 -MAX_INTERPOLATION_DEPTH = 10
408.103 -
408.104 -
408.105 -
408.106 -# exception classes
408.107 -class Error(Exception):
408.108 - """Base class for ConfigParser exceptions."""
408.109 -
408.110 - def __init__(self, msg=''):
408.111 - self.message = msg
408.112 - Exception.__init__(self, msg)
408.113 -
408.114 - def __repr__(self):
408.115 - return self.message
408.116 -
408.117 - __str__ = __repr__
408.118 -
408.119 -class NoSectionError(Error):
408.120 - """Rasssised when no section matches a requested option."""
408.121 -
408.122 - def __init__(self, section):
408.123 - Error.__init__(self, 'No section: ' + `section`)
408.124 - self.section = section
408.125 -
408.126 -class duplicateSectionError(Error):
408.127 - """Raised when a section is multiply-created."""
408.128 -
408.129 - def __Init__(self, section):
408.130 - Error.__init__(self, "Section %r already exists" % section)
408.131 - self.section = section
408.132 -
408.133 -class _noOptionError(Error):
408.134 - """A requested option was not found."""
408.135 -
408.136 - def __init__(self, option, section):
408.137 - Error.__init__(self, "No option %r in section: %r" %
408.138 - (option, section))
408.139 - self.option = option
408.140 - self.section = section
408.141 -
408.142 -class _interpolationError(Error):
408.143 - """Base class for interpolation-related exceptions."""
408.144 -
408.145 - def __init__(self, option, section, msg):
408.146 - Error.__init__(self, msg)
408.147 - self.option = option
408.148 - self.section = section
408.149 -
408.150 -class InterpolationMissingOptionError(InterpolationError):
408.151 - """A string substitution required a setting which was not available."""
408.152 -
408.153 - def __init__(self, option, section, rawval, reference):
408.154 - msg = ("Bad value substitution:\n"
408.155 - "\tsection: [%s]\n"
408.156 - "\toption : %s\n"
408.157 - "\tkey : %s\n"
408.158 - "\trawval : %s\n"
408.159 - % (section, option, reference, rawval))
408.160 - InterpolationError.__init__(self, option, section, msg)
408.161 - self.reference = reference
408.162 -
408.163 -class InterpolationSyntaxError(InterpolationError):
408.164 - """Raised when the source text into which substitutions are made
408.165 - does not conform to the required syntax."""
408.166 -
408.167 -class InterpolationDepthError(InterpolationError):
408.168 - """Raised when substitutions are nested too deeply."""
408.169 -
408.170 - def __init__(self, option, section, rawval):
408.171 - msg = ("Value interpolation too deeply recursive:\n"
408.172 - "\tsection: [%s]\n"
408.173 - "\toption : %s\n"
408.174 - "\trawval : %s\n"
408.175 - % (section, option, rawval))
408.176 - InterpolationError.__init__(self, option, section, msg)
408.177 -
408.178 -class ParsingError(Error):
408.179 - """Raised when a configuration file does not follow legal syntax."""
408.180 -
408.181 - def __init__(self, filename):
408.182 - Error.__init__(self, 'File contains parsing errors: %s' % filename)
408.183 - self.filename = filename
408.184 - self.errors = []
408.185 -
408.186 - def append(self, lineno, line):
408.187 - self.errors.append((lineno, line))
408.188 - self.message += '\n\t[line %2d]: %s' % (lineno, line)
408.189 -
408.190 -class MissingSectionHeaderError(ParsingError):
408.191 - """Raised when a key-value pair is found before any section header."""
408.192 -
408.193 - def __init__(self, filename, lineno, line):
408.194 - Error.__init__(
408.195 - self,
408.196 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
408.197 - (filename, lineno, line))
408.198 - self.filename = filename
408.199 - self.lineno = lineno
408.200 - self.line = line
408.201 -
408.202 -
408.203 -
408.204 -class RawConfigParser:
408.205 - def __init__(self, defaults=None):
408.206 - self._sections = {}
408.207 - if defaults is None:
408.208 - self._defaults = {}
408.209 - else:
408.210 - self._defaults = defaults
408.211 -
408.212 - def Defaults(self):
408.213 - return self._defaults
408.214 -
408.215 - def _Sections(self):
408.216 - """Return a list of section names, excluding [DEFAULT]"""
408.217 - # self._sections will never have [DEFAULT] in it
408.218 - return self._sections.keys()
408.219 -
408.220 - def add_section(self, section):
408.221 - """Create a new section in the configuration.
408.222 -
408.223 - Raise DuplicateSectionError if a section by the specified name
408.224 - already exists.
408.225 - """
408.226 - if section in self._sections:
408.227 - raise DuplicateSectionError(section)
408.228 - self._sections[section] = {}
408.229 -
408.230 - def has_section(self, section):
408.231 - """Indicate whether the named section is present in the configuration.
408.232 -
408.233 - The DEFAULT section is not acknowledged.
408.234 - """
408.235 - return section in self._sections
408.236 -
408.237 - def options(self, section):
408.238 - """Return a list of option names for the given section name."""
408.239 - try:
408.240 - opts = self._sections[section].copy()
408.241 - except KeyError:
408.242 - raise NoSectionError(section)
408.243 - opts.update(self._defaults)
408.244 - if '__name__' in opts:
408.245 - del opts['__name__']
408.246 - return opts.keys()
408.247 -
408.248 - def read(self, filenames):
408.249 - """Read and parse a filename or a list of filenames.
408.250 -
408.251 - Files that cannot be opened are silently ignored; this is
408.252 - designed so that you can specify a list of potential
408.253 - configuration file locations (e.g. current directory, user's
408.254 - home directory, systemwide directory), and all existing
408.255 - configuration files in the list will be read. A single
408.256 - filename may also be given.
408.257 - """
408.258 - if isinstance(filenames, basestring):
408.259 - filenames = [filenames]
408.260 - for filename in filenames:
408.261 - try:
408.262 - fp = open(filename)
408.263 - except IOError:
408.264 - continue
408.265 - self._read(fp, filename)
408.266 - fp.close()
408.267 -
408.268 - def readfp(self, fp, filename=None):
408.269 - """Like read() but the argument must be a file-like object.
408.270 -
408.271 - The `fp' argument must have a `readline' method. Optional
408.272 - second argument is the `filename', which if not given, is
408.273 - taken from fp.name. If fp has no `name' attribute, `<???>' is
408.274 - used.
408.275 -
408.276 - """
408.277 - if filename is None:
408.278 - try:
408.279 - filename = fp.name
408.280 - except AttributeError:
408.281 - filename = '<???>'
408.282 - self._read(fp, filename)
408.283 -
408.284 - def get(self, section, option):
408.285 - opt = self.optionxform(option)
408.286 - if section not in self._sections:
408.287 - if section != DEFAULTSECT:
408.288 - raise NoSectionError(section)
408.289 - if opt in self._defaults:
408.290 - return self._defaults[opt]
408.291 - else:
408.292 - raise NoOptionError(option, section)
408.293 - elif opt in self._sections[section]:
408.294 - return self._sections[section][opt]
408.295 - elif opt in self._defaults:
408.296 - return self._defaults[opt]
408.297 - else:
408.298 - raise NoOptionError(option, section)
408.299 -
408.300 - def items(self, section):
408.301 - try:
408.302 - d2 = self._sections[section]
408.303 - except KeyError:
408.304 - if section != DEFAULTSECT:
408.305 - raise NoSectionError(section)
408.306 - d2 = {}
408.307 - d = self._defaults.copy()
408.308 - d.update(d2)
408.309 - if "__name__" in d:
408.310 - del d["__name__"]
408.311 - return d.items()
408.312 -
408.313 - def _get(self, section, conv, option):
408.314 - return conv(self.get(section, option))
408.315 -
408.316 - def getint(self, section, option):
408.317 - return self._get(section, int, option)
408.318 -
408.319 - def getfloat(self, section, option):
408.320 - return self._get(section, float, option)
408.321 -
408.322 - _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
408.323 - '0': False, 'no': False, 'false': False, 'off': False}
408.324 -
408.325 - def getboolean(self, section, option):
408.326 - v = self.get(section, option)
408.327 - if v.lower() not in self._boolean_states:
408.328 - raise ValueError, 'Not a boolean: %s' % v
408.329 - return self._boolean_states[v.lower()]
408.330 -
408.331 - def optionxform(self, optionstr):
408.332 - return optionstr.lower()
408.333 -
408.334 - def has_option(self, section, option):
408.335 - """Check for the existence of a given option in a given section."""
408.336 - if not section or section == DEFAULTSECT:
408.337 - option = self.optionxform(option)
408.338 - return option in self._defaults
408.339 - elif section not in self._sections:
408.340 - return False
408.341 - else:
408.342 - option = self.optionxform(option)
408.343 - return (option in self._sections[section]
408.344 - or option in self._defaults)
408.345 -
408.346 - def set(self, section, option, value):
408.347 - """Set an option."""
408.348 - if not section or section == DEFAULTSECT:
408.349 - sectdict = self._defaults
408.350 - else:
408.351 - try:
408.352 - sectdict = self._sections[section]
408.353 - except KeyError:
408.354 - raise NoSectionError(section)
408.355 - sectdict[self.optionxform(option)] = value
408.356 -
408.357 - def write(self, fp):
408.358 - """Write an .ini-format representation of the configuration state."""
408.359 - if self._defaults:
408.360 - fp.write("[%s]\n" % DEFAULTSECT)
408.361 - for (key, value) in self._defaults.items():
408.362 - fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
408.363 - fp.write("\n")
408.364 - for section in self._sections:
408.365 - fp.write("[%s]\n" % section)
408.366 - for (key, value) in self._sections[section].items():
408.367 - if key != "__name__":
408.368 - fp.write("%s = %s\n" %
408.369 - (key, str(value).replace('\n', '\n\t')))
408.370 - fp.write("\n")
408.371 -
408.372 - def remove_option(self, section, option):
408.373 - """Remove an option."""
408.374 - if not section or section == DEFAULTSECT:
408.375 - sectdict = self._defaults
408.376 - else:
408.377 - try:
408.378 - sectdict = self._sections[section]
408.379 - except KeyError:
408.380 - raise NoSectionError(section)
408.381 - option = self.optionxform(option)
408.382 - existed = option in sectdict
408.383 - if existed:
408.384 - del sectdict[option]
408.385 - return existed
408.386 -
408.387 - def remove_section(self, section):
408.388 - """Remove a file section."""
408.389 - existed = section in self._sections
408.390 - if existed:
408.391 - del self._sections[section]
408.392 - return existed
408.393 -
408.394 - #
408.395 - # Regular expressions for parsing section headers and options.
408.396 - #
408.397 - SECTCRE = re.compile(
408.398 - r'\[' # [
408.399 - r'(?P<header>[^]]+)' # very permissive!
408.400 - r'\]' # ]
408.401 - )
408.402 - OPTCRE = re.compile(
408.403 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
408.404 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
408.405 - # followed by separator
408.406 - # (either : or =), followed
408.407 - # by any # space/tab
408.408 - r'(?P<value>.*)$' # everything up to eol
408.409 - )
408.410 -
408.411 - def _read(self, fp, fpname):
408.412 - """Parse a sectioned setup file.
408.413 -
408.414 - The sections in setup file contains a title line at the top,
408.415 - indicated by a name in square brackets (`[]'), plus key/value
408.416 - options lines, indicated by `name: value' format lines.
408.417 - Continuations are represented by an embedded newline then
408.418 - leading whitespace. Blank lines, lines beginning with a '#',
408.419 - and just about everything else are ignored.
408.420 - """
408.421 - cursect = None # None, or a dictionary
408.422 - optname = None
408.423 - lineno = 0
408.424 - e = None # None, or an exception
408.425 - while True:
408.426 - line = fp.readline()
408.427 - if not line:
408.428 - break
408.429 - lineno = lineno + 1
408.430 - # comment or blank line?
408.431 - if line.strip() == '' or line[0] in '#;':
408.432 - continue
408.433 - if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
408.434 - # no leading whitespace
408.435 - continue
408.436 - # continuation line?
408.437 - if line[0].isspace() and cursect is not None and optname:
408.438 - value = line.strip()
408.439 - if value:
408.440 - cursect[optname] = "%s\n%s" % (cursect[optname], value)
408.441 - # a section header or option header?
408.442 - else:
408.443 - # is it a section header?
408.444 - mo = self.SECTCRE.match(line)
408.445 - if mo:
408.446 - sectname = mo.group('header')
408.447 - if sectname in self._sections:
408.448 - cursect = self._sections[sectname]
408.449 - elif sectname == DEFAULTSECT:
408.450 - cursect = self._defaults
408.451 - else:
408.452 - cursect = {'__name__': sectname}
408.453 - self._sections[sectname] = cursect
408.454 - # So sections can't start with a continuation line
408.455 - optname = None
408.456 - # no section header in the file?
408.457 - elif cursect is None:
408.458 - raise MissingSectionHeaderError(fpname, lineno, `line`)
408.459 - # an option line?
408.460 - else:
408.461 - mo = self.OPTCRE.match(line)
408.462 - if mo:
408.463 - optname, vi, optval = mo.group('option', 'vi', 'value')
408.464 - if vi in ('=', ':') and ';' in optval:
408.465 - # ';' is a comment delimiter only if it follows
408.466 - # a spacing character
408.467 - pos = optval.find(';')
408.468 - if pos != -1 and optval[pos-1].isspace():
408.469 - optval = optval[:pos]
408.470 - optval = optval.strip()
408.471 - # allow empty values
408.472 - if optval == '""':
408.473 - optval = ''
408.474 - optname = self.optionxform(optname.rstrip())
408.475 - cursect[optname] = optval
408.476 - else:
408.477 - # a non-fatal parsing error occurred. set up the
408.478 - # exception but keep going. the exception will be
408.479 - # raised at the end of the file and will contain a
408.480 - # list of all bogus lines
408.481 - if not e:
408.482 - e = ParsingError(fpname)
408.483 - e.append(lineno, `line`)
408.484 - # if any parsing errors occurred, raise an exception
408.485 - if e:
408.486 - raise e
408.487 -
408.488 -
408.489 -class ConfigParser(RawConfigParser):
408.490 -
408.491 - def get(self, section, option, raw=False, vars=None):
408.492 - """Get an option value for a given section.
408.493 -
408.494 - All % interpolations are expanded in the return values, based on the
408.495 - defaults passed into the constructor, unless the optional argument
408.496 - `raw' is true. Additional substitutions may be provided using the
408.497 - `vars' argument, which must be a dictionary whose contents overrides
408.498 - any pre-existing defaults.
408.499 -
408.500 - The section DEFAULT is special.
408.501 - """
408.502 - d = self._defaults.copy()
408.503 - try:
408.504 - d.update(self._sections[section])
408.505 - except KeyError:
408.506 - if section != DEFAULTSECT:
408.507 - raise NoSectionError(section)
408.508 - # Update with the entry specific variables
408.509 - if vars is not None:
408.510 - d.update(vars)
408.511 - option = self.optionxform(option)
408.512 - try:
408.513 - value = d[option]
408.514 - except KeyError:
408.515 - raise NoOptionError(option, section)
408.516 -
408.517 - if raw:
408.518 - return value
408.519 - else:
408.520 - return self._interpolate(section, option, value, d)
408.521 -
408.522 - def items(self, section, raw=False, vars=None):
408.523 - """Return a list of tuples with (name, value) for each option
408.524 - in the section.
408.525 -
408.526 - All % interpolations are expanded in the return values, based on the
408.527 - defaults passed into the constructor, unless the optional argument
408.528 - `raw' is true. Additional substitutions may be provided using the
408.529 - `vars' argument, which must be a dictionary whose contents overrides
408.530 - any pre-existing defaults.
408.531 -
408.532 - The section DEFAULT is special.
408.533 - """
408.534 - d = self._defaults.copy()
408.535 - try:
408.536 - d.update(self._sections[section])
408.537 - except KeyError:
408.538 - if section != DEFAULTSECT:
408.539 - raise NoSectionError(section)
408.540 - # Update with the entry specific variables
408.541 - if vars:
408.542 - d.update(vars)
408.543 - options = d.keys()
408.544 - if "__name__" in options:
408.545 - options.remove("__name__")
408.546 - if raw:
408.547 - return [(option, d[option])
408.548 - for option in options]
408.549 - else:
408.550 - return [(option, self._interpolate(section, option, d[option], d))
408.551 - for option in options]
408.552 -
408.553 - def _interpolate(self, section, option, rawval, vars):
408.554 - # do the string interpolation
408.555 - value = rawval
408.556 - depth = MAX_INTERPOLATION_DEPTH
408.557 - while depth: # Loop through this until it's done
408.558 - depth -= 1
408.559 - if value.find("%(") != -1:
408.560 - try:
408.561 - value = value % vars
408.562 - except KeyError, e:
408.563 - raise InterpolationMissingOptionError(
408.564 - option, section, rawval, e[0])
408.565 - else:
408.566 - break
408.567 - if value.find("%(") != -1:
408.568 - raise InterpolationDepthError(option, section, rawval)
408.569 - return value
408.570 -
408.571 -
408.572 -class SafeConfigParser(ConfigParser):
408.573 -
408.574 - def _interpolate(self, section, option, rawval, vars):
408.575 - # do the string interpolation
408.576 - L = []
408.577 - self._interpolate_some(option, L, rawval, section, vars, 1)
408.578 - return ''.join(L)
408.579 -
408.580 - _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
408.581 -
408.582 - def _interpolate_some(self, option, accum, rest, section, map, depth):
408.583 - if depth > MAX_INTERPOLATION_DEPTH:
408.584 - raise InterpolationDepthError(option, section, rest)
408.585 - while rest:
408.586 - p = rest.find("%")
408.587 - if p < 0:
408.588 - accum.append(rest)
408.589 - return
408.590 - if p > 0:
408.591 - accum.append(rest[:p])
408.592 - rest = rest[p:]
408.593 - # p is no longer used
408.594 - c = rest[1:2]
408.595 - if c == "%":
408.596 - accum.append("%")
408.597 - rest = rest[2:]
408.598 - elif c == "(":
408.599 - m = self._interpvar_match(rest)
408.600 - if m is None:
408.601 - raise InterpolationSyntaxError(option, section,
408.602 - "bad interpolation variable reference %r" % rest)
408.603 - var = m.group(1)
408.604 - rest = rest[m.end():]
408.605 - try:
408.606 - v = map[var]
408.607 - except KeyError:
408.608 - raise InterpolationMissingOptionError(
408.609 - option, section, rest, var)
408.610 - if "%" in v:
408.611 - self._interpolate_some(option, accum, v,
408.612 - section, map, depth + 1)
408.613 - else:
408.614 - accum.append(v)
408.615 - else:
408.616 - raise InterpolationSyntaxError(
408.617 - option, section,
408.618 - "'%' must be followed by '%' or '(', found: " + `ret`)
409.1 --- a/python.editor/test/unit/data/testfiles/names.py.testHint2.hints Sun Jan 04 13:11:53 2015 -0600
409.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
409.3 @@ -1,39 +0,0 @@
409.4 -class duplicateSectionError(Error):
409.5 - ---------------------
409.6 -HINT:Name "duplicateSectionError" is not a valid class name according to your code style (CapitalizedWords)
409.7 -FIX:Ignore name violations for "duplicateSectionError"
409.8 -FIX:Change preferred class name style to mixedCase
409.9 -FIX:Turn off class name style checks
409.10 - def __Init__(self, section):
409.11 - --------
409.12 -HINT:Name "__Init__" is not a valid function name according to your code style (lowercase_with_underscores)
409.13 -FIX:Ignore name violations for "__Init__"
409.14 -FIX:Change preferred function name style to CapitalizedWords
409.15 -FIX:Change preferred function name style to Capitalized_With_Underscores
409.16 -FIX:Turn off function name style checks
409.17 -class _noOptionError(Error):
409.18 - --------------
409.19 -HINT:Name "_noOptionError" is not a valid class name according to your code style (CapitalizedWords)
409.20 -FIX:Ignore name violations for "_noOptionError"
409.21 -FIX:Change preferred class name style to mixedCase
409.22 -FIX:Turn off class name style checks
409.23 -class _interpolationError(Error):
409.24 - -------------------
409.25 -HINT:Name "_interpolationError" is not a valid class name according to your code style (CapitalizedWords)
409.26 -FIX:Ignore name violations for "_interpolationError"
409.27 -FIX:Change preferred class name style to mixedCase
409.28 -FIX:Turn off class name style checks
409.29 - def Defaults(self):
409.30 - --------
409.31 -HINT:Name "Defaults" is not a valid function name according to your code style (lowercase_with_underscores)
409.32 -FIX:Ignore name violations for "Defaults"
409.33 -FIX:Change preferred function name style to CapitalizedWords
409.34 -FIX:Change preferred function name style to Capitalized_With_Underscores
409.35 -FIX:Turn off function name style checks
409.36 - def _Sections(self):
409.37 - ---------
409.38 -HINT:Name "_Sections" is not a valid function name according to your code style (lowercase_with_underscores)
409.39 -FIX:Ignore name violations for "_Sections"
409.40 -FIX:Change preferred function name style to CapitalizedWords
409.41 -FIX:Change preferred function name style to Capitalized_With_Underscores
409.42 -FIX:Turn off function name style checks
410.1 --- a/python.editor/test/unit/data/testfiles/names2.py Sun Jan 04 13:11:53 2015 -0600
410.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
410.3 @@ -1,31 +0,0 @@
410.4 -class A:
410.5 - def foo():
410.6 - self.filename = filename
410.7 -
410.8 -def toplevel(x,y,z):
410.9 - print "hello"
410.10 -
410.11 -def toplevel2():
410.12 - print "hello"
410.13 -
410.14 -class Bar:
410.15 - def noargs():
410.16 - print "hello"
410.17 -
410.18 - def okay1(self):
410.19 - print "hello"
410.20 -
410.21 - def okay2(cls):
410.22 - print "hello"
410.23 -
410.24 - def okay3(self, bar):
410.25 - print "hello"
410.26 -
410.27 - def okay4(cls, bar):
410.28 - print "hello"
410.29 -
410.30 - def bad1():
410.31 - print "hello"
410.32 -
410.33 - def bad2(filename):
410.34 - print "hello"
411.1 --- a/python.editor/test/unit/data/testfiles/names2.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
411.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
411.3 @@ -1,31 +0,0 @@
411.4 -class A:
411.5 - def foo():
411.6 - self.filename = filename
411.7 -
411.8 -def toplevel(x,y,z):
411.9 - print "hello"
411.10 -
411.11 -def toplevel2():
411.12 - print "hello"
411.13 -
411.14 -class Bar:
411.15 - def noargs(self):
411.16 - print "hello"
411.17 -
411.18 - def okay1(self):
411.19 - print "hello"
411.20 -
411.21 - def okay2(cls):
411.22 - print "hello"
411.23 -
411.24 - def okay3(self, bar):
411.25 - print "hello"
411.26 -
411.27 - def okay4(cls, bar):
411.28 - print "hello"
411.29 -
411.30 - def bad1():
411.31 - print "hello"
411.32 -
411.33 - def bad2(filename):
411.34 - print "hello"
412.1 --- a/python.editor/test/unit/data/testfiles/names2.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
412.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
412.3 @@ -1,31 +0,0 @@
412.4 -class A:
412.5 - def foo():
412.6 - self.filename = filename
412.7 -
412.8 -def toplevel(x,y,z):
412.9 - print "hello"
412.10 -
412.11 -def toplevel2():
412.12 - print "hello"
412.13 -
412.14 -class Bar:
412.15 - def noargs():
412.16 - print "hello"
412.17 -
412.18 - def okay1(self):
412.19 - print "hello"
412.20 -
412.21 - def okay2(cls):
412.22 - print "hello"
412.23 -
412.24 - def okay3(self, bar):
412.25 - print "hello"
412.26 -
412.27 - def okay4(cls, bar):
412.28 - print "hello"
412.29 -
412.30 - def bad1():
412.31 - print "hello"
412.32 -
412.33 - def bad2(self):
412.34 - print "hello"
413.1 --- a/python.editor/test/unit/data/testfiles/names2.py.testHint3.hints Sun Jan 04 13:11:53 2015 -0600
413.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
413.3 @@ -1,17 +0,0 @@
413.4 - def foo():
413.5 - -
413.6 -HINT:First argument should be 'self' or 'cls'
413.7 -FIX:Insert a new first parameter "self"
413.8 - def noargs():
413.9 - -
413.10 -HINT:First argument should be 'self' or 'cls'
413.11 -FIX:Insert a new first parameter "self"
413.12 - def bad1():
413.13 - -
413.14 -HINT:First argument should be 'self' or 'cls'
413.15 -FIX:Insert a new first parameter "self"
413.16 - def bad2(filename):
413.17 - --------
413.18 -HINT:First argument (filename) should be self or cls
413.19 -FIX:Insert a new first parameter "self"
413.20 -FIX:Rename first parameter "filename" to self
414.1 --- a/python.editor/test/unit/data/testfiles/occurrences1.py Sun Jan 04 13:11:53 2015 -0600
414.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
414.3 @@ -1,6 +0,0 @@
414.4 -__builtin__.repr(x)
414.5 -x.repr(x)
414.6 -
414.7 -def repr(self)
414.8 - print "Test"
414.9 -
415.1 --- a/python.editor/test/unit/data/testfiles/occurrences1.py.test150581b.occurrences Sun Jan 04 13:11:53 2015 -0600
415.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
415.3 @@ -1,1 +0,0 @@
415.4 -__builtin__.|>MARK_OCCURRENCES:re^pr<|(x)
416.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py Sun Jan 04 13:11:53 2015 -0600
416.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
416.3 @@ -1,43 +0,0 @@
416.4 -import module1
416.5 -import module2
416.6 -import module3 as module4
416.7 -
416.8 -toplevelvar = 1
416.9 -toplevelvar2 = 2
416.10 -toplevelvar3 = 3
416.11 -toplevelvar4 = 4
416.12 -
416.13 -def myfunc(funcparam):
416.14 - localvar = 1
416.15 - toplevelvar4 = 6
416.16 - print toplevelvar4
416.17 - x = myfunc
416.18 - myfunc(5)
416.19 - x()
416.20 - pass
416.21 -
416.22 -class MyClass(SuperClass):
416.23 - var_in_class = 1
416.24 - def mymethod(self,param1,param2):
416.25 - in_method = 1
416.26 - in_method = 2
416.27 - print in_method
416.28 - print var_in_class
416.29 - print toplevelvar
416.30 - print toplevelvar2
416.31 - module1.x
416.32 - print param2
416.33 - module4.y
416.34 - toplevelvar3 = 3
416.35 - def myfunc():
416.36 - in_func = 1
416.37 - print in_method
416.38 - print in_func
416.39 - in_method = 2
416.40 - del toplevelvar2
416.41 - print toplevelvar2
416.42 - print toplevelvar3
416.43 - print toplevelvar4
416.44 -
416.45 - def othermethod(self,param3):
416.46 - pass
417.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testLocals3.completion Sun Jan 04 13:11:53 2015 -0600
417.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
417.3 @@ -1,7 +0,0 @@
417.4 -Code completion result for source line:
417.5 -tople|velvar = 1
417.6 -(QueryType=COMPLETION, NameKind=PREFIX)
417.7 -VARIABLE toplevelvar
417.8 -VARIABLE toplevelvar2
417.9 -VARIABLE toplevelvar3
417.10 -VARIABLE toplevelvar4
418.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testLocals4.completion Sun Jan 04 13:11:53 2015 -0600
418.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
418.3 @@ -1,1234 +0,0 @@
418.4 -Code completion result for source line:
418.5 -print |toplevelvar2
418.6 -(QueryType=COMPLETION, NameKind=PREFIX)
418.7 -MODULE module1
418.8 -MODULE module2
418.9 -MODULE module4
418.10 -CLASS MyClass
418.11 -METHOD myfunc()
418.12 -VARIABLE in_method
418.13 -VARIABLE param1
418.14 -VARIABLE param2
418.15 -VARIABLE self
418.16 -VARIABLE toplevelvar
418.17 -VARIABLE toplevelvar2
418.18 -VARIABLE toplevelvar3
418.19 -VARIABLE toplevelvar4
418.20 -------------------------------------
418.21 -CLASS A
418.22 -CLASS ABCMeta
418.23 -CLASS AEServer
418.24 -CLASS AEText
418.25 -CLASS ASTVisitor
418.26 -CLASS AbstractBasicAuthHandler
418.27 -CLASS AbstractClassCode
418.28 -CLASS AbstractCompileMode
418.29 -CLASS AbstractDigestAuthHandler
418.30 -CLASS AbstractFormatter
418.31 -CLASS AbstractFunctionCode
418.32 -CLASS AbstractHTTPHandler
418.33 -CLASS AbstractWriter
418.34 -CLASS Add
418.35 -CLASS And
418.36 -CLASS Application
418.37 -CLASS ArgumentError
418.38 -CLASS ArithmeticError
418.39 -CLASS ArithmeticError
418.40 -CLASS Array
418.41 -CLASS ArrayInstance
418.42 -CLASS AssAttr
418.43 -CLASS AssList
418.44 -CLASS AssName
418.45 -CLASS AssTuple
418.46 -CLASS Assert
418.47 -CLASS AssertionError
418.48 -CLASS AssertionError
418.49 -CLASS Assign
418.50 -CLASS AsyncResult
418.51 -CLASS Attr
418.52 -CLASS AttributeError
418.53 -CLASS AttributeError
418.54 -CLASS AttributeList
418.55 -CLASS AttributeMap
418.56 -CLASS Attributes
418.57 -CLASS AttributesImpl
418.58 -CLASS AttributesNS
418.59 -CLASS AttributesNSImpl
418.60 -CLASS AugAssign
418.61 -CLASS AugGetattr
418.62 -CLASS AugName
418.63 -CLASS AugSlice
418.64 -CLASS AugSubscript
418.65 -CLASS AuthenticationError
418.66 -CLASS AutoGILError
418.67 -CLASS B
418.68 -CLASS BCPPCompiler
418.69 -CLASS BCPTestCase
418.70 -CLASS BZ2Compressor
418.71 -CLASS BZ2Decompressor
418.72 -CLASS BZ2File
418.73 -CLASS Babyl
418.74 -CLASS BabylMailbox
418.75 -CLASS BabylMessage
418.76 -CLASS Backquote
418.77 -CLASS BadBoundaryPointsErr
418.78 -CLASS BadFutureParser
418.79 -CLASS BadOptionError
418.80 -CLASS BadStatusLine
418.81 -CLASS BadZipfile
418.82 -CLASS Balloon
418.83 -CLASS Bar
418.84 -CLASS BaseCGIHandler
418.85 -CLASS BaseCookie
418.86 -CLASS BaseException
418.87 -CLASS BaseException
418.88 -CLASS BaseHTTPRequestHandler
418.89 -CLASS BaseHandler
418.90 -CLASS BaseIncrementalParser
418.91 -CLASS BaseManager
418.92 -CLASS BaseProxy
418.93 -CLASS BaseRequestHandler
418.94 -CLASS BaseRotatingHandler
418.95 -CLASS BaseSet
418.96 -CLASS BasicModuleImporter
418.97 -CLASS BasicModuleLoader
418.98 -CLASS BastionClass
418.99 -CLASS Baz
418.100 -CLASS Bdb
418.101 -CLASS BdbQuit
418.102 -CLASS BigEndianStructure
418.103 -CLASS Binary
418.104 -CLASS Bitand
418.105 -CLASS Bitor
418.106 -CLASS Bitxor
418.107 -CLASS Block
418.108 -CLASS BlockFinder
418.109 -CLASS BlockingIOError
418.110 -CLASS Boolean
418.111 -CLASS BoundaryError
418.112 -CLASS BoundedSemaphore
418.113 -CLASS Break
418.114 -CLASS Breakpoint
418.115 -CLASS BsdDbShelf
418.116 -CLASS BufferTooShort
418.117 -CLASS BufferedIOBase
418.118 -CLASS BufferedRWPair
418.119 -CLASS BufferedRandom
418.120 -CLASS BufferedReader
418.121 -CLASS BufferedWriter
418.122 -CLASS BufferingFormatter
418.123 -CLASS BufferingHandler
418.124 -CLASS BuildPyTestCase
418.125 -CLASS BuildScriptsTestCase
418.126 -CLASS BuiltinImporter
418.127 -CLASS Bulkcopy
418.128 -CLASS ButtonBox
418.129 -CLASS BytesIO
418.130 -CLASS C
418.131 -CLASS CAB
418.132 -CLASS CCompiler
418.133 -CLASS CCompilerError
418.134 -CLASS CDATASection
418.135 -CLASS CDLL
418.136 -CLASS CGIHTTPRequestHandler
418.137 -CLASS CGIHandler
418.138 -CLASS CGIXMLRPCRequestHandler
418.139 -CLASS CacheFTPHandler
418.140 -CLASS CallFunc
418.141 -CLASS CalledProcessError
418.142 -CLASS CannotSendHeader
418.143 -CLASS CannotSendRequest
418.144 -CLASS Canonizer
418.145 -CLASS CharacterData
418.146 -CLASS Charset
418.147 -CLASS CharsetError
418.148 -CLASS CheckList
418.149 -CLASS Childless
418.150 -CLASS Chunk
418.151 -CLASS Clamped
418.152 -CLASS Class
418.153 -CLASS ClassCodeGenerator
418.154 -CLASS ClassScope
418.155 -CLASS Cmd
418.156 -CLASS CodeGenerator
418.157 -CLASS Codec
418.158 -CLASS CodecRegistryError
418.159 -CLASS ComboBox
418.160 -CLASS Command
418.161 -CLASS CommandCompiler
418.162 -CLASS Comment
418.163 -CLASS Compare
418.164 -CLASS Comparison
418.165 -CLASS Compile
418.166 -CLASS CompileError
418.167 -CLASS Completer
418.168 -CLASS Complex
418.169 -CLASS ComponentItem
418.170 -CLASS Condition
418.171 -CLASS ConfigParser
418.172 -CLASS Connection
418.173 -CLASS Const
418.174 -CLASS ContentGenerator
418.175 -CLASS ContentHandler
418.176 -CLASS Context
418.177 -CLASS Continue
418.178 -CLASS Control
418.179 -CLASS ControlsWindow
418.180 -CLASS ConversionError
418.181 -CLASS Cookie
418.182 -CLASS CookieError
418.183 -CLASS CookieJar
418.184 -CLASS CookiePolicy
418.185 -CLASS CoverageResults
418.186 -CLASS Cursor
418.187 -CLASS CygwinCCompiler
418.188 -CLASS D
418.189 -CLASS DOMBuilder
418.190 -CLASS DOMEntityResolver
418.191 -CLASS DOMError
418.192 -CLASS DOMEventStream
418.193 -CLASS DOMException
418.194 -CLASS DOMImplementation
418.195 -CLASS DOMInputSource
418.196 -CLASS DOMStringSizeErr
418.197 -CLASS DTDHandler
418.198 -CLASS Data
418.199 -CLASS Database
418.200 -CLASS DatagramHandler
418.201 -CLASS DatagramRequestHandler
418.202 -CLASS DateTime
418.203 -CLASS DbfilenameShelf
418.204 -CLASS DebugRunner
418.205 -CLASS DebuggingServer
418.206 -CLASS Decimal
418.207 -CLASS DecimalException
418.208 -CLASS DeclHandler
418.209 -CLASS DecodedGenerator
418.210 -CLASS Decorators
418.211 -CLASS DefaultCookiePolicy
418.212 -CLASS DefaultHandler
418.213 -CLASS Delegator
418.214 -CLASS DeprecationWarning
418.215 -CLASS DeprecationWarning
418.216 -CLASS Dialect
418.217 -CLASS Dialog
418.218 -CLASS DialogWindow
418.219 -CLASS Dict
418.220 -CLASS DictMixin
418.221 -CLASS DictReader
418.222 -CLASS DictWriter
418.223 -CLASS Differ
418.224 -CLASS DirList
418.225 -CLASS DirSelectBox
418.226 -CLASS DirSelectDialog
418.227 -CLASS DirTree
418.228 -CLASS Directory
418.229 -CLASS Discard
418.230 -CLASS Distribution
418.231 -CLASS DistributionMetadata
418.232 -CLASS DistributionTestCase
418.233 -CLASS DistutilsArgError
418.234 -CLASS DistutilsClassError
418.235 -CLASS DistutilsError
418.236 -CLASS DistutilsExecError
418.237 -CLASS DistutilsFileError
418.238 -CLASS DistutilsGetoptError
418.239 -CLASS DistutilsInternalError
418.240 -CLASS DistutilsModuleError
418.241 -CLASS DistutilsOptionError
418.242 -CLASS DistutilsPlatformError
418.243 -CLASS DistutilsSetupError
418.244 -CLASS DistutilsTemplateError
418.245 -CLASS Div
418.246 -CLASS DivisionByZero
418.247 -CLASS Doc
418.248 -CLASS DocCGIXMLRPCRequestHandler
418.249 -CLASS DocTest
418.250 -CLASS DocTestFailure
418.251 -CLASS DocTestFinder
418.252 -CLASS DocTestParser
418.253 -CLASS DocTestRunner
418.254 -CLASS DocXMLRPCRequestHandler
418.255 -CLASS DocXMLRPCServer
418.256 -CLASS Document
418.257 -CLASS DocumentFragment
418.258 -CLASS DocumentHandler
418.259 -CLASS DocumentType
418.260 -CLASS DomstringSizeErr
418.261 -CLASS DumbWriter
418.262 -CLASS DummyCommand
418.263 -CLASS DuplicateSectionError
418.264 -CLASS DynLoadSuffixImporter
418.265 -CLASS EMXCCompiler
418.266 -CLASS EOFError
418.267 -CLASS EOFError
418.268 -CLASS ESISDocHandler
418.269 -CLASS Element
418.270 -CLASS ElementInfo
418.271 -CLASS ElementTree
418.272 -CLASS Ellipsis
418.273 -CLASS Empty
418.274 -CLASS EmptyNode
418.275 -CLASS EndOfBlock
418.276 -CLASS Entity
418.277 -CLASS EntityResolver
418.278 -CLASS Enum
418.279 -CLASS EnvironmentError
418.280 -CLASS EnvironmentError
418.281 -CLASS Error
418.282 -CLASS ErrorDuringImport
418.283 -CLASS ErrorHandler
418.284 -CLASS ErrorPrinter
418.285 -CLASS ErrorRaiser
418.286 -CLASS Event
418.287 -CLASS EventBroadcaster
418.288 -CLASS EventException
418.289 -CLASS ExFileSelectBox
418.290 -CLASS Example
418.291 -CLASS ExampleASTVisitor
418.292 -CLASS Exception
418.293 -CLASS Exception
418.294 -CLASS Exec
418.295 -CLASS ExitNow
418.296 -CLASS ExpatError
418.297 -CLASS ExpatParser
418.298 -CLASS Expression
418.299 -CLASS ExpressionCodeGenerator
418.300 -CLASS Extension
418.301 -CLASS F
418.302 -CLASS FTP
418.303 -CLASS FTPHandler
418.304 -CLASS Factory
418.305 -CLASS FancyGetopt
418.306 -CLASS FancyModuleLoader
418.307 -CLASS FancyURLopener
418.308 -CLASS Fault
418.309 -CLASS Feature
418.310 -CLASS FeedParser
418.311 -CLASS FieldStorage
418.312 -CLASS FileCookieJar
418.313 -CLASS FileEntry
418.314 -CLASS FileHandler
418.315 -CLASS FileIO
418.316 -CLASS FileInput
418.317 -CLASS FileList
418.318 -CLASS FileSelectBox
418.319 -CLASS FileWrapper
418.320 -CLASS Filter
418.321 -CLASS Filterer
418.322 -CLASS FingerHandler
418.323 -CLASS FirstHeaderLineIsContinuationD
418.324 -CLASS FloatingPointError
418.325 -CLASS FloatingPointError
418.326 -CLASS FloorDiv
418.327 -CLASS FlowGraph
418.328 -CLASS Folder
418.329 -CLASS Foo
418.330 -CLASS For
418.331 -CLASS ForkingMixIn
418.332 -CLASS ForkingTCPServer
418.333 -CLASS ForkingUDPServer
418.334 -CLASS Form
418.335 -CLASS FormContent
418.336 -CLASS FormContentDict
418.337 -CLASS Formatter
418.338 -CLASS Fraction
418.339 -CLASS From
418.340 -CLASS FtException
418.341 -CLASS Full
418.342 -CLASS FuncPtr
418.343 -CLASS Function
418.344 -CLASS FunctionCodeGenerator
418.345 -CLASS FunctionScope
418.346 -CLASS FunctionTestCase
418.347 -CLASS FutureParser
418.348 -CLASS FutureWarning
418.349 -CLASS FutureWarning
418.350 -CLASS GNUTranslations
418.351 -CLASS GenExpr
418.352 -CLASS GenExprFor
418.353 -CLASS GenExprIf
418.354 -CLASS GenExprInner
418.355 -CLASS GenExprScope
418.356 -CLASS Generator
418.357 -CLASS GeneratorExit
418.358 -CLASS GeneratorExit
418.359 -CLASS Getattr
418.360 -CLASS GetattrMagic
418.361 -CLASS GetoptError
418.362 -CLASS Global
418.363 -CLASS GopherError
418.364 -CLASS GopherHandler
418.365 -CLASS GridBag
418.366 -CLASS GzipFile
418.367 -CLASS HList
418.368 -CLASS HMAC
418.369 -CLASS HRESULT
418.370 -CLASS HTMLDoc
418.371 -CLASS HTMLParseError
418.372 -CLASS HTMLParser
418.373 -CLASS HTMLRepr
418.374 -CLASS HTTP
418.375 -CLASS HTTPBasicAuthHandler
418.376 -CLASS HTTPConnection
418.377 -CLASS HTTPCookieProcessor
418.378 -CLASS HTTPDefaultErrorHandler
418.379 -CLASS HTTPDigestAuthHandler
418.380 -CLASS HTTPError
418.381 -CLASS HTTPErrorProcessor
418.382 -CLASS HTTPException
418.383 -CLASS HTTPHandler
418.384 -CLASS HTTPPasswordMgr
418.385 -CLASS HTTPPasswordMgrWithDefaultReal
418.386 -CLASS HTTPRedirectHandler
418.387 -CLASS HTTPResponse
418.388 -CLASS HTTPSConnection
418.389 -CLASS HTTPSHandler
418.390 -CLASS HTTPServer
418.391 -CLASS Handler
418.392 -CLASS HandlerBase
418.393 -CLASS Header
418.394 -CLASS HeaderParseError
418.395 -CLASS HeaderParser
418.396 -CLASS Headers
418.397 -CLASS HelpFormatter
418.398 -CLASS Helper
418.399 -CLASS HierarchyRequestErr
418.400 -CLASS Hook
418.401 -CLASS Hooks
418.402 -CLASS HtmlDiff
418.403 -CLASS IC
418.404 -CLASS IMAP4
418.405 -CLASS IMAP4_SSL
418.406 -CLASS IMAP4_stream
418.407 -CLASS IOBase
418.408 -CLASS IOError
418.409 -CLASS IOError
418.410 -CLASS Identified
418.411 -CLASS If
418.412 -CLASS IfExp
418.413 -CLASS Ignore
418.414 -CLASS IllegalMonthError
418.415 -CLASS IllegalWeekdayError
418.416 -CLASS ImmutableSet
418.417 -CLASS ImpImporter
418.418 -CLASS ImpLoader
418.419 -CLASS Import
418.420 -CLASS ImportError
418.421 -CLASS ImportError
418.422 -CLASS ImportManager
418.423 -CLASS ImportWarning
418.424 -CLASS ImportWarning
418.425 -CLASS Importer
418.426 -CLASS ImproperConnectionState
418.427 -CLASS Incomplete
418.428 -CLASS IncompleteRead
418.429 -CLASS IncrementalDecoder
418.430 -CLASS IncrementalEncoder
418.431 -CLASS IncrementalNewlineDecoder
418.432 -CLASS IncrementalParser
418.433 -CLASS IndentedHelpFormatter
418.434 -CLASS IndexError
418.435 -CLASS IndexError
418.436 -CLASS IndexSizeErr
418.437 -CLASS Inexact
418.438 -CLASS IniParser
418.439 -CLASS InputOnly
418.440 -CLASS InputSource
418.441 -CLASS InsertionLoc
418.442 -CLASS InstallScriptsTestCase
418.443 -CLASS InstallTestCase
418.444 -CLASS Integral
418.445 -CLASS Interactive
418.446 -CLASS InteractiveCodeGenerator
418.447 -CLASS InteractiveConsole
418.448 -CLASS InteractiveInterpreter
418.449 -CLASS InterpFormContentDict
418.450 -CLASS InterpolationDepthError
418.451 -CLASS InterpolationError
418.452 -CLASS InterpolationSyntaxError
418.453 -CLASS IntlText
418.454 -CLASS IntlWritingCode
418.455 -CLASS InuseAttributeErr
418.456 -CLASS InvalidAccessErr
418.457 -CLASS InvalidCharacterErr
418.458 -CLASS InvalidModificationErr
418.459 -CLASS InvalidNodeTypeErr
418.460 -CLASS InvalidOperation
418.461 -CLASS InvalidStateErr
418.462 -CLASS InvalidURL
418.463 -CLASS Invert
418.464 -CLASS IsqlCmd
418.465 -CLASS IsqlExit
418.466 -CLASS IterableUserDict
418.467 -CLASS JSONDecoder
418.468 -CLASS JSONEncoder
418.469 -CLASS JavaSAXParser
418.470 -CLASS JoinableQueue
418.471 -CLASS JyDTDHandlerWrapper
418.472 -CLASS JyEntityResolverWrapper
418.473 -CLASS JyErrorHandlerWrapper
418.474 -CLASS JyInputSourceWrapper
418.475 -CLASS JythonCompiler
418.476 -CLASS JythonSignalHandler
418.477 -CLASS KeyError
418.478 -CLASS KeyError
418.479 -CLASS KeyboardInterrupt
418.480 -CLASS KeyboardInterrupt
418.481 -CLASS Keyword
418.482 -CLASS LOBTestCase
418.483 -CLASS LWPCookieJar
418.484 -CLASS LabelEntry
418.485 -CLASS LabelFrame
418.486 -CLASS Lambda
418.487 -CLASS LambdaScope
418.488 -CLASS LargeZipFile
418.489 -CLASS LeftShift
418.490 -CLASS LexicalHandler
418.491 -CLASS LexicalXMLGenerator
418.492 -CLASS LibError
418.493 -CLASS LibraryLoader
418.494 -CLASS LineAddrTable
418.495 -CLASS LinkError
418.496 -CLASS List
418.497 -CLASS ListComp
418.498 -CLASS ListCompFor
418.499 -CLASS ListCompIf
418.500 -CLASS ListNoteBook
418.501 -CLASS Listener
418.502 -CLASS LittleEndianStructure
418.503 -CLASS LoadError
418.504 -CLASS LocalNameFinder
418.505 -CLASS Location
418.506 -CLASS Locator
418.507 -CLASS Lock
418.508 -CLASS Log
418.509 -CLASS LogRecord
418.510 -CLASS Logger
418.511 -CLASS LoggingSilencer
418.512 -CLASS Logical
418.513 -CLASS LookupError
418.514 -CLASS LookupError
418.515 -CLASS LooseVersion
418.516 -CLASS MH
418.517 -CLASS MHMailbox
418.518 -CLASS MHMessage
418.519 -CLASS MIMEApplication
418.520 -CLASS MIMEAudio
418.521 -CLASS MIMEBase
418.522 -CLASS MIMEImage
418.523 -CLASS MIMEMessage
418.524 -CLASS MIMEMultipart
418.525 -CLASS MIMENonMultipart
418.526 -CLASS MIMEText
418.527 -CLASS MMDF
418.528 -CLASS MMDFMessage
418.529 -CLASS MSVCCompiler
418.530 -CLASS MWerksCompiler
418.531 -CLASS MacroExpander
418.532 -CLASS Mailbox
418.533 -CLASS Maildir
418.534 -CLASS MaildirMessage
418.535 -CLASS MailmanProxy
418.536 -CLASS MalformedHeaderDefect
418.537 -CLASS Manager
418.538 -CLASS Marshaller
418.539 -CLASS MemoryError
418.540 -CLASS MemoryError
418.541 -CLASS MemoryHandler
418.542 -CLASS Message
418.543 -CLASS MessageDefect
418.544 -CLASS MessageError
418.545 -CLASS MessageParseError
418.546 -CLASS MetadataTestCase
418.547 -CLASS Meter
418.548 -CLASS MimeWriter
418.549 -CLASS Mingw32CCompiler
418.550 -CLASS MiniApplication
418.551 -CLASS MiniFieldStorage
418.552 -CLASS MisplacedEnvelopeHeaderDefect
418.553 -CLASS MissingSectionHeaderError
418.554 -CLASS MmdfMailbox
418.555 -CLASS Mod
418.556 -CLASS Model
418.557 -CLASS Module
418.558 -CLASS ModuleCodeGenerator
418.559 -CLASS ModuleFinder
418.560 -CLASS ModuleImporter
418.561 -CLASS ModuleLoader
418.562 -CLASS ModuleScanner
418.563 -CLASS ModuleScope
418.564 -CLASS MozillaCookieJar
418.565 -CLASS Mul
418.566 -CLASS MultiCall
418.567 -CLASS MultiCallIterator
418.568 -CLASS MultiFile
418.569 -CLASS MultipartConversionError
418.570 -CLASS MultipartInvariantViolationDef
418.571 -CLASS MutableString
418.572 -CLASS MyClass
418.573 -CLASS MyTest
418.574 -CLASS NNTP
418.575 -CLASS NNTPDataError
418.576 -CLASS NNTPPermanentError
418.577 -CLASS NNTPProtocolError
418.578 -CLASS NNTPReplyError
418.579 -CLASS NNTPTemporaryError
418.580 -CLASS NProperty
418.581 -CLASS NTEventLogHandler
418.582 -CLASS NULL
418.583 -CLASS Name
418.584 -CLASS NameError
418.585 -CLASS NameError
418.586 -CLASS NamedNodeMap
418.587 -CLASS NamespaceErr
418.588 -CLASS NannyNag
418.589 -CLASS NestedScopeMixin
418.590 -CLASS Netrc
418.591 -CLASS NetrcParseError
418.592 -CLASS NewStyle
418.593 -CLASS NoBoundaryInMultipartDefect
418.594 -CLASS NoDataAllowedErr
418.595 -CLASS NoModificationAllowedErr
418.596 -CLASS NoOpMetaClass
418.597 -CLASS NoOptionError
418.598 -CLASS NoSectionError
418.599 -CLASS Node
418.600 -CLASS NodeFilter
418.601 -CLASS NodeTransformer
418.602 -CLASS NodeVisitor
418.603 -CLASS Not
418.604 -CLASS NotANumber
418.605 -CLASS NotConnected
418.606 -CLASS NotFoundErr
418.607 -CLASS NotImplementedError
418.608 -CLASS NotImplementedError
418.609 -CLASS NotSupportedErr
418.610 -CLASS Notation
418.611 -CLASS NoteBook
418.612 -CLASS NullFormatter
418.613 -CLASS NullImporter
418.614 -CLASS NullTranslations
418.615 -CLASS NullWriter
418.616 -CLASS Number
418.617 -CLASS OSError
418.618 -CLASS OSError
418.619 -CLASS OSSAudioError
418.620 -CLASS ObjectSpecifier
418.621 -CLASS OleDLL
418.622 -CLASS OpFinder
418.623 -CLASS OpenerDirector
418.624 -CLASS OptParseError
418.625 -CLASS Option
418.626 -CLASS OptionConflictError
418.627 -CLASS OptionContainer
418.628 -CLASS OptionDummy
418.629 -CLASS OptionError
418.630 -CLASS OptionGroup
418.631 -CLASS OptionMenu
418.632 -CLASS OptionParser
418.633 -CLASS OptionValueError
418.634 -CLASS Or
418.635 -CLASS OracleSPTest
418.636 -CLASS Ordinal
418.637 -CLASS OutputChecker
418.638 -CLASS Overflow
418.639 -CLASS OverflowError
418.640 -CLASS OverflowError
418.641 -CLASS POP3
418.642 -CLASS POP3_SSL
418.643 -CLASS Packer
418.644 -CLASS PanedWindow
418.645 -CLASS Panel
418.646 -CLASS Parser
418.647 -CLASS ParserBase
418.648 -CLASS ParserError
418.649 -CLASS ParsingError
418.650 -CLASS Pass
418.651 -CLASS Pattern
418.652 -CLASS Pdb
418.653 -CLASS PendingDeprecationWarning
418.654 -CLASS PendingDeprecationWarning
418.655 -CLASS PickleError
418.656 -CLASS Pickler
418.657 -CLASS PicklingError
418.658 -CLASS PlaceHolder
418.659 -CLASS Popen
418.660 -CLASS Popen3
418.661 -CLASS Popen4
418.662 -CLASS PopupMenu
418.663 -CLASS PortableUnixMailbox
418.664 -CLASS Power
418.665 -CLASS PreprocessError
418.666 -CLASS PrettyPrinter
418.667 -CLASS Print
418.668 -CLASS Printnl
418.669 -CLASS Process
418.670 -CLASS ProcessingInstruction
418.671 -CLASS Profile
418.672 -CLASS ProgressBar
418.673 -CLASS Prompt
418.674 -CLASS ProtocolError
418.675 -CLASS ProxyBasicAuthHandler
418.676 -CLASS ProxyDigestAuthHandler
418.677 -CLASS ProxyHandler
418.678 -CLASS PullDOM
418.679 -CLASS PureProxy
418.680 -CLASS PyCompileError
418.681 -CLASS PyDLL
418.682 -CLASS PyDialog
418.683 -CLASS PyFlowGraph
418.684 -CLASS PyHKEY
418.685 -CLASS PyZipFile
418.686 -CLASS QDPoint
418.687 -CLASS QDRectangle
418.688 -CLASS QName
418.689 -CLASS Queue
418.690 -CLASS RExec
418.691 -CLASS RGBColor
418.692 -CLASS RLock
418.693 -CLASS RadioButtonGroup
418.694 -CLASS Raise
418.695 -CLASS Random
418.696 -CLASS Range
418.697 -CLASS RangeException
418.698 -CLASS Rational
418.699 -CLASS RawConfigParser
418.700 -CLASS RawIOBase
418.701 -CLASS RawTurtle
418.702 -CLASS ReadOnlySequentialNamedNodeMap
418.703 -CLASS Real
418.704 -CLASS Record
418.705 -CLASS ReferenceError
418.706 -CLASS ReferenceError
418.707 -CLASS Repr
418.708 -CLASS Request
418.709 -CLASS ResponseError
418.710 -CLASS ResponseNotReady
418.711 -CLASS ResultSet
418.712 -CLASS ResultSetRow
418.713 -CLASS Return
418.714 -CLASS RightShift
418.715 -CLASS RobotFileParser
418.716 -CLASS RootLogger
418.717 -CLASS RotatingFileHandler
418.718 -CLASS Rounded
418.719 -CLASS Row
418.720 -CLASS RuntimeError
418.721 -CLASS RuntimeError
418.722 -CLASS RuntimeWarning
418.723 -CLASS RuntimeWarning
418.724 -CLASS SAX2DOM
418.725 -CLASS SAXException
418.726 -CLASS SAXNotRecognizedException
418.727 -CLASS SAXNotSupportedException
418.728 -CLASS SAXParseException
418.729 -CLASS SAXReaderNotAvailable
418.730 -CLASS SGMLParseError
418.731 -CLASS SGMLParser
418.732 -CLASS SMTP
418.733 -CLASS SMTPAuthenticationError
418.734 -CLASS SMTPConnectError
418.735 -CLASS SMTPDataError
418.736 -CLASS SMTPException
418.737 -CLASS SMTPHandler
418.738 -CLASS SMTPHeloError
418.739 -CLASS SMTPRecipientsRefused
418.740 -CLASS SMTPResponseException
418.741 -CLASS SMTPSenderRefused
418.742 -CLASS SMTPServer
418.743 -CLASS SMTPServerDisconnected
418.744 -CLASS SQLServerSPTest
418.745 -CLASS SQLTestCase
418.746 -CLASS SSLError
418.747 -CLASS SSLSocket
418.748 -CLASS ST
418.749 -CLASS SafeConfigParser
418.750 -CLASS SafeTransport
418.751 -CLASS Schema
418.752 -CLASS Scope
418.753 -CLASS Screen
418.754 -CLASS ScrolledCavas
418.755 -CLASS ScrolledText
418.756 -CLASS ScrolledWindow
418.757 -CLASS Select
418.758 -CLASS Semaphore
418.759 -CLASS SequenceMatcher
418.760 -CLASS SerialCookie
418.761 -CLASS Server
418.762 -CLASS ServerHTMLDoc
418.763 -CLASS ServerProxy
418.764 -CLASS Set
418.765 -CLASS SgmlopParser
418.766 -CLASS Shape
418.767 -CLASS Shelf
418.768 -CLASS SimpleCookie
418.769 -CLASS SimpleHTTPRequestHandler
418.770 -CLASS SimpleHandler
418.771 -CLASS SimpleLocator
418.772 -CLASS SimpleXMLRPCDispatcher
418.773 -CLASS SimpleXMLRPCRequestHandler
418.774 -CLASS SimpleXMLRPCServer
418.775 -CLASS Slice
418.776 -CLASS Sliceobj
418.777 -CLASS SlowParser
418.778 -CLASS SmartCookie
418.779 -CLASS Sniffer
418.780 -CLASS SocketHandler
418.781 -CLASS SocketType
418.782 -CLASS Stack
418.783 -CLASS StackDepthTracker
418.784 -CLASS StandardError
418.785 -CLASS StandardError
418.786 -CLASS StartBoundaryNotFoundDefect
418.787 -CLASS Stats
418.788 -CLASS StdButtonBox
418.789 -CLASS Stmt
418.790 -CLASS StopIteration
418.791 -CLASS StopIteration
418.792 -CLASS StopTokenizing
418.793 -CLASS Strange
418.794 -CLASS StreamConverter
418.795 -CLASS StreamHandler
418.796 -CLASS StreamReader
418.797 -CLASS StreamRequestHandler
418.798 -CLASS StreamWriter
418.799 -CLASS StrictVersion
418.800 -CLASS StringIO
418.801 -CLASS Struct
418.802 -CLASS Structure
418.803 -CLASS StyledText
418.804 -CLASS Sub
418.805 -CLASS SubPattern
418.806 -CLASS Subnormal
418.807 -CLASS Subscript
418.808 -CLASS SummaryInformation
418.809 -CLASS Super
418.810 -CLASS SuperSuper
418.811 -CLASS SvFormContentDict
418.812 -CLASS Symbol
418.813 -CLASS SymbolTable
418.814 -CLASS SymbolVisitor
418.815 -CLASS SyncManager
418.816 -CLASS SyntaxErr
418.817 -CLASS SyntaxError
418.818 -CLASS SyntaxError
418.819 -CLASS SyntaxErrorChecker
418.820 -CLASS SyntaxWarning
418.821 -CLASS SyntaxWarning
418.822 -CLASS SysLogHandler
418.823 -CLASS SystemError
418.824 -CLASS SystemError
418.825 -CLASS SystemExit
418.826 -CLASS SystemExit
418.827 -CLASS SystemRandom
418.828 -CLASS TCPServer
418.829 -CLASS TList
418.830 -CLASS TalkTo
418.831 -CLASS TarError
418.832 -CLASS TarFile
418.833 -CLASS TarInfo
418.834 -CLASS Telnet
418.835 -CLASS TempdirManager
418.836 -CLASS Template
418.837 -CLASS Test
418.838 -CLASS TestCase
418.839 -CLASS TestClass
418.840 -CLASS TestCrispinTorture
418.841 -CLASS TestDistribution
418.842 -CLASS TestLoader
418.843 -CLASS TestResult
418.844 -CLASS TestSuite
418.845 -CLASS TestThread
418.846 -CLASS TestXMLParser
418.847 -CLASS Testcase
418.848 -CLASS Tester
418.849 -CLASS Text
418.850 -CLASS TextDoc
418.851 -CLASS TextFile
418.852 -CLASS TextIOBase
418.853 -CLASS TextIOWrapper
418.854 -CLASS TextRepr
418.855 -CLASS TextTestRunner
418.856 -CLASS TextWrapper
418.857 -CLASS Textbox
418.858 -CLASS Thread
418.859 -CLASS ThreadingMixIn
418.860 -CLASS ThreadingTCPServer
418.861 -CLASS ThreadingUDPServer
418.862 -CLASS ThreadingUnixDatagramServer
418.863 -CLASS ThreadingUnixStreamServer
418.864 -CLASS TimedRotatingFileHandler
418.865 -CLASS Timer
418.866 -CLASS TitledHelpFormatter
418.867 -CLASS Tix
418.868 -CLASS Tk
418.869 -CLASS TokenError
418.870 -CLASS Tokenizer
418.871 -CLASS TortureBase
418.872 -CLASS Trace
418.873 -CLASS Transformer
418.874 -CLASS Transport
418.875 -CLASS Tree
418.876 -CLASS TreeBuilder
418.877 -CLASS TryExcept
418.878 -CLASS TryFinally
418.879 -CLASS Tuple
418.880 -CLASS TupleArg
418.881 -CLASS Turtle
418.882 -CLASS TurtleScreen
418.883 -CLASS Type
418.884 -CLASS TypeError
418.885 -CLASS TypeError
418.886 -CLASS TypeInfo
418.887 -CLASS UDPServer
418.888 -CLASS URLError
418.889 -CLASS UUID
418.890 -CLASS UnaryAdd
418.891 -CLASS UnarySub
418.892 -CLASS UnboundLocalError
418.893 -CLASS UnboundLocalError
418.894 -CLASS Underflow
418.895 -CLASS UnexpectedException
418.896 -CLASS UnicodeDecodeError
418.897 -CLASS UnicodeDecodeError
418.898 -CLASS UnicodeEncodeError
418.899 -CLASS UnicodeEncodeError
418.900 -CLASS UnicodeError
418.901 -CLASS UnicodeError
418.902 -CLASS UnicodeTranslateError
418.903 -CLASS UnicodeTranslateError
418.904 -CLASS UnicodeWarning
418.905 -CLASS UnicodeWarning
418.906 -CLASS UnimplementedFileMode
418.907 -CLASS Union
418.908 -CLASS UnixCCompiler
418.909 -CLASS UnixDatagramServer
418.910 -CLASS UnixMailbox
418.911 -CLASS UnixStreamServer
418.912 -CLASS Unknown
418.913 -CLASS UnknownFileError
418.914 -CLASS UnknownHandler
418.915 -CLASS UnknownProtocol
418.916 -CLASS UnknownTransferEncoding
418.917 -CLASS Unload
418.918 -CLASS Unmarshaller
418.919 -CLASS Unpacker
418.920 -CLASS Unpickler
418.921 -CLASS UnpicklingError
418.922 -CLASS UnspecifiedEventTypeErr
418.923 -CLASS UnsupportedOperation
418.924 -CLASS UserDataHandler
418.925 -CLASS UserDict
418.926 -CLASS UserList
418.927 -CLASS UserString
418.928 -CLASS UserWarning
418.929 -CLASS UserWarning
418.930 -CLASS ValidationErr
418.931 -CLASS ValueError
418.932 -CLASS ValueError
418.933 -CLASS Values
418.934 -CLASS Vec2D
418.935 -CLASS Vendor
418.936 -CLASS Version
418.937 -CLASS VersionPredicate
418.938 -CLASS View
418.939 -CLASS WSGIRequestHandler
418.940 -CLASS WSGIServer
418.941 -CLASS Warning
418.942 -CLASS Warning
418.943 -CLASS Wave_read
418.944 -CLASS Wave_write
418.945 -CLASS WeakKeyDictionary
418.946 -CLASS WeakValueDictionary
418.947 -CLASS While
418.948 -CLASS WichmannHill
418.949 -CLASS WinDLL
418.950 -CLASS Window
418.951 -CLASS WindowsError
418.952 -CLASS WindowsError
418.953 -CLASS With
418.954 -CLASS WrongDocumentErr
418.955 -CLASS X
418.956 -CLASS XMLFilter
418.957 -CLASS XMLFilterBase
418.958 -CLASS XMLFilterImpl
418.959 -CLASS XMLGenerator
418.960 -CLASS XMLParser
418.961 -CLASS XMLRPCDocGenerator
418.962 -CLASS XMLReader
418.963 -CLASS XMLTreeBuilder
418.964 -CLASS XmlParseErr
418.965 -CLASS Yield
418.966 -CLASS Yuck
418.967 -CLASS ZeroDivisionError
418.968 -CLASS ZeroDivisionError
418.969 -CLASS ZipFile
418.970 -CLASS ZipImportError
418.971 -CLASS ZipInfo
418.972 -CLASS _CData [PROTECTE
418.973 -CLASS _FuncPtr [PROTECTE
418.974 -CLASS _SimpleCData [PROTECTE
418.975 -CLASS _posixfile_
418.976 -CLASS array
418.977 -CLASS async_chat
418.978 -CLASS bdist
418.979 -CLASS bdist_dumb
418.980 -CLASS bdist_msi
418.981 -CLASS bdist_rpm
418.982 -CLASS bdist_wininst
418.983 -CLASS bool
418.984 -CLASS bsddbobject
418.985 -CLASS build
418.986 -CLASS build_clib
418.987 -CLASS build_ext
418.988 -CLASS build_py
418.989 -CLASS build_scripts
418.990 -CLASS c_bool
418.991 -CLASS c_byte
418.992 -CLASS c_char
418.993 -CLASS c_char_p
418.994 -CLASS c_double
418.995 -CLASS c_float
418.996 -CLASS c_int
418.997 -CLASS c_int16
418.998 -CLASS c_int32
418.999 -CLASS c_int64
418.1000 -CLASS c_int8
418.1001 -CLASS c_long
418.1002 -CLASS c_longdouble
418.1003 -CLASS c_longlong
418.1004 -CLASS c_short
418.1005 -CLASS c_size_t
418.1006 -CLASS c_ubyte
418.1007 -CLASS c_uint
418.1008 -CLASS c_uint16
418.1009 -CLASS c_uint32
418.1010 -CLASS c_uint64
418.1011 -CLASS c_uint8
418.1012 -CLASS c_ulong
418.1013 -CLASS c_ulonglong
418.1014 -CLASS c_ushort
418.1015 -CLASS c_void_p
418.1016 -CLASS c_wchar
418.1017 -CLASS c_wchar_p
418.1018 -CLASS class
418.1019 -CLASS class
418.1020 -CLASS clean
418.1021 -CLASS closing
418.1022 -CLASS complex
418.1023 -CLASS compressobj
418.1024 -CLASS config
418.1025 -CLASS container
418.1026 -CLASS container
418.1027 -CLASS contextmanager
418.1028 -CLASS contextmanager
418.1029 -CLASS controller
418.1030 -CLASS date
418.1031 -CLASS datetime
418.1032 -CLASS dbexts
418.1033 -CLASS dbextsTestCase
418.1034 -CLASS dbhash
418.1035 -CLASS decompressobj
418.1036 -CLASS deque
418.1037 -CLASS dict
418.1038 -CLASS dict
418.1039 -CLASS dircmp
418.1040 -CLASS dispatcher
418.1041 -CLASS dispatcher_with_send
418.1042 -CLASS dl
418.1043 -CLASS error
418.1044 -CLASS error_data
418.1045 -CLASS error_proto
418.1046 -CLASS error_reply
418.1047 -CLASS excel
418.1048 -CLASS excel_tab
418.1049 -CLASS executor
418.1050 -CLASS fifo
418.1051 -CLASS file
418.1052 -CLASS file
418.1053 -CLASS file_dispatcher
418.1054 -CLASS file_wrapper
418.1055 -CLASS float
418.1056 -CLASS float
418.1057 -CLASS foo
418.1058 -CLASS gaierror
418.1059 -CLASS herror
418.1060 -CLASS install
418.1061 -CLASS install_data
418.1062 -CLASS install_egg_info
418.1063 -CLASS install_headers
418.1064 -CLASS install_lib
418.1065 -CLASS install_misc
418.1066 -CLASS install_scripts
418.1067 -CLASS instance
418.1068 -CLASS instance
418.1069 -CLASS int
418.1070 -CLASS iterator
418.1071 -CLASS iterator
418.1072 -CLASS list
418.1073 -CLASS local
418.1074 -CLASS lock
418.1075 -CLASS long
418.1076 -CLASS main
418.1077 -CLASS mbox
418.1078 -CLASS mboxMessage
418.1079 -CLASS mllib
418.1080 -CLASS mmap
418.1081 -CLASS multiprocessing.Pool
418.1082 -CLASS mutex
418.1083 -CLASS mxODBCProxy
418.1084 -CLASS netrc
418.1085 -CLASS object
418.1086 -CLASS object
418.1087 -CLASS oss_audio_device
418.1088 -CLASS oss_mixer_device
418.1089 -CLASS poll
418.1090 -CLASS py_object
418.1091 -CLASS register
418.1092 -CLASS scheduler
418.1093 -CLASS sdist
418.1094 -CLASS set
418.1095 -CLASS set
418.1096 -CLASS shlex
418.1097 -CLASS simple_producer
418.1098 -CLASS socket
418.1099 -CLASS stat_result
418.1100 -CLASS str
418.1101 -CLASS str
418.1102 -CLASS test_dist
418.1103 -CLASS test_zxjdbc
418.1104 -CLASS time
418.1105 -CLASS timedelta
418.1106 -CLASS timeout
418.1107 -CLASS tixCommand
418.1108 -CLASS tmxxx
418.1109 -CLASS tuple
418.1110 -CLASS tzinfo
418.1111 -CLASS unicode
418.1112 -CLASS unicode
418.1113 -CLASS upload
418.1114 -CLASS window
418.1115 -CLASS xmlparser
418.1116 -CLASS zipimporter
418.1117 -CLASS zxAPITestCase
418.1118 -CLASS zxCoreTestCase
418.1119 -CLASS zxJDBCTestCase
418.1120 -METHOD __import__(name, globals, loca
418.1121 -METHOD abs(x)
418.1122 -METHOD all(iterable)
418.1123 -METHOD any(iterable)
418.1124 -METHOD ---apply(function, args, ke---
418.1125 -METHOD basestring()
418.1126 -METHOD bin(x)
418.1127 -METHOD bool(x)
418.1128 -METHOD buffer(object, offset, size)
418.1129 -METHOD callable(object)
418.1130 -METHOD chr(i)
418.1131 -METHOD classmethod(function)
418.1132 -METHOD cmp(x, y)
418.1133 -METHOD coerce(x, y)
418.1134 -METHOD compile(source, filename, mode
418.1135 -METHOD complex(real, imag)
418.1136 -METHOD delattr(object, name)
418.1137 -METHOD dict(arg)
418.1138 -METHOD dir(object)
418.1139 -METHOD divmod(a, b)
418.1140 -METHOD enumerate(sequence, start)
418.1141 -METHOD eval(expression, globals, loca
418.1142 -METHOD execfile(filename, globals, lo
418.1143 -METHOD exit(code)
418.1144 -METHOD file(filename, mode, bufsize)
418.1145 -METHOD filter(function, iterable)
418.1146 -METHOD float(x)
418.1147 -METHOD frozenset(iterable)
418.1148 -METHOD getattr(object, name, default)
418.1149 -METHOD globals()
418.1150 -METHOD hasattr(object, name)
418.1151 -METHOD hash(object)
418.1152 -METHOD help(object)
418.1153 -METHOD hex(x)
418.1154 -METHOD id(object)
418.1155 -METHOD input(prompt)
418.1156 -METHOD int(x, radix)
418.1157 -METHOD intern(string)
418.1158 -METHOD isinstance(object, classinfo)
418.1159 -METHOD issubclass(class, classinfo)
418.1160 -METHOD iter(o, sentinel)
418.1161 -METHOD len(s)
418.1162 -METHOD list(iterable)
418.1163 -METHOD locals()
418.1164 -METHOD long(x, radix)
418.1165 -METHOD map(function, iterable)
418.1166 -METHOD max(iterable, argskey)
418.1167 -METHOD min(iterable, argskey)
418.1168 -METHOD next(iterator, default)
418.1169 -METHOD object()
418.1170 -METHOD oct(x)
418.1171 -METHOD open(filename, mode, bufsize)
418.1172 -METHOD ord(c)
418.1173 -METHOD pow(x, y, z)
418.1174 -METHOD print(object, sep, end, file)
418.1175 -METHOD property(fget, fset, fdel, doc
418.1176 -METHOD quit(code)
418.1177 -METHOD range(start, stop, step)
418.1178 -METHOD raw_input(prompt)
418.1179 -METHOD reduce(function, iterable, ini
418.1180 -METHOD reload(module)
418.1181 -METHOD repr(object)
418.1182 -METHOD reversed(seq)
418.1183 -METHOD round(x, n)
418.1184 -METHOD set(iterable)
418.1185 -METHOD setattr(object, name, value)
418.1186 -METHOD slice(start, stop, step)
418.1187 -METHOD sorted(iterable, cmp, key, rev
418.1188 -METHOD staticmethod(function)
418.1189 -METHOD str(object)
418.1190 -METHOD sum(iterable, start)
418.1191 -METHOD super(type, object-or-type)
418.1192 -METHOD tuple(iterable)
418.1193 -METHOD type(name, bases, dict)
418.1194 -METHOD type(object)
418.1195 -METHOD unichr(i)
418.1196 -METHOD unicode(object, encoding, erro
418.1197 -METHOD vars(object)
418.1198 -METHOD xrange(start, stop, step)
418.1199 -METHOD zip(iterable)
418.1200 -VARIABLE Ellipsis
418.1201 -VARIABLE False
418.1202 -VARIABLE None
418.1203 -VARIABLE NotImplemented
418.1204 -VARIABLE True
418.1205 -VARIABLE __debug__
418.1206 -VARIABLE copyright
418.1207 -KEYWORD and
418.1208 -KEYWORD as
418.1209 -KEYWORD assert
418.1210 -KEYWORD break
418.1211 -KEYWORD class
418.1212 -KEYWORD continue
418.1213 -KEYWORD def
418.1214 -KEYWORD del
418.1215 -KEYWORD elif
418.1216 -KEYWORD else
418.1217 -KEYWORD except
418.1218 -KEYWORD exec
418.1219 -KEYWORD finally
418.1220 -KEYWORD for
418.1221 -KEYWORD from
418.1222 -KEYWORD global
418.1223 -KEYWORD if
418.1224 -KEYWORD import
418.1225 -KEYWORD in
418.1226 -KEYWORD is
418.1227 -KEYWORD lambda
418.1228 -KEYWORD not
418.1229 -KEYWORD or
418.1230 -KEYWORD pass
418.1231 -KEYWORD print
418.1232 -KEYWORD raise
418.1233 -KEYWORD return
418.1234 -KEYWORD try
418.1235 -KEYWORD while
418.1236 -KEYWORD with
418.1237 -KEYWORD yield
419.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testLocals5.completion Sun Jan 04 13:11:53 2015 -0600
419.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
419.3 @@ -1,1236 +0,0 @@
419.4 -Code completion result for source line:
419.5 -x = |myfunc
419.6 -(QueryType=COMPLETION, NameKind=PREFIX)
419.7 -MODULE module1
419.8 -MODULE module2
419.9 -MODULE module4
419.10 -CLASS MyClass
419.11 -METHOD myfunc(funcparam)
419.12 -VARIABLE funcparam
419.13 -VARIABLE localvar
419.14 -VARIABLE toplevelvar
419.15 -VARIABLE toplevelvar2
419.16 -VARIABLE toplevelvar3
419.17 -VARIABLE toplevelvar4
419.18 -VARIABLE x
419.19 -------------------------------------
419.20 -CLASS A
419.21 -CLASS ABCMeta
419.22 -CLASS AEServer
419.23 -CLASS AEText
419.24 -CLASS ASTVisitor
419.25 -CLASS AbstractBasicAuthHandler
419.26 -CLASS AbstractClassCode
419.27 -CLASS AbstractCompileMode
419.28 -CLASS AbstractDigestAuthHandler
419.29 -CLASS AbstractFormatter
419.30 -CLASS AbstractFunctionCode
419.31 -CLASS AbstractHTTPHandler
419.32 -CLASS AbstractWriter
419.33 -CLASS Add
419.34 -CLASS AddressList
419.35 -CLASS And
419.36 -CLASS Application
419.37 -CLASS ArgumentError
419.38 -CLASS ArithmeticError
419.39 -CLASS ArithmeticError
419.40 -CLASS Array
419.41 -CLASS ArrayInstance
419.42 -CLASS AssAttr
419.43 -CLASS AssList
419.44 -CLASS AssName
419.45 -CLASS AssTuple
419.46 -CLASS Assert
419.47 -CLASS AssertionError
419.48 -CLASS AssertionError
419.49 -CLASS Assign
419.50 -CLASS AsyncResult
419.51 -CLASS Attr
419.52 -CLASS AttributeError
419.53 -CLASS AttributeError
419.54 -CLASS AttributeList
419.55 -CLASS AttributeMap
419.56 -CLASS Attributes
419.57 -CLASS AttributesImpl
419.58 -CLASS AttributesNS
419.59 -CLASS AttributesNSImpl
419.60 -CLASS AugAssign
419.61 -CLASS AugGetattr
419.62 -CLASS AugName
419.63 -CLASS AugSlice
419.64 -CLASS AugSubscript
419.65 -CLASS AuthenticationError
419.66 -CLASS AutoGILError
419.67 -CLASS B
419.68 -CLASS BCPPCompiler
419.69 -CLASS BCPTestCase
419.70 -CLASS BZ2Compressor
419.71 -CLASS BZ2Decompressor
419.72 -CLASS BZ2File
419.73 -CLASS Babyl
419.74 -CLASS BabylMailbox
419.75 -CLASS BabylMessage
419.76 -CLASS Backquote
419.77 -CLASS BadBoundaryPointsErr
419.78 -CLASS BadFutureParser
419.79 -CLASS BadOptionError
419.80 -CLASS BadStatusLine
419.81 -CLASS BadZipfile
419.82 -CLASS Balloon
419.83 -CLASS Bar
419.84 -CLASS BaseCGIHandler
419.85 -CLASS BaseCookie
419.86 -CLASS BaseException
419.87 -CLASS BaseException
419.88 -CLASS BaseHTTPRequestHandler
419.89 -CLASS BaseHandler
419.90 -CLASS BaseIncrementalParser
419.91 -CLASS BaseManager
419.92 -CLASS BaseProxy
419.93 -CLASS BaseRequestHandler
419.94 -CLASS BaseRotatingHandler
419.95 -CLASS BaseSet
419.96 -CLASS BasicModuleImporter
419.97 -CLASS BasicModuleLoader
419.98 -CLASS BastionClass
419.99 -CLASS Baz
419.100 -CLASS Bdb
419.101 -CLASS BdbQuit
419.102 -CLASS BigEndianStructure
419.103 -CLASS Binary
419.104 -CLASS Bitand
419.105 -CLASS Bitor
419.106 -CLASS Bitxor
419.107 -CLASS Block
419.108 -CLASS BlockFinder
419.109 -CLASS BlockingIOError
419.110 -CLASS Boolean
419.111 -CLASS BoundaryError
419.112 -CLASS BoundedSemaphore
419.113 -CLASS Break
419.114 -CLASS Breakpoint
419.115 -CLASS BsdDbShelf
419.116 -CLASS BufferTooShort
419.117 -CLASS BufferedIOBase
419.118 -CLASS BufferedRWPair
419.119 -CLASS BufferedRandom
419.120 -CLASS BufferedReader
419.121 -CLASS BufferedWriter
419.122 -CLASS BufferingFormatter
419.123 -CLASS BufferingHandler
419.124 -CLASS BuildPyTestCase
419.125 -CLASS BuildScriptsTestCase
419.126 -CLASS BuiltinImporter
419.127 -CLASS Bulkcopy
419.128 -CLASS ButtonBox
419.129 -CLASS BytesIO
419.130 -CLASS C
419.131 -CLASS CAB
419.132 -CLASS CCompiler
419.133 -CLASS CCompilerError
419.134 -CLASS CDATASection
419.135 -CLASS CDLL
419.136 -CLASS CGIHTTPRequestHandler
419.137 -CLASS CGIHandler
419.138 -CLASS CGIXMLRPCRequestHandler
419.139 -CLASS CacheFTPHandler
419.140 -CLASS CallFunc
419.141 -CLASS CalledProcessError
419.142 -CLASS CannotSendHeader
419.143 -CLASS CannotSendRequest
419.144 -CLASS Canonizer
419.145 -CLASS CharacterData
419.146 -CLASS Charset
419.147 -CLASS CharsetError
419.148 -CLASS CheckList
419.149 -CLASS Childless
419.150 -CLASS Chunk
419.151 -CLASS Clamped
419.152 -CLASS Class
419.153 -CLASS ClassCodeGenerator
419.154 -CLASS ClassScope
419.155 -CLASS Cmd
419.156 -CLASS CodeGenerator
419.157 -CLASS Codec
419.158 -CLASS CodecRegistryError
419.159 -CLASS ComboBox
419.160 -CLASS Command
419.161 -CLASS CommandCompiler
419.162 -CLASS Comment
419.163 -CLASS Compare
419.164 -CLASS Comparison
419.165 -CLASS Compile
419.166 -CLASS CompileError
419.167 -CLASS Completer
419.168 -CLASS Complex
419.169 -CLASS ComponentItem
419.170 -CLASS Condition
419.171 -CLASS ConfigParser
419.172 -CLASS Connection
419.173 -CLASS Const
419.174 -CLASS ContentGenerator
419.175 -CLASS ContentHandler
419.176 -CLASS Context
419.177 -CLASS Continue
419.178 -CLASS Control
419.179 -CLASS ControlsWindow
419.180 -CLASS ConversionError
419.181 -CLASS Cookie
419.182 -CLASS CookieError
419.183 -CLASS CookieJar
419.184 -CLASS CookiePolicy
419.185 -CLASS CoverageResults
419.186 -CLASS Cursor
419.187 -CLASS CygwinCCompiler
419.188 -CLASS D
419.189 -CLASS DOMBuilder
419.190 -CLASS DOMEntityResolver
419.191 -CLASS DOMError
419.192 -CLASS DOMEventStream
419.193 -CLASS DOMException
419.194 -CLASS DOMImplementation
419.195 -CLASS DOMInputSource
419.196 -CLASS DOMStringSizeErr
419.197 -CLASS DTDHandler
419.198 -CLASS Data
419.199 -CLASS Database
419.200 -CLASS DatagramHandler
419.201 -CLASS DatagramRequestHandler
419.202 -CLASS DateTime
419.203 -CLASS DbfilenameShelf
419.204 -CLASS DebugRunner
419.205 -CLASS DebuggingServer
419.206 -CLASS Decimal
419.207 -CLASS DecimalException
419.208 -CLASS DeclHandler
419.209 -CLASS DecodedGenerator
419.210 -CLASS Decorators
419.211 -CLASS DefaultCookiePolicy
419.212 -CLASS DefaultHandler
419.213 -CLASS Delegator
419.214 -CLASS DeprecationWarning
419.215 -CLASS DeprecationWarning
419.216 -CLASS Dialect
419.217 -CLASS Dialog
419.218 -CLASS DialogWindow
419.219 -CLASS Dict
419.220 -CLASS DictMixin
419.221 -CLASS DictReader
419.222 -CLASS DictWriter
419.223 -CLASS Differ
419.224 -CLASS DirList
419.225 -CLASS DirSelectBox
419.226 -CLASS DirSelectDialog
419.227 -CLASS DirTree
419.228 -CLASS Directory
419.229 -CLASS Discard
419.230 -CLASS Distribution
419.231 -CLASS DistributionMetadata
419.232 -CLASS DistributionTestCase
419.233 -CLASS DistutilsArgError
419.234 -CLASS DistutilsClassError
419.235 -CLASS DistutilsError
419.236 -CLASS DistutilsExecError
419.237 -CLASS DistutilsFileError
419.238 -CLASS DistutilsGetoptError
419.239 -CLASS DistutilsInternalError
419.240 -CLASS DistutilsModuleError
419.241 -CLASS DistutilsOptionError
419.242 -CLASS DistutilsPlatformError
419.243 -CLASS DistutilsSetupError
419.244 -CLASS DistutilsTemplateError
419.245 -CLASS Div
419.246 -CLASS DivisionByZero
419.247 -CLASS Doc
419.248 -CLASS DocCGIXMLRPCRequestHandler
419.249 -CLASS DocTest
419.250 -CLASS DocTestFailure
419.251 -CLASS DocTestFinder
419.252 -CLASS DocTestParser
419.253 -CLASS DocTestRunner
419.254 -CLASS DocXMLRPCRequestHandler
419.255 -CLASS DocXMLRPCServer
419.256 -CLASS Document
419.257 -CLASS DocumentFragment
419.258 -CLASS DocumentHandler
419.259 -CLASS DocumentType
419.260 -CLASS DomstringSizeErr
419.261 -CLASS DumbWriter
419.262 -CLASS DummyCommand
419.263 -CLASS DuplicateSectionError
419.264 -CLASS DynLoadSuffixImporter
419.265 -CLASS EMXCCompiler
419.266 -CLASS EOFError
419.267 -CLASS EOFError
419.268 -CLASS ESISDocHandler
419.269 -CLASS Element
419.270 -CLASS ElementInfo
419.271 -CLASS ElementTree
419.272 -CLASS Ellipsis
419.273 -CLASS Empty
419.274 -CLASS EmptyNode
419.275 -CLASS EndOfBlock
419.276 -CLASS Entity
419.277 -CLASS EntityResolver
419.278 -CLASS Enum
419.279 -CLASS EnvironmentError
419.280 -CLASS EnvironmentError
419.281 -CLASS Error
419.282 -CLASS ErrorDuringImport
419.283 -CLASS ErrorHandler
419.284 -CLASS ErrorPrinter
419.285 -CLASS ErrorRaiser
419.286 -CLASS Event
419.287 -CLASS EventBroadcaster
419.288 -CLASS EventException
419.289 -CLASS ExFileSelectBox
419.290 -CLASS Example
419.291 -CLASS ExampleASTVisitor
419.292 -CLASS Exception
419.293 -CLASS Exception
419.294 -CLASS Exec
419.295 -CLASS ExitNow
419.296 -CLASS ExpatError
419.297 -CLASS ExpatParser
419.298 -CLASS Expression
419.299 -CLASS ExpressionCodeGenerator
419.300 -CLASS Extension
419.301 -CLASS F
419.302 -CLASS FTP
419.303 -CLASS FTPHandler
419.304 -CLASS Factory
419.305 -CLASS FancyGetopt
419.306 -CLASS FancyModuleLoader
419.307 -CLASS FancyURLopener
419.308 -CLASS Fault
419.309 -CLASS Feature
419.310 -CLASS FeedParser
419.311 -CLASS FieldStorage
419.312 -CLASS FileCookieJar
419.313 -CLASS FileEntry
419.314 -CLASS FileHandler
419.315 -CLASS FileIO
419.316 -CLASS FileInput
419.317 -CLASS FileList
419.318 -CLASS FileSelectBox
419.319 -CLASS FileWrapper
419.320 -CLASS Filter
419.321 -CLASS Filterer
419.322 -CLASS FingerHandler
419.323 -CLASS FirstHeaderLineIsContinuationD
419.324 -CLASS FloatingPointError
419.325 -CLASS FloatingPointError
419.326 -CLASS FloorDiv
419.327 -CLASS FlowGraph
419.328 -CLASS Folder
419.329 -CLASS Foo
419.330 -CLASS For
419.331 -CLASS ForkingMixIn
419.332 -CLASS ForkingTCPServer
419.333 -CLASS ForkingUDPServer
419.334 -CLASS Form
419.335 -CLASS FormContent
419.336 -CLASS FormContentDict
419.337 -CLASS Formatter
419.338 -CLASS Fraction
419.339 -CLASS From
419.340 -CLASS FtException
419.341 -CLASS Full
419.342 -CLASS FuncPtr
419.343 -CLASS Function
419.344 -CLASS FunctionCodeGenerator
419.345 -CLASS FunctionScope
419.346 -CLASS FunctionTestCase
419.347 -CLASS FutureParser
419.348 -CLASS FutureWarning
419.349 -CLASS FutureWarning
419.350 -CLASS GNUTranslations
419.351 -CLASS GenExpr
419.352 -CLASS GenExprFor
419.353 -CLASS GenExprIf
419.354 -CLASS GenExprInner
419.355 -CLASS GenExprScope
419.356 -CLASS Generator
419.357 -CLASS GeneratorExit
419.358 -CLASS GeneratorExit
419.359 -CLASS Getattr
419.360 -CLASS GetattrMagic
419.361 -CLASS GetoptError
419.362 -CLASS Global
419.363 -CLASS GopherError
419.364 -CLASS GopherHandler
419.365 -CLASS GridBag
419.366 -CLASS GzipFile
419.367 -CLASS HList
419.368 -CLASS HMAC
419.369 -CLASS HRESULT
419.370 -CLASS HTMLDoc
419.371 -CLASS HTMLParseError
419.372 -CLASS HTMLParser
419.373 -CLASS HTMLRepr
419.374 -CLASS HTTP
419.375 -CLASS HTTPBasicAuthHandler
419.376 -CLASS HTTPConnection
419.377 -CLASS HTTPCookieProcessor
419.378 -CLASS HTTPDefaultErrorHandler
419.379 -CLASS HTTPDigestAuthHandler
419.380 -CLASS HTTPError
419.381 -CLASS HTTPErrorProcessor
419.382 -CLASS HTTPException
419.383 -CLASS HTTPHandler
419.384 -CLASS HTTPPasswordMgr
419.385 -CLASS HTTPPasswordMgrWithDefaultReal
419.386 -CLASS HTTPRedirectHandler
419.387 -CLASS HTTPResponse
419.388 -CLASS HTTPSConnection
419.389 -CLASS HTTPSHandler
419.390 -CLASS HTTPServer
419.391 -CLASS Handler
419.392 -CLASS HandlerBase
419.393 -CLASS Header
419.394 -CLASS HeaderParseError
419.395 -CLASS HeaderParser
419.396 -CLASS Headers
419.397 -CLASS HelpFormatter
419.398 -CLASS Helper
419.399 -CLASS HierarchyRequestErr
419.400 -CLASS Hook
419.401 -CLASS Hooks
419.402 -CLASS HtmlDiff
419.403 -CLASS IC
419.404 -CLASS IMAP4
419.405 -CLASS IMAP4_SSL
419.406 -CLASS IMAP4_stream
419.407 -CLASS IOBase
419.408 -CLASS IOError
419.409 -CLASS IOError
419.410 -CLASS Identified
419.411 -CLASS If
419.412 -CLASS IfExp
419.413 -CLASS Ignore
419.414 -CLASS IllegalMonthError
419.415 -CLASS IllegalWeekdayError
419.416 -CLASS ImmutableSet
419.417 -CLASS ImpImporter
419.418 -CLASS ImpLoader
419.419 -CLASS Import
419.420 -CLASS ImportError
419.421 -CLASS ImportError
419.422 -CLASS ImportManager
419.423 -CLASS ImportWarning
419.424 -CLASS ImportWarning
419.425 -CLASS Importer
419.426 -CLASS ImproperConnectionState
419.427 -CLASS Incomplete
419.428 -CLASS IncompleteRead
419.429 -CLASS IncrementalDecoder
419.430 -CLASS IncrementalEncoder
419.431 -CLASS IncrementalNewlineDecoder
419.432 -CLASS IncrementalParser
419.433 -CLASS IndentedHelpFormatter
419.434 -CLASS IndexError
419.435 -CLASS IndexError
419.436 -CLASS IndexSizeErr
419.437 -CLASS Inexact
419.438 -CLASS IniParser
419.439 -CLASS InputOnly
419.440 -CLASS InputSource
419.441 -CLASS InsertionLoc
419.442 -CLASS InstallScriptsTestCase
419.443 -CLASS InstallTestCase
419.444 -CLASS Integral
419.445 -CLASS Interactive
419.446 -CLASS InteractiveCodeGenerator
419.447 -CLASS InteractiveConsole
419.448 -CLASS InteractiveInterpreter
419.449 -CLASS InterpFormContentDict
419.450 -CLASS InterpolationDepthError
419.451 -CLASS InterpolationError
419.452 -CLASS InterpolationSyntaxError
419.453 -CLASS IntlText
419.454 -CLASS IntlWritingCode
419.455 -CLASS InuseAttributeErr
419.456 -CLASS InvalidAccessErr
419.457 -CLASS InvalidCharacterErr
419.458 -CLASS InvalidModificationErr
419.459 -CLASS InvalidNodeTypeErr
419.460 -CLASS InvalidOperation
419.461 -CLASS InvalidStateErr
419.462 -CLASS InvalidURL
419.463 -CLASS Invert
419.464 -CLASS IsqlCmd
419.465 -CLASS IsqlExit
419.466 -CLASS IterableUserDict
419.467 -CLASS JSONDecoder
419.468 -CLASS JSONEncoder
419.469 -CLASS JavaSAXParser
419.470 -CLASS JoinableQueue
419.471 -CLASS JyDTDHandlerWrapper
419.472 -CLASS JyEntityResolverWrapper
419.473 -CLASS JyErrorHandlerWrapper
419.474 -CLASS JyInputSourceWrapper
419.475 -CLASS JythonCompiler
419.476 -CLASS JythonSignalHandler
419.477 -CLASS KeyError
419.478 -CLASS KeyError
419.479 -CLASS KeyboardInterrupt
419.480 -CLASS KeyboardInterrupt
419.481 -CLASS Keyword
419.482 -CLASS LOBTestCase
419.483 -CLASS LWPCookieJar
419.484 -CLASS LabelEntry
419.485 -CLASS LabelFrame
419.486 -CLASS Lambda
419.487 -CLASS LambdaScope
419.488 -CLASS LargeZipFile
419.489 -CLASS LeftShift
419.490 -CLASS LexicalHandler
419.491 -CLASS LexicalXMLGenerator
419.492 -CLASS LibError
419.493 -CLASS LibraryLoader
419.494 -CLASS LineAddrTable
419.495 -CLASS LinkError
419.496 -CLASS List
419.497 -CLASS ListComp
419.498 -CLASS ListCompFor
419.499 -CLASS ListCompIf
419.500 -CLASS ListNoteBook
419.501 -CLASS Listener
419.502 -CLASS LittleEndianStructure
419.503 -CLASS LoadError
419.504 -CLASS LocalNameFinder
419.505 -CLASS Location
419.506 -CLASS Locator
419.507 -CLASS Lock
419.508 -CLASS Log
419.509 -CLASS LogRecord
419.510 -CLASS Logger
419.511 -CLASS LoggingSilencer
419.512 -CLASS Logical
419.513 -CLASS LookupError
419.514 -CLASS LookupError
419.515 -CLASS LooseVersion
419.516 -CLASS MH
419.517 -CLASS MHMailbox
419.518 -CLASS MHMessage
419.519 -CLASS MIMEApplication
419.520 -CLASS MIMEAudio
419.521 -CLASS MIMEBase
419.522 -CLASS MIMEImage
419.523 -CLASS MIMEMessage
419.524 -CLASS MIMEMultipart
419.525 -CLASS MIMENonMultipart
419.526 -CLASS MIMEText
419.527 -CLASS MMDF
419.528 -CLASS MMDFMessage
419.529 -CLASS MSVCCompiler
419.530 -CLASS MWerksCompiler
419.531 -CLASS MacroExpander
419.532 -CLASS Mailbox
419.533 -CLASS Maildir
419.534 -CLASS MaildirMessage
419.535 -CLASS MailmanProxy
419.536 -CLASS MalformedHeaderDefect
419.537 -CLASS Manager
419.538 -CLASS Marshaller
419.539 -CLASS MemoryError
419.540 -CLASS MemoryError
419.541 -CLASS MemoryHandler
419.542 -CLASS Message
419.543 -CLASS MessageDefect
419.544 -CLASS MessageError
419.545 -CLASS MessageParseError
419.546 -CLASS MetadataTestCase
419.547 -CLASS Meter
419.548 -CLASS MimeWriter
419.549 -CLASS Mingw32CCompiler
419.550 -CLASS MiniApplication
419.551 -CLASS MiniFieldStorage
419.552 -CLASS MisplacedEnvelopeHeaderDefect
419.553 -CLASS MissingSectionHeaderError
419.554 -CLASS MmdfMailbox
419.555 -CLASS Mod
419.556 -CLASS Model
419.557 -CLASS Module
419.558 -CLASS ModuleCodeGenerator
419.559 -CLASS ModuleFinder
419.560 -CLASS ModuleImporter
419.561 -CLASS ModuleLoader
419.562 -CLASS ModuleScanner
419.563 -CLASS ModuleScope
419.564 -CLASS MozillaCookieJar
419.565 -CLASS Mul
419.566 -CLASS MultiCall
419.567 -CLASS MultiCallIterator
419.568 -CLASS MultiFile
419.569 -CLASS MultipartConversionError
419.570 -CLASS MultipartInvariantViolationDef
419.571 -CLASS MutableString
419.572 -CLASS MyClass
419.573 -CLASS MyTest
419.574 -CLASS NNTP
419.575 -CLASS NNTPDataError
419.576 -CLASS NNTPPermanentError
419.577 -CLASS NNTPProtocolError
419.578 -CLASS NNTPReplyError
419.579 -CLASS NNTPTemporaryError
419.580 -CLASS NProperty
419.581 -CLASS NTEventLogHandler
419.582 -CLASS NULL
419.583 -CLASS Name
419.584 -CLASS NameError
419.585 -CLASS NameError
419.586 -CLASS NamedNodeMap
419.587 -CLASS NamespaceErr
419.588 -CLASS NannyNag
419.589 -CLASS NestedScopeMixin
419.590 -CLASS Netrc
419.591 -CLASS NetrcParseError
419.592 -CLASS NewStyle
419.593 -CLASS NoBoundaryInMultipartDefect
419.594 -CLASS NoDataAllowedErr
419.595 -CLASS NoModificationAllowedErr
419.596 -CLASS NoOpMetaClass
419.597 -CLASS NoOptionError
419.598 -CLASS NoSectionError
419.599 -CLASS Node
419.600 -CLASS NodeFilter
419.601 -CLASS NodeTransformer
419.602 -CLASS NodeVisitor
419.603 -CLASS Not
419.604 -CLASS NotANumber
419.605 -CLASS NotConnected
419.606 -CLASS NotFoundErr
419.607 -CLASS NotImplementedError
419.608 -CLASS NotImplementedError
419.609 -CLASS NotSupportedErr
419.610 -CLASS Notation
419.611 -CLASS NoteBook
419.612 -CLASS NullFormatter
419.613 -CLASS NullImporter
419.614 -CLASS NullTranslations
419.615 -CLASS NullWriter
419.616 -CLASS Number
419.617 -CLASS OSError
419.618 -CLASS OSError
419.619 -CLASS OSSAudioError
419.620 -CLASS ObjectSpecifier
419.621 -CLASS OleDLL
419.622 -CLASS OpFinder
419.623 -CLASS OpenerDirector
419.624 -CLASS OptParseError
419.625 -CLASS Option
419.626 -CLASS OptionConflictError
419.627 -CLASS OptionContainer
419.628 -CLASS OptionDummy
419.629 -CLASS OptionError
419.630 -CLASS OptionGroup
419.631 -CLASS OptionMenu
419.632 -CLASS OptionParser
419.633 -CLASS OptionValueError
419.634 -CLASS Or
419.635 -CLASS OracleSPTest
419.636 -CLASS Ordinal
419.637 -CLASS OutputChecker
419.638 -CLASS Overflow
419.639 -CLASS OverflowError
419.640 -CLASS OverflowError
419.641 -CLASS POP3
419.642 -CLASS POP3_SSL
419.643 -CLASS Packer
419.644 -CLASS PanedWindow
419.645 -CLASS Panel
419.646 -CLASS Parser
419.647 -CLASS ParserBase
419.648 -CLASS ParserError
419.649 -CLASS ParsingError
419.650 -CLASS Pass
419.651 -CLASS Pattern
419.652 -CLASS Pdb
419.653 -CLASS PendingDeprecationWarning
419.654 -CLASS PendingDeprecationWarning
419.655 -CLASS PickleError
419.656 -CLASS Pickler
419.657 -CLASS PicklingError
419.658 -CLASS PlaceHolder
419.659 -CLASS Popen
419.660 -CLASS Popen3
419.661 -CLASS Popen4
419.662 -CLASS PopupMenu
419.663 -CLASS PortableUnixMailbox
419.664 -CLASS Power
419.665 -CLASS PreprocessError
419.666 -CLASS PrettyPrinter
419.667 -CLASS Print
419.668 -CLASS Printnl
419.669 -CLASS Process
419.670 -CLASS ProcessingInstruction
419.671 -CLASS Profile
419.672 -CLASS ProgressBar
419.673 -CLASS Prompt
419.674 -CLASS ProtocolError
419.675 -CLASS ProxyBasicAuthHandler
419.676 -CLASS ProxyDigestAuthHandler
419.677 -CLASS ProxyHandler
419.678 -CLASS PullDOM
419.679 -CLASS PureProxy
419.680 -CLASS PyCompileError
419.681 -CLASS PyDLL
419.682 -CLASS PyDialog
419.683 -CLASS PyFlowGraph
419.684 -CLASS PyHKEY
419.685 -CLASS PyZipFile
419.686 -CLASS QDPoint
419.687 -CLASS QDRectangle
419.688 -CLASS QName
419.689 -CLASS Queue
419.690 -CLASS RExec
419.691 -CLASS RGBColor
419.692 -CLASS RLock
419.693 -CLASS RadioButtonGroup
419.694 -CLASS Raise
419.695 -CLASS Random
419.696 -CLASS Range
419.697 -CLASS RangeException
419.698 -CLASS Rational
419.699 -CLASS RawConfigParser
419.700 -CLASS RawIOBase
419.701 -CLASS RawTurtle
419.702 -CLASS ReadOnlySequentialNamedNodeMap
419.703 -CLASS Real
419.704 -CLASS Record
419.705 -CLASS ReferenceError
419.706 -CLASS ReferenceError
419.707 -CLASS Repr
419.708 -CLASS Request
419.709 -CLASS ResponseError
419.710 -CLASS ResponseNotReady
419.711 -CLASS ResultSet
419.712 -CLASS ResultSetRow
419.713 -CLASS Return
419.714 -CLASS RightShift
419.715 -CLASS RobotFileParser
419.716 -CLASS RootLogger
419.717 -CLASS RotatingFileHandler
419.718 -CLASS Rounded
419.719 -CLASS Row
419.720 -CLASS RuntimeError
419.721 -CLASS RuntimeError
419.722 -CLASS RuntimeWarning
419.723 -CLASS RuntimeWarning
419.724 -CLASS SAX2DOM
419.725 -CLASS SAXException
419.726 -CLASS SAXNotRecognizedException
419.727 -CLASS SAXNotSupportedException
419.728 -CLASS SAXParseException
419.729 -CLASS SAXReaderNotAvailable
419.730 -CLASS SGMLParseError
419.731 -CLASS SGMLParser
419.732 -CLASS SMTP
419.733 -CLASS SMTPAuthenticationError
419.734 -CLASS SMTPConnectError
419.735 -CLASS SMTPDataError
419.736 -CLASS SMTPException
419.737 -CLASS SMTPHandler
419.738 -CLASS SMTPHeloError
419.739 -CLASS SMTPRecipientsRefused
419.740 -CLASS SMTPResponseException
419.741 -CLASS SMTPSenderRefused
419.742 -CLASS SMTPServer
419.743 -CLASS SMTPServerDisconnected
419.744 -CLASS SQLServerSPTest
419.745 -CLASS SQLTestCase
419.746 -CLASS SSLError
419.747 -CLASS SSLSocket
419.748 -CLASS ST
419.749 -CLASS SafeConfigParser
419.750 -CLASS SafeTransport
419.751 -CLASS Scanner
419.752 -CLASS Schema
419.753 -CLASS Scope
419.754 -CLASS Screen
419.755 -CLASS ScrolledCavas
419.756 -CLASS ScrolledText
419.757 -CLASS ScrolledWindow
419.758 -CLASS Select
419.759 -CLASS Semaphore
419.760 -CLASS SequenceMatcher
419.761 -CLASS SerialCookie
419.762 -CLASS Server
419.763 -CLASS ServerHTMLDoc
419.764 -CLASS ServerProxy
419.765 -CLASS Set
419.766 -CLASS SgmlopParser
419.767 -CLASS Shape
419.768 -CLASS Shelf
419.769 -CLASS SimpleCookie
419.770 -CLASS SimpleHTTPRequestHandler
419.771 -CLASS SimpleHandler
419.772 -CLASS SimpleLocator
419.773 -CLASS SimpleXMLRPCDispatcher
419.774 -CLASS SimpleXMLRPCRequestHandler
419.775 -CLASS SimpleXMLRPCServer
419.776 -CLASS Slice
419.777 -CLASS Sliceobj
419.778 -CLASS SlowParser
419.779 -CLASS SmartCookie
419.780 -CLASS Sniffer
419.781 -CLASS SocketHandler
419.782 -CLASS SocketType
419.783 -CLASS Stack
419.784 -CLASS StackDepthTracker
419.785 -CLASS StandardError
419.786 -CLASS StandardError
419.787 -CLASS StartBoundaryNotFoundDefect
419.788 -CLASS Stats
419.789 -CLASS StdButtonBox
419.790 -CLASS Stmt
419.791 -CLASS StopIteration
419.792 -CLASS StopIteration
419.793 -CLASS StopTokenizing
419.794 -CLASS Strange
419.795 -CLASS StreamConverter
419.796 -CLASS StreamHandler
419.797 -CLASS StreamReader
419.798 -CLASS StreamRequestHandler
419.799 -CLASS StreamWriter
419.800 -CLASS StrictVersion
419.801 -CLASS StringIO
419.802 -CLASS Struct
419.803 -CLASS Structure
419.804 -CLASS StyledText
419.805 -CLASS Sub
419.806 -CLASS SubPattern
419.807 -CLASS Subnormal
419.808 -CLASS Subscript
419.809 -CLASS SummaryInformation
419.810 -CLASS Super
419.811 -CLASS SuperSuper
419.812 -CLASS SvFormContentDict
419.813 -CLASS Symbol
419.814 -CLASS SymbolTable
419.815 -CLASS SymbolVisitor
419.816 -CLASS SyncManager
419.817 -CLASS SyntaxErr
419.818 -CLASS SyntaxError
419.819 -CLASS SyntaxError
419.820 -CLASS SyntaxErrorChecker
419.821 -CLASS SyntaxWarning
419.822 -CLASS SyntaxWarning
419.823 -CLASS SysLogHandler
419.824 -CLASS SystemError
419.825 -CLASS SystemError
419.826 -CLASS SystemExit
419.827 -CLASS SystemExit
419.828 -CLASS SystemRandom
419.829 -CLASS TCPServer
419.830 -CLASS TList
419.831 -CLASS TalkTo
419.832 -CLASS TarError
419.833 -CLASS TarFile
419.834 -CLASS TarInfo
419.835 -CLASS Telnet
419.836 -CLASS TempdirManager
419.837 -CLASS Template
419.838 -CLASS Test
419.839 -CLASS TestCase
419.840 -CLASS TestClass
419.841 -CLASS TestCrispinTorture
419.842 -CLASS TestDistribution
419.843 -CLASS TestLoader
419.844 -CLASS TestResult
419.845 -CLASS TestSuite
419.846 -CLASS TestThread
419.847 -CLASS TestXMLParser
419.848 -CLASS Testcase
419.849 -CLASS Tester
419.850 -CLASS Text
419.851 -CLASS TextDoc
419.852 -CLASS TextFile
419.853 -CLASS TextIOBase
419.854 -CLASS TextIOWrapper
419.855 -CLASS TextRepr
419.856 -CLASS TextTestRunner
419.857 -CLASS TextWrapper
419.858 -CLASS Textbox
419.859 -CLASS Thread
419.860 -CLASS ThreadingMixIn
419.861 -CLASS ThreadingTCPServer
419.862 -CLASS ThreadingUDPServer
419.863 -CLASS ThreadingUnixDatagramServer
419.864 -CLASS ThreadingUnixStreamServer
419.865 -CLASS TimedRotatingFileHandler
419.866 -CLASS Timer
419.867 -CLASS TitledHelpFormatter
419.868 -CLASS Tix
419.869 -CLASS Tk
419.870 -CLASS TokenError
419.871 -CLASS Tokenizer
419.872 -CLASS TortureBase
419.873 -CLASS Trace
419.874 -CLASS Transformer
419.875 -CLASS Transport
419.876 -CLASS Tree
419.877 -CLASS TreeBuilder
419.878 -CLASS TryExcept
419.879 -CLASS TryFinally
419.880 -CLASS Tuple
419.881 -CLASS TupleArg
419.882 -CLASS Turtle
419.883 -CLASS TurtleScreen
419.884 -CLASS Type
419.885 -CLASS TypeError
419.886 -CLASS TypeError
419.887 -CLASS TypeInfo
419.888 -CLASS UDPServer
419.889 -CLASS URLError
419.890 -CLASS URLopener
419.891 -CLASS UUID
419.892 -CLASS UnaryAdd
419.893 -CLASS UnarySub
419.894 -CLASS UnboundLocalError
419.895 -CLASS UnboundLocalError
419.896 -CLASS Underflow
419.897 -CLASS UnexpectedException
419.898 -CLASS UnicodeDecodeError
419.899 -CLASS UnicodeDecodeError
419.900 -CLASS UnicodeEncodeError
419.901 -CLASS UnicodeEncodeError
419.902 -CLASS UnicodeError
419.903 -CLASS UnicodeError
419.904 -CLASS UnicodeTranslateError
419.905 -CLASS UnicodeTranslateError
419.906 -CLASS UnicodeWarning
419.907 -CLASS UnicodeWarning
419.908 -CLASS UnimplementedFileMode
419.909 -CLASS Union
419.910 -CLASS UnixCCompiler
419.911 -CLASS UnixDatagramServer
419.912 -CLASS UnixMailbox
419.913 -CLASS UnixStreamServer
419.914 -CLASS Unknown
419.915 -CLASS UnknownFileError
419.916 -CLASS UnknownHandler
419.917 -CLASS UnknownProtocol
419.918 -CLASS UnknownTransferEncoding
419.919 -CLASS Unload
419.920 -CLASS Unmarshaller
419.921 -CLASS Unpacker
419.922 -CLASS Unpickler
419.923 -CLASS UnpicklingError
419.924 -CLASS UnspecifiedEventTypeErr
419.925 -CLASS UnsupportedOperation
419.926 -CLASS UserDataHandler
419.927 -CLASS UserDict
419.928 -CLASS UserList
419.929 -CLASS UserString
419.930 -CLASS UserWarning
419.931 -CLASS UserWarning
419.932 -CLASS ValidationErr
419.933 -CLASS ValueError
419.934 -CLASS ValueError
419.935 -CLASS Values
419.936 -CLASS Vec2D
419.937 -CLASS Vendor
419.938 -CLASS Version
419.939 -CLASS VersionPredicate
419.940 -CLASS View
419.941 -CLASS WSGIRequestHandler
419.942 -CLASS WSGIServer
419.943 -CLASS Warning
419.944 -CLASS Warning
419.945 -CLASS Wave_read
419.946 -CLASS Wave_write
419.947 -CLASS WeakKeyDictionary
419.948 -CLASS WeakValueDictionary
419.949 -CLASS While
419.950 -CLASS WichmannHill
419.951 -CLASS WinDLL
419.952 -CLASS Window
419.953 -CLASS WindowsError
419.954 -CLASS WindowsError
419.955 -CLASS With
419.956 -CLASS WrongDocumentErr
419.957 -CLASS X
419.958 -CLASS XMLFilter
419.959 -CLASS XMLFilterBase
419.960 -CLASS XMLFilterImpl
419.961 -CLASS XMLGenerator
419.962 -CLASS XMLParser
419.963 -CLASS XMLRPCDocGenerator
419.964 -CLASS XMLReader
419.965 -CLASS XMLTreeBuilder
419.966 -CLASS XmlParseErr
419.967 -CLASS Yield
419.968 -CLASS Yuck
419.969 -CLASS ZeroDivisionError
419.970 -CLASS ZeroDivisionError
419.971 -CLASS ZipFile
419.972 -CLASS ZipImportError
419.973 -CLASS ZipInfo
419.974 -CLASS _CData [PROTECTE
419.975 -CLASS _FuncPtr [PROTECTE
419.976 -CLASS _SimpleCData [PROTECTE
419.977 -CLASS _posixfile_
419.978 -CLASS array
419.979 -CLASS async_chat
419.980 -CLASS bdist
419.981 -CLASS bdist_dumb
419.982 -CLASS bdist_msi
419.983 -CLASS bdist_rpm
419.984 -CLASS bdist_wininst
419.985 -CLASS bool
419.986 -CLASS bsddbobject
419.987 -CLASS build
419.988 -CLASS build_clib
419.989 -CLASS build_ext
419.990 -CLASS build_py
419.991 -CLASS build_scripts
419.992 -CLASS c_bool
419.993 -CLASS c_byte
419.994 -CLASS c_char
419.995 -CLASS c_char_p
419.996 -CLASS c_double
419.997 -CLASS c_float
419.998 -CLASS c_int
419.999 -CLASS c_int16
419.1000 -CLASS c_int32
419.1001 -CLASS c_int64
419.1002 -CLASS c_int8
419.1003 -CLASS c_long
419.1004 -CLASS c_longdouble
419.1005 -CLASS c_longlong
419.1006 -CLASS c_short
419.1007 -CLASS c_size_t
419.1008 -CLASS c_ubyte
419.1009 -CLASS c_uint
419.1010 -CLASS c_uint16
419.1011 -CLASS c_uint32
419.1012 -CLASS c_uint64
419.1013 -CLASS c_uint8
419.1014 -CLASS c_ulong
419.1015 -CLASS c_ulonglong
419.1016 -CLASS c_ushort
419.1017 -CLASS c_void_p
419.1018 -CLASS c_wchar
419.1019 -CLASS c_wchar_p
419.1020 -CLASS class
419.1021 -CLASS class
419.1022 -CLASS clean
419.1023 -CLASS closing
419.1024 -CLASS complex
419.1025 -CLASS compressobj
419.1026 -CLASS config
419.1027 -CLASS container
419.1028 -CLASS container
419.1029 -CLASS contextmanager
419.1030 -CLASS contextmanager
419.1031 -CLASS controller
419.1032 -CLASS date
419.1033 -CLASS datetime
419.1034 -CLASS dbexts
419.1035 -CLASS dbextsTestCase
419.1036 -CLASS dbhash
419.1037 -CLASS decompressobj
419.1038 -CLASS deque
419.1039 -CLASS dict
419.1040 -CLASS dict
419.1041 -CLASS dircmp
419.1042 -CLASS dispatcher
419.1043 -CLASS dispatcher_with_send
419.1044 -CLASS dl
419.1045 -CLASS error
419.1046 -CLASS error_data
419.1047 -CLASS error_proto
419.1048 -CLASS error_reply
419.1049 -CLASS excel
419.1050 -CLASS excel_tab
419.1051 -CLASS executor
419.1052 -CLASS fifo
419.1053 -CLASS file
419.1054 -CLASS file
419.1055 -CLASS file_dispatcher
419.1056 -CLASS file_wrapper
419.1057 -CLASS float
419.1058 -CLASS float
419.1059 -CLASS foo
419.1060 -CLASS gaierror
419.1061 -CLASS herror
419.1062 -CLASS install
419.1063 -CLASS install_data
419.1064 -CLASS install_egg_info
419.1065 -CLASS install_headers
419.1066 -CLASS install_lib
419.1067 -CLASS install_misc
419.1068 -CLASS install_scripts
419.1069 -CLASS instance
419.1070 -CLASS instance
419.1071 -CLASS int
419.1072 -CLASS iterator
419.1073 -CLASS iterator
419.1074 -CLASS list
419.1075 -CLASS local
419.1076 -CLASS lock
419.1077 -CLASS long
419.1078 -CLASS main
419.1079 -CLASS mbox
419.1080 -CLASS mboxMessage
419.1081 -CLASS mllib
419.1082 -CLASS mmap
419.1083 -CLASS multiprocessing.Pool
419.1084 -CLASS mutex
419.1085 -CLASS mxODBCProxy
419.1086 -CLASS netrc
419.1087 -CLASS object
419.1088 -CLASS object
419.1089 -CLASS oss_audio_device
419.1090 -CLASS oss_mixer_device
419.1091 -CLASS poll
419.1092 -CLASS py_object
419.1093 -CLASS register
419.1094 -CLASS scheduler
419.1095 -CLASS sdist
419.1096 -CLASS set
419.1097 -CLASS set
419.1098 -CLASS shlex
419.1099 -CLASS simple_producer
419.1100 -CLASS socket
419.1101 -CLASS stat_result
419.1102 -CLASS str
419.1103 -CLASS str
419.1104 -CLASS test_dist
419.1105 -CLASS test_zxjdbc
419.1106 -CLASS time
419.1107 -CLASS timedelta
419.1108 -CLASS timeout
419.1109 -CLASS tixCommand
419.1110 -CLASS tmxxx
419.1111 -CLASS tuple
419.1112 -CLASS tzinfo
419.1113 -CLASS unicode
419.1114 -CLASS unicode
419.1115 -CLASS upload
419.1116 -CLASS window
419.1117 -CLASS xmlparser
419.1118 -CLASS zipimporter
419.1119 -CLASS zxAPITestCase
419.1120 -CLASS zxCoreTestCase
419.1121 -CLASS zxJDBCTestCase
419.1122 -METHOD __import__(name, globals, loca
419.1123 -METHOD abs(x)
419.1124 -METHOD all(iterable)
419.1125 -METHOD any(iterable)
419.1126 -METHOD ---apply(function, args, ke---
419.1127 -METHOD basestring()
419.1128 -METHOD bin(x)
419.1129 -METHOD bool(x)
419.1130 -METHOD buffer(object, offset, size)
419.1131 -METHOD callable(object)
419.1132 -METHOD chr(i)
419.1133 -METHOD classmethod(function)
419.1134 -METHOD cmp(x, y)
419.1135 -METHOD coerce(x, y)
419.1136 -METHOD compile(source, filename, mode
419.1137 -METHOD complex(real, imag)
419.1138 -METHOD delattr(object, name)
419.1139 -METHOD dict(arg)
419.1140 -METHOD dir(object)
419.1141 -METHOD divmod(a, b)
419.1142 -METHOD enumerate(sequence, start)
419.1143 -METHOD eval(expression, globals, loca
419.1144 -METHOD execfile(filename, globals, lo
419.1145 -METHOD exit(code)
419.1146 -METHOD file(filename, mode, bufsize)
419.1147 -METHOD filter(function, iterable)
419.1148 -METHOD float(x)
419.1149 -METHOD frozenset(iterable)
419.1150 -METHOD getattr(object, name, default)
419.1151 -METHOD globals()
419.1152 -METHOD hasattr(object, name)
419.1153 -METHOD hash(object)
419.1154 -METHOD help(object)
419.1155 -METHOD hex(x)
419.1156 -METHOD id(object)
419.1157 -METHOD input(prompt)
419.1158 -METHOD int(x, radix)
419.1159 -METHOD intern(string)
419.1160 -METHOD isinstance(object, classinfo)
419.1161 -METHOD issubclass(class, classinfo)
419.1162 -METHOD iter(o, sentinel)
419.1163 -METHOD len(s)
419.1164 -METHOD list(iterable)
419.1165 -METHOD locals()
419.1166 -METHOD long(x, radix)
419.1167 -METHOD map(function, iterable)
419.1168 -METHOD max(iterable, argskey)
419.1169 -METHOD min(iterable, argskey)
419.1170 -METHOD next(iterator, default)
419.1171 -METHOD object()
419.1172 -METHOD oct(x)
419.1173 -METHOD open(filename, mode, bufsize)
419.1174 -METHOD ord(c)
419.1175 -METHOD pow(x, y, z)
419.1176 -METHOD print(object, sep, end, file)
419.1177 -METHOD property(fget, fset, fdel, doc
419.1178 -METHOD quit(code)
419.1179 -METHOD range(start, stop, step)
419.1180 -METHOD raw_input(prompt)
419.1181 -METHOD reduce(function, iterable, ini
419.1182 -METHOD reload(module)
419.1183 -METHOD repr(object)
419.1184 -METHOD reversed(seq)
419.1185 -METHOD round(x, n)
419.1186 -METHOD set(iterable)
419.1187 -METHOD setattr(object, name, value)
419.1188 -METHOD slice(start, stop, step)
419.1189 -METHOD sorted(iterable, cmp, key, rev
419.1190 -METHOD staticmethod(function)
419.1191 -METHOD str(object)
419.1192 -METHOD sum(iterable, start)
419.1193 -METHOD super(type, object-or-type)
419.1194 -METHOD tuple(iterable)
419.1195 -METHOD type(name, bases, dict)
419.1196 -METHOD type(object)
419.1197 -METHOD unichr(i)
419.1198 -METHOD unicode(object, encoding, erro
419.1199 -METHOD vars(object)
419.1200 -METHOD xrange(start, stop, step)
419.1201 -METHOD zip(iterable)
419.1202 -VARIABLE Ellipsis
419.1203 -VARIABLE False
419.1204 -VARIABLE None
419.1205 -VARIABLE NotImplemented
419.1206 -VARIABLE True
419.1207 -VARIABLE __debug__
419.1208 -VARIABLE copyright
419.1209 -KEYWORD and
419.1210 -KEYWORD as
419.1211 -KEYWORD assert
419.1212 -KEYWORD break
419.1213 -KEYWORD class
419.1214 -KEYWORD continue
419.1215 -KEYWORD def
419.1216 -KEYWORD del
419.1217 -KEYWORD elif
419.1218 -KEYWORD else
419.1219 -KEYWORD except
419.1220 -KEYWORD exec
419.1221 -KEYWORD finally
419.1222 -KEYWORD for
419.1223 -KEYWORD from
419.1224 -KEYWORD global
419.1225 -KEYWORD if
419.1226 -KEYWORD import
419.1227 -KEYWORD in
419.1228 -KEYWORD is
419.1229 -KEYWORD lambda
419.1230 -KEYWORD not
419.1231 -KEYWORD or
419.1232 -KEYWORD pass
419.1233 -KEYWORD print
419.1234 -KEYWORD raise
419.1235 -KEYWORD return
419.1236 -KEYWORD try
419.1237 -KEYWORD while
419.1238 -KEYWORD with
419.1239 -KEYWORD yield
420.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testLocals7.completion Sun Jan 04 13:11:53 2015 -0600
420.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
420.3 @@ -1,12 +0,0 @@
420.4 -Code completion result for source line:
420.5 -print t|oplevelvar2
420.6 -(QueryType=COMPLETION, NameKind=PREFIX)
420.7 -VARIABLE toplevelvar
420.8 -VARIABLE toplevelvar2
420.9 -VARIABLE toplevelvar3
420.10 -VARIABLE toplevelvar4
420.11 -------------------------------------
420.12 -METHOD tuple(iterable)
420.13 -METHOD type(name, bases, dict)
420.14 -METHOD type(object)
420.15 -KEYWORD try
421.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testMarks4.occurrences Sun Jan 04 13:11:53 2015 -0600
421.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
421.3 @@ -1,3 +0,0 @@
421.4 -def |>MARK_OCCURRENCES:myfunc<|(funcparam):
421.5 - x = |>MARK_OCCURRENCES:myf^unc<|
421.6 - |>MARK_OCCURRENCES:myfunc<|(5)
422.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testMarks5.occurrences Sun Jan 04 13:11:53 2015 -0600
422.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
422.3 @@ -1,2 +0,0 @@
422.4 -import |>MARK_OCCURRENCES:m^odule1<|
422.5 - |>MARK_OCCURRENCES:module1<|.x
423.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testMarks6.occurrences Sun Jan 04 13:11:53 2015 -0600
423.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
423.3 @@ -1,2 +0,0 @@
423.4 -import module3 as |>MARK_OCCURRENCES:modu^le4<|
423.5 - |>MARK_OCCURRENCES:module4<|.y
424.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testMarks7.occurrences Sun Jan 04 13:11:53 2015 -0600
424.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
424.3 @@ -1,2 +0,0 @@
424.4 -|>MARK_OCCURRENCES:toplevelv^ar2<| = 2
424.5 - print |>MARK_OCCURRENCES:toplevelvar2<|
425.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testMarks8.occurrences Sun Jan 04 13:11:53 2015 -0600
425.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
425.3 @@ -1,2 +0,0 @@
425.4 - def mymethod(self,param1,|>MARK_OCCURRENCES:pa^ram2<|):
425.5 - print |>MARK_OCCURRENCES:param2<|
426.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testRename4.rename Sun Jan 04 13:11:53 2015 -0600
426.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
426.3 @@ -1,2 +0,0 @@
426.4 -12: |>toplevelvar4<| = 6
426.5 -13: print |>toplevelvar4<|
427.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testRename5.rename Sun Jan 04 13:11:53 2015 -0600
427.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
427.3 @@ -1,1 +0,0 @@
427.4 -Requires Interactive Refactoring
428.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testRename6.rename Sun Jan 04 13:11:53 2015 -0600
428.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
428.3 @@ -1,1 +0,0 @@
428.4 -Requires Interactive Refactoring
429.1 --- a/python.editor/test/unit/data/testfiles/old-decorators1.py Sun Jan 04 13:11:53 2015 -0600
429.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
429.3 @@ -1,4 +0,0 @@
429.4 -def foo(self):
429.5 - perform method operation
429.6 -foo = classmethod(foo)
429.7 -
430.1 --- a/python.editor/test/unit/data/testfiles/old-decorators1.py.scopes Sun Jan 04 13:11:53 2015 -0600
430.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
430.3 @@ -1,11 +0,0 @@
430.4 -=============================================
430.5 -<file-top>: Module : OffsetRange[0,66>
430.6 -classmethod [read][called][UNRESOLVED][node=Name]
430.7 -foo [bound][function][def][read][node=FunctionDef]
430.8 -
430.9 - =============================================
430.10 - foo: FunctionDef : OffsetRange[0,44>
430.11 - method [free][read][node=Name]
430.12 - perform [free][read][node=Name]
430.13 - self [bound][param][data][unused][node=Name]
430.14 -
431.1 --- a/python.editor/test/unit/data/testfiles/old-decorators2.py Sun Jan 04 13:11:53 2015 -0600
431.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
431.3 @@ -1,5 +0,0 @@
431.4 -def foo(cls):
431.5 - pass
431.6 -foo = synchronized(lock)(foo)
431.7 -foo = classmethod(foo)
431.8 -
432.1 --- a/python.editor/test/unit/data/testfiles/old-decorators2.py.scopes Sun Jan 04 13:11:53 2015 -0600
432.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
432.3 @@ -1,11 +0,0 @@
432.4 -=============================================
432.5 -<file-top>: Module : OffsetRange[0,75>
432.6 -classmethod [read][called][UNRESOLVED][node=Name]
432.7 -foo [bound][function][def][read][node=FunctionDef]
432.8 -lock [read][UNRESOLVED][node=Name]
432.9 -synchronized [read][called][UNRESOLVED][node=Name]
432.10 -
432.11 - =============================================
432.12 - foo: FunctionDef : OffsetRange[0,23>
432.13 - cls [bound][param][data][unused][node=Name]
432.14 -
433.1 --- a/python.editor/test/unit/data/testfiles/org.py Sun Jan 04 13:11:53 2015 -0600
433.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
433.3 @@ -1,1 +0,0 @@
433.4 -from or
434.1 --- a/python.editor/test/unit/data/testfiles/org.py.testKeywordFrom.completion Sun Jan 04 13:11:53 2015 -0600
434.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
434.3 @@ -1,5 +0,0 @@
434.4 -Code completion result for source line:
434.5 -from or|
434.6 -(QueryType=COMPLETION, NameKind=PREFIX)
434.7 -------------------------------------
434.8 -KEYWORD org
435.1 --- a/python.editor/test/unit/data/testfiles/os.py Sun Jan 04 13:11:53 2015 -0600
435.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
435.3 @@ -1,738 +0,0 @@
435.4 -r"""OS routines for Mac, NT, or Posix depending on what system we're on.
435.5 -
435.6 -This exports:
435.7 - - all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
435.8 - - os.path is one of the modules posixpath, ntpath, or macpath
435.9 - - os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos'
435.10 - - os.curdir is a string representing the current directory ('.' or ':')
435.11 - - os.pardir is a string representing the parent directory ('..' or '::')
435.12 - - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
435.13 - - os.extsep is the extension separator ('.' or '/')
435.14 - - os.altsep is the alternate pathname separator (None or '/')
435.15 - - os.pathsep is the component separator used in $PATH etc
435.16 - - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
435.17 - - os.defpath is the default search path for executables
435.18 - - os.devnull is the file path of the null device ('/dev/null', etc.)
435.19 -
435.20 -Programs that import and use 'os' stand a better chance of being
435.21 -portable between different platforms. Of course, they must then
435.22 -only use functions that are defined by all platforms (e.g., unlink
435.23 -and opendir), and leave all pathname manipulation to os.path
435.24 -(e.g., split and join).
435.25 -"""
435.26 -
435.27 -#'
435.28 -
435.29 -import sys
435.30 -
435.31 -_names = sys.builtin_module_names
435.32 -
435.33 -# Note: more names are added to __all__ later.
435.34 -__all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep",
435.35 - "defpath", "name", "path", "devnull",
435.36 - "SEEK_SET", "SEEK_CUR", "SEEK_END"]
435.37 -
435.38 -def _get_exports_list(module):
435.39 - try:
435.40 - return list(module.__all__)
435.41 - except AttributeError:
435.42 - return [n for n in dir(module) if n[0] != '_']
435.43 -
435.44 -if 'posix' in _names:
435.45 - name = 'posix'
435.46 - linesep = '\n'
435.47 - from posix import *
435.48 - try:
435.49 - from posix import _exit
435.50 - except ImportError:
435.51 - pass
435.52 - import posixpath as path
435.53 -
435.54 - import posix
435.55 - __all__.extend(_get_exports_list(posix))
435.56 - del posix
435.57 -
435.58 -elif 'nt' in _names:
435.59 - name = 'nt'
435.60 - linesep = '\r\n'
435.61 - from nt import *
435.62 - try:
435.63 - from nt import _exit
435.64 - except ImportError:
435.65 - pass
435.66 - import ntpath as path
435.67 -
435.68 - import nt
435.69 - __all__.extend(_get_exports_list(nt))
435.70 - del nt
435.71 -
435.72 -elif 'os2' in _names:
435.73 - name = 'os2'
435.74 - linesep = '\r\n'
435.75 - from os2 import *
435.76 - try:
435.77 - from os2 import _exit
435.78 - except ImportError:
435.79 - pass
435.80 - if sys.version.find('EMX GCC') == -1:
435.81 - import ntpath as path
435.82 - else:
435.83 - import os2emxpath as path
435.84 - from _emx_link import link
435.85 -
435.86 - import os2
435.87 - __all__.extend(_get_exports_list(os2))
435.88 - del os2
435.89 -
435.90 -elif 'mac' in _names:
435.91 - name = 'mac'
435.92 - linesep = '\r'
435.93 - from mac import *
435.94 - try:
435.95 - from mac import _exit
435.96 - except ImportError:
435.97 - pass
435.98 - import macpath as path
435.99 -
435.100 - import mac
435.101 - __all__.extend(_get_exports_list(mac))
435.102 - del mac
435.103 -
435.104 -elif 'ce' in _names:
435.105 - name = 'ce'
435.106 - linesep = '\r\n'
435.107 - from ce import *
435.108 - try:
435.109 - from ce import _exit
435.110 - except ImportError:
435.111 - pass
435.112 - # We can use the standard Windows path.
435.113 - import ntpath as path
435.114 -
435.115 - import ce
435.116 - __all__.extend(_get_exports_list(ce))
435.117 - del ce
435.118 -
435.119 -elif 'riscos' in _names:
435.120 - name = 'riscos'
435.121 - linesep = '\n'
435.122 - from riscos import *
435.123 - try:
435.124 - from riscos import _exit
435.125 - except ImportError:
435.126 - pass
435.127 - import riscospath as path
435.128 -
435.129 - import riscos
435.130 - __all__.extend(_get_exports_list(riscos))
435.131 - del riscos
435.132 -
435.133 -else:
435.134 - raise ImportError, 'no os specific module found'
435.135 -
435.136 -sys.modules['os.path'] = path
435.137 -from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
435.138 - devnull)
435.139 -
435.140 -del _names
435.141 -
435.142 -# Python uses fixed values for the SEEK_ constants; they are mapped
435.143 -# to native constants if necessary in posixmodule.c
435.144 -SEEK_SET = 0
435.145 -SEEK_CUR = 1
435.146 -SEEK_END = 2
435.147 -
435.148 -#'
435.149 -
435.150 -# Super directory utilities.
435.151 -# (Inspired by Eric Raymond; the doc strings are mostly his)
435.152 -
435.153 -def makedirs(name, mode=0777):
435.154 - """makedirs(path [, mode=0777])
435.155 -
435.156 - Super-mkdir; create a leaf directory and all intermediate ones.
435.157 - Works like mkdir, except that any intermediate path segment (not
435.158 - just the rightmost) will be created if it does not exist. This is
435.159 - recursive.
435.160 -
435.161 - """
435.162 - from errno import EEXIST
435.163 - head, tail = path.split(name)
435.164 - if not tail:
435.165 - head, tail = path.split(head)
435.166 - if head and tail and not path.exists(head):
435.167 - try:
435.168 - makedirs(head, mode)
435.169 - except OSError, e:
435.170 - # be happy if someone already created the path
435.171 - if e.errno != EEXIST:
435.172 - raise
435.173 - if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists
435.174 - return
435.175 - mkdir(name, mode)
435.176 -
435.177 -def removedirs(name):
435.178 - """removedirs(path)
435.179 -
435.180 - Super-rmdir; remove a leaf directory and all empty intermediate
435.181 - ones. Works like rmdir except that, if the leaf directory is
435.182 - successfully removed, directories corresponding to rightmost path
435.183 - segments will be pruned away until either the whole path is
435.184 - consumed or an error occurs. Errors during this latter phase are
435.185 - ignored -- they generally mean that a directory was not empty.
435.186 -
435.187 - """
435.188 - rmdir(name)
435.189 - head, tail = path.split(name)
435.190 - if not tail:
435.191 - head, tail = path.split(head)
435.192 - while head and tail:
435.193 - try:
435.194 - rmdir(head)
435.195 - except error:
435.196 - break
435.197 - head, tail = path.split(head)
435.198 -
435.199 -def renames(old, new):
435.200 - """renames(old, new)
435.201 -
435.202 - Super-rename; create directories as necessary and delete any left
435.203 - empty. Works like rename, except creation of any intermediate
435.204 - directories needed to make the new pathname good is attempted
435.205 - first. After the rename, directories corresponding to rightmost
435.206 - path segments of the old name will be pruned way until either the
435.207 - whole path is consumed or a nonempty directory is found.
435.208 -
435.209 - Note: this function can fail with the new directory structure made
435.210 - if you lack permissions needed to unlink the leaf directory or
435.211 - file.
435.212 -
435.213 - """
435.214 - head, tail = path.split(new)
435.215 - if head and tail and not path.exists(head):
435.216 - makedirs(head)
435.217 - rename(old, new)
435.218 - head, tail = path.split(old)
435.219 - if head and tail:
435.220 - try:
435.221 - removedirs(head)
435.222 - except error:
435.223 - pass
435.224 -
435.225 -__all__.extend(["makedirs", "removedirs", "renames"])
435.226 -
435.227 -def walk(top, topdown=True, onerror=None):
435.228 - """Directory tree generator.
435.229 -
435.230 - For each directory in the directory tree rooted at top (including top
435.231 - itself, but excluding '.' and '..'), yields a 3-tuple
435.232 -
435.233 - dirpath, dirnames, filenames
435.234 -
435.235 - dirpath is a string, the path to the directory. dirnames is a list of
435.236 - the names of the subdirectories in dirpath (excluding '.' and '..').
435.237 - filenames is a list of the names of the non-directory files in dirpath.
435.238 - Note that the names in the lists are just names, with no path components.
435.239 - To get a full path (which begins with top) to a file or directory in
435.240 - dirpath, do os.path.join(dirpath, name).
435.241 -
435.242 - If optional arg 'topdown' is true or not specified, the triple for a
435.243 - directory is generated before the triples for any of its subdirectories
435.244 - (directories are generated top down). If topdown is false, the triple
435.245 - for a directory is generated after the triples for all of its
435.246 - subdirectories (directories are generated bottom up).
435.247 -
435.248 - When topdown is true, the caller can modify the dirnames list in-place
435.249 - (e.g., via del or slice assignment), and walk will only recurse into the
435.250 - subdirectories whose names remain in dirnames; this can be used to prune
435.251 - the search, or to impose a specific order of visiting. Modifying
435.252 - dirnames when topdown is false is ineffective, since the directories in
435.253 - dirnames have already been generated by the time dirnames itself is
435.254 - generated.
435.255 -
435.256 - By default errors from the os.listdir() call are ignored. If
435.257 - optional arg 'onerror' is specified, it should be a function; it
435.258 - will be called with one argument, an os.error instance. It can
435.259 - report the error to continue with the walk, or raise the exception
435.260 - to abort the walk. Note that the filename is available as the
435.261 - filename attribute of the exception object.
435.262 -
435.263 - Caution: if you pass a relative pathname for top, don't change the
435.264 - current working directory between resumptions of walk. walk never
435.265 - changes the current directory, and assumes that the client doesn't
435.266 - either.
435.267 -
435.268 - Example:
435.269 -
435.270 - from os.path import join, getsize
435.271 - for root, dirs, files in walk('python/Lib/email'):
435.272 - print root, "consumes",
435.273 - print sum([getsize(join(root, name)) for name in files]),
435.274 - print "bytes in", len(files), "non-directory files"
435.275 - if 'CVS' in dirs:
435.276 - dirs.remove('CVS') # don't visit CVS directories
435.277 - """
435.278 -
435.279 - from os.path import join, isdir, islink
435.280 -
435.281 - # We may not have read permission for top, in which case we can't
435.282 - # get a list of the files the directory contains. os.path.walk
435.283 - # always suppressed the exception then, rather than blow up for a
435.284 - # minor reason when (say) a thousand readable directories are still
435.285 - # left to visit. That logic is copied here.
435.286 - try:
435.287 - # Note that listdir and error are globals in this module due
435.288 - # to earlier import-*.
435.289 - names = listdir(top)
435.290 - except error, err:
435.291 - if onerror is not None:
435.292 - onerror(err)
435.293 - return
435.294 -
435.295 - dirs, nondirs = [], []
435.296 - for name in names:
435.297 - if isdir(join(top, name)):
435.298 - dirs.append(name)
435.299 - else:
435.300 - nondirs.append(name)
435.301 -
435.302 - if topdown:
435.303 - yield top, dirs, nondirs
435.304 - for name in dirs:
435.305 - path = join(top, name)
435.306 - if not islink(path):
435.307 - for x in walk(path, topdown, onerror):
435.308 - yield x
435.309 - if not topdown:
435.310 - yield top, dirs, nondirs
435.311 -
435.312 -__all__.append("walk")
435.313 -
435.314 -# Make sure os.environ exists, at least
435.315 -try:
435.316 - environ
435.317 -except NameError:
435.318 - environ = {}
435.319 -
435.320 -def execl(file, *args):
435.321 - """execl(file, *args)
435.322 -
435.323 - Execute the executable file with argument list args, replacing the
435.324 - current process. """
435.325 - execv(file, args)
435.326 -
435.327 -def execle(file, *args):
435.328 - """execle(file, *args, env)
435.329 -
435.330 - Execute the executable file with argument list args and
435.331 - environment env, replacing the current process. """
435.332 - env = args[-1]
435.333 - execve(file, args[:-1], env)
435.334 -
435.335 -def execlp(file, *args):
435.336 - """execlp(file, *args)
435.337 -
435.338 - Execute the executable file (which is searched for along $PATH)
435.339 - with argument list args, replacing the current process. """
435.340 - execvp(file, args)
435.341 -
435.342 -def execlpe(file, *args):
435.343 - """execlpe(file, *args, env)
435.344 -
435.345 - Execute the executable file (which is searched for along $PATH)
435.346 - with argument list args and environment env, replacing the current
435.347 - process. """
435.348 - env = args[-1]
435.349 - execvpe(file, args[:-1], env)
435.350 -
435.351 -def execvp(file, args):
435.352 - """execp(file, args)
435.353 -
435.354 - Execute the executable file (which is searched for along $PATH)
435.355 - with argument list args, replacing the current process.
435.356 - args may be a list or tuple of strings. """
435.357 - _execvpe(file, args)
435.358 -
435.359 -def execvpe(file, args, env):
435.360 - """execvpe(file, args, env)
435.361 -
435.362 - Execute the executable file (which is searched for along $PATH)
435.363 - with argument list args and environment env , replacing the
435.364 - current process.
435.365 - args may be a list or tuple of strings. """
435.366 - _execvpe(file, args, env)
435.367 -
435.368 -__all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])
435.369 -
435.370 -def _execvpe(file, args, env=None):
435.371 - from errno import ENOENT, ENOTDIR
435.372 -
435.373 - if env is not None:
435.374 - func = execve
435.375 - argrest = (args, env)
435.376 - else:
435.377 - func = execv
435.378 - argrest = (args,)
435.379 - env = environ
435.380 -
435.381 - head, tail = path.split(file)
435.382 - if head:
435.383 - func(file, *argrest)
435.384 - return
435.385 - if 'PATH' in env:
435.386 - envpath = env['PATH']
435.387 - else:
435.388 - envpath = defpath
435.389 - PATH = envpath.split(pathsep)
435.390 - saved_exc = None
435.391 - saved_tb = None
435.392 - for dir in PATH:
435.393 - fullname = path.join(dir, file)
435.394 - try:
435.395 - func(fullname, *argrest)
435.396 - except error, e:
435.397 - tb = sys.exc_info()[2]
435.398 - if (e.errno != ENOENT and e.errno != ENOTDIR
435.399 - and saved_exc is None):
435.400 - saved_exc = e
435.401 - saved_tb = tb
435.402 - if saved_exc:
435.403 - raise error, saved_exc, saved_tb
435.404 - raise error, e, tb
435.405 -
435.406 -# Change environ to automatically call putenv() if it exists
435.407 -try:
435.408 - # This will fail if there's no putenv
435.409 - putenv
435.410 -except NameError:
435.411 - pass
435.412 -else:
435.413 - import UserDict
435.414 -
435.415 - # Fake unsetenv() for Windows
435.416 - # not sure about os2 here but
435.417 - # I'm guessing they are the same.
435.418 -
435.419 - if name in ('os2', 'nt'):
435.420 - def unsetenv(key):
435.421 - putenv(key, "")
435.422 -
435.423 - if name == "riscos":
435.424 - # On RISC OS, all env access goes through getenv and putenv
435.425 - from riscosenviron import _Environ
435.426 - elif name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE
435.427 - # But we store them as upper case
435.428 - class _Environ(UserDict.IterableUserDict):
435.429 - def __init__(self, environ):
435.430 - UserDict.UserDict.__init__(self)
435.431 - data = self.data
435.432 - for k, v in environ.items():
435.433 - data[k.upper()] = v
435.434 - def __setitem__(self, key, item):
435.435 - putenv(key, item)
435.436 - self.data[key.upper()] = item
435.437 - def __getitem__(self, key):
435.438 - return self.data[key.upper()]
435.439 - try:
435.440 - unsetenv
435.441 - except NameError:
435.442 - def __delitem__(self, key):
435.443 - del self.data[key.upper()]
435.444 - else:
435.445 - def __delitem__(self, key):
435.446 - unsetenv(key)
435.447 - del self.data[key.upper()]
435.448 - def has_key(self, key):
435.449 - return key.upper() in self.data
435.450 - def __contains__(self, key):
435.451 - return key.upper() in self.data
435.452 - def get(self, key, failobj=None):
435.453 - return self.data.get(key.upper(), failobj)
435.454 - def update(self, dict=None, **kwargs):
435.455 - if dict:
435.456 - try:
435.457 - keys = dict.keys()
435.458 - except AttributeError:
435.459 - # List of (key, value)
435.460 - for k, v in dict:
435.461 - self[k] = v
435.462 - else:
435.463 - # got keys
435.464 - # cannot use items(), since mappings
435.465 - # may not have them.
435.466 - for k in keys:
435.467 - self[k] = dict[k]
435.468 - if kwargs:
435.469 - self.update(kwargs)
435.470 - def copy(self):
435.471 - return dict(self)
435.472 -
435.473 - else: # Where Env Var Names Can Be Mixed Case
435.474 - class _Environ(UserDict.IterableUserDict):
435.475 - def __init__(self, environ):
435.476 - UserDict.UserDict.__init__(self)
435.477 - self.data = environ
435.478 - def __setitem__(self, key, item):
435.479 - putenv(key, item)
435.480 - self.data[key] = item
435.481 - def update(self, dict=None, **kwargs):
435.482 - if dict:
435.483 - try:
435.484 - keys = dict.keys()
435.485 - except AttributeError:
435.486 - # List of (key, value)
435.487 - for k, v in dict:
435.488 - self[k] = v
435.489 - else:
435.490 - # got keys
435.491 - # cannot use items(), since mappings
435.492 - # may not have them.
435.493 - for k in keys:
435.494 - self[k] = dict[k]
435.495 - if kwargs:
435.496 - self.update(kwargs)
435.497 - try:
435.498 - unsetenv
435.499 - except NameError:
435.500 - pass
435.501 - else:
435.502 - def __delitem__(self, key):
435.503 - unsetenv(key)
435.504 - del self.data[key]
435.505 - def copy(self):
435.506 - return dict(self)
435.507 -
435.508 -
435.509 - environ = _Environ(environ)
435.510 -
435.511 -def getenv(key, default=None):
435.512 - """Get an environment variable, return None if it doesn't exist.
435.513 - The optional second argument can specify an alternate default."""
435.514 - return environ.get(key, default)
435.515 -__all__.append("getenv")
435.516 -
435.517 -def _exists(name):
435.518 - try:
435.519 - eval(name)
435.520 - return True
435.521 - except NameError:
435.522 - return False
435.523 -
435.524 -# Supply spawn*() (probably only for Unix)
435.525 -if _exists("fork") and not _exists("spawnv") and _exists("execv"):
435.526 -
435.527 - P_WAIT = 0
435.528 - P_NOWAIT = P_NOWAITO = 1
435.529 -
435.530 - # XXX Should we support P_DETACH? I suppose it could fork()**2
435.531 - # and close the std I/O streams. Also, P_OVERLAY is the same
435.532 - # as execv*()?
435.533 -
435.534 - def _spawnvef(mode, file, args, env, func):
435.535 - # Internal helper; func is the exec*() function to use
435.536 - pid = fork()
435.537 - if not pid:
435.538 - # Child
435.539 - try:
435.540 - if env is None:
435.541 - func(file, args)
435.542 - else:
435.543 - func(file, args, env)
435.544 - except:
435.545 - _exit(127)
435.546 - else:
435.547 - # Parent
435.548 - if mode == P_NOWAIT:
435.549 - return pid # Caller is responsible for waiting!
435.550 - while 1:
435.551 - wpid, sts = waitpid(pid, 0)
435.552 - if WIFSTOPPED(sts):
435.553 - continue
435.554 - elif WIFSIGNALED(sts):
435.555 - return -WTERMSIG(sts)
435.556 - elif WIFEXITED(sts):
435.557 - return WEXITSTATUS(sts)
435.558 - else:
435.559 - raise error, "Not stopped, signaled or exited???"
435.560 -
435.561 - def spawnv(mode, file, args):
435.562 - """spawnv(mode, file, args) -> integer
435.563 -
435.564 -Execute file with arguments from args in a subprocess.
435.565 -If mode == P_NOWAIT return the pid of the process.
435.566 -If mode == P_WAIT return the process's exit code if it exits normally;
435.567 -otherwise return -SIG, where SIG is the signal that killed it. """
435.568 - return _spawnvef(mode, file, args, None, execv)
435.569 -
435.570 - def spawnve(mode, file, args, env):
435.571 - """spawnve(mode, file, args, env) -> integer
435.572 -
435.573 -Execute file with arguments from args in a subprocess with the
435.574 -specified environment.
435.575 -If mode == P_NOWAIT return the pid of the process.
435.576 -If mode == P_WAIT return the process's exit code if it exits normally;
435.577 -otherwise return -SIG, where SIG is the signal that killed it. """
435.578 - return _spawnvef(mode, file, args, env, execve)
435.579 -
435.580 - # Note: spawnvp[e] is't currently supported on Windows
435.581 -
435.582 - def spawnvp(mode, file, args):
435.583 - """spawnvp(mode, file, args) -> integer
435.584 -
435.585 -Execute file (which is looked for along $PATH) with arguments from
435.586 -args in a subprocess.
435.587 -If mode == P_NOWAIT return the pid of the process.
435.588 -If mode == P_WAIT return the process's exit code if it exits normally;
435.589 -otherwise return -SIG, where SIG is the signal that killed it. """
435.590 - return _spawnvef(mode, file, args, None, execvp)
435.591 -
435.592 - def spawnvpe(mode, file, args, env):
435.593 - """spawnvpe(mode, file, args, env) -> integer
435.594 -
435.595 -Execute file (which is looked for along $PATH) with arguments from
435.596 -args in a subprocess with the supplied environment.
435.597 -If mode == P_NOWAIT return the pid of the process.
435.598 -If mode == P_WAIT return the process's exit code if it exits normally;
435.599 -otherwise return -SIG, where SIG is the signal that killed it. """
435.600 - return _spawnvef(mode, file, args, env, execvpe)
435.601 -
435.602 -if _exists("spawnv"):
435.603 - # These aren't supplied by the basic Windows code
435.604 - # but can be easily implemented in Python
435.605 -
435.606 - def spawnl(mode, file, *args):
435.607 - """spawnl(mode, file, *args) -> integer
435.608 -
435.609 -Execute file with arguments from args in a subprocess.
435.610 -If mode == P_NOWAIT return the pid of the process.
435.611 -If mode == P_WAIT return the process's exit code if it exits normally;
435.612 -otherwise return -SIG, where SIG is the signal that killed it. """
435.613 - return spawnv(mode, file, args)
435.614 -
435.615 - def spawnle(mode, file, *args):
435.616 - """spawnle(mode, file, *args, env) -> integer
435.617 -
435.618 -Execute file with arguments from args in a subprocess with the
435.619 -supplied environment.
435.620 -If mode == P_NOWAIT return the pid of the process.
435.621 -If mode == P_WAIT return the process's exit code if it exits normally;
435.622 -otherwise return -SIG, where SIG is the signal that killed it. """
435.623 - env = args[-1]
435.624 - return spawnve(mode, file, args[:-1], env)
435.625 -
435.626 -
435.627 - __all__.extend(["spawnv", "spawnve", "spawnl", "spawnle",])
435.628 -
435.629 -
435.630 -if _exists("spawnvp"):
435.631 - # At the moment, Windows doesn't implement spawnvp[e],
435.632 - # so it won't have spawnlp[e] either.
435.633 - def spawnlp(mode, file, *args):
435.634 - """spawnlp(mode, file, *args) -> integer
435.635 -
435.636 -Execute file (which is looked for along $PATH) with arguments from
435.637 -args in a subprocess with the supplied environment.
435.638 -If mode == P_NOWAIT return the pid of the process.
435.639 -If mode == P_WAIT return the process's exit code if it exits normally;
435.640 -otherwise return -SIG, where SIG is the signal that killed it. """
435.641 - return spawnvp(mode, file, args)
435.642 -
435.643 - def spawnlpe(mode, file, *args):
435.644 - """spawnlpe(mode, file, *args, env) -> integer
435.645 -
435.646 -Execute file (which is looked for along $PATH) with arguments from
435.647 -args in a subprocess with the supplied environment.
435.648 -If mode == P_NOWAIT return the pid of the process.
435.649 -If mode == P_WAIT return the process's exit code if it exits normally;
435.650 -otherwise return -SIG, where SIG is the signal that killed it. """
435.651 - env = args[-1]
435.652 - return spawnvpe(mode, file, args[:-1], env)
435.653 -
435.654 -
435.655 - __all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",])
435.656 -
435.657 -
435.658 -# Supply popen2 etc. (for Unix)
435.659 -if _exists("fork"):
435.660 - if not _exists("popen2"):
435.661 - def popen2(cmd, mode="t", bufsize=-1):
435.662 - """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'
435.663 - may be a sequence, in which case arguments will be passed directly to
435.664 - the program without shell intervention (as with os.spawnv()). If 'cmd'
435.665 - is a string it will be passed to the shell (as with os.system()). If
435.666 - 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
435.667 - file objects (child_stdin, child_stdout) are returned."""
435.668 - import popen2
435.669 - stdout, stdin = popen2.popen2(cmd, bufsize)
435.670 - return stdin, stdout
435.671 - __all__.append("popen2")
435.672 -
435.673 - if not _exists("popen3"):
435.674 - def popen3(cmd, mode="t", bufsize=-1):
435.675 - """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'
435.676 - may be a sequence, in which case arguments will be passed directly to
435.677 - the program without shell intervention (as with os.spawnv()). If 'cmd'
435.678 - is a string it will be passed to the shell (as with os.system()). If
435.679 - 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
435.680 - file objects (child_stdin, child_stdout, child_stderr) are returned."""
435.681 - import popen2
435.682 - stdout, stdin, stderr = popen2.popen3(cmd, bufsize)
435.683 - return stdin, stdout, stderr
435.684 - __all__.append("popen3")
435.685 -
435.686 - if not _exists("popen4"):
435.687 - def popen4(cmd, mode="t", bufsize=-1):
435.688 - """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'
435.689 - may be a sequence, in which case arguments will be passed directly to
435.690 - the program without shell intervention (as with os.spawnv()). If 'cmd'
435.691 - is a string it will be passed to the shell (as with os.system()). If
435.692 - 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
435.693 - file objects (child_stdin, child_stdout_stderr) are returned."""
435.694 - import popen2
435.695 - stdout, stdin = popen2.popen4(cmd, bufsize)
435.696 - return stdin, stdout
435.697 - __all__.append("popen4")
435.698 -
435.699 -import copy_reg as _copy_reg
435.700 -
435.701 -def _make_stat_result(tup, dict):
435.702 - return stat_result(tup, dict)
435.703 -
435.704 -def _pickle_stat_result(sr):
435.705 - (type, args) = sr.__reduce__()
435.706 - return (_make_stat_result, args)
435.707 -
435.708 -try:
435.709 - _copy_reg.pickle(stat_result, _pickle_stat_result, _make_stat_result)
435.710 -except NameError: # stat_result may not exist
435.711 - pass
435.712 -
435.713 -def _make_statvfs_result(tup, dict):
435.714 - return statvfs_result(tup, dict)
435.715 -
435.716 -def _pickle_statvfs_result(sr):
435.717 - (type, args) = sr.__reduce__()
435.718 - return (_make_statvfs_result, args)
435.719 -
435.720 -try:
435.721 - _copy_reg.pickle(statvfs_result, _pickle_statvfs_result,
435.722 - _make_statvfs_result)
435.723 -except NameError: # statvfs_result may not exist
435.724 - pass
435.725 -
435.726 -if not _exists("urandom"):
435.727 - def urandom(n):
435.728 - """urandom(n) -> str
435.729 -
435.730 - Return a string of n random bytes suitable for cryptographic use.
435.731 -
435.732 - """
435.733 - try:
435.734 - _urandomfd = open("/dev/urandom", O_RDONLY)
435.735 - except (OSError, IOError):
435.736 - raise NotImplementedError("/dev/urandom (or equivalent) not found")
435.737 - bytes = ""
435.738 - while len(bytes) < n:
435.739 - bytes += read(_urandomfd, n - len(bytes))
435.740 - close(_urandomfd)
435.741 - return bytes
436.1 --- a/python.editor/test/unit/data/testfiles/os.py.indexed Sun Jan 04 13:11:53 2015 -0600
436.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
436.3 @@ -1,88 +0,0 @@
436.4 -
436.5 -
436.6 -Document 0
436.7 -Searchable Keys:
436.8 - class : _Environ
436.9 - class-ig : _environ
436.10 - extends : IterableUserDict
436.11 - in : os
436.12 - member : __delitem__;F;;self,key;
436.13 - member : __init__;c;|CONSTRUCTOR|;self,environ;
436.14 - member : __setitem__;F;;self,key,item;
436.15 - member : copy;F;;self;
436.16 - member : data;D;;
436.17 - member : update;F;;self,dict,kwargs;
436.18 -
436.19 -Not Searchable Keys:
436.20 - clzattrs : ;|PRIVATE|;
436.21 -
436.22 -
436.23 -Document 1
436.24 -Searchable Keys:
436.25 - item : P_NOWAIT;D;;
436.26 - item : P_NOWAITO;D;;
436.27 - item : P_WAIT;D;;
436.28 - item : SEEK_CUR;D;;
436.29 - item : SEEK_END;D;;
436.30 - item : SEEK_SET;D;;
436.31 - item : UserDict;I;;
436.32 - item : _Environ;C;|PRIVATE|;
436.33 - item : __all__;D;;
436.34 - item : _copy_reg;I;|PRIVATE|;
436.35 - item : _execvpe;F;|PRIVATE|;file,args,env;
436.36 - item : _exists;F;|PRIVATE|;name;
436.37 - item : _exit;I;|PRIVATE|;
436.38 - item : _get_exports_list;F;|PRIVATE|;module;
436.39 - item : _make_stat_result;F;|PRIVATE|;tup,dict;
436.40 - item : _make_statvfs_result;F;|PRIVATE|;tup,dict;
436.41 - item : _names;D;|PRIVATE|;
436.42 - item : _pickle_stat_result;F;|PRIVATE|;sr;
436.43 - item : _pickle_statvfs_result;F;|PRIVATE|;sr;
436.44 - item : _spawnvef;F;|PRIVATE|;mode,file,args,env,func;
436.45 - item : altsep;I;;
436.46 - item : ce;I;;
436.47 - item : curdir;I;;
436.48 - item : defpath;I;;
436.49 - item : devnull;I;;
436.50 - item : environ;D;;
436.51 - item : execl;F;;file,args;
436.52 - item : execle;F;;file,args;
436.53 - item : execlp;F;;file,args;
436.54 - item : execlpe;F;;file,args;
436.55 - item : execvp;F;;file,args;
436.56 - item : execvpe;F;;file,args,env;
436.57 - item : extsep;I;;
436.58 - item : getenv;F;;key,default;
436.59 - item : linesep;D;;
436.60 - item : link;I;;
436.61 - item : mac;I;;
436.62 - item : makedirs;F;;name,mode;
436.63 - item : name;D;;
436.64 - item : nt;I;;
436.65 - item : os2;I;;
436.66 - item : pardir;I;;
436.67 - item : path;I;;
436.68 - item : pathsep;I;;
436.69 - item : popen2;F;;cmd,mode,bufsize;
436.70 - item : popen3;F;;cmd,mode,bufsize;
436.71 - item : popen4;F;;cmd,mode,bufsize;
436.72 - item : posix;I;;
436.73 - item : removedirs;F;;name;
436.74 - item : renames;F;;old,new;
436.75 - item : riscos;I;;
436.76 - item : sep;I;;
436.77 - item : spawnl;F;;mode,file,args;
436.78 - item : spawnle;F;;mode,file,args;
436.79 - item : spawnlp;F;;mode,file,args;
436.80 - item : spawnlpe;F;;mode,file,args;
436.81 - item : spawnv;F;;mode,file,args;
436.82 - item : spawnve;F;;mode,file,args,env;
436.83 - item : spawnvp;F;;mode,file,args;
436.84 - item : spawnvpe;F;;mode,file,args,env;
436.85 - item : sys;I;;
436.86 - item : unsetenv;F;;key;
436.87 - item : urandom;F;;n;
436.88 - item : walk;F;;top,topdown,onerror;
436.89 - module : os
436.90 -
436.91 -Not Searchable Keys:
437.1 --- a/python.editor/test/unit/data/testfiles/os.py.scopes Sun Jan 04 13:11:53 2015 -0600
437.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
437.3 @@ -1,531 +0,0 @@
437.4 -=============================================
437.5 -<file-top>: Module : OffsetRange[0,24666>
437.6 -* [bound][imported][data][node=ImportFrom]
437.7 -ImportError [read][UNRESOLVED][node=Name]
437.8 -NameError [read][UNRESOLVED][node=Name]
437.9 -None [read][UNRESOLVED][node=Name]
437.10 -P_NOWAIT [bound][data][read][node=Name]
437.11 -P_NOWAITO [bound][data][node=Name]
437.12 -P_WAIT [bound][data][node=Name]
437.13 -SEEK_CUR [bound][data][node=Name]
437.14 -SEEK_END [bound][data][node=Name]
437.15 -SEEK_SET [bound][data][node=Name]
437.16 -True [read][UNRESOLVED][node=Name]
437.17 -UserDict [bound][imported][data][read][node=Import]
437.18 -_Environ [bound][imported][private][class][def][read][called][node=ClassDef]
437.19 -__all__ [bound][data][read][node=Name]
437.20 -_copy_reg [bound][imported][private][data][read][node=Import]
437.21 -_execvpe [bound][private][function][def][node=FunctionDef]
437.22 -_exists [bound][private][function][def][read][called][node=FunctionDef]
437.23 -_exit [bound][imported][private][data][read][called][node=ImportFrom]
437.24 -_get_exports_list [bound][private][function][def][read][called][node=FunctionDef]
437.25 -_make_stat_result [bound][private][function][def][read][node=FunctionDef]
437.26 -_make_statvfs_result [bound][private][function][def][read][node=FunctionDef]
437.27 -_names [bound][private][data][read][node=Name]
437.28 -_pickle_stat_result [bound][private][function][def][read][node=FunctionDef]
437.29 -_pickle_statvfs_result [bound][private][function][def][read][node=FunctionDef]
437.30 -_spawnvef [bound][private][function][def][read][called][node=FunctionDef]
437.31 -altsep [bound][imported][data][node=ImportFrom]
437.32 -ce [bound][imported][data][read][node=Import]
437.33 -curdir [bound][imported][data][read][node=ImportFrom]
437.34 -defpath [bound][imported][data][read][node=ImportFrom]
437.35 -devnull [bound][imported][data][node=ImportFrom]
437.36 -environ [bound][data][read][node=Name]
437.37 -execl [bound][function][def][node=FunctionDef]
437.38 -execle [bound][function][def][node=FunctionDef]
437.39 -execlp [bound][function][def][node=FunctionDef]
437.40 -execlpe [bound][function][def][node=FunctionDef]
437.41 -execvp [bound][function][def][read][node=FunctionDef]
437.42 -execvpe [bound][function][def][read][node=FunctionDef]
437.43 -extsep [bound][imported][data][node=ImportFrom]
437.44 -getenv [bound][function][def][node=FunctionDef]
437.45 -linesep [bound][data][node=Name]
437.46 -link [bound][imported][data][node=ImportFrom]
437.47 -mac [bound][imported][data][read][node=Import]
437.48 -makedirs [bound][function][def][read][called][node=FunctionDef]
437.49 -name [bound][data][read][node=Name]
437.50 -nt [bound][imported][data][read][node=Import]
437.51 -os2 [bound][imported][data][read][node=Import]
437.52 -pardir [bound][imported][data][node=ImportFrom]
437.53 -path [bound][imported][data][read][node=Import]
437.54 -pathsep [bound][imported][data][read][node=ImportFrom]
437.55 -popen2 [bound][function][def][node=FunctionDef]
437.56 -popen3 [bound][function][def][node=FunctionDef]
437.57 -popen4 [bound][function][def][node=FunctionDef]
437.58 -posix [bound][imported][data][read][node=Import]
437.59 -putenv [read][UNRESOLVED][node=Name]
437.60 -removedirs [bound][function][def][read][called][node=FunctionDef]
437.61 -renames [bound][function][def][node=FunctionDef]
437.62 -riscos [bound][imported][data][read][node=Import]
437.63 -sep [bound][imported][data][node=ImportFrom]
437.64 -spawnl [bound][function][def][node=FunctionDef]
437.65 -spawnle [bound][function][def][node=FunctionDef]
437.66 -spawnlp [bound][function][def][node=FunctionDef]
437.67 -spawnlpe [bound][function][def][node=FunctionDef]
437.68 -spawnv [bound][function][def][read][called][node=FunctionDef]
437.69 -spawnve [bound][function][def][read][called][node=FunctionDef]
437.70 -spawnvp [bound][function][def][read][called][node=FunctionDef]
437.71 -spawnvpe [bound][function][def][read][called][node=FunctionDef]
437.72 -stat_result [read][UNRESOLVED][node=Name]
437.73 -statvfs_result [read][UNRESOLVED][node=Name]
437.74 -sys [bound][imported][data][read][node=Import]
437.75 -unsetenv [bound][function][def][read][called][node=FunctionDef]
437.76 -urandom [bound][function][def][node=FunctionDef]
437.77 -walk [bound][function][def][read][called][node=FunctionDef]
437.78 -
437.79 - =============================================
437.80 - _get_exports_list: FunctionDef : OffsetRange[1451,1610>
437.81 - AttributeError [free][read][node=Name]
437.82 - _[39_16] [bound][private][data][unused][node=ListComp]
437.83 - dir [free][read][called][node=Name]
437.84 - list [free][read][called][node=Name]
437.85 - module [bound][param][data][read][node=Name]
437.86 - n [bound][data][read][node=Name]
437.87 -
437.88 - =============================================
437.89 - makedirs: FunctionDef : OffsetRange[3783,4559>
437.90 - EEXIST [bound][imported][data][read][node=ImportFrom]
437.91 - OSError [free][read][node=Name]
437.92 - curdir [free][read][node=Name]
437.93 - e [bound][data][read][node=Name]
437.94 - head [bound][data][read][node=Name]
437.95 - makedirs [free][read][called][node=Name]
437.96 - mkdir [free][read][called][node=Name]
437.97 - mode [bound][param][data][read][node=Name]
437.98 - name [bound][param][data][read][node=Name]
437.99 - path [free][read][node=Name]
437.100 - tail [bound][data][read][node=Name]
437.101 -
437.102 - =============================================
437.103 - removedirs: FunctionDef : OffsetRange[4559,5266>
437.104 - error [free][read][node=Name]
437.105 - head [bound][data][read][node=Name]
437.106 - name [bound][param][data][read][node=Name]
437.107 - path [free][read][node=Name]
437.108 - rmdir [free][read][called][node=Name]
437.109 - tail [bound][data][read][node=Name]
437.110 -
437.111 - =============================================
437.112 - renames: FunctionDef : OffsetRange[5266,6138>
437.113 - error [free][read][node=Name]
437.114 - head [bound][data][read][node=Name]
437.115 - makedirs [free][read][called][node=Name]
437.116 - new [bound][param][data][read][node=Name]
437.117 - old [bound][param][data][read][node=Name]
437.118 - path [free][read][node=Name]
437.119 - removedirs [free][read][called][node=Name]
437.120 - rename [free][read][called][node=Name]
437.121 - tail [bound][data][read][node=Name]
437.122 -
437.123 - =============================================
437.124 - walk: FunctionDef : OffsetRange[6193,9684>
437.125 - None [free][read][node=Name]
437.126 - dirs [bound][data][read][node=Name]
437.127 - err [bound][data][read][node=Name]
437.128 - error [free][read][node=Name]
437.129 - isdir [bound][imported][data][read][called][node=ImportFrom]
437.130 - islink [bound][imported][data][read][called][node=ImportFrom]
437.131 - join [bound][imported][data][read][called][node=ImportFrom]
437.132 - listdir [free][read][called][node=Name]
437.133 - name [bound][data][read][node=Name]
437.134 - names [bound][data][read][node=Name]
437.135 - nondirs [bound][data][read][node=Name]
437.136 - onerror [bound][param][data][read][called][node=Name]
437.137 - path [bound][data][read][node=Name]
437.138 - top [bound][param][data][read][node=Name]
437.139 - topdown [bound][param][data][read][node=Name]
437.140 - walk [free][read][called][node=Name]
437.141 - x [bound][data][read][node=Name]
437.142 -
437.143 - =============================================
437.144 - execl: FunctionDef : OffsetRange[9801,9971>
437.145 - args [bound][param][data][read][node=arguments]
437.146 - execv [free][read][called][node=Name]
437.147 - file [bound][param][data][read][node=Name]
437.148 -
437.149 - =============================================
437.150 - execle: FunctionDef : OffsetRange[9971,10198>
437.151 - args [bound][param][data][read][node=arguments]
437.152 - env [bound][data][read][node=Name]
437.153 - execve [free][read][called][node=Name]
437.154 - file [bound][param][data][read][node=Name]
437.155 -
437.156 - =============================================
437.157 - execlp: FunctionDef : OffsetRange[10198,10407>
437.158 - args [bound][param][data][read][node=arguments]
437.159 - execvp [free][read][called][node=Name]
437.160 - file [bound][param][data][read][node=Name]
437.161 -
437.162 - =============================================
437.163 - execlpe: FunctionDef : OffsetRange[10407,10677>
437.164 - args [bound][param][data][read][node=arguments]
437.165 - env [bound][data][read][node=Name]
437.166 - execvpe [free][read][called][node=Name]
437.167 - file [bound][param][data][read][node=Name]
437.168 -
437.169 - =============================================
437.170 - execvp: FunctionDef : OffsetRange[10677,10929>
437.171 - _execvpe [free][read][called][node=Name]
437.172 - args [bound][param][data][read][node=Name]
437.173 - file [bound][param][data][read][node=Name]
437.174 -
437.175 - =============================================
437.176 - execvpe: FunctionDef : OffsetRange[10929,11224>
437.177 - _execvpe [free][read][called][node=Name]
437.178 - args [bound][param][data][read][node=Name]
437.179 - env [bound][param][data][read][node=Name]
437.180 - file [bound][param][data][read][node=Name]
437.181 -
437.182 - =============================================
437.183 - _execvpe: FunctionDef : OffsetRange[11298,12255>
437.184 - ENOENT [bound][imported][data][read][node=ImportFrom]
437.185 - ENOTDIR [bound][imported][data][read][node=ImportFrom]
437.186 - None [free][read][node=Name]
437.187 - PATH [bound][data][read][node=Name]
437.188 - argrest [bound][data][read][node=Name]
437.189 - args [bound][param][data][read][node=Name]
437.190 - defpath [free][read][node=Name]
437.191 - dir [bound][data][read][node=Name]
437.192 - e [bound][data][read][node=Name]
437.193 - env [bound][param][data][read][node=Name]
437.194 - environ [free][read][node=Name]
437.195 - envpath [bound][data][read][node=Name]
437.196 - error [free][read][node=Name]
437.197 - execv [free][read][node=Name]
437.198 - execve [free][read][node=Name]
437.199 - file [bound][param][data][read][node=Name]
437.200 - fullname [bound][data][read][node=Name]
437.201 - func [bound][data][read][called][node=Name]
437.202 - head [bound][data][read][node=Name]
437.203 - path [free][read][node=Name]
437.204 - pathsep [free][read][node=Name]
437.205 - saved_exc [bound][data][read][node=Name]
437.206 - saved_tb [bound][data][read][node=Name]
437.207 - sys [free][read][node=Name]
437.208 - tail [bound][data][unused][node=Name]
437.209 - tb [bound][data][read][node=Name]
437.210 -
437.211 - =============================================
437.212 - unsetenv: FunctionDef : OffsetRange[12512,12563>
437.213 - key [bound][param][data][read][node=Name]
437.214 - putenv [free][read][called][node=Name]
437.215 -
437.216 - =============================================
437.217 - class _Environ: ClassDef : OffsetRange[12819,14567>
437.218 - NameError [free][read][node=Name]
437.219 - None [free][read][node=Name]
437.220 - __contains__ [bound][function][def][node=FunctionDef]
437.221 - __delitem__ [bound][function][def][node=FunctionDef]
437.222 - __getitem__ [bound][function][def][node=FunctionDef]
437.223 - __init__ [bound][function][def][node=FunctionDef]
437.224 - __setitem__ [bound][function][def][node=FunctionDef]
437.225 - copy [bound][function][def][node=FunctionDef]
437.226 - get [bound][function][def][node=FunctionDef]
437.227 - has_key [bound][function][def][node=FunctionDef]
437.228 - unsetenv [free][read][node=Name]
437.229 - update [bound][function][def][node=FunctionDef]
437.230 -
437.231 - =============================================
437.232 - __init__: FunctionDef : OffsetRange[12874,13081>
437.233 - UserDict [free][read][node=Name]
437.234 - data [bound][data][read][node=Name]
437.235 - environ [bound][param][data][read][node=Name]
437.236 - k [bound][data][read][node=Name]
437.237 - self [bound][param][data][read][node=Name]
437.238 - v [bound][data][read][node=Name]
437.239 - ------ Attributes ---------------------------------------
437.240 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
437.241 -
437.242 - =============================================
437.243 - __setitem__: FunctionDef : OffsetRange[13082,13207>
437.244 - item [bound][param][data][read][node=Name]
437.245 - key [bound][param][data][read][node=Name]
437.246 - putenv [free][read][called][node=Name]
437.247 - self [bound][param][data][read][node=Name]
437.248 - ------ Attributes ---------------------------------------
437.249 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
437.250 -
437.251 - =============================================
437.252 - __getitem__: FunctionDef : OffsetRange[13208,13293>
437.253 - key [bound][param][data][read][node=Name]
437.254 - self [bound][param][data][read][node=Name]
437.255 - ------ Attributes ---------------------------------------
437.256 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
437.257 -
437.258 - =============================================
437.259 - __delitem__: FunctionDef : OffsetRange[13370,13456>
437.260 - key [bound][param][data][read][node=Name]
437.261 - self [bound][param][data][read][node=Name]
437.262 - ------ Attributes ---------------------------------------
437.263 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
437.264 -
437.265 - =============================================
437.266 - __delitem__: FunctionDef : OffsetRange[13479,13599>
437.267 - key [bound][param][data][read][node=Name]
437.268 - self [bound][param][data][read][node=Name]
437.269 - unsetenv [free][read][called][node=Name]
437.270 - ------ Attributes ---------------------------------------
437.271 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
437.272 -
437.273 - =============================================
437.274 - has_key: FunctionDef : OffsetRange[13600,13683>
437.275 - key [bound][param][data][read][node=Name]
437.276 - self [bound][param][data][read][node=Name]
437.277 - ------ Attributes ---------------------------------------
437.278 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
437.279 -
437.280 - =============================================
437.281 - __contains__: FunctionDef : OffsetRange[13684,13772>
437.282 - key [bound][param][data][read][node=Name]
437.283 - self [bound][param][data][read][node=Name]
437.284 - ------ Attributes ---------------------------------------
437.285 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
437.286 -
437.287 - =============================================
437.288 - get: FunctionDef : OffsetRange[13773,13877>
437.289 - failobj [bound][param][data][read][node=Name]
437.290 - key [bound][param][data][read][node=Name]
437.291 - self [bound][param][data][read][node=Name]
437.292 - ------ Attributes ---------------------------------------
437.293 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
437.294 -
437.295 - =============================================
437.296 - update: FunctionDef : OffsetRange[13878,14512>
437.297 - AttributeError [free][read][node=Name]
437.298 - dict [bound][param][data][read][node=Name]
437.299 - k [bound][data][read][node=Name]
437.300 - keys [bound][data][read][node=Name]
437.301 - kwargs [bound][param][data][read][node=arguments]
437.302 - self [bound][param][data][read][node=Name]
437.303 - v [bound][data][read][node=Name]
437.304 - ------ Attributes ---------------------------------------
437.305 - update : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
437.306 -
437.307 - =============================================
437.308 - copy: FunctionDef : OffsetRange[14513,14567>
437.309 - dict [free][read][called][node=Name]
437.310 - self [bound][param][data][read][node=Name]
437.311 -
437.312 - =============================================
437.313 - class _Environ: ClassDef : OffsetRange[14623,15841>
437.314 - NameError [free][read][node=Name]
437.315 - None [free][read][node=Name]
437.316 - __delitem__ [bound][function][def][node=FunctionDef]
437.317 - __init__ [bound][function][def][node=FunctionDef]
437.318 - __setitem__ [bound][function][def][node=FunctionDef]
437.319 - copy [bound][function][def][node=FunctionDef]
437.320 - unsetenv [free][read][node=Name]
437.321 - update [bound][function][def][node=FunctionDef]
437.322 - ------ Attributes ---------------------------------------
437.323 - data : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
437.324 -
437.325 - =============================================
437.326 - __init__: FunctionDef : OffsetRange[14678,14803>
437.327 - UserDict [free][read][node=Name]
437.328 - environ [bound][param][data][read][node=Name]
437.329 - self [bound][param][data][read][node=Name]
437.330 -
437.331 - =============================================
437.332 - __setitem__: FunctionDef : OffsetRange[14804,14921>
437.333 - item [bound][param][data][read][node=Name]
437.334 - key [bound][param][data][read][node=Name]
437.335 - putenv [free][read][called][node=Name]
437.336 - self [bound][param][data][read][node=Name]
437.337 - ------ Attributes ---------------------------------------
437.338 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
437.339 -
437.340 - =============================================
437.341 - update: FunctionDef : OffsetRange[14922,15557>
437.342 - AttributeError [free][read][node=Name]
437.343 - dict [bound][param][data][read][node=Name]
437.344 - k [bound][data][read][node=Name]
437.345 - keys [bound][data][read][node=Name]
437.346 - kwargs [bound][param][data][read][node=arguments]
437.347 - self [bound][param][data][read][node=Name]
437.348 - v [bound][data][read][node=Name]
437.349 - ------ Attributes ---------------------------------------
437.350 - update : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
437.351 -
437.352 - =============================================
437.353 - __delitem__: FunctionDef : OffsetRange[15673,15785>
437.354 - key [bound][param][data][read][node=Name]
437.355 - self [bound][param][data][read][node=Name]
437.356 - unsetenv [free][read][called][node=Name]
437.357 - ------ Attributes ---------------------------------------
437.358 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
437.359 -
437.360 - =============================================
437.361 - copy: FunctionDef : OffsetRange[15786,15841>
437.362 - dict [free][read][called][node=Name]
437.363 - self [bound][param][data][read][node=Name]
437.364 -
437.365 - =============================================
437.366 - getenv: FunctionDef : OffsetRange[15871,16078>
437.367 - default [bound][param][data][read][node=Name]
437.368 - environ [free][read][node=Name]
437.369 - key [bound][param][data][read][node=Name]
437.370 -
437.371 - =============================================
437.372 - _exists: FunctionDef : OffsetRange[16104,16258>
437.373 - False [free][read][node=Name]
437.374 - NameError [free][read][node=Name]
437.375 - True [free][read][node=Name]
437.376 - eval [free][read][called][node=Name]
437.377 - name [bound][param][data][read][node=Name]
437.378 -
437.379 - =============================================
437.380 - _spawnvef: FunctionDef : OffsetRange[16529,17414>
437.381 - None [free][read][node=Name]
437.382 - P_NOWAIT [free][read][node=Name]
437.383 - WEXITSTATUS [free][read][called][node=Name]
437.384 - WIFEXITED [free][read][called][node=Name]
437.385 - WIFSIGNALED [free][read][called][node=Name]
437.386 - WIFSTOPPED [free][read][called][node=Name]
437.387 - WTERMSIG [free][read][called][node=Name]
437.388 - _exit [free][read][called][node=Name]
437.389 - args [bound][param][data][read][node=Name]
437.390 - env [bound][param][data][read][node=Name]
437.391 - error [free][read][node=Name]
437.392 - file [bound][param][data][read][node=Name]
437.393 - fork [free][read][called][node=Name]
437.394 - func [bound][param][data][read][called][node=Name]
437.395 - mode [bound][param][data][read][node=Name]
437.396 - pid [bound][data][read][node=Name]
437.397 - sts [bound][data][read][node=Name]
437.398 - waitpid [free][read][called][node=Name]
437.399 - wpid [bound][data][unused][node=Name]
437.400 -
437.401 - =============================================
437.402 - spawnv: FunctionDef : OffsetRange[17415,17797>
437.403 - None [free][read][node=Name]
437.404 - _spawnvef [free][read][called][node=Name]
437.405 - args [bound][param][data][read][node=Name]
437.406 - execv [free][read][node=Name]
437.407 - file [bound][param][data][read][node=Name]
437.408 - mode [bound][param][data][read][node=Name]
437.409 -
437.410 - =============================================
437.411 - spawnve: FunctionDef : OffsetRange[17798,18283>
437.412 - _spawnvef [free][read][called][node=Name]
437.413 - args [bound][param][data][read][node=Name]
437.414 - env [bound][param][data][read][node=Name]
437.415 - execve [free][read][node=Name]
437.416 - file [bound][param][data][read][node=Name]
437.417 - mode [bound][param][data][read][node=Name]
437.418 -
437.419 - =============================================
437.420 - spawnvp: FunctionDef : OffsetRange[18284,18703>
437.421 - None [free][read][node=Name]
437.422 - _spawnvef [free][read][called][node=Name]
437.423 - args [bound][param][data][read][node=Name]
437.424 - execvp [free][read][node=Name]
437.425 - file [bound][param][data][read][node=Name]
437.426 - mode [bound][param][data][read][node=Name]
437.427 -
437.428 - =============================================
437.429 - spawnvpe: FunctionDef : OffsetRange[18704,19162>
437.430 - _spawnvef [free][read][called][node=Name]
437.431 - args [bound][param][data][read][node=Name]
437.432 - env [bound][param][data][read][node=Name]
437.433 - execvpe [free][read][node=Name]
437.434 - file [bound][param][data][read][node=Name]
437.435 - mode [bound][param][data][read][node=Name]
437.436 -
437.437 - =============================================
437.438 - spawnl: FunctionDef : OffsetRange[19289,19657>
437.439 - args [bound][param][data][read][node=arguments]
437.440 - file [bound][param][data][read][node=Name]
437.441 - mode [bound][param][data][read][node=Name]
437.442 - spawnv [free][read][called][node=Name]
437.443 -
437.444 - =============================================
437.445 - spawnle: FunctionDef : OffsetRange[19658,20098>
437.446 - args [bound][param][data][read][node=arguments]
437.447 - env [bound][data][read][node=Name]
437.448 - file [bound][param][data][read][node=Name]
437.449 - mode [bound][param][data][read][node=Name]
437.450 - spawnve [free][read][called][node=Name]
437.451 -
437.452 - =============================================
437.453 - spawnlp: FunctionDef : OffsetRange[20289,20724>
437.454 - args [bound][param][data][read][node=arguments]
437.455 - file [bound][param][data][read][node=Name]
437.456 - mode [bound][param][data][read][node=Name]
437.457 - spawnvp [free][read][called][node=Name]
437.458 -
437.459 - =============================================
437.460 - spawnlpe: FunctionDef : OffsetRange[20725,21202>
437.461 - args [bound][param][data][read][node=arguments]
437.462 - env [bound][data][read][node=Name]
437.463 - file [bound][param][data][read][node=Name]
437.464 - mode [bound][param][data][read][node=Name]
437.465 - spawnvpe [free][read][called][node=Name]
437.466 -
437.467 - =============================================
437.468 - popen2: FunctionDef : OffsetRange[21359,22002>
437.469 - bufsize [bound][param][data][read][node=Name]
437.470 - cmd [bound][param][data][read][node=Name]
437.471 - mode [bound][param][data][unused][node=Name]
437.472 - popen2 [bound][imported][data][read][node=Import]
437.473 - stdin [bound][data][read][node=Name]
437.474 - stdout [bound][data][read][node=Name]
437.475 -
437.476 - =============================================
437.477 - popen3: FunctionDef : OffsetRange[22067,22740>
437.478 - bufsize [bound][param][data][read][node=Name]
437.479 - cmd [bound][param][data][read][node=Name]
437.480 - mode [bound][param][data][unused][node=Name]
437.481 - popen2 [bound][imported][data][read][node=Import]
437.482 - stderr [bound][data][read][node=Name]
437.483 - stdin [bound][data][read][node=Name]
437.484 - stdout [bound][data][read][node=Name]
437.485 -
437.486 - =============================================
437.487 - popen4: FunctionDef : OffsetRange[22805,23455>
437.488 - bufsize [bound][param][data][read][node=Name]
437.489 - cmd [bound][param][data][read][node=Name]
437.490 - mode [bound][param][data][unused][node=Name]
437.491 - popen2 [bound][imported][data][read][node=Import]
437.492 - stdin [bound][data][read][node=Name]
437.493 - stdout [bound][data][read][node=Name]
437.494 -
437.495 - =============================================
437.496 - _make_stat_result: FunctionDef : OffsetRange[23512,23581>
437.497 - dict [bound][param][data][read][node=Name]
437.498 - stat_result [free][read][called][node=Name]
437.499 - tup [bound][param][data][read][node=Name]
437.500 -
437.501 - =============================================
437.502 - _pickle_stat_result: FunctionDef : OffsetRange[23581,23683>
437.503 - _make_stat_result [free][read][node=Name]
437.504 - args [bound][data][read][node=Name]
437.505 - sr [bound][param][data][read][node=Name]
437.506 - type [bound][data][unused][node=Name]
437.507 -
437.508 - =============================================
437.509 - _make_statvfs_result: FunctionDef : OffsetRange[23818,23893>
437.510 - dict [bound][param][data][read][node=Name]
437.511 - statvfs_result [free][read][called][node=Name]
437.512 - tup [bound][param][data][read][node=Name]
437.513 -
437.514 - =============================================
437.515 - _pickle_statvfs_result: FunctionDef : OffsetRange[23893,24001>
437.516 - _make_statvfs_result [free][read][node=Name]
437.517 - args [bound][data][read][node=Name]
437.518 - sr [bound][param][data][read][node=Name]
437.519 - type [bound][data][unused][node=Name]
437.520 -
437.521 - =============================================
437.522 - urandom: FunctionDef : OffsetRange[24200,24666>
437.523 - IOError [free][read][node=Name]
437.524 - NotImplementedError [free][read][called][node=Name]
437.525 - OSError [free][read][node=Name]
437.526 - O_RDONLY [free][read][node=Name]
437.527 - _urandomfd [bound][private][data][read][node=Name]
437.528 - bytes [bound][data][read][node=Name]
437.529 - close [free][read][called][node=Name]
437.530 - len [free][read][called][node=Name]
437.531 - n [bound][param][data][read][node=Name]
437.532 - open [free][read][called][node=Name]
437.533 - read [free][read][called][node=Name]
437.534 -
438.1 --- a/python.editor/test/unit/data/testfiles/overrides.py Sun Jan 04 13:11:53 2015 -0600
438.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
438.3 @@ -1,23 +0,0 @@
438.4 -class Ancestor:
438.5 - def overridden_method1(self, a, b):
438.6 - pass
438.7 - def overridden_method2(self, c, d):
438.8 - pass
438.9 -
438.10 -class Middle(Ancestor):
438.11 - def overridden_method1(self, a, b):
438.12 - pass
438.13 -
438.14 -class Middle2(Ancestor):
438.15 - def overridden_method2(self, a, b):
438.16 - pass
438.17 -
438.18 - def overridden_method1(self, a, b):
438.19 - pass
438.20 -
438.21 -class Child(Middle, Middle2):
438.22 - def overridden_method1(self, a, b): # Final
438.23 - pass
438.24 - def overridden_method2(self, c, d): # Final
438.25 - pass
438.26 -
439.1 --- a/python.editor/test/unit/data/testfiles/overrides.py.testDeclaration8.declarations Sun Jan 04 13:11:53 2015 -0600
439.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
439.3 @@ -1,24 +0,0 @@
439.4 -overrides.py:288:
439.5 - def |overridden_method1(self, a, b):
439.6 - pass
439.7 -
439.8 -
439.9 -Alternative Locations:
439.10 -overridden_method1(self, a, b) in Middle in overrides.py
439.11 -overrides.py:151:class Middle(Ancestor):
439.12 - |def overridden_method1(self, a, b):
439.13 - pass
439.14 -
439.15 -
439.16 -overridden_method1(self, a, b) in Ancestor in overrides.py
439.17 -overrides.py:20:class Ancestor:
439.18 - |def overridden_method1(self, a, b):
439.19 - pass
439.20 -
439.21 -
439.22 -overridden_method1(self, a, b) in Middle2 in overrides.py
439.23 -overrides.py:284:
439.24 - |def overridden_method1(self, a, b):
439.25 - pass
439.26 -
439.27 -
440.1 --- a/python.editor/test/unit/data/testfiles/overrides.py.testDeclaration9.declarations Sun Jan 04 13:11:53 2015 -0600
440.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
440.3 @@ -1,18 +0,0 @@
440.4 -overrides.py:234:class Middle2(Ancestor):
440.5 - def |overridden_method2(self, a, b):
440.6 - pass
440.7 -
440.8 -
440.9 -Alternative Locations:
440.10 -overridden_method2(self, a, b) in Middle2 in overrides.py
440.11 -overrides.py:230:class Middle2(Ancestor):
440.12 - |def overridden_method2(self, a, b):
440.13 - pass
440.14 -
440.15 -
440.16 -overridden_method2(self, c, d) in Ancestor in overrides.py
440.17 -overrides.py:73: pass
440.18 - |def overridden_method2(self, c, d):
440.19 - pass
440.20 -
440.21 -
441.1 --- a/python.editor/test/unit/data/testfiles/package/subpackage1/__init__.py Sun Jan 04 13:11:53 2015 -0600
441.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
441.3 @@ -1,9 +0,0 @@
441.4 -from .moduleY import spam
441.5 -from .moduleY import spam as ham
441.6 -from . import moduleY
441.7 -from ..subpackage1 import moduleY
441.8 -from ..subpackage2.moduleZ import eggs
441.9 -from ..moduleA import foo
441.10 -from ...package import bar
441.11 -from ...sys import path
441.12 -
442.1 --- a/python.editor/test/unit/data/testfiles/package/subpackage1/__init__.py.testFixInit.imported Sun Jan 04 13:11:53 2015 -0600
442.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
442.3 @@ -1,9 +0,0 @@
442.4 -from . import moduleY
442.5 -from ...package import bar
442.6 -from ...sys import path
442.7 -from ..moduleA import foo
442.8 -from ..subpackage1 import moduleY
442.9 -from ..subpackage2.moduleZ import eggs
442.10 -from .moduleY import spam as ham
442.11 -from .moduleY import spam
442.12 -
443.1 --- a/python.editor/test/unit/data/testfiles/package/subpackage1/moduleX.py Sun Jan 04 13:11:53 2015 -0600
443.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
443.3 @@ -1,9 +0,0 @@
443.4 -from .moduleY import spam
443.5 -from .moduleY import spam as ham
443.6 -from . import moduleY
443.7 -from ..subpackage1 import moduleY
443.8 -from ..subpackage2.moduleZ import eggs
443.9 -from ..moduleA import foo
443.10 -from ...package import bar
443.11 -from ...sys import path
443.12 -
444.1 --- a/python.editor/test/unit/data/testfiles/package/subpackage1/moduleX.py.testFix4.fixed Sun Jan 04 13:11:53 2015 -0600
444.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
444.3 @@ -1,9 +0,0 @@
444.4 -from .moduleY import spam
444.5 -from .moduleY import spam as ham
444.6 -from package.subpackage1 import moduleY
444.7 -from ..subpackage1 import moduleY
444.8 -from ..subpackage2.moduleZ import eggs
444.9 -from ..moduleA import foo
444.10 -from ...package import bar
444.11 -from ...sys import path
444.12 -
445.1 --- a/python.editor/test/unit/data/testfiles/package/subpackage1/moduleX.py.testFix5.fixed Sun Jan 04 13:11:53 2015 -0600
445.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
445.3 @@ -1,9 +0,0 @@
445.4 -from package.subpackage1.moduleY import spam
445.5 -from .moduleY import spam as ham
445.6 -from . import moduleY
445.7 -from ..subpackage1 import moduleY
445.8 -from ..subpackage2.moduleZ import eggs
445.9 -from ..moduleA import foo
445.10 -from ...package import bar
445.11 -from ...sys import path
445.12 -
446.1 --- a/python.editor/test/unit/data/testfiles/package/subpackage1/moduleX.py.testHint2.hints Sun Jan 04 13:11:53 2015 -0600
446.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
446.3 @@ -1,32 +0,0 @@
446.4 -from .moduleY import spam
446.5 --------------------------
446.6 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
446.7 -FIX:Replace with absolute import
446.8 -from .moduleY import spam as ham
446.9 ---------------------------------
446.10 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
446.11 -FIX:Replace with absolute import
446.12 -from . import moduleY
446.13 ----------------------
446.14 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
446.15 -FIX:Replace with absolute import
446.16 -from ..subpackage1 import moduleY
446.17 ----------------------------------
446.18 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
446.19 -FIX:Replace with absolute import
446.20 -from ..subpackage2.moduleZ import eggs
446.21 ---------------------------------------
446.22 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
446.23 -FIX:Replace with absolute import
446.24 -from ..moduleA import foo
446.25 --------------------------
446.26 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
446.27 -FIX:Replace with absolute import
446.28 -from ...package import bar
446.29 ---------------------------
446.30 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
446.31 -FIX:Replace with absolute import
446.32 -from ...sys import path
446.33 ------------------------
446.34 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
446.35 -FIX:Replace with absolute import
447.1 --- a/python.editor/test/unit/data/testfiles/pickle.py Sun Jan 04 13:11:53 2015 -0600
447.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
447.3 @@ -1,1383 +0,0 @@
447.4 -"""Create portable serialized representations of Python objects.
447.5 -
447.6 -See module cPickle for a (much) faster implementation.
447.7 -See module copy_reg for a mechanism for registering custom picklers.
447.8 -See module pickletools source for extensive comments.
447.9 -
447.10 -Classes:
447.11 -
447.12 - Pickler
447.13 - Unpickler
447.14 -
447.15 -Functions:
447.16 -
447.17 - dump(object, file)
447.18 - dumps(object) -> string
447.19 - load(file) -> object
447.20 - loads(string) -> object
447.21 -
447.22 -Misc variables:
447.23 -
447.24 - __version__
447.25 - format_version
447.26 - compatible_formats
447.27 -
447.28 -"""
447.29 -
447.30 -__version__ = "$Revision: 38432 $" # Code version
447.31 -
447.32 -from types import *
447.33 -from copy_reg import dispatch_table
447.34 -from copy_reg import _extension_registry, _inverted_registry, _extension_cache
447.35 -import marshal
447.36 -import sys
447.37 -import struct
447.38 -import re
447.39 -
447.40 -__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
447.41 - "Unpickler", "dump", "dumps", "load", "loads"]
447.42 -
447.43 -# These are purely informational; no code uses these.
447.44 -format_version = "2.0" # File format version we write
447.45 -compatible_formats = ["1.0", # Original protocol 0
447.46 - "1.1", # Protocol 0 with INST added
447.47 - "1.2", # Original protocol 1
447.48 - "1.3", # Protocol 1 with BINFLOAT added
447.49 - "2.0", # Protocol 2
447.50 - ] # Old format versions we can read
447.51 -
447.52 -# Keep in synch with cPickle. This is the highest protocol number we
447.53 -# know how to read.
447.54 -HIGHEST_PROTOCOL = 2
447.55 -
447.56 -# Why use struct.pack() for pickling but marshal.loads() for
447.57 -# unpickling? struct.pack() is 40% faster than marshal.dumps(), but
447.58 -# marshal.loads() is twice as fast as struct.unpack()!
447.59 -mloads = marshal.loads
447.60 -
447.61 -class PickleError(Exception):
447.62 - """A common base class for the other pickling exceptions."""
447.63 - pass
447.64 -
447.65 -class PicklingError(PickleError):
447.66 - """This exception is raised when an unpicklable object is passed to the
447.67 - dump() method.
447.68 -
447.69 - """
447.70 - pass
447.71 -
447.72 -class UnpicklingError(PickleError):
447.73 - """This exception is raised when there is a problem unpickling an object,
447.74 - such as a security violation.
447.75 -
447.76 - Note that other exceptions may also be raised during unpickling, including
447.77 - (but not necessarily limited to) AttributeError, EOFError, ImportError,
447.78 - and IndexError.
447.79 -
447.80 - """
447.81 - pass
447.82 -
447.83 -# An instance of _Stop is raised by Unpickler.load_stop() in response to
447.84 -# the STOP opcode, passing the object that is the result of unpickling.
447.85 -class _Stop(Exception):
447.86 - def __init__(self, value):
447.87 - self.value = value
447.88 -
447.89 -# Jython has PyStringMap; it's a dict subclass with string keys
447.90 -try:
447.91 - from org.python.core import PyStringMap
447.92 -except ImportError:
447.93 - PyStringMap = None
447.94 -
447.95 -# UnicodeType may or may not be exported (normally imported from types)
447.96 -try:
447.97 - UnicodeType
447.98 -except NameError:
447.99 - UnicodeType = None
447.100 -
447.101 -# Pickle opcodes. See pickletools.py for extensive docs. The listing
447.102 -# here is in kind-of alphabetical order of 1-character pickle code.
447.103 -# pickletools groups them by purpose.
447.104 -
447.105 -MARK = '(' # push special markobject on stack
447.106 -STOP = '.' # every pickle ends with STOP
447.107 -POP = '0' # discard topmost stack item
447.108 -POP_MARK = '1' # discard stack top through topmost markobject
447.109 -DUP = '2' # duplicate top stack item
447.110 -FLOAT = 'F' # push float object; decimal string argument
447.111 -INT = 'I' # push integer or bool; decimal string argument
447.112 -BININT = 'J' # push four-byte signed int
447.113 -BININT1 = 'K' # push 1-byte unsigned int
447.114 -LONG = 'L' # push long; decimal string argument
447.115 -BININT2 = 'M' # push 2-byte unsigned int
447.116 -NONE = 'N' # push None
447.117 -PERSID = 'P' # push persistent object; id is taken from string arg
447.118 -BINPERSID = 'Q' # " " " ; " " " " stack
447.119 -REDUCE = 'R' # apply callable to argtuple, both on stack
447.120 -STRING = 'S' # push string; NL-terminated string argument
447.121 -BINSTRING = 'T' # push string; counted binary string argument
447.122 -SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
447.123 -UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
447.124 -BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
447.125 -APPEND = 'a' # append stack top to list below it
447.126 -BUILD = 'b' # call __setstate__ or __dict__.update()
447.127 -GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
447.128 -DICT = 'd' # build a dict from stack items
447.129 -EMPTY_DICT = '}' # push empty dict
447.130 -APPENDS = 'e' # extend list on stack by topmost stack slice
447.131 -GET = 'g' # push item from memo on stack; index is string arg
447.132 -BINGET = 'h' # " " " " " " ; " " 1-byte arg
447.133 -INST = 'i' # build & push class instance
447.134 -LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
447.135 -LIST = 'l' # build list from topmost stack items
447.136 -EMPTY_LIST = ']' # push empty list
447.137 -OBJ = 'o' # build & push class instance
447.138 -PUT = 'p' # store stack top in memo; index is string arg
447.139 -BINPUT = 'q' # " " " " " ; " " 1-byte arg
447.140 -LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
447.141 -SETITEM = 's' # add key+value pair to dict
447.142 -TUPLE = 't' # build tuple from topmost stack items
447.143 -EMPTY_TUPLE = ')' # push empty tuple
447.144 -SETITEMS = 'u' # modify dict by adding topmost key+value pairs
447.145 -BINFLOAT = 'G' # push float; arg is 8-byte float encoding
447.146 -
447.147 -TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
447.148 -FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
447.149 -
447.150 -# Protocol 2
447.151 -
447.152 -PROTO = '\x80' # identify pickle protocol
447.153 -NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple
447.154 -EXT1 = '\x82' # push object from extension registry; 1-byte index
447.155 -EXT2 = '\x83' # ditto, but 2-byte index
447.156 -EXT4 = '\x84' # ditto, but 4-byte index
447.157 -TUPLE1 = '\x85' # build 1-tuple from stack top
447.158 -TUPLE2 = '\x86' # build 2-tuple from two topmost stack items
447.159 -TUPLE3 = '\x87' # build 3-tuple from three topmost stack items
447.160 -NEWTRUE = '\x88' # push True
447.161 -NEWFALSE = '\x89' # push False
447.162 -LONG1 = '\x8a' # push long from < 256 bytes
447.163 -LONG4 = '\x8b' # push really big long
447.164 -
447.165 -_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
447.166 -
447.167 -
447.168 -__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
447.169 -del x
447.170 -
447.171 -
447.172 -# Pickling machinery
447.173 -
447.174 -class Pickler:
447.175 -
447.176 - def __init__(self, file, protocol=None):
447.177 - """This takes a file-like object for writing a pickle data stream.
447.178 -
447.179 - The optional protocol argument tells the pickler to use the
447.180 - given protocol; supported protocols are 0, 1, 2. The default
447.181 - protocol is 0, to be backwards compatible. (Protocol 0 is the
447.182 - only protocol that can be written to a file opened in text
447.183 - mode and read back successfully. When using a protocol higher
447.184 - than 0, make sure the file is opened in binary mode, both when
447.185 - pickling and unpickling.)
447.186 -
447.187 - Protocol 1 is more efficient than protocol 0; protocol 2 is
447.188 - more efficient than protocol 1.
447.189 -
447.190 - Specifying a negative protocol version selects the highest
447.191 - protocol version supported. The higher the protocol used, the
447.192 - more recent the version of Python needed to read the pickle
447.193 - produced.
447.194 -
447.195 - The file parameter must have a write() method that accepts a single
447.196 - string argument. It can thus be an open file object, a StringIO
447.197 - object, or any other custom object that meets this interface.
447.198 -
447.199 - """
447.200 - if protocol is None:
447.201 - protocol = 0
447.202 - if protocol < 0:
447.203 - protocol = HIGHEST_PROTOCOL
447.204 - elif not 0 <= protocol <= HIGHEST_PROTOCOL:
447.205 - raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
447.206 - self.write = file.write
447.207 - self.memo = {}
447.208 - self.proto = int(protocol)
447.209 - self.bin = protocol >= 1
447.210 - self.fast = 0
447.211 -
447.212 - def clear_memo(self):
447.213 - """Clears the pickler's "memo".
447.214 -
447.215 - The memo is the data structure that remembers which objects the
447.216 - pickler has already seen, so that shared or recursive objects are
447.217 - pickled by reference and not by value. This method is useful when
447.218 - re-using picklers.
447.219 -
447.220 - """
447.221 - self.memo.clear()
447.222 -
447.223 - def dump(self, obj):
447.224 - """Write a pickled representation of obj to the open file."""
447.225 - if self.proto >= 2:
447.226 - self.write(PROTO + chr(self.proto))
447.227 - self.save(obj)
447.228 - self.write(STOP)
447.229 -
447.230 - def memoize(self, obj):
447.231 - """Store an object in the memo."""
447.232 -
447.233 - # The Pickler memo is a dictionary mapping object ids to 2-tuples
447.234 - # that contain the Unpickler memo key and the object being memoized.
447.235 - # The memo key is written to the pickle and will become
447.236 - # the key in the Unpickler's memo. The object is stored in the
447.237 - # Pickler memo so that transient objects are kept alive during
447.238 - # pickling.
447.239 -
447.240 - # The use of the Unpickler memo length as the memo key is just a
447.241 - # convention. The only requirement is that the memo values be unique.
447.242 - # But there appears no advantage to any other scheme, and this
447.243 - # scheme allows the Unpickler memo to be implemented as a plain (but
447.244 - # growable) array, indexed by memo key.
447.245 - if self.fast:
447.246 - return
447.247 - assert id(obj) not in self.memo
447.248 - memo_len = len(self.memo)
447.249 - self.write(self.put(memo_len))
447.250 - self.memo[id(obj)] = memo_len, obj
447.251 -
447.252 - # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
447.253 - def put(self, i, pack=struct.pack):
447.254 - if self.bin:
447.255 - if i < 256:
447.256 - return BINPUT + chr(i)
447.257 - else:
447.258 - return LONG_BINPUT + pack("<i", i)
447.259 -
447.260 - return PUT + repr(i) + '\n'
447.261 -
447.262 - # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
447.263 - def get(self, i, pack=struct.pack):
447.264 - if self.bin:
447.265 - if i < 256:
447.266 - return BINGET + chr(i)
447.267 - else:
447.268 - return LONG_BINGET + pack("<i", i)
447.269 -
447.270 - return GET + repr(i) + '\n'
447.271 -
447.272 - def save(self, obj):
447.273 - # Check for persistent id (defined by a subclass)
447.274 - pid = self.persistent_id(obj)
447.275 - if pid:
447.276 - self.save_pers(pid)
447.277 - return
447.278 -
447.279 - # Check the memo
447.280 - x = self.memo.get(id(obj))
447.281 - if x:
447.282 - self.write(self.get(x[0]))
447.283 - return
447.284 -
447.285 - # Check the type dispatch table
447.286 - t = type(obj)
447.287 - f = self.dispatch.get(t)
447.288 - if f:
447.289 - f(self, obj) # Call unbound method with explicit self
447.290 - return
447.291 -
447.292 - # Check for a class with a custom metaclass; treat as regular class
447.293 - try:
447.294 - issc = issubclass(t, TypeType)
447.295 - except TypeError: # t is not a class (old Boost; see SF #502085)
447.296 - issc = 0
447.297 - if issc:
447.298 - self.save_global(obj)
447.299 - return
447.300 -
447.301 - # Check copy_reg.dispatch_table
447.302 - reduce = dispatch_table.get(t)
447.303 - if reduce:
447.304 - rv = reduce(obj)
447.305 - else:
447.306 - # Check for a __reduce_ex__ method, fall back to __reduce__
447.307 - reduce = getattr(obj, "__reduce_ex__", None)
447.308 - if reduce:
447.309 - rv = reduce(self.proto)
447.310 - else:
447.311 - reduce = getattr(obj, "__reduce__", None)
447.312 - if reduce:
447.313 - rv = reduce()
447.314 - else:
447.315 - raise PicklingError("Can't pickle %r object: %r" %
447.316 - (t.__name__, obj))
447.317 -
447.318 - # Check for string returned by reduce(), meaning "save as global"
447.319 - if type(rv) is StringType:
447.320 - self.save_global(obj, rv)
447.321 - return
447.322 -
447.323 - # Assert that reduce() returned a tuple
447.324 - if type(rv) is not TupleType:
447.325 - raise PicklingError("%s must return string or tuple" % reduce)
447.326 -
447.327 - # Assert that it returned an appropriately sized tuple
447.328 - l = len(rv)
447.329 - if not (2 <= l <= 5):
447.330 - raise PicklingError("Tuple returned by %s must have "
447.331 - "two to five elements" % reduce)
447.332 -
447.333 - # Save the reduce() output and finally memoize the object
447.334 - self.save_reduce(obj=obj, *rv)
447.335 -
447.336 - def persistent_id(self, obj):
447.337 - # This exists so a subclass can override it
447.338 - return None
447.339 -
447.340 - def save_pers(self, pid):
447.341 - # Save a persistent id reference
447.342 - if self.bin:
447.343 - self.save(pid)
447.344 - self.write(BINPERSID)
447.345 - else:
447.346 - self.write(PERSID + str(pid) + '\n')
447.347 -
447.348 - def save_reduce(self, func, args, state=None,
447.349 - listitems=None, dictitems=None, obj=None):
447.350 - # This API is called by some subclasses
447.351 -
447.352 - # Assert that args is a tuple or None
447.353 - if not isinstance(args, TupleType):
447.354 - raise PicklingError("args from reduce() should be a tuple")
447.355 -
447.356 - # Assert that func is callable
447.357 - if not callable(func):
447.358 - raise PicklingError("func from reduce should be callable")
447.359 -
447.360 - save = self.save
447.361 - write = self.write
447.362 -
447.363 - # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
447.364 - if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
447.365 - # A __reduce__ implementation can direct protocol 2 to
447.366 - # use the more efficient NEWOBJ opcode, while still
447.367 - # allowing protocol 0 and 1 to work normally. For this to
447.368 - # work, the function returned by __reduce__ should be
447.369 - # called __newobj__, and its first argument should be a
447.370 - # new-style class. The implementation for __newobj__
447.371 - # should be as follows, although pickle has no way to
447.372 - # verify this:
447.373 - #
447.374 - # def __newobj__(cls, *args):
447.375 - # return cls.__new__(cls, *args)
447.376 - #
447.377 - # Protocols 0 and 1 will pickle a reference to __newobj__,
447.378 - # while protocol 2 (and above) will pickle a reference to
447.379 - # cls, the remaining args tuple, and the NEWOBJ code,
447.380 - # which calls cls.__new__(cls, *args) at unpickling time
447.381 - # (see load_newobj below). If __reduce__ returns a
447.382 - # three-tuple, the state from the third tuple item will be
447.383 - # pickled regardless of the protocol, calling __setstate__
447.384 - # at unpickling time (see load_build below).
447.385 - #
447.386 - # Note that no standard __newobj__ implementation exists;
447.387 - # you have to provide your own. This is to enforce
447.388 - # compatibility with Python 2.2 (pickles written using
447.389 - # protocol 0 or 1 in Python 2.3 should be unpicklable by
447.390 - # Python 2.2).
447.391 - cls = args[0]
447.392 - if not hasattr(cls, "__new__"):
447.393 - raise PicklingError(
447.394 - "args[0] from __newobj__ args has no __new__")
447.395 - if obj is not None and cls is not obj.__class__:
447.396 - raise PicklingError(
447.397 - "args[0] from __newobj__ args has the wrong class")
447.398 - args = args[1:]
447.399 - save(cls)
447.400 - save(args)
447.401 - write(NEWOBJ)
447.402 - else:
447.403 - save(func)
447.404 - save(args)
447.405 - write(REDUCE)
447.406 -
447.407 - if obj is not None:
447.408 - self.memoize(obj)
447.409 -
447.410 - # More new special cases (that work with older protocols as
447.411 - # well): when __reduce__ returns a tuple with 4 or 5 items,
447.412 - # the 4th and 5th item should be iterators that provide list
447.413 - # items and dict items (as (key, value) tuples), or None.
447.414 -
447.415 - if listitems is not None:
447.416 - self._batch_appends(listitems)
447.417 -
447.418 - if dictitems is not None:
447.419 - self._batch_setitems(dictitems)
447.420 -
447.421 - if state is not None:
447.422 - save(state)
447.423 - write(BUILD)
447.424 -
447.425 - # Methods below this point are dispatched through the dispatch table
447.426 -
447.427 - dispatch = {}
447.428 -
447.429 - def save_none(self, obj):
447.430 - self.write(NONE)
447.431 - dispatch[NoneType] = save_none
447.432 -
447.433 - def save_bool(self, obj):
447.434 - if self.proto >= 2:
447.435 - self.write(obj and NEWTRUE or NEWFALSE)
447.436 - else:
447.437 - self.write(obj and TRUE or FALSE)
447.438 - dispatch[bool] = save_bool
447.439 -
447.440 - def save_int(self, obj, pack=struct.pack):
447.441 - if self.bin:
447.442 - # If the int is small enough to fit in a signed 4-byte 2's-comp
447.443 - # format, we can store it more efficiently than the general
447.444 - # case.
447.445 - # First one- and two-byte unsigned ints:
447.446 - if obj >= 0:
447.447 - if obj <= 0xff:
447.448 - self.write(BININT1 + chr(obj))
447.449 - return
447.450 - if obj <= 0xffff:
447.451 - self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
447.452 - return
447.453 - # Next check for 4-byte signed ints:
447.454 - high_bits = obj >> 31 # note that Python shift sign-extends
447.455 - if high_bits == 0 or high_bits == -1:
447.456 - # All high bits are copies of bit 2**31, so the value
447.457 - # fits in a 4-byte signed int.
447.458 - self.write(BININT + pack("<i", obj))
447.459 - return
447.460 - # Text pickle, or int too big to fit in signed 4-byte format.
447.461 - self.write(INT + repr(obj) + '\n')
447.462 - dispatch[IntType] = save_int
447.463 -
447.464 - def save_long(self, obj, pack=struct.pack):
447.465 - if self.proto >= 2:
447.466 - bytes = encode_long(obj)
447.467 - n = len(bytes)
447.468 - if n < 256:
447.469 - self.write(LONG1 + chr(n) + bytes)
447.470 - else:
447.471 - self.write(LONG4 + pack("<i", n) + bytes)
447.472 - return
447.473 - self.write(LONG + repr(obj) + '\n')
447.474 - dispatch[LongType] = save_long
447.475 -
447.476 - def save_float(self, obj, pack=struct.pack):
447.477 - if self.bin:
447.478 - self.write(BINFLOAT + pack('>d', obj))
447.479 - else:
447.480 - self.write(FLOAT + repr(obj) + '\n')
447.481 - dispatch[FloatType] = save_float
447.482 -
447.483 - def save_string(self, obj, pack=struct.pack):
447.484 - if self.bin:
447.485 - n = len(obj)
447.486 - if n < 256:
447.487 - self.write(SHORT_BINSTRING + chr(n) + obj)
447.488 - else:
447.489 - self.write(BINSTRING + pack("<i", n) + obj)
447.490 - else:
447.491 - self.write(STRING + repr(obj) + '\n')
447.492 - self.memoize(obj)
447.493 - dispatch[StringType] = save_string
447.494 -
447.495 - def save_unicode(self, obj, pack=struct.pack):
447.496 - if self.bin:
447.497 - encoding = obj.encode('utf-8')
447.498 - n = len(encoding)
447.499 - self.write(BINUNICODE + pack("<i", n) + encoding)
447.500 - else:
447.501 - obj = obj.replace("\\", "\\u005c")
447.502 - obj = obj.replace("\n", "\\u000a")
447.503 - self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
447.504 - self.memoize(obj)
447.505 - dispatch[UnicodeType] = save_unicode
447.506 -
447.507 - if StringType == UnicodeType:
447.508 - # This is true for Jython
447.509 - def save_string(self, obj, pack=struct.pack):
447.510 - unicode = obj.isunicode()
447.511 -
447.512 - if self.bin:
447.513 - if unicode:
447.514 - obj = obj.encode("utf-8")
447.515 - l = len(obj)
447.516 - if l < 256 and not unicode:
447.517 - self.write(SHORT_BINSTRING + chr(l) + obj)
447.518 - else:
447.519 - s = pack("<i", l)
447.520 - if unicode:
447.521 - self.write(BINUNICODE + s + obj)
447.522 - else:
447.523 - self.write(BINSTRING + s + obj)
447.524 - else:
447.525 - if unicode:
447.526 - obj = obj.replace("\\", "\\u005c")
447.527 - obj = obj.replace("\n", "\\u000a")
447.528 - obj = obj.encode('raw-unicode-escape')
447.529 - self.write(UNICODE + obj + '\n')
447.530 - else:
447.531 - self.write(STRING + repr(obj) + '\n')
447.532 - self.memoize(obj)
447.533 - dispatch[StringType] = save_string
447.534 -
447.535 - def save_tuple(self, obj):
447.536 - write = self.write
447.537 - proto = self.proto
447.538 -
447.539 - n = len(obj)
447.540 - if n == 0:
447.541 - if proto:
447.542 - write(EMPTY_TUPLE)
447.543 - else:
447.544 - write(MARK + TUPLE)
447.545 - return
447.546 -
447.547 - save = self.save
447.548 - memo = self.memo
447.549 - if n <= 3 and proto >= 2:
447.550 - for element in obj:
447.551 - save(element)
447.552 - # Subtle. Same as in the big comment below.
447.553 - if id(obj) in memo:
447.554 - get = self.get(memo[id(obj)][0])
447.555 - write(POP * n + get)
447.556 - else:
447.557 - write(_tuplesize2code[n])
447.558 - self.memoize(obj)
447.559 - return
447.560 -
447.561 - # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
447.562 - # has more than 3 elements.
447.563 - write(MARK)
447.564 - for element in obj:
447.565 - save(element)
447.566 -
447.567 - if id(obj) in memo:
447.568 - # Subtle. d was not in memo when we entered save_tuple(), so
447.569 - # the process of saving the tuple's elements must have saved
447.570 - # the tuple itself: the tuple is recursive. The proper action
447.571 - # now is to throw away everything we put on the stack, and
447.572 - # simply GET the tuple (it's already constructed). This check
447.573 - # could have been done in the "for element" loop instead, but
447.574 - # recursive tuples are a rare thing.
447.575 - get = self.get(memo[id(obj)][0])
447.576 - if proto:
447.577 - write(POP_MARK + get)
447.578 - else: # proto 0 -- POP_MARK not available
447.579 - write(POP * (n+1) + get)
447.580 - return
447.581 -
447.582 - # No recursion.
447.583 - self.write(TUPLE)
447.584 - self.memoize(obj)
447.585 -
447.586 - dispatch[TupleType] = save_tuple
447.587 -
447.588 - # save_empty_tuple() isn't used by anything in Python 2.3. However, I
447.589 - # found a Pickler subclass in Zope3 that calls it, so it's not harmless
447.590 - # to remove it.
447.591 - def save_empty_tuple(self, obj):
447.592 - self.write(EMPTY_TUPLE)
447.593 -
447.594 - def save_list(self, obj):
447.595 - write = self.write
447.596 -
447.597 - if self.bin:
447.598 - write(EMPTY_LIST)
447.599 - else: # proto 0 -- can't use EMPTY_LIST
447.600 - write(MARK + LIST)
447.601 -
447.602 - self.memoize(obj)
447.603 - self._batch_appends(iter(obj))
447.604 -
447.605 - dispatch[ListType] = save_list
447.606 -
447.607 - # Keep in synch with cPickle's BATCHSIZE. Nothing will break if it gets
447.608 - # out of synch, though.
447.609 - _BATCHSIZE = 1000
447.610 -
447.611 - def _batch_appends(self, items):
447.612 - # Helper to batch up APPENDS sequences
447.613 - save = self.save
447.614 - write = self.write
447.615 -
447.616 - if not self.bin:
447.617 - for x in items:
447.618 - save(x)
447.619 - write(APPEND)
447.620 - return
447.621 -
447.622 - r = xrange(self._BATCHSIZE)
447.623 - while items is not None:
447.624 - tmp = []
447.625 - for i in r:
447.626 - try:
447.627 - x = items.next()
447.628 - tmp.append(x)
447.629 - except StopIteration:
447.630 - items = None
447.631 - break
447.632 - n = len(tmp)
447.633 - if n > 1:
447.634 - write(MARK)
447.635 - for x in tmp:
447.636 - save(x)
447.637 - write(APPENDS)
447.638 - elif n:
447.639 - save(tmp[0])
447.640 - write(APPEND)
447.641 - # else tmp is empty, and we're done
447.642 -
447.643 - def save_dict(self, obj):
447.644 - write = self.write
447.645 -
447.646 - if self.bin:
447.647 - write(EMPTY_DICT)
447.648 - else: # proto 0 -- can't use EMPTY_DICT
447.649 - write(MARK + DICT)
447.650 -
447.651 - self.memoize(obj)
447.652 - self._batch_setitems(obj.iteritems())
447.653 -
447.654 - dispatch[DictionaryType] = save_dict
447.655 - if not PyStringMap is None:
447.656 - dispatch[PyStringMap] = save_dict
447.657 -
447.658 - def _batch_setitems(self, items):
447.659 - # Helper to batch up SETITEMS sequences; proto >= 1 only
447.660 - save = self.save
447.661 - write = self.write
447.662 -
447.663 - if not self.bin:
447.664 - for k, v in items:
447.665 - save(k)
447.666 - save(v)
447.667 - write(SETITEM)
447.668 - return
447.669 -
447.670 - r = xrange(self._BATCHSIZE)
447.671 - while items is not None:
447.672 - tmp = []
447.673 - for i in r:
447.674 - try:
447.675 - tmp.append(items.next())
447.676 - except StopIteration:
447.677 - items = None
447.678 - break
447.679 - n = len(tmp)
447.680 - if n > 1:
447.681 - write(MARK)
447.682 - for k, v in tmp:
447.683 - save(k)
447.684 - save(v)
447.685 - write(SETITEMS)
447.686 - elif n:
447.687 - k, v = tmp[0]
447.688 - save(k)
447.689 - save(v)
447.690 - write(SETITEM)
447.691 - # else tmp is empty, and we're done
447.692 -
447.693 - def save_inst(self, obj):
447.694 - cls = obj.__class__
447.695 -
447.696 - memo = self.memo
447.697 - write = self.write
447.698 - save = self.save
447.699 -
447.700 - if hasattr(obj, '__getinitargs__'):
447.701 - args = obj.__getinitargs__()
447.702 - len(args) # XXX Assert it's a sequence
447.703 - _keep_alive(args, memo)
447.704 - else:
447.705 - args = ()
447.706 -
447.707 - write(MARK)
447.708 -
447.709 - if self.bin:
447.710 - save(cls)
447.711 - for arg in args:
447.712 - save(arg)
447.713 - write(OBJ)
447.714 - else:
447.715 - for arg in args:
447.716 - save(arg)
447.717 - write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
447.718 -
447.719 - self.memoize(obj)
447.720 -
447.721 - try:
447.722 - getstate = obj.__getstate__
447.723 - except AttributeError:
447.724 - stuff = obj.__dict__
447.725 - else:
447.726 - stuff = getstate()
447.727 - _keep_alive(stuff, memo)
447.728 - save(stuff)
447.729 - write(BUILD)
447.730 -
447.731 - dispatch[InstanceType] = save_inst
447.732 -
447.733 - def save_global(self, obj, name=None, pack=struct.pack):
447.734 - write = self.write
447.735 - memo = self.memo
447.736 -
447.737 - if name is None:
447.738 - name = obj.__name__
447.739 -
447.740 - module = getattr(obj, "__module__", None)
447.741 - if module is None:
447.742 - module = whichmodule(obj, name)
447.743 -
447.744 - try:
447.745 - __import__(module)
447.746 - mod = sys.modules[module]
447.747 - klass = getattr(mod, name)
447.748 - except (ImportError, KeyError, AttributeError):
447.749 - raise PicklingError(
447.750 - "Can't pickle %r: it's not found as %s.%s" %
447.751 - (obj, module, name))
447.752 - else:
447.753 - if klass is not obj:
447.754 - raise PicklingError(
447.755 - "Can't pickle %r: it's not the same object as %s.%s" %
447.756 - (obj, module, name))
447.757 -
447.758 - if self.proto >= 2:
447.759 - code = _extension_registry.get((module, name))
447.760 - if code:
447.761 - assert code > 0
447.762 - if code <= 0xff:
447.763 - write(EXT1 + chr(code))
447.764 - elif code <= 0xffff:
447.765 - write("%c%c%c" % (EXT2, code&0xff, code>>8))
447.766 - else:
447.767 - write(EXT4 + pack("<i", code))
447.768 - return
447.769 -
447.770 - write(GLOBAL + module + '\n' + name + '\n')
447.771 - self.memoize(obj)
447.772 -
447.773 - dispatch[ClassType] = save_global
447.774 - dispatch[FunctionType] = save_global
447.775 - dispatch[BuiltinFunctionType] = save_global
447.776 - dispatch[TypeType] = save_global
447.777 -
447.778 -# Pickling helpers
447.779 -
447.780 -def _keep_alive(x, memo):
447.781 - """Keeps a reference to the object x in the memo.
447.782 -
447.783 - Because we remember objects by their id, we have
447.784 - to assure that possibly temporary objects are kept
447.785 - alive by referencing them.
447.786 - We store a reference at the id of the memo, which should
447.787 - normally not be used unless someone tries to deepcopy
447.788 - the memo itself...
447.789 - """
447.790 - try:
447.791 - memo[id(memo)].append(x)
447.792 - except KeyError:
447.793 - # aha, this is the first one :-)
447.794 - memo[id(memo)]=[x]
447.795 -
447.796 -
447.797 -# A cache for whichmodule(), mapping a function object to the name of
447.798 -# the module in which the function was found.
447.799 -
447.800 -classmap = {} # called classmap for backwards compatibility
447.801 -
447.802 -def whichmodule(func, funcname):
447.803 - """Figure out the module in which a function occurs.
447.804 -
447.805 - Search sys.modules for the module.
447.806 - Cache in classmap.
447.807 - Return a module name.
447.808 - If the function cannot be found, return "__main__".
447.809 - """
447.810 - # Python functions should always get an __module__ from their globals.
447.811 - mod = getattr(func, "__module__", None)
447.812 - if mod is not None:
447.813 - return mod
447.814 - if func in classmap:
447.815 - return classmap[func]
447.816 -
447.817 - for name, module in sys.modules.items():
447.818 - if module is None:
447.819 - continue # skip dummy package entries
447.820 - if name != '__main__' and getattr(module, funcname, None) is func:
447.821 - break
447.822 - else:
447.823 - name = '__main__'
447.824 - classmap[func] = name
447.825 - return name
447.826 -
447.827 -
447.828 -# Unpickling machinery
447.829 -
447.830 -class Unpickler:
447.831 -
447.832 - def __init__(self, file):
447.833 - """This takes a file-like object for reading a pickle data stream.
447.834 -
447.835 - The protocol version of the pickle is detected automatically, so no
447.836 - proto argument is needed.
447.837 -
447.838 - The file-like object must have two methods, a read() method that
447.839 - takes an integer argument, and a readline() method that requires no
447.840 - arguments. Both methods should return a string. Thus file-like
447.841 - object can be a file object opened for reading, a StringIO object,
447.842 - or any other custom object that meets this interface.
447.843 - """
447.844 - self.readline = file.readline
447.845 - self.read = file.read
447.846 - self.memo = {}
447.847 -
447.848 - def load(self):
447.849 - """Read a pickled object representation from the open file.
447.850 -
447.851 - Return the reconstituted object hierarchy specified in the file.
447.852 - """
447.853 - self.mark = object() # any new unique object
447.854 - self.stack = []
447.855 - self.append = self.stack.append
447.856 - read = self.read
447.857 - dispatch = self.dispatch
447.858 - try:
447.859 - while 1:
447.860 - key = read(1)
447.861 - dispatch[key](self)
447.862 - except _Stop, stopinst:
447.863 - return stopinst.value
447.864 -
447.865 - # Return largest index k such that self.stack[k] is self.mark.
447.866 - # If the stack doesn't contain a mark, eventually raises IndexError.
447.867 - # This could be sped by maintaining another stack, of indices at which
447.868 - # the mark appears. For that matter, the latter stack would suffice,
447.869 - # and we wouldn't need to push mark objects on self.stack at all.
447.870 - # Doing so is probably a good thing, though, since if the pickle is
447.871 - # corrupt (or hostile) we may get a clue from finding self.mark embedded
447.872 - # in unpickled objects.
447.873 - def marker(self):
447.874 - stack = self.stack
447.875 - mark = self.mark
447.876 - k = len(stack)-1
447.877 - while stack[k] is not mark: k = k-1
447.878 - return k
447.879 -
447.880 - dispatch = {}
447.881 -
447.882 - def load_eof(self):
447.883 - raise EOFError
447.884 - dispatch[''] = load_eof
447.885 -
447.886 - def load_proto(self):
447.887 - proto = ord(self.read(1))
447.888 - if not 0 <= proto <= 2:
447.889 - raise ValueError, "unsupported pickle protocol: %d" % proto
447.890 - dispatch[PROTO] = load_proto
447.891 -
447.892 - def load_persid(self):
447.893 - pid = self.readline()[:-1]
447.894 - self.append(self.persistent_load(pid))
447.895 - dispatch[PERSID] = load_persid
447.896 -
447.897 - def load_binpersid(self):
447.898 - pid = self.stack.pop()
447.899 - self.append(self.persistent_load(pid))
447.900 - dispatch[BINPERSID] = load_binpersid
447.901 -
447.902 - def load_none(self):
447.903 - self.append(None)
447.904 - dispatch[NONE] = load_none
447.905 -
447.906 - def load_false(self):
447.907 - self.append(False)
447.908 - dispatch[NEWFALSE] = load_false
447.909 -
447.910 - def load_true(self):
447.911 - self.append(True)
447.912 - dispatch[NEWTRUE] = load_true
447.913 -
447.914 - def load_int(self):
447.915 - data = self.readline()
447.916 - if data == FALSE[1:]:
447.917 - val = False
447.918 - elif data == TRUE[1:]:
447.919 - val = True
447.920 - else:
447.921 - try:
447.922 - val = int(data)
447.923 - except ValueError:
447.924 - val = long(data)
447.925 - self.append(val)
447.926 - dispatch[INT] = load_int
447.927 -
447.928 - def load_binint(self):
447.929 - self.append(mloads('i' + self.read(4)))
447.930 - dispatch[BININT] = load_binint
447.931 -
447.932 - def load_binint1(self):
447.933 - self.append(ord(self.read(1)))
447.934 - dispatch[BININT1] = load_binint1
447.935 -
447.936 - def load_binint2(self):
447.937 - self.append(mloads('i' + self.read(2) + '\000\000'))
447.938 - dispatch[BININT2] = load_binint2
447.939 -
447.940 - def load_long(self):
447.941 - self.append(long(self.readline()[:-1], 0))
447.942 - dispatch[LONG] = load_long
447.943 -
447.944 - def load_long1(self):
447.945 - n = ord(self.read(1))
447.946 - bytes = self.read(n)
447.947 - self.append(decode_long(bytes))
447.948 - dispatch[LONG1] = load_long1
447.949 -
447.950 - def load_long4(self):
447.951 - n = mloads('i' + self.read(4))
447.952 - bytes = self.read(n)
447.953 - self.append(decode_long(bytes))
447.954 - dispatch[LONG4] = load_long4
447.955 -
447.956 - def load_float(self):
447.957 - self.append(float(self.readline()[:-1]))
447.958 - dispatch[FLOAT] = load_float
447.959 -
447.960 - def load_binfloat(self, unpack=struct.unpack):
447.961 - self.append(unpack('>d', self.read(8))[0])
447.962 - dispatch[BINFLOAT] = load_binfloat
447.963 -
447.964 - def load_string(self):
447.965 - rep = self.readline()[:-1]
447.966 - for q in "\"'": # double or single quote
447.967 - if rep.startswith(q):
447.968 - if not rep.endswith(q):
447.969 - raise ValueError, "insecure string pickle"
447.970 - rep = rep[len(q):-len(q)]
447.971 - break
447.972 - else:
447.973 - raise ValueError, "insecure string pickle"
447.974 - self.append(rep.decode("string-escape"))
447.975 - dispatch[STRING] = load_string
447.976 -
447.977 - def load_binstring(self):
447.978 - len = mloads('i' + self.read(4))
447.979 - self.append(self.read(len))
447.980 - dispatch[BINSTRING] = load_binstring
447.981 -
447.982 - def load_unicode(self):
447.983 - self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
447.984 - dispatch[UNICODE] = load_unicode
447.985 -
447.986 - def load_binunicode(self):
447.987 - len = mloads('i' + self.read(4))
447.988 - self.append(unicode(self.read(len),'utf-8'))
447.989 - dispatch[BINUNICODE] = load_binunicode
447.990 -
447.991 - def load_short_binstring(self):
447.992 - len = ord(self.read(1))
447.993 - self.append(self.read(len))
447.994 - dispatch[SHORT_BINSTRING] = load_short_binstring
447.995 -
447.996 - def load_tuple(self):
447.997 - k = self.marker()
447.998 - self.stack[k:] = [tuple(self.stack[k+1:])]
447.999 - dispatch[TUPLE] = load_tuple
447.1000 -
447.1001 - def load_empty_tuple(self):
447.1002 - self.stack.append(())
447.1003 - dispatch[EMPTY_TUPLE] = load_empty_tuple
447.1004 -
447.1005 - def load_tuple1(self):
447.1006 - self.stack[-1] = (self.stack[-1],)
447.1007 - dispatch[TUPLE1] = load_tuple1
447.1008 -
447.1009 - def load_tuple2(self):
447.1010 - self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
447.1011 - dispatch[TUPLE2] = load_tuple2
447.1012 -
447.1013 - def load_tuple3(self):
447.1014 - self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
447.1015 - dispatch[TUPLE3] = load_tuple3
447.1016 -
447.1017 - def load_empty_list(self):
447.1018 - self.stack.append([])
447.1019 - dispatch[EMPTY_LIST] = load_empty_list
447.1020 -
447.1021 - def load_empty_dictionary(self):
447.1022 - self.stack.append({})
447.1023 - dispatch[EMPTY_DICT] = load_empty_dictionary
447.1024 -
447.1025 - def load_list(self):
447.1026 - k = self.marker()
447.1027 - self.stack[k:] = [self.stack[k+1:]]
447.1028 - dispatch[LIST] = load_list
447.1029 -
447.1030 - def load_dict(self):
447.1031 - k = self.marker()
447.1032 - d = {}
447.1033 - items = self.stack[k+1:]
447.1034 - for i in range(0, len(items), 2):
447.1035 - key = items[i]
447.1036 - value = items[i+1]
447.1037 - d[key] = value
447.1038 - self.stack[k:] = [d]
447.1039 - dispatch[DICT] = load_dict
447.1040 -
447.1041 - # INST and OBJ differ only in how they get a class object. It's not
447.1042 - # only sensible to do the rest in a common routine, the two routines
447.1043 - # previously diverged and grew different bugs.
447.1044 - # klass is the class to instantiate, and k points to the topmost mark
447.1045 - # object, following which are the arguments for klass.__init__.
447.1046 - def _instantiate(self, klass, k):
447.1047 - args = tuple(self.stack[k+1:])
447.1048 - del self.stack[k:]
447.1049 - instantiated = 0
447.1050 - if (not args and
447.1051 - type(klass) is ClassType and
447.1052 - not hasattr(klass, "__getinitargs__")):
447.1053 - try:
447.1054 - value = _EmptyClass()
447.1055 - value.__class__ = klass
447.1056 - instantiated = 1
447.1057 - except RuntimeError:
447.1058 - # In restricted execution, assignment to inst.__class__ is
447.1059 - # prohibited
447.1060 - pass
447.1061 - if not instantiated:
447.1062 - try:
447.1063 - value = klass(*args)
447.1064 - except TypeError, err:
447.1065 - raise TypeError, "in constructor for %s: %s" % (
447.1066 - klass.__name__, str(err)), sys.exc_info()[2]
447.1067 - self.append(value)
447.1068 -
447.1069 - def load_inst(self):
447.1070 - module = self.readline()[:-1]
447.1071 - name = self.readline()[:-1]
447.1072 - klass = self.find_class(module, name)
447.1073 - self._instantiate(klass, self.marker())
447.1074 - dispatch[INST] = load_inst
447.1075 -
447.1076 - def load_obj(self):
447.1077 - # Stack is ... markobject classobject arg1 arg2 ...
447.1078 - k = self.marker()
447.1079 - klass = self.stack.pop(k+1)
447.1080 - self._instantiate(klass, k)
447.1081 - dispatch[OBJ] = load_obj
447.1082 -
447.1083 - def load_newobj(self):
447.1084 - args = self.stack.pop()
447.1085 - cls = self.stack[-1]
447.1086 - obj = cls.__new__(cls, *args)
447.1087 - self.stack[-1] = obj
447.1088 - dispatch[NEWOBJ] = load_newobj
447.1089 -
447.1090 - def load_global(self):
447.1091 - module = self.readline()[:-1]
447.1092 - name = self.readline()[:-1]
447.1093 - klass = self.find_class(module, name)
447.1094 - self.append(klass)
447.1095 - dispatch[GLOBAL] = load_global
447.1096 -
447.1097 - def load_ext1(self):
447.1098 - code = ord(self.read(1))
447.1099 - self.get_extension(code)
447.1100 - dispatch[EXT1] = load_ext1
447.1101 -
447.1102 - def load_ext2(self):
447.1103 - code = mloads('i' + self.read(2) + '\000\000')
447.1104 - self.get_extension(code)
447.1105 - dispatch[EXT2] = load_ext2
447.1106 -
447.1107 - def load_ext4(self):
447.1108 - code = mloads('i' + self.read(4))
447.1109 - self.get_extension(code)
447.1110 - dispatch[EXT4] = load_ext4
447.1111 -
447.1112 - def get_extension(self, code):
447.1113 - nil = []
447.1114 - obj = _extension_cache.get(code, nil)
447.1115 - if obj is not nil:
447.1116 - self.append(obj)
447.1117 - return
447.1118 - key = _inverted_registry.get(code)
447.1119 - if not key:
447.1120 - raise ValueError("unregistered extension code %d" % code)
447.1121 - obj = self.find_class(*key)
447.1122 - _extension_cache[code] = obj
447.1123 - self.append(obj)
447.1124 -
447.1125 - def find_class(self, module, name):
447.1126 - # Subclasses may override this
447.1127 - __import__(module)
447.1128 - mod = sys.modules[module]
447.1129 - klass = getattr(mod, name)
447.1130 - return klass
447.1131 -
447.1132 - def load_reduce(self):
447.1133 - stack = self.stack
447.1134 - args = stack.pop()
447.1135 - func = stack[-1]
447.1136 - value = func(*args)
447.1137 - stack[-1] = value
447.1138 - dispatch[REDUCE] = load_reduce
447.1139 -
447.1140 - def load_pop(self):
447.1141 - del self.stack[-1]
447.1142 - dispatch[POP] = load_pop
447.1143 -
447.1144 - def load_pop_mark(self):
447.1145 - k = self.marker()
447.1146 - del self.stack[k:]
447.1147 - dispatch[POP_MARK] = load_pop_mark
447.1148 -
447.1149 - def load_dup(self):
447.1150 - self.append(self.stack[-1])
447.1151 - dispatch[DUP] = load_dup
447.1152 -
447.1153 - def load_get(self):
447.1154 - self.append(self.memo[self.readline()[:-1]])
447.1155 - dispatch[GET] = load_get
447.1156 -
447.1157 - def load_binget(self):
447.1158 - i = ord(self.read(1))
447.1159 - self.append(self.memo[repr(i)])
447.1160 - dispatch[BINGET] = load_binget
447.1161 -
447.1162 - def load_long_binget(self):
447.1163 - i = mloads('i' + self.read(4))
447.1164 - self.append(self.memo[repr(i)])
447.1165 - dispatch[LONG_BINGET] = load_long_binget
447.1166 -
447.1167 - def load_put(self):
447.1168 - self.memo[self.readline()[:-1]] = self.stack[-1]
447.1169 - dispatch[PUT] = load_put
447.1170 -
447.1171 - def load_binput(self):
447.1172 - i = ord(self.read(1))
447.1173 - self.memo[repr(i)] = self.stack[-1]
447.1174 - dispatch[BINPUT] = load_binput
447.1175 -
447.1176 - def load_long_binput(self):
447.1177 - i = mloads('i' + self.read(4))
447.1178 - self.memo[repr(i)] = self.stack[-1]
447.1179 - dispatch[LONG_BINPUT] = load_long_binput
447.1180 -
447.1181 - def load_append(self):
447.1182 - stack = self.stack
447.1183 - value = stack.pop()
447.1184 - list = stack[-1]
447.1185 - list.append(value)
447.1186 - dispatch[APPEND] = load_append
447.1187 -
447.1188 - def load_appends(self):
447.1189 - stack = self.stack
447.1190 - mark = self.marker()
447.1191 - list = stack[mark - 1]
447.1192 - list.extend(stack[mark + 1:])
447.1193 - del stack[mark:]
447.1194 - dispatch[APPENDS] = load_appends
447.1195 -
447.1196 - def load_setitem(self):
447.1197 - stack = self.stack
447.1198 - value = stack.pop()
447.1199 - key = stack.pop()
447.1200 - dict = stack[-1]
447.1201 - dict[key] = value
447.1202 - dispatch[SETITEM] = load_setitem
447.1203 -
447.1204 - def load_setitems(self):
447.1205 - stack = self.stack
447.1206 - mark = self.marker()
447.1207 - dict = stack[mark - 1]
447.1208 - for i in range(mark + 1, len(stack), 2):
447.1209 - dict[stack[i]] = stack[i + 1]
447.1210 -
447.1211 - del stack[mark:]
447.1212 - dispatch[SETITEMS] = load_setitems
447.1213 -
447.1214 - def load_build(self):
447.1215 - stack = self.stack
447.1216 - state = stack.pop()
447.1217 - inst = stack[-1]
447.1218 - setstate = getattr(inst, "__setstate__", None)
447.1219 - if setstate:
447.1220 - setstate(state)
447.1221 - return
447.1222 - slotstate = None
447.1223 - if isinstance(state, tuple) and len(state) == 2:
447.1224 - state, slotstate = state
447.1225 - if state:
447.1226 - try:
447.1227 - inst.__dict__.update(state)
447.1228 - except RuntimeError:
447.1229 - # XXX In restricted execution, the instance's __dict__
447.1230 - # is not accessible. Use the old way of unpickling
447.1231 - # the instance variables. This is a semantic
447.1232 - # difference when unpickling in restricted
447.1233 - # vs. unrestricted modes.
447.1234 - # Note, however, that cPickle has never tried to do the
447.1235 - # .update() business, and always uses
447.1236 - # PyObject_SetItem(inst.__dict__, key, value) in a
447.1237 - # loop over state.items().
447.1238 - for k, v in state.items():
447.1239 - setattr(inst, k, v)
447.1240 - if slotstate:
447.1241 - for k, v in slotstate.items():
447.1242 - setattr(inst, k, v)
447.1243 - dispatch[BUILD] = load_build
447.1244 -
447.1245 - def load_mark(self):
447.1246 - self.append(self.mark)
447.1247 - dispatch[MARK] = load_mark
447.1248 -
447.1249 - def load_stop(self):
447.1250 - value = self.stack.pop()
447.1251 - raise _Stop(value)
447.1252 - dispatch[STOP] = load_stop
447.1253 -
447.1254 -# Helper class for load_inst/load_obj
447.1255 -
447.1256 -class _EmptyClass:
447.1257 - pass
447.1258 -
447.1259 -# Encode/decode longs in linear time.
447.1260 -
447.1261 -import binascii as _binascii
447.1262 -
447.1263 -def encode_long(x):
447.1264 - r"""Encode a long to a two's complement little-endian binary string.
447.1265 - Note that 0L is a special case, returning an empty string, to save a
447.1266 - byte in the LONG1 pickling context.
447.1267 -
447.1268 - >>> encode_long(0L)
447.1269 - ''
447.1270 - >>> encode_long(255L)
447.1271 - '\xff\x00'
447.1272 - >>> encode_long(32767L)
447.1273 - '\xff\x7f'
447.1274 - >>> encode_long(-256L)
447.1275 - '\x00\xff'
447.1276 - >>> encode_long(-32768L)
447.1277 - '\x00\x80'
447.1278 - >>> encode_long(-128L)
447.1279 - '\x80'
447.1280 - >>> encode_long(127L)
447.1281 - '\x7f'
447.1282 - >>>
447.1283 - """
447.1284 -
447.1285 - if x == 0:
447.1286 - return ''
447.1287 - if x > 0:
447.1288 - ashex = hex(x)
447.1289 - assert ashex.startswith("0x")
447.1290 - njunkchars = 2 + ashex.endswith('L')
447.1291 - nibbles = len(ashex) - njunkchars
447.1292 - if nibbles & 1:
447.1293 - # need an even # of nibbles for unhexlify
447.1294 - ashex = "0x0" + ashex[2:]
447.1295 - elif int(ashex[2], 16) >= 8:
447.1296 - # "looks negative", so need a byte of sign bits
447.1297 - ashex = "0x00" + ashex[2:]
447.1298 - else:
447.1299 - # Build the 256's-complement: (1L << nbytes) + x. The trick is
447.1300 - # to find the number of bytes in linear time (although that should
447.1301 - # really be a constant-time task).
447.1302 - ashex = hex(-x)
447.1303 - assert ashex.startswith("0x")
447.1304 - njunkchars = 2 + ashex.endswith('L')
447.1305 - nibbles = len(ashex) - njunkchars
447.1306 - if nibbles & 1:
447.1307 - # Extend to a full byte.
447.1308 - nibbles += 1
447.1309 - nbits = nibbles * 4
447.1310 - x += 1L << nbits
447.1311 - assert x > 0
447.1312 - ashex = hex(x)
447.1313 - njunkchars = 2 + ashex.endswith('L')
447.1314 - newnibbles = len(ashex) - njunkchars
447.1315 - if newnibbles < nibbles:
447.1316 - ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
447.1317 - if int(ashex[2], 16) < 8:
447.1318 - # "looks positive", so need a byte of sign bits
447.1319 - ashex = "0xff" + ashex[2:]
447.1320 -
447.1321 - if ashex.endswith('L'):
447.1322 - ashex = ashex[2:-1]
447.1323 - else:
447.1324 - ashex = ashex[2:]
447.1325 - assert len(ashex) & 1 == 0, (x, ashex)
447.1326 - binary = _binascii.unhexlify(ashex)
447.1327 - return binary[::-1]
447.1328 -
447.1329 -def decode_long(data):
447.1330 - r"""Decode a long from a two's complement little-endian binary string.
447.1331 -
447.1332 - >>> decode_long('')
447.1333 - 0L
447.1334 - >>> decode_long("\xff\x00")
447.1335 - 255L
447.1336 - >>> decode_long("\xff\x7f")
447.1337 - 32767L
447.1338 - >>> decode_long("\x00\xff")
447.1339 - -256L
447.1340 - >>> decode_long("\x00\x80")
447.1341 - -32768L
447.1342 - >>> decode_long("\x80")
447.1343 - -128L
447.1344 - >>> decode_long("\x7f")
447.1345 - 127L
447.1346 - """
447.1347 -
447.1348 - nbytes = len(data)
447.1349 - if nbytes == 0:
447.1350 - return 0L
447.1351 - ashex = _binascii.hexlify(data[::-1])
447.1352 - n = long(ashex, 16) # quadratic time before Python 2.3; linear now
447.1353 - if data[-1] >= '\x80':
447.1354 - n -= 1L << (nbytes * 8)
447.1355 - return n
447.1356 -
447.1357 -# Shorthands
447.1358 -
447.1359 -try:
447.1360 - from cStringIO import StringIO
447.1361 -except ImportError:
447.1362 - from StringIO import StringIO
447.1363 -
447.1364 -def dump(obj, file, protocol=None):
447.1365 - Pickler(file, protocol).dump(obj)
447.1366 -
447.1367 -def dumps(obj, protocol=None):
447.1368 - file = StringIO()
447.1369 - Pickler(file, protocol).dump(obj)
447.1370 - return file.getvalue()
447.1371 -
447.1372 -def load(file):
447.1373 - return Unpickler(file).load()
447.1374 -
447.1375 -def loads(str):
447.1376 - file = StringIO(str)
447.1377 - return Unpickler(file).load()
447.1378 -
447.1379 -# Doctest
447.1380 -
447.1381 -def _test():
447.1382 - import doctest
447.1383 - return doctest.testmod()
447.1384 -
447.1385 -if __name__ == "__main__":
447.1386 - _test()
448.1 --- a/python.editor/test/unit/data/testfiles/pickle.py.testDoc3.html Sun Jan 04 13:11:53 2015 -0600
448.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
448.3 @@ -1,40 +0,0 @@
448.4 -<html><body>
448.5 -<pre>Code completion result for source line:
448.6 -import |re
448.7 -(QueryType=COMPLETION, NameKind=PREFIX)
448.8 -------------------------------------
448.9 -KEYWORD pickle null
448.10 -</pre><h2>Documentation:</h2><pre><b>pickle</b></pre>
448.11 -
448.12 -<hr>
448.13 -Create portable serialized representations of Python objects.
448.14 -
448.15 -<br><br>
448.16 -See module cPickle for a (much) faster implementation.
448.17 -See module copy_reg for a mechanism for registering custom picklers.
448.18 -See module pickletools source for extensive comments.
448.19 -
448.20 -<br><br>
448.21 -Classes:
448.22 -
448.23 -<br><br>
448.24 - Pickler
448.25 - Unpickler
448.26 -
448.27 -<br><br>
448.28 -Functions:
448.29 -
448.30 -<br><br>
448.31 - dump(object, file)
448.32 - dumps(object) -> string
448.33 - load(file) -> object
448.34 - loads(string) -> object
448.35 -
448.36 -<br><br>
448.37 -Misc variables:
448.38 -
448.39 -<br><br>
448.40 - __version__
448.41 - format_version
448.42 - compatible_formats
448.43 -</body></html>
449.1 --- a/python.editor/test/unit/data/testfiles/pickle.py.testDoc5.html Sun Jan 04 13:11:53 2015 -0600
449.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
449.3 @@ -1,14 +0,0 @@
449.4 -<html><body>
449.5 -<pre>Code completion result for source line:
449.6 -self.append(decode_lo|ng(bytes))
449.7 -(QueryType=COMPLETION, NameKind=PREFIX)
449.8 -METHOD decode_long(data) pickle
449.9 -</pre><h2>Documentation:</h2><pre><i>pickle</i><br><b>decode_long</b>(<font color="#808080">data</font>)</pre>
449.10 -
449.11 -<hr>
449.12 -Decode a long from a two's complement little-endian binary string.
449.13 -
449.14 -<br><br>
449.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>
449.16 -<br><br>
449.17 -</body></html>
450.1 --- a/python.editor/test/unit/data/testfiles/properties.py Sun Jan 04 13:11:53 2015 -0600
450.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
450.3 @@ -1,8 +0,0 @@
450.4 -class Foo(object):
450.5 - @property
450.6 - def bar(self):
450.7 - return "Foo:bar"
450.8 -
450.9 -x = Foo()
450.10 -x.bar
450.11 -
451.1 --- a/python.editor/test/unit/data/testfiles/properties.py.indexed Sun Jan 04 13:11:53 2015 -0600
451.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
451.3 @@ -1,20 +0,0 @@
451.4 -
451.5 -
451.6 -Document 0
451.7 -Searchable Keys:
451.8 - class : Foo
451.9 - class-ig : foo
451.10 - extends : object
451.11 - in : properties
451.12 - member : bar;A;;self;
451.13 -
451.14 -Not Searchable Keys:
451.15 -
451.16 -
451.17 -Document 1
451.18 -Searchable Keys:
451.19 - item : Foo;C;;
451.20 - item : x;D;;
451.21 - module : properties
451.22 -
451.23 -Not Searchable Keys:
452.1 --- a/python.editor/test/unit/data/testfiles/properties.py.testProperties.completion Sun Jan 04 13:11:53 2015 -0600
452.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
452.3 @@ -1,4 +0,0 @@
452.4 -Code completion result for source line:
452.5 -x.ba|r
452.6 -(QueryType=COMPLETION, NameKind=PREFIX)
452.7 -ATTRIBUTE bar
453.1 --- a/python.editor/test/unit/data/testfiles/rawstringdoc.py Sun Jan 04 13:11:53 2015 -0600
453.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
453.3 @@ -1,24 +0,0 @@
453.4 -r"""OS routines for Java, with some attempts to support NT, and Posix
453.5 -functionality.
453.6 -
453.7 -This exports:
453.8 - - all functions from posix, nt, dos, os2, mac, or ce, e.g. unlink, stat, etc.
453.9 - - os.path is one of the modules posixpath, ntpath, macpath, or dospath
453.10 - - os.name is 'posix', 'nt', 'dos', 'os2', 'mac', 'ce' or 'riscos'
453.11 - - os.curdir is a string representing the current directory ('.' or ':')
453.12 - - os.pardir is a string representing the parent directory ('..' or '::')
453.13 - - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
453.14 - - os.altsep is the alternate pathname separator (None or '/')
453.15 - - os.pathsep is the component separator used in $PATH etc
453.16 - - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
453.17 - - os.defpath is the default search path for executables
453.18 -
453.19 -Programs that import and use 'os' stand a better chance of being
453.20 -portable between different platforms. Of course, they must then
453.21 -only use functions that are defined by all platforms (e.g., unlink
453.22 -and opendir), and leave all pathname manipulation to os.path
453.23 -(e.g., split and join).
453.24 -"""
453.25 -
453.26 -import rawstringdoc
453.27 -
454.1 --- a/python.editor/test/unit/data/testfiles/rawstringdoc.py.html Sun Jan 04 13:11:53 2015 -0600
454.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
454.3 @@ -1,28 +0,0 @@
454.4 -<html><body>
454.5 -<h2 style="color: green">Next Comment</h2>
454.6 -<pre><b>rawstringdoc.py</b></pre>
454.7 -
454.8 -<hr>
454.9 -OS routines for Java, with some attempts to support NT, and Posix
454.10 -functionality.
454.11 -
454.12 -<br><br>
454.13 -This exports:
454.14 -<br> - all functions from posix, nt, dos, os2, mac, or ce, e.g. unlink, stat, etc.
454.15 -<br> - os.path is one of the modules posixpath, ntpath, macpath, or dospath
454.16 -<br> - os.name is 'posix', 'nt', 'dos', 'os2', 'mac', 'ce' or 'riscos'
454.17 -<br> - os.curdir is a string representing the current directory ('.' or ':')
454.18 -<br> - os.pardir is a string representing the parent directory ('..' or '::')
454.19 -<br> - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
454.20 -<br> - os.altsep is the alternate pathname separator (None or '/')
454.21 -<br> - os.pathsep is the component separator used in $PATH etc
454.22 -<br> - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
454.23 -<br> - os.defpath is the default search path for executables
454.24 -
454.25 -<br><br>
454.26 -Programs that import and use 'os' stand a better chance of being
454.27 -portable between different platforms. Of course, they must then
454.28 -only use functions that are defined by all platforms (e.g., unlink
454.29 -and opendir), and leave all pathname manipulation to os.path
454.30 -(e.g., split and join).
454.31 -</body></html>
455.1 --- a/python.editor/test/unit/data/testfiles/rst/bz2.rst Sun Jan 04 13:11:53 2015 -0600
455.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
455.3 @@ -1,197 +0,0 @@
455.4 -
455.5 -:mod:`bz2` --- Compression compatible with :program:`bzip2`
455.6 -===========================================================
455.7 -
455.8 -.. module:: bz2
455.9 - :synopsis: Interface to compression and decompression routines compatible with bzip2.
455.10 -.. moduleauthor:: Gustavo Niemeyer <niemeyer@conectiva.com>
455.11 -.. sectionauthor:: Gustavo Niemeyer <niemeyer@conectiva.com>
455.12 -
455.13 -
455.14 -.. versionadded:: 2.3
455.15 -
455.16 -This module provides a comprehensive interface for the bz2 compression library.
455.17 -It implements a complete file interface, one-shot (de)compression functions, and
455.18 -types for sequential (de)compression.
455.19 -
455.20 -For other archive formats, see the :mod:`gzip`, :mod:`zipfile`, and
455.21 -:mod:`tarfile` modules.
455.22 -
455.23 -Here is a summary of the features offered by the bz2 module:
455.24 -
455.25 -* :class:`BZ2File` class implements a complete file interface, including
455.26 - :meth:`readline`, :meth:`readlines`, :meth:`writelines`, :meth:`seek`, etc;
455.27 -
455.28 -* :class:`BZ2File` class implements emulated :meth:`seek` support;
455.29 -
455.30 -* :class:`BZ2File` class implements universal newline support;
455.31 -
455.32 -* :class:`BZ2File` class offers an optimized line iteration using the readahead
455.33 - algorithm borrowed from file objects;
455.34 -
455.35 -* Sequential (de)compression supported by :class:`BZ2Compressor` and
455.36 - :class:`BZ2Decompressor` classes;
455.37 -
455.38 -* One-shot (de)compression supported by :func:`compress` and :func:`decompress`
455.39 - functions;
455.40 -
455.41 -* Thread safety uses individual locking mechanism.
455.42 -
455.43 -
455.44 -(De)compression of files
455.45 -------------------------
455.46 -
455.47 -Handling of compressed files is offered by the :class:`BZ2File` class.
455.48 -
455.49 -
455.50 -.. class:: BZ2File(filename[, mode[, buffering[, compresslevel]]])
455.51 -
455.52 - Open a bz2 file. Mode can be either ``'r'`` or ``'w'``, for reading (default)
455.53 - or writing. When opened for writing, the file will be created if it doesn't
455.54 - exist, and truncated otherwise. If *buffering* is given, ``0`` means
455.55 - unbuffered, and larger numbers specify the buffer size; the default is
455.56 - ``0``. If *compresslevel* is given, it must be a number between ``1`` and
455.57 - ``9``; the default is ``9``. Add a ``'U'`` to mode to open the file for input
455.58 - with universal newline support. Any line ending in the input file will be
455.59 - seen as a ``'\n'`` in Python. Also, a file so opened gains the attribute
455.60 - :attr:`newlines`; the value for this attribute is one of ``None`` (no newline
455.61 - read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the
455.62 - newline types seen. Universal newlines are available only when
455.63 - reading. Instances support iteration in the same way as normal :class:`file`
455.64 - instances.
455.65 -
455.66 -
455.67 - .. method:: close()
455.68 -
455.69 - Close the file. Sets data attribute :attr:`closed` to true. A closed file
455.70 - cannot be used for further I/O operations. :meth:`close` may be called
455.71 - more than once without error.
455.72 -
455.73 -
455.74 - .. method:: read([size])
455.75 -
455.76 - Read at most *size* uncompressed bytes, returned as a string. If the
455.77 - *size* argument is negative or omitted, read until EOF is reached.
455.78 -
455.79 -
455.80 - .. method:: readline([size])
455.81 -
455.82 - Return the next line from the file, as a string, retaining newline. A
455.83 - non-negative *size* argument limits the maximum number of bytes to return
455.84 - (an incomplete line may be returned then). Return an empty string at EOF.
455.85 -
455.86 -
455.87 - .. method:: readlines([size])
455.88 -
455.89 - Return a list of lines read. The optional *size* argument, if given, is an
455.90 - approximate bound on the total number of bytes in the lines returned.
455.91 -
455.92 -
455.93 - .. method:: xreadlines()
455.94 -
455.95 - For backward compatibility. :class:`BZ2File` objects now include the
455.96 - performance optimizations previously implemented in the :mod:`xreadlines`
455.97 - module.
455.98 -
455.99 - .. deprecated:: 2.3
455.100 - This exists only for compatibility with the method by this name on
455.101 - :class:`file` objects, which is deprecated. Use ``for line in file``
455.102 - instead.
455.103 -
455.104 -
455.105 - .. method:: seek(offset[, whence])
455.106 -
455.107 - Move to new file position. Argument *offset* is a byte count. Optional
455.108 - argument *whence* defaults to ``os.SEEK_SET`` or ``0`` (offset from start
455.109 - of file; offset should be ``>= 0``); other values are ``os.SEEK_CUR`` or
455.110 - ``1`` (move relative to current position; offset can be positive or
455.111 - negative), and ``os.SEEK_END`` or ``2`` (move relative to end of file;
455.112 - offset is usually negative, although many platforms allow seeking beyond
455.113 - the end of a file).
455.114 -
455.115 - Note that seeking of bz2 files is emulated, and depending on the
455.116 - parameters the operation may be extremely slow.
455.117 -
455.118 -
455.119 - .. method:: tell()
455.120 -
455.121 - Return the current file position, an integer (may be a long integer).
455.122 -
455.123 -
455.124 - .. method:: write(data)
455.125 -
455.126 - Write string *data* to file. Note that due to buffering, :meth:`close` may
455.127 - be needed before the file on disk reflects the data written.
455.128 -
455.129 -
455.130 - .. method:: writelines(sequence_of_strings)
455.131 -
455.132 - Write the sequence of strings to the file. Note that newlines are not
455.133 - added. The sequence can be any iterable object producing strings. This is
455.134 - equivalent to calling write() for each string.
455.135 -
455.136 -
455.137 -Sequential (de)compression
455.138 ---------------------------
455.139 -
455.140 -Sequential compression and decompression is done using the classes
455.141 -:class:`BZ2Compressor` and :class:`BZ2Decompressor`.
455.142 -
455.143 -
455.144 -.. class:: BZ2Compressor([compresslevel])
455.145 -
455.146 - Create a new compressor object. This object may be used to compress data
455.147 - sequentially. If you want to compress data in one shot, use the
455.148 - :func:`compress` function instead. The *compresslevel* parameter, if given,
455.149 - must be a number between ``1`` and ``9``; the default is ``9``.
455.150 -
455.151 -
455.152 - .. method:: compress(data)
455.153 -
455.154 - Provide more data to the compressor object. It will return chunks of
455.155 - compressed data whenever possible. When you've finished providing data to
455.156 - compress, call the :meth:`flush` method to finish the compression process,
455.157 - and return what is left in internal buffers.
455.158 -
455.159 -
455.160 - .. method:: flush()
455.161 -
455.162 - Finish the compression process and return what is left in internal
455.163 - buffers. You must not use the compressor object after calling this method.
455.164 -
455.165 -
455.166 -.. class:: BZ2Decompressor()
455.167 -
455.168 - Create a new decompressor object. This object may be used to decompress data
455.169 - sequentially. If you want to decompress data in one shot, use the
455.170 - :func:`decompress` function instead.
455.171 -
455.172 -
455.173 - .. method:: decompress(data)
455.174 -
455.175 - Provide more data to the decompressor object. It will return chunks of
455.176 - decompressed data whenever possible. If you try to decompress data after
455.177 - the end of stream is found, :exc:`EOFError` will be raised. If any data
455.178 - was found after the end of stream, it'll be ignored and saved in
455.179 - :attr:`unused_data` attribute.
455.180 -
455.181 -
455.182 -One-shot (de)compression
455.183 -------------------------
455.184 -
455.185 -One-shot compression and decompression is provided through the :func:`compress`
455.186 -and :func:`decompress` functions.
455.187 -
455.188 -
455.189 -.. function:: compress(data[, compresslevel])
455.190 -
455.191 - Compress *data* in one shot. If you want to compress data sequentially, use
455.192 - an instance of :class:`BZ2Compressor` instead. The *compresslevel* parameter,
455.193 - if given, must be a number between ``1`` and ``9``; the default is ``9``.
455.194 -
455.195 -
455.196 -.. function:: decompress(data)
455.197 -
455.198 - Decompress *data* in one shot. If you want to decompress data sequentially,
455.199 - use an instance of :class:`BZ2Decompressor` instead.
455.200 -
456.1 --- a/python.editor/test/unit/data/testfiles/rst/bz2.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,58 +0,0 @@
456.4 -
456.5 -
456.6 -Document 0
456.7 -Searchable Keys:
456.8 - class : BZ2Compressor
456.9 - class-ig : bz2compressor
456.10 - in : bz2
456.11 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;compresslevel;
456.12 - member : compress;F;|DOCUMENTED|DOC_ONLY|;data;
456.13 - member : flush;F;|DOCUMENTED|DOC_ONLY|;;
456.14 -
456.15 -Not Searchable Keys:
456.16 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
456.17 -
456.18 -
456.19 -Document 1
456.20 -Searchable Keys:
456.21 - class : BZ2Decompressor
456.22 - class-ig : bz2decompressor
456.23 - in : bz2
456.24 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
456.25 - member : decompress;F;|DOCUMENTED|DOC_ONLY|;data;
456.26 -
456.27 -Not Searchable Keys:
456.28 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
456.29 -
456.30 -
456.31 -Document 2
456.32 -Searchable Keys:
456.33 - class : BZ2File
456.34 - class-ig : bz2file
456.35 - in : bz2
456.36 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;filename,mode,buffering,compresslevel;
456.37 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
456.38 - member : read;F;|DOCUMENTED|DOC_ONLY|;size;
456.39 - member : readline;F;|DOCUMENTED|DOC_ONLY|;size;
456.40 - member : readlines;F;|DOCUMENTED|DOC_ONLY|;size;
456.41 - member : seek;F;|DOCUMENTED|DOC_ONLY|;offset,whence;
456.42 - member : tell;F;|DOCUMENTED|DOC_ONLY|;;
456.43 - member : write;F;|DOCUMENTED|DOC_ONLY|;data;
456.44 - member : writelines;F;|DOCUMENTED|DOC_ONLY|;sequence_of_strings;
456.45 - member : xreadlines;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;;
456.46 -
456.47 -Not Searchable Keys:
456.48 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
456.49 -
456.50 -
456.51 -Document 3
456.52 -Searchable Keys:
456.53 - item : BZ2Compressor;C;|DOCUMENTED|DOC_ONLY|;
456.54 - item : BZ2Decompressor;C;|DOCUMENTED|DOC_ONLY|;
456.55 - item : BZ2File;C;|DOCUMENTED|DOC_ONLY|;
456.56 - item : compress;F;|DOCUMENTED|DOC_ONLY|;data,compresslevel;
456.57 - item : decompress;F;|DOCUMENTED|DOC_ONLY|;data;
456.58 - module : bz2
456.59 -
456.60 -Not Searchable Keys:
456.61 - modattrs : S
457.1 --- a/python.editor/test/unit/data/testfiles/rst/collections.rst Sun Jan 04 13:11:53 2015 -0600
457.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
457.3 @@ -1,690 +0,0 @@
457.4 -
457.5 -:mod:`collections` --- High-performance container datatypes
457.6 -===========================================================
457.7 -
457.8 -.. module:: collections
457.9 - :synopsis: High-performance datatypes
457.10 -.. moduleauthor:: Raymond Hettinger <python@rcn.com>
457.11 -.. sectionauthor:: Raymond Hettinger <python@rcn.com>
457.12 -
457.13 -.. versionadded:: 2.4
457.14 -
457.15 -.. testsetup:: *
457.16 -
457.17 - from collections import *
457.18 - import itertools
457.19 - __name__ = '<doctest>'
457.20 -
457.21 -This module implements high-performance container datatypes. Currently,
457.22 -there are two datatypes, :class:`deque` and :class:`defaultdict`, and
457.23 -one datatype factory function, :func:`namedtuple`.
457.24 -
457.25 -.. versionchanged:: 2.5
457.26 - Added :class:`defaultdict`.
457.27 -
457.28 -.. versionchanged:: 2.6
457.29 - Added :func:`namedtuple`.
457.30 -
457.31 -The specialized containers provided in this module provide alternatives
457.32 -to Python's general purpose built-in containers, :class:`dict`,
457.33 -:class:`list`, :class:`set`, and :class:`tuple`.
457.34 -
457.35 -Besides the containers provided here, the optional :mod:`bsddb`
457.36 -module offers the ability to create in-memory or file based ordered
457.37 -dictionaries with string keys using the :meth:`bsddb.btopen` method.
457.38 -
457.39 -In addition to containers, the collections module provides some ABCs
457.40 -(abstract base classes) that can be used to test whether a class
457.41 -provides a particular interface, for example, is it hashable or
457.42 -a mapping.
457.43 -
457.44 -.. versionchanged:: 2.6
457.45 - Added abstract base classes.
457.46 -
457.47 -ABCs - abstract base classes
457.48 -----------------------------
457.49 -
457.50 -The collections module offers the following ABCs:
457.51 -
457.52 -========================= ===================== ====================== ====================================================
457.53 -ABC Inherits Abstract Methods Mixin Methods
457.54 -========================= ===================== ====================== ====================================================
457.55 -:class:`Container` ``__contains__``
457.56 -:class:`Hashable` ``__hash__``
457.57 -:class:`Iterable` ``__iter__``
457.58 -:class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__``
457.59 -:class:`Sized` ``__len__``
457.60 -:class:`Callable` ``__call__``
457.61 -
457.62 -:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``. ``__iter__``, ``__reversed__``.
457.63 - :class:`Iterable`, and ``__len__`` ``index``, and ``count``
457.64 - :class:`Container`
457.65 -
457.66 -:class:`MutableSequnce` :class:`Sequence` ``__getitem__`` Inherited Sequence methods and
457.67 - ``__delitem__``, ``append``, ``reverse``, ``extend``, ``pop``,
457.68 - ``insert``, ``remove``, and ``__iadd__``
457.69 - and ``__len__``
457.70 -
457.71 -:class:`Set` :class:`Sized`, ``__len__``, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
457.72 - :class:`Iterable`, ``__iter__``, and ``__gt__``, ``__ge__``, ``__and__``, ``__or__``
457.73 - :class:`Container` ``__contains__`` ``__sub__``, ``__xor__``, and ``isdisjoint``
457.74 -
457.75 -:class:`MutableSet` :class:`Set` ``add`` and Inherited Set methods and
457.76 - ``discard`` ``clear``, ``pop``, ``remove``, ``__ior__``,
457.77 - ``__iand__``, ``__ixor__``, and ``__isub__``
457.78 -
457.79 -:class:`Mapping` :class:`Sized`, ``__getitem__``, ``__contains__``, ``keys``, ``items``, ``values``,
457.80 - :class:`Iterable`, ``__len__``. and ``get``, ``__eq__``, and ``__ne__``
457.81 - :class:`Container` ``__iter__``
457.82 -
457.83 -:class:`MutableMapping` :class:`Mapping` ``__getitem__`` Inherited Mapping methods and
457.84 - ``__setitem__``, ``pop``, ``popitem``, ``clear``, ``update``,
457.85 - ``__delitem__``, and ``setdefault``
457.86 - ``__iter__``, and
457.87 - ``__len__``
457.88 -
457.89 -:class:`MappingView` :class:`Sized` ``__len__``
457.90 -:class:`KeysView` :class:`MappingView`, ``__contains__``,
457.91 - :class:`Set` ``__iter__``
457.92 -:class:`ItemsView` :class:`MappingView`, ``__contains__``,
457.93 - :class:`Set` ``__iter__``
457.94 -:class:`ValuesView` :class:`MappingView` ``__contains__``, ``__iter__``
457.95 -========================= ===================== ====================== ====================================================
457.96 -
457.97 -These ABCs allow us to ask classes or instances if they provide
457.98 -particular functionality, for example::
457.99 -
457.100 - size = None
457.101 - if isinstance(myvar, collections.Sized):
457.102 - size = len(myvar)
457.103 -
457.104 -Several of the ABCs are also useful as mixins that make it easier to develop
457.105 -classes supporting container APIs. For example, to write a class supporting
457.106 -the full :class:`Set` API, it only necessary to supply the three underlying
457.107 -abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
457.108 -The ABC supplies the remaining methods such as :meth:`__and__` and
457.109 -:meth:`isdisjoint` ::
457.110 -
457.111 - class ListBasedSet(collections.Set):
457.112 - ''' Alternate set implementation favoring space over speed
457.113 - and not requiring the set elements to be hashable. '''
457.114 - def __init__(self, iterable):
457.115 - self.elements = lst = []
457.116 - for value in iterable:
457.117 - if value not in lst:
457.118 - lst.append(value)
457.119 - def __iter__(self):
457.120 - return iter(self.elements)
457.121 - def __contains__(self, value):
457.122 - return value in self.elements
457.123 - def __len__(self):
457.124 - return len(self.elements)
457.125 -
457.126 - s1 = ListBasedSet('abcdef')
457.127 - s2 = ListBasedSet('defghi')
457.128 - overlap = s1 & s2 # The __and__() method is supported automatically
457.129 -
457.130 -Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
457.131 -
457.132 -(1)
457.133 - Since some set operations create new sets, the default mixin methods need
457.134 - a way to create new instances from an iterable. The class constructor is
457.135 - assumed to have a signature in the form ``ClassName(iterable)``.
457.136 - That assumption is factored-out to an internal classmethod called
457.137 - :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
457.138 - If the :class:`Set` mixin is being used in a class with a different
457.139 - constructor signature, you will need to override :meth:`from_iterable`
457.140 - with a classmethod that can construct new instances from
457.141 - an iterable argument.
457.142 -
457.143 -(2)
457.144 - To override the comparisons (presumably for speed, as the
457.145 - semantics are fixed), redefine :meth:`__le__` and
457.146 - then the other operations will automatically follow suit.
457.147 -
457.148 -(3)
457.149 - The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value
457.150 - for the set; however, :meth:`__hash__` is not defined because not all sets
457.151 - are hashable or immutable. To add set hashabilty using mixins,
457.152 - inherit from both :meth:`Set` and :meth:`Hashable`, then define
457.153 - ``__hash__ = Set._hash``.
457.154 -
457.155 -(For more about ABCs, see the :mod:`abc` module and :pep:`3119`.)
457.156 -
457.157 -
457.158 -
457.159 -.. _deque-objects:
457.160 -
457.161 -:class:`deque` objects
457.162 -----------------------
457.163 -
457.164 -
457.165 -.. class:: deque([iterable[, maxlen]])
457.166 -
457.167 - Returns a new deque object initialized left-to-right (using :meth:`append`) with
457.168 - data from *iterable*. If *iterable* is not specified, the new deque is empty.
457.169 -
457.170 - Deques are a generalization of stacks and queues (the name is pronounced "deck"
457.171 - and is short for "double-ended queue"). Deques support thread-safe, memory
457.172 - efficient appends and pops from either side of the deque with approximately the
457.173 - same O(1) performance in either direction.
457.174 -
457.175 - Though :class:`list` objects support similar operations, they are optimized for
457.176 - fast fixed-length operations and incur O(n) memory movement costs for
457.177 - ``pop(0)`` and ``insert(0, v)`` operations which change both the size and
457.178 - position of the underlying data representation.
457.179 -
457.180 - .. versionadded:: 2.4
457.181 -
457.182 - If *maxlen* is not specified or is *None*, deques may grow to an
457.183 - arbitrary length. Otherwise, the deque is bounded to the specified maximum
457.184 - length. Once a bounded length deque is full, when new items are added, a
457.185 - corresponding number of items are discarded from the opposite end. Bounded
457.186 - length deques provide functionality similar to the ``tail`` filter in
457.187 - Unix. They are also useful for tracking transactions and other pools of data
457.188 - where only the most recent activity is of interest.
457.189 -
457.190 - .. versionchanged:: 2.6
457.191 - Added *maxlen* parameter.
457.192 -
457.193 - Deque objects support the following methods:
457.194 -
457.195 -
457.196 - .. method:: append(x)
457.197 -
457.198 - Add *x* to the right side of the deque.
457.199 -
457.200 -
457.201 - .. method:: appendleft(x)
457.202 -
457.203 - Add *x* to the left side of the deque.
457.204 -
457.205 -
457.206 - .. method:: clear()
457.207 -
457.208 - Remove all elements from the deque leaving it with length 0.
457.209 -
457.210 -
457.211 - .. method:: extend(iterable)
457.212 -
457.213 - Extend the right side of the deque by appending elements from the iterable
457.214 - argument.
457.215 -
457.216 -
457.217 - .. method:: extendleft(iterable)
457.218 -
457.219 - Extend the left side of the deque by appending elements from *iterable*.
457.220 - Note, the series of left appends results in reversing the order of
457.221 - elements in the iterable argument.
457.222 -
457.223 -
457.224 - .. method:: pop()
457.225 -
457.226 - Remove and return an element from the right side of the deque. If no
457.227 - elements are present, raises an :exc:`IndexError`.
457.228 -
457.229 -
457.230 - .. method:: popleft()
457.231 -
457.232 - Remove and return an element from the left side of the deque. If no
457.233 - elements are present, raises an :exc:`IndexError`.
457.234 -
457.235 -
457.236 - .. method:: remove(value)
457.237 -
457.238 - Removed the first occurrence of *value*. If not found, raises a
457.239 - :exc:`ValueError`.
457.240 -
457.241 - .. versionadded:: 2.5
457.242 -
457.243 -
457.244 - .. method:: rotate(n)
457.245 -
457.246 - Rotate the deque *n* steps to the right. If *n* is negative, rotate to
457.247 - the left. Rotating one step to the right is equivalent to:
457.248 - ``d.appendleft(d.pop())``.
457.249 -
457.250 -
457.251 -In addition to the above, deques support iteration, pickling, ``len(d)``,
457.252 -``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with
457.253 -the :keyword:`in` operator, and subscript references such as ``d[-1]``.
457.254 -
457.255 -Example:
457.256 -
457.257 -.. doctest::
457.258 -
457.259 - >>> from collections import deque
457.260 - >>> d = deque('ghi') # make a new deque with three items
457.261 - >>> for elem in d: # iterate over the deque's elements
457.262 - ... print elem.upper()
457.263 - G
457.264 - H
457.265 - I
457.266 -
457.267 - >>> d.append('j') # add a new entry to the right side
457.268 - >>> d.appendleft('f') # add a new entry to the left side
457.269 - >>> d # show the representation of the deque
457.270 - deque(['f', 'g', 'h', 'i', 'j'])
457.271 -
457.272 - >>> d.pop() # return and remove the rightmost item
457.273 - 'j'
457.274 - >>> d.popleft() # return and remove the leftmost item
457.275 - 'f'
457.276 - >>> list(d) # list the contents of the deque
457.277 - ['g', 'h', 'i']
457.278 - >>> d[0] # peek at leftmost item
457.279 - 'g'
457.280 - >>> d[-1] # peek at rightmost item
457.281 - 'i'
457.282 -
457.283 - >>> list(reversed(d)) # list the contents of a deque in reverse
457.284 - ['i', 'h', 'g']
457.285 - >>> 'h' in d # search the deque
457.286 - True
457.287 - >>> d.extend('jkl') # add multiple elements at once
457.288 - >>> d
457.289 - deque(['g', 'h', 'i', 'j', 'k', 'l'])
457.290 - >>> d.rotate(1) # right rotation
457.291 - >>> d
457.292 - deque(['l', 'g', 'h', 'i', 'j', 'k'])
457.293 - >>> d.rotate(-1) # left rotation
457.294 - >>> d
457.295 - deque(['g', 'h', 'i', 'j', 'k', 'l'])
457.296 -
457.297 - >>> deque(reversed(d)) # make a new deque in reverse order
457.298 - deque(['l', 'k', 'j', 'i', 'h', 'g'])
457.299 - >>> d.clear() # empty the deque
457.300 - >>> d.pop() # cannot pop from an empty deque
457.301 - Traceback (most recent call last):
457.302 - File "<pyshell#6>", line 1, in -toplevel-
457.303 - d.pop()
457.304 - IndexError: pop from an empty deque
457.305 -
457.306 - >>> d.extendleft('abc') # extendleft() reverses the input order
457.307 - >>> d
457.308 - deque(['c', 'b', 'a'])
457.309 -
457.310 -
457.311 -.. _deque-recipes:
457.312 -
457.313 -:class:`deque` Recipes
457.314 -^^^^^^^^^^^^^^^^^^^^^^
457.315 -
457.316 -This section shows various approaches to working with deques.
457.317 -
457.318 -The :meth:`rotate` method provides a way to implement :class:`deque` slicing and
457.319 -deletion. For example, a pure python implementation of ``del d[n]`` relies on
457.320 -the :meth:`rotate` method to position elements to be popped::
457.321 -
457.322 - def delete_nth(d, n):
457.323 - d.rotate(-n)
457.324 - d.popleft()
457.325 - d.rotate(n)
457.326 -
457.327 -To implement :class:`deque` slicing, use a similar approach applying
457.328 -:meth:`rotate` to bring a target element to the left side of the deque. Remove
457.329 -old entries with :meth:`popleft`, add new entries with :meth:`extend`, and then
457.330 -reverse the rotation.
457.331 -With minor variations on that approach, it is easy to implement Forth style
457.332 -stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``,
457.333 -``rot``, and ``roll``.
457.334 -
457.335 -Multi-pass data reduction algorithms can be succinctly expressed and efficiently
457.336 -coded by extracting elements with multiple calls to :meth:`popleft`, applying
457.337 -a reduction function, and calling :meth:`append` to add the result back to the
457.338 -deque.
457.339 -
457.340 -For example, building a balanced binary tree of nested lists entails reducing
457.341 -two adjacent nodes into one by grouping them in a list:
457.342 -
457.343 - >>> def maketree(iterable):
457.344 - ... d = deque(iterable)
457.345 - ... while len(d) > 1:
457.346 - ... pair = [d.popleft(), d.popleft()]
457.347 - ... d.append(pair)
457.348 - ... return list(d)
457.349 - ...
457.350 - >>> print maketree('abcdefgh')
457.351 - [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
457.352 -
457.353 -Bounded length deques provide functionality similar to the ``tail`` filter
457.354 -in Unix::
457.355 -
457.356 - def tail(filename, n=10):
457.357 - 'Return the last n lines of a file'
457.358 - return deque(open(filename), n)
457.359 -
457.360 -.. _defaultdict-objects:
457.361 -
457.362 -:class:`defaultdict` objects
457.363 -----------------------------
457.364 -
457.365 -
457.366 -.. class:: defaultdict([default_factory[, ...]])
457.367 -
457.368 - Returns a new dictionary-like object. :class:`defaultdict` is a subclass of the
457.369 - builtin :class:`dict` class. It overrides one method and adds one writable
457.370 - instance variable. The remaining functionality is the same as for the
457.371 - :class:`dict` class and is not documented here.
457.372 -
457.373 - The first argument provides the initial value for the :attr:`default_factory`
457.374 - attribute; it defaults to ``None``. All remaining arguments are treated the same
457.375 - as if they were passed to the :class:`dict` constructor, including keyword
457.376 - arguments.
457.377 -
457.378 - .. versionadded:: 2.5
457.379 -
457.380 - :class:`defaultdict` objects support the following method in addition to the
457.381 - standard :class:`dict` operations:
457.382 -
457.383 -
457.384 - .. method:: defaultdict.__missing__(key)
457.385 -
457.386 - If the :attr:`default_factory` attribute is ``None``, this raises a
457.387 - :exc:`KeyError` exception with the *key* as argument.
457.388 -
457.389 - If :attr:`default_factory` is not ``None``, it is called without arguments
457.390 - to provide a default value for the given *key*, this value is inserted in
457.391 - the dictionary for the *key*, and returned.
457.392 -
457.393 - If calling :attr:`default_factory` raises an exception this exception is
457.394 - propagated unchanged.
457.395 -
457.396 - This method is called by the :meth:`__getitem__` method of the
457.397 - :class:`dict` class when the requested key is not found; whatever it
457.398 - returns or raises is then returned or raised by :meth:`__getitem__`.
457.399 -
457.400 -
457.401 - :class:`defaultdict` objects support the following instance variable:
457.402 -
457.403 -
457.404 - .. attribute:: defaultdict.default_factory
457.405 -
457.406 - This attribute is used by the :meth:`__missing__` method; it is
457.407 - initialized from the first argument to the constructor, if present, or to
457.408 - ``None``, if absent.
457.409 -
457.410 -
457.411 -.. _defaultdict-examples:
457.412 -
457.413 -:class:`defaultdict` Examples
457.414 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
457.415 -
457.416 -Using :class:`list` as the :attr:`default_factory`, it is easy to group a
457.417 -sequence of key-value pairs into a dictionary of lists:
457.418 -
457.419 - >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
457.420 - >>> d = defaultdict(list)
457.421 - >>> for k, v in s:
457.422 - ... d[k].append(v)
457.423 - ...
457.424 - >>> d.items()
457.425 - [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
457.426 -
457.427 -When each key is encountered for the first time, it is not already in the
457.428 -mapping; so an entry is automatically created using the :attr:`default_factory`
457.429 -function which returns an empty :class:`list`. The :meth:`list.append`
457.430 -operation then attaches the value to the new list. When keys are encountered
457.431 -again, the look-up proceeds normally (returning the list for that key) and the
457.432 -:meth:`list.append` operation adds another value to the list. This technique is
457.433 -simpler and faster than an equivalent technique using :meth:`dict.setdefault`:
457.434 -
457.435 - >>> d = {}
457.436 - >>> for k, v in s:
457.437 - ... d.setdefault(k, []).append(v)
457.438 - ...
457.439 - >>> d.items()
457.440 - [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
457.441 -
457.442 -Setting the :attr:`default_factory` to :class:`int` makes the
457.443 -:class:`defaultdict` useful for counting (like a bag or multiset in other
457.444 -languages):
457.445 -
457.446 - >>> s = 'mississippi'
457.447 - >>> d = defaultdict(int)
457.448 - >>> for k in s:
457.449 - ... d[k] += 1
457.450 - ...
457.451 - >>> d.items()
457.452 - [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
457.453 -
457.454 -When a letter is first encountered, it is missing from the mapping, so the
457.455 -:attr:`default_factory` function calls :func:`int` to supply a default count of
457.456 -zero. The increment operation then builds up the count for each letter.
457.457 -
457.458 -The function :func:`int` which always returns zero is just a special case of
457.459 -constant functions. A faster and more flexible way to create constant functions
457.460 -is to use :func:`itertools.repeat` which can supply any constant value (not just
457.461 -zero):
457.462 -
457.463 - >>> def constant_factory(value):
457.464 - ... return itertools.repeat(value).next
457.465 - >>> d = defaultdict(constant_factory('<missing>'))
457.466 - >>> d.update(name='John', action='ran')
457.467 - >>> '%(name)s %(action)s to %(object)s' % d
457.468 - 'John ran to <missing>'
457.469 -
457.470 -Setting the :attr:`default_factory` to :class:`set` makes the
457.471 -:class:`defaultdict` useful for building a dictionary of sets:
457.472 -
457.473 - >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
457.474 - >>> d = defaultdict(set)
457.475 - >>> for k, v in s:
457.476 - ... d[k].add(v)
457.477 - ...
457.478 - >>> d.items()
457.479 - [('blue', set([2, 4])), ('red', set([1, 3]))]
457.480 -
457.481 -
457.482 -.. _named-tuple-factory:
457.483 -
457.484 -:func:`namedtuple` Factory Function for Tuples with Named Fields
457.485 -----------------------------------------------------------------
457.486 -
457.487 -Named tuples assign meaning to each position in a tuple and allow for more readable,
457.488 -self-documenting code. They can be used wherever regular tuples are used, and
457.489 -they add the ability to access fields by name instead of position index.
457.490 -
457.491 -.. function:: namedtuple(typename, fieldnames, [verbose])
457.492 -
457.493 - Returns a new tuple subclass named *typename*. The new subclass is used to
457.494 - create tuple-like objects that have fields accessible by attribute lookup as
457.495 - well as being indexable and iterable. Instances of the subclass also have a
457.496 - helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__`
457.497 - method which lists the tuple contents in a ``name=value`` format.
457.498 -
457.499 - The *fieldnames* are a single string with each fieldname separated by whitespace
457.500 - and/or commas, for example ``'x y'`` or ``'x, y'``. Alternatively, *fieldnames*
457.501 - can be a sequence of strings such as ``['x', 'y']``.
457.502 -
457.503 - Any valid Python identifier may be used for a fieldname except for names
457.504 - starting with an underscore. Valid identifiers consist of letters, digits,
457.505 - and underscores but do not start with a digit or underscore and cannot be
457.506 - a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, *print*,
457.507 - or *raise*.
457.508 -
457.509 - If *verbose* is true, the class definition is printed just before being built.
457.510 -
457.511 - Named tuple instances do not have per-instance dictionaries, so they are
457.512 - lightweight and require no more memory than regular tuples.
457.513 -
457.514 - .. versionadded:: 2.6
457.515 -
457.516 -Example:
457.517 -
457.518 -.. doctest::
457.519 - :options: +NORMALIZE_WHITESPACE
457.520 -
457.521 - >>> Point = namedtuple('Point', 'x y', verbose=True)
457.522 - class Point(tuple):
457.523 - 'Point(x, y)'
457.524 - <BLANKLINE>
457.525 - __slots__ = ()
457.526 - <BLANKLINE>
457.527 - _fields = ('x', 'y')
457.528 - <BLANKLINE>
457.529 - def __new__(cls, x, y):
457.530 - return tuple.__new__(cls, (x, y))
457.531 - <BLANKLINE>
457.532 - @classmethod
457.533 - def _make(cls, iterable, new=tuple.__new__, len=len):
457.534 - 'Make a new Point object from a sequence or iterable'
457.535 - result = new(cls, iterable)
457.536 - if len(result) != 2:
457.537 - raise TypeError('Expected 2 arguments, got %d' % len(result))
457.538 - return result
457.539 - <BLANKLINE>
457.540 - def __repr__(self):
457.541 - return 'Point(x=%r, y=%r)' % self
457.542 - <BLANKLINE>
457.543 - def _asdict(t):
457.544 - 'Return a new dict which maps field names to their values'
457.545 - return {'x': t[0], 'y': t[1]}
457.546 - <BLANKLINE>
457.547 - def _replace(self, **kwds):
457.548 - 'Return a new Point object replacing specified fields with new values'
457.549 - result = self._make(map(kwds.pop, ('x', 'y'), self))
457.550 - if kwds:
457.551 - raise ValueError('Got unexpected field names: %r' % kwds.keys())
457.552 - return result
457.553 - <BLANKLINE>
457.554 - def __getnewargs__(self):
457.555 - return tuple(self)
457.556 - <BLANKLINE>
457.557 - x = property(itemgetter(0))
457.558 - y = property(itemgetter(1))
457.559 -
457.560 - >>> p = Point(11, y=22) # instantiate with positional or keyword arguments
457.561 - >>> p[0] + p[1] # indexable like the plain tuple (11, 22)
457.562 - 33
457.563 - >>> x, y = p # unpack like a regular tuple
457.564 - >>> x, y
457.565 - (11, 22)
457.566 - >>> p.x + p.y # fields also accessible by name
457.567 - 33
457.568 - >>> p # readable __repr__ with a name=value style
457.569 - Point(x=11, y=22)
457.570 -
457.571 -Named tuples are especially useful for assigning field names to result tuples returned
457.572 -by the :mod:`csv` or :mod:`sqlite3` modules::
457.573 -
457.574 - EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
457.575 -
457.576 - import csv
457.577 - for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
457.578 - print emp.name, emp.title
457.579 -
457.580 - import sqlite3
457.581 - conn = sqlite3.connect('/companydata')
457.582 - cursor = conn.cursor()
457.583 - cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
457.584 - for emp in map(EmployeeRecord._make, cursor.fetchall()):
457.585 - print emp.name, emp.title
457.586 -
457.587 -In addition to the methods inherited from tuples, named tuples support
457.588 -three additional methods and one attribute. To prevent conflicts with
457.589 -field names, the method and attribute names start with an underscore.
457.590 -
457.591 -.. method:: somenamedtuple._make(iterable)
457.592 -
457.593 - Class method that makes a new instance from an existing sequence or iterable.
457.594 -
457.595 -.. doctest::
457.596 -
457.597 - >>> t = [11, 22]
457.598 - >>> Point._make(t)
457.599 - Point(x=11, y=22)
457.600 -
457.601 -.. method:: somenamedtuple._asdict()
457.602 -
457.603 - Return a new dict which maps field names to their corresponding values::
457.604 -
457.605 - >>> p._asdict()
457.606 - {'x': 11, 'y': 22}
457.607 -
457.608 -.. method:: somenamedtuple._replace(kwargs)
457.609 -
457.610 - Return a new instance of the named tuple replacing specified fields with new
457.611 - values:
457.612 -
457.613 -::
457.614 -
457.615 - >>> p = Point(x=11, y=22)
457.616 - >>> p._replace(x=33)
457.617 - Point(x=33, y=22)
457.618 -
457.619 - >>> for partnum, record in inventory.items():
457.620 - ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
457.621 -
457.622 -.. attribute:: somenamedtuple._fields
457.623 -
457.624 - Tuple of strings listing the field names. Useful for introspection
457.625 - and for creating new named tuple types from existing named tuples.
457.626 -
457.627 -.. doctest::
457.628 -
457.629 - >>> p._fields # view the field names
457.630 - ('x', 'y')
457.631 -
457.632 - >>> Color = namedtuple('Color', 'red green blue')
457.633 - >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
457.634 - >>> Pixel(11, 22, 128, 255, 0)
457.635 - Pixel(x=11, y=22, red=128, green=255, blue=0)
457.636 -
457.637 -To retrieve a field whose name is stored in a string, use the :func:`getattr`
457.638 -function:
457.639 -
457.640 - >>> getattr(p, 'x')
457.641 - 11
457.642 -
457.643 -To convert a dictionary to a named tuple, use the double-star-operator [#]_:
457.644 -
457.645 - >>> d = {'x': 11, 'y': 22}
457.646 - >>> Point(**d)
457.647 - Point(x=11, y=22)
457.648 -
457.649 -Since a named tuple is a regular Python class, it is easy to add or change
457.650 -functionality with a subclass. Here is how to add a calculated field and
457.651 -a fixed-width print format:
457.652 -
457.653 - >>> class Point(namedtuple('Point', 'x y')):
457.654 - ... __slots__ = ()
457.655 - ... @property
457.656 - ... def hypot(self):
457.657 - ... return (self.x ** 2 + self.y ** 2) ** 0.5
457.658 - ... def __str__(self):
457.659 - ... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
457.660 -
457.661 - >>> for p in Point(3, 4), Point(14, 5/7.):
457.662 - ... print p
457.663 - Point: x= 3.000 y= 4.000 hypot= 5.000
457.664 - Point: x=14.000 y= 0.714 hypot=14.018
457.665 -
457.666 -The subclass shown above sets ``__slots__`` to an empty tuple. This keeps
457.667 -keep memory requirements low by preventing the creation of instance dictionaries.
457.668 -
457.669 -Subclassing is not useful for adding new, stored fields. Instead, simply
457.670 -create a new named tuple type from the :attr:`_fields` attribute:
457.671 -
457.672 - >>> Point3D = namedtuple('Point3D', Point._fields + ('z',))
457.673 -
457.674 -Default values can be implemented by using :meth:`_replace` to
457.675 -customize a prototype instance:
457.676 -
457.677 - >>> Account = namedtuple('Account', 'owner balance transaction_count')
457.678 - >>> default_account = Account('<owner name>', 0.0, 0)
457.679 - >>> johns_account = default_account._replace(owner='John')
457.680 -
457.681 -Enumerated constants can be implemented with named tuples, but it is simpler
457.682 -and more efficient to use a simple class declaration:
457.683 -
457.684 - >>> Status = namedtuple('Status', 'open pending closed')._make(range(3))
457.685 - >>> Status.open, Status.pending, Status.closed
457.686 - (0, 1, 2)
457.687 - >>> class Status:
457.688 - ... open, pending, closed = range(3)
457.689 -
457.690 -.. rubric:: Footnotes
457.691 -
457.692 -.. [#] For information on the double-star-operator see
457.693 - :ref:`tut-unpacking-arguments` and :ref:`calls`.
458.1 --- a/python.editor/test/unit/data/testfiles/rst/collections.rst.indexed Sun Jan 04 13:11:53 2015 -0600
458.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
458.3 @@ -1,44 +0,0 @@
458.4 -
458.5 -
458.6 -Document 0
458.7 -Searchable Keys:
458.8 - class : defaultdict
458.9 - class-ig : defaultdict
458.10 - in : collections
458.11 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;default_factory;
458.12 - member : __missing__;F;|DOCUMENTED|DOC_ONLY|;key;
458.13 - member : default_factory;A;|DOCUMENTED|DOC_ONLY|;
458.14 -
458.15 -Not Searchable Keys:
458.16 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
458.17 -
458.18 -
458.19 -Document 1
458.20 -Searchable Keys:
458.21 - class : deque
458.22 - class-ig : deque
458.23 - in : collections
458.24 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;iterable,maxlen;
458.25 - member : append;F;|DOCUMENTED|DOC_ONLY|;x;
458.26 - member : appendleft;F;|DOCUMENTED|DOC_ONLY|;x;
458.27 - member : clear;F;|DOCUMENTED|DOC_ONLY|;;
458.28 - member : extend;F;|DOCUMENTED|DOC_ONLY|;iterable;
458.29 - member : extendleft;F;|DOCUMENTED|DOC_ONLY|;iterable;
458.30 - member : pop;F;|DOCUMENTED|DOC_ONLY|;;
458.31 - member : popleft;F;|DOCUMENTED|DOC_ONLY|;;
458.32 - member : remove;F;|DOCUMENTED|DOC_ONLY|;value;
458.33 - member : rotate;F;|DOCUMENTED|DOC_ONLY|;n;
458.34 -
458.35 -Not Searchable Keys:
458.36 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
458.37 -
458.38 -
458.39 -Document 2
458.40 -Searchable Keys:
458.41 - item : defaultdict;C;|DOCUMENTED|DOC_ONLY|;
458.42 - item : deque;C;|DOCUMENTED|DOC_ONLY|;
458.43 - item : namedtuple;F;|DOCUMENTED|DOC_ONLY|;typename,fieldnames,verbose;
458.44 - module : collections
458.45 -
458.46 -Not Searchable Keys:
458.47 - modattrs : S
459.1 --- a/python.editor/test/unit/data/testfiles/rst/constants.rst Sun Jan 04 13:11:53 2015 -0600
459.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
459.3 @@ -1,73 +0,0 @@
459.4 -Built-in Constants
459.5 -==================
459.6 -
459.7 -A small number of constants live in the built-in namespace. They are:
459.8 -
459.9 -
459.10 -.. data:: False
459.11 -
459.12 - The false value of the :class:`bool` type.
459.13 -
459.14 - .. versionadded:: 2.3
459.15 -
459.16 -
459.17 -.. data:: True
459.18 -
459.19 - The true value of the :class:`bool` type.
459.20 -
459.21 - .. versionadded:: 2.3
459.22 -
459.23 -
459.24 -.. data:: None
459.25 -
459.26 - The sole value of :attr:`types.NoneType`. ``None`` is frequently used to
459.27 - represent the absence of a value, as when default arguments are not passed to a
459.28 - function.
459.29 -
459.30 - .. versionchanged:: 2.4
459.31 - Assignments to ``None`` are illegal and raise a :exc:`SyntaxError`.
459.32 -
459.33 -
459.34 -.. data:: NotImplemented
459.35 -
459.36 - Special value which can be returned by the "rich comparison" special methods
459.37 - (:meth:`__eq__`, :meth:`__lt__`, and friends), to indicate that the comparison
459.38 - is not implemented with respect to the other type.
459.39 -
459.40 -
459.41 -.. data:: Ellipsis
459.42 -
459.43 - Special value used in conjunction with extended slicing syntax.
459.44 -
459.45 - .. XXX Someone who understands extended slicing should fill in here.
459.46 -
459.47 -
459.48 -.. data:: __debug__
459.49 -
459.50 - This constant is true if Python was not started with an :option:`-O` option.
459.51 - Assignments to :const:`__debug__` are illegal and raise a :exc:`SyntaxError`.
459.52 - See also the :keyword:`assert` statement.
459.53 -
459.54 -
459.55 -Constants added by the :mod:`site` module
459.56 ------------------------------------------
459.57 -
459.58 -The :mod:`site` module (which is imported automatically during startup, except
459.59 -if the :option:`-S` command-line option is given) adds several constants to the
459.60 -built-in namespace. They are useful for the interactive interpreter shell and
459.61 -should not be used in programs.
459.62 -
459.63 -.. data:: quit([code=None])
459.64 - exit([code=None])
459.65 -
459.66 - Objects that when printed, print a message like "Use quit() or Ctrl-D
459.67 - (i.e. EOF) to exit", and when called, raise :exc:`SystemExit` with the
459.68 - specified exit code, and when .
459.69 -
459.70 -.. data:: copyright
459.71 - license
459.72 - credits
459.73 -
459.74 - Objects that when printed, print a message like "Type license() to see the
459.75 - full license text", and when called, display the corresponding text in a
459.76 - pager-like fashion (one screen at a time).
460.1 --- a/python.editor/test/unit/data/testfiles/rst/constants.rst.indexed Sun Jan 04 13:11:53 2015 -0600
460.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
460.3 @@ -1,17 +0,0 @@
460.4 -
460.5 -
460.6 -Document 0
460.7 -Searchable Keys:
460.8 - item : Ellipsis;D;|DOCUMENTED|DOC_ONLY|;
460.9 - item : False;D;|DOCUMENTED|DOC_ONLY|;
460.10 - item : None;D;|DOCUMENTED|DOC_ONLY|;
460.11 - item : NotImplemented;D;|DOCUMENTED|DOC_ONLY|;
460.12 - item : True;D;|DOCUMENTED|DOC_ONLY|;
460.13 - item : __debug__;D;|DOCUMENTED|DOC_ONLY|;
460.14 - item : copyright;D;|DOCUMENTED|DOC_ONLY|;
460.15 - item : exit;F;|DOCUMENTED|DOC_ONLY|;code;
460.16 - item : quit;F;|DOCUMENTED|DOC_ONLY|;code;
460.17 - module : constants
460.18 -
460.19 -Not Searchable Keys:
460.20 - modattrs : S
461.1 --- a/python.editor/test/unit/data/testfiles/rst/ctypes.rst Sun Jan 04 13:11:53 2015 -0600
461.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
461.3 @@ -1,2483 +0,0 @@
461.4 -
461.5 -:mod:`ctypes` --- A foreign function library for Python.
461.6 -========================================================
461.7 -
461.8 -.. module:: ctypes
461.9 - :synopsis: A foreign function library for Python.
461.10 -.. moduleauthor:: Thomas Heller <theller@python.net>
461.11 -
461.12 -
461.13 -.. versionadded:: 2.5
461.14 -
461.15 -``ctypes`` is a foreign function library for Python. It provides C compatible
461.16 -data types, and allows calling functions in DLLs or shared libraries. It can be
461.17 -used to wrap these libraries in pure Python.
461.18 -
461.19 -
461.20 -.. _ctypes-ctypes-tutorial:
461.21 -
461.22 -ctypes tutorial
461.23 ----------------
461.24 -
461.25 -Note: The code samples in this tutorial use ``doctest`` to make sure that they
461.26 -actually work. Since some code samples behave differently under Linux, Windows,
461.27 -or Mac OS X, they contain doctest directives in comments.
461.28 -
461.29 -Note: Some code samples reference the ctypes :class:`c_int` type. This type is
461.30 -an alias for the :class:`c_long` type on 32-bit systems. So, you should not be
461.31 -confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
461.32 -they are actually the same type.
461.33 -
461.34 -
461.35 -.. _ctypes-loading-dynamic-link-libraries:
461.36 -
461.37 -Loading dynamic link libraries
461.38 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
461.39 -
461.40 -``ctypes`` exports the *cdll*, and on Windows *windll* and *oledll*
461.41 -objects, for loading dynamic link libraries.
461.42 -
461.43 -You load libraries by accessing them as attributes of these objects. *cdll*
461.44 -loads libraries which export functions using the standard ``cdecl`` calling
461.45 -convention, while *windll* libraries call functions using the ``stdcall``
461.46 -calling convention. *oledll* also uses the ``stdcall`` calling convention, and
461.47 -assumes the functions return a Windows :class:`HRESULT` error code. The error
461.48 -code is used to automatically raise a :class:`WindowsError` exception when
461.49 -the function call fails.
461.50 -
461.51 -Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
461.52 -library containing most standard C functions, and uses the cdecl calling
461.53 -convention::
461.54 -
461.55 - >>> from ctypes import *
461.56 - >>> print windll.kernel32 # doctest: +WINDOWS
461.57 - <WinDLL 'kernel32', handle ... at ...>
461.58 - >>> print cdll.msvcrt # doctest: +WINDOWS
461.59 - <CDLL 'msvcrt', handle ... at ...>
461.60 - >>> libc = cdll.msvcrt # doctest: +WINDOWS
461.61 - >>>
461.62 -
461.63 -Windows appends the usual ``.dll`` file suffix automatically.
461.64 -
461.65 -On Linux, it is required to specify the filename *including* the extension to
461.66 -load a library, so attribute access can not be used to load libraries. Either the
461.67 -:meth:`LoadLibrary` method of the dll loaders should be used, or you should load
461.68 -the library by creating an instance of CDLL by calling the constructor::
461.69 -
461.70 - >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
461.71 - <CDLL 'libc.so.6', handle ... at ...>
461.72 - >>> libc = CDLL("libc.so.6") # doctest: +LINUX
461.73 - >>> libc # doctest: +LINUX
461.74 - <CDLL 'libc.so.6', handle ... at ...>
461.75 - >>>
461.76 -
461.77 -.. XXX Add section for Mac OS X.
461.78 -
461.79 -
461.80 -.. _ctypes-accessing-functions-from-loaded-dlls:
461.81 -
461.82 -Accessing functions from loaded dlls
461.83 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
461.84 -
461.85 -Functions are accessed as attributes of dll objects::
461.86 -
461.87 - >>> from ctypes import *
461.88 - >>> libc.printf
461.89 - <_FuncPtr object at 0x...>
461.90 - >>> print windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
461.91 - <_FuncPtr object at 0x...>
461.92 - >>> print windll.kernel32.MyOwnFunction # doctest: +WINDOWS
461.93 - Traceback (most recent call last):
461.94 - File "<stdin>", line 1, in ?
461.95 - File "ctypes.py", line 239, in __getattr__
461.96 - func = _StdcallFuncPtr(name, self)
461.97 - AttributeError: function 'MyOwnFunction' not found
461.98 - >>>
461.99 -
461.100 -Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
461.101 -as well as UNICODE versions of a function. The UNICODE version is exported with
461.102 -an ``W`` appended to the name, while the ANSI version is exported with an ``A``
461.103 -appended to the name. The win32 ``GetModuleHandle`` function, which returns a
461.104 -*module handle* for a given module name, has the following C prototype, and a
461.105 -macro is used to expose one of them as ``GetModuleHandle`` depending on whether
461.106 -UNICODE is defined or not::
461.107 -
461.108 - /* ANSI version */
461.109 - HMODULE GetModuleHandleA(LPCSTR lpModuleName);
461.110 - /* UNICODE version */
461.111 - HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
461.112 -
461.113 -*windll* does not try to select one of them by magic, you must access the
461.114 -version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
461.115 -explicitly, and then call it with strings or unicode strings
461.116 -respectively.
461.117 -
461.118 -Sometimes, dlls export functions with names which aren't valid Python
461.119 -identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use ``getattr``
461.120 -to retrieve the function::
461.121 -
461.122 - >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
461.123 - <_FuncPtr object at 0x...>
461.124 - >>>
461.125 -
461.126 -On Windows, some dlls export functions not by name but by ordinal. These
461.127 -functions can be accessed by indexing the dll object with the ordinal number::
461.128 -
461.129 - >>> cdll.kernel32[1] # doctest: +WINDOWS
461.130 - <_FuncPtr object at 0x...>
461.131 - >>> cdll.kernel32[0] # doctest: +WINDOWS
461.132 - Traceback (most recent call last):
461.133 - File "<stdin>", line 1, in ?
461.134 - File "ctypes.py", line 310, in __getitem__
461.135 - func = _StdcallFuncPtr(name, self)
461.136 - AttributeError: function ordinal 0 not found
461.137 - >>>
461.138 -
461.139 -
461.140 -.. _ctypes-calling-functions:
461.141 -
461.142 -Calling functions
461.143 -^^^^^^^^^^^^^^^^^
461.144 -
461.145 -You can call these functions like any other Python callable. This example uses
461.146 -the ``time()`` function, which returns system time in seconds since the Unix
461.147 -epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
461.148 -handle.
461.149 -
461.150 -This example calls both functions with a NULL pointer (``None`` should be used
461.151 -as the NULL pointer)::
461.152 -
461.153 - >>> print libc.time(None) # doctest: +SKIP
461.154 - 1150640792
461.155 - >>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS
461.156 - 0x1d000000
461.157 - >>>
461.158 -
461.159 -``ctypes`` tries to protect you from calling functions with the wrong number of
461.160 -arguments or the wrong calling convention. Unfortunately this only works on
461.161 -Windows. It does this by examining the stack after the function returns, so
461.162 -although an error is raised the function *has* been called::
461.163 -
461.164 - >>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS
461.165 - Traceback (most recent call last):
461.166 - File "<stdin>", line 1, in ?
461.167 - ValueError: Procedure probably called with not enough arguments (4 bytes missing)
461.168 - >>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS
461.169 - Traceback (most recent call last):
461.170 - File "<stdin>", line 1, in ?
461.171 - ValueError: Procedure probably called with too many arguments (4 bytes in excess)
461.172 - >>>
461.173 -
461.174 -The same exception is raised when you call an ``stdcall`` function with the
461.175 -``cdecl`` calling convention, or vice versa::
461.176 -
461.177 - >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
461.178 - Traceback (most recent call last):
461.179 - File "<stdin>", line 1, in ?
461.180 - ValueError: Procedure probably called with not enough arguments (4 bytes missing)
461.181 - >>>
461.182 -
461.183 - >>> windll.msvcrt.printf("spam") # doctest: +WINDOWS
461.184 - Traceback (most recent call last):
461.185 - File "<stdin>", line 1, in ?
461.186 - ValueError: Procedure probably called with too many arguments (4 bytes in excess)
461.187 - >>>
461.188 -
461.189 -To find out the correct calling convention you have to look into the C header
461.190 -file or the documentation for the function you want to call.
461.191 -
461.192 -On Windows, ``ctypes`` uses win32 structured exception handling to prevent
461.193 -crashes from general protection faults when functions are called with invalid
461.194 -argument values::
461.195 -
461.196 - >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
461.197 - Traceback (most recent call last):
461.198 - File "<stdin>", line 1, in ?
461.199 - WindowsError: exception: access violation reading 0x00000020
461.200 - >>>
461.201 -
461.202 -There are, however, enough ways to crash Python with ``ctypes``, so you should
461.203 -be careful anyway.
461.204 -
461.205 -``None``, integers, longs, byte strings and unicode strings are the only native
461.206 -Python objects that can directly be used as parameters in these function calls.
461.207 -``None`` is passed as a C ``NULL`` pointer, byte strings and unicode strings are
461.208 -passed as pointer to the memory block that contains their data (``char *`` or
461.209 -``wchar_t *``). Python integers and Python longs are passed as the platforms
461.210 -default C ``int`` type, their value is masked to fit into the C type.
461.211 -
461.212 -Before we move on calling functions with other parameter types, we have to learn
461.213 -more about ``ctypes`` data types.
461.214 -
461.215 -
461.216 -.. _ctypes-fundamental-data-types:
461.217 -
461.218 -Fundamental data types
461.219 -^^^^^^^^^^^^^^^^^^^^^^
461.220 -
461.221 -``ctypes`` defines a number of primitive C compatible data types :
461.222 -
461.223 - +----------------------+--------------------------------+----------------------------+
461.224 - | ctypes type | C type | Python type |
461.225 - +======================+================================+============================+
461.226 - | :class:`c_char` | ``char`` | 1-character string |
461.227 - +----------------------+--------------------------------+----------------------------+
461.228 - | :class:`c_wchar` | ``wchar_t`` | 1-character unicode string |
461.229 - +----------------------+--------------------------------+----------------------------+
461.230 - | :class:`c_byte` | ``char`` | int/long |
461.231 - +----------------------+--------------------------------+----------------------------+
461.232 - | :class:`c_ubyte` | ``unsigned char`` | int/long |
461.233 - +----------------------+--------------------------------+----------------------------+
461.234 - | :class:`c_short` | ``short`` | int/long |
461.235 - +----------------------+--------------------------------+----------------------------+
461.236 - | :class:`c_ushort` | ``unsigned short`` | int/long |
461.237 - +----------------------+--------------------------------+----------------------------+
461.238 - | :class:`c_int` | ``int`` | int/long |
461.239 - +----------------------+--------------------------------+----------------------------+
461.240 - | :class:`c_uint` | ``unsigned int`` | int/long |
461.241 - +----------------------+--------------------------------+----------------------------+
461.242 - | :class:`c_long` | ``long`` | int/long |
461.243 - +----------------------+--------------------------------+----------------------------+
461.244 - | :class:`c_ulong` | ``unsigned long`` | int/long |
461.245 - +----------------------+--------------------------------+----------------------------+
461.246 - | :class:`c_longlong` | ``__int64`` or ``long long`` | int/long |
461.247 - +----------------------+--------------------------------+----------------------------+
461.248 - | :class:`c_ulonglong` | ``unsigned __int64`` or | int/long |
461.249 - | | ``unsigned long long`` | |
461.250 - +----------------------+--------------------------------+----------------------------+
461.251 - | :class:`c_float` | ``float`` | float |
461.252 - +----------------------+--------------------------------+----------------------------+
461.253 - | :class:`c_double` | ``double`` | float |
461.254 - +----------------------+--------------------------------+----------------------------+
461.255 - | :class:`c_longdouble`| ``long double`` | float |
461.256 - +----------------------+--------------------------------+----------------------------+
461.257 - | :class:`c_char_p` | ``char *`` (NUL terminated) | string or ``None`` |
461.258 - +----------------------+--------------------------------+----------------------------+
461.259 - | :class:`c_wchar_p` | ``wchar_t *`` (NUL terminated) | unicode or ``None`` |
461.260 - +----------------------+--------------------------------+----------------------------+
461.261 - | :class:`c_void_p` | ``void *`` | int/long or ``None`` |
461.262 - +----------------------+--------------------------------+----------------------------+
461.263 -
461.264 -
461.265 -All these types can be created by calling them with an optional initializer of
461.266 -the correct type and value::
461.267 -
461.268 - >>> c_int()
461.269 - c_long(0)
461.270 - >>> c_char_p("Hello, World")
461.271 - c_char_p('Hello, World')
461.272 - >>> c_ushort(-3)
461.273 - c_ushort(65533)
461.274 - >>>
461.275 -
461.276 -Since these types are mutable, their value can also be changed afterwards::
461.277 -
461.278 - >>> i = c_int(42)
461.279 - >>> print i
461.280 - c_long(42)
461.281 - >>> print i.value
461.282 - 42
461.283 - >>> i.value = -99
461.284 - >>> print i.value
461.285 - -99
461.286 - >>>
461.287 -
461.288 -Assigning a new value to instances of the pointer types :class:`c_char_p`,
461.289 -:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
461.290 -point to, *not the contents* of the memory block (of course not, because Python
461.291 -strings are immutable)::
461.292 -
461.293 - >>> s = "Hello, World"
461.294 - >>> c_s = c_char_p(s)
461.295 - >>> print c_s
461.296 - c_char_p('Hello, World')
461.297 - >>> c_s.value = "Hi, there"
461.298 - >>> print c_s
461.299 - c_char_p('Hi, there')
461.300 - >>> print s # first string is unchanged
461.301 - Hello, World
461.302 - >>>
461.303 -
461.304 -You should be careful, however, not to pass them to functions expecting pointers
461.305 -to mutable memory. If you need mutable memory blocks, ctypes has a
461.306 -``create_string_buffer`` function which creates these in various ways. The
461.307 -current memory block contents can be accessed (or changed) with the ``raw``
461.308 -property; if you want to access it as NUL terminated string, use the ``value``
461.309 -property::
461.310 -
461.311 - >>> from ctypes import *
461.312 - >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
461.313 - >>> print sizeof(p), repr(p.raw)
461.314 - 3 '\x00\x00\x00'
461.315 - >>> p = create_string_buffer("Hello") # create a buffer containing a NUL terminated string
461.316 - >>> print sizeof(p), repr(p.raw)
461.317 - 6 'Hello\x00'
461.318 - >>> print repr(p.value)
461.319 - 'Hello'
461.320 - >>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer
461.321 - >>> print sizeof(p), repr(p.raw)
461.322 - 10 'Hello\x00\x00\x00\x00\x00'
461.323 - >>> p.value = "Hi"
461.324 - >>> print sizeof(p), repr(p.raw)
461.325 - 10 'Hi\x00lo\x00\x00\x00\x00\x00'
461.326 - >>>
461.327 -
461.328 -The ``create_string_buffer`` function replaces the ``c_buffer`` function (which
461.329 -is still available as an alias), as well as the ``c_string`` function from
461.330 -earlier ctypes releases. To create a mutable memory block containing unicode
461.331 -characters of the C type ``wchar_t`` use the ``create_unicode_buffer`` function.
461.332 -
461.333 -
461.334 -.. _ctypes-calling-functions-continued:
461.335 -
461.336 -Calling functions, continued
461.337 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^
461.338 -
461.339 -Note that printf prints to the real standard output channel, *not* to
461.340 -``sys.stdout``, so these examples will only work at the console prompt, not from
461.341 -within *IDLE* or *PythonWin*::
461.342 -
461.343 - >>> printf = libc.printf
461.344 - >>> printf("Hello, %s\n", "World!")
461.345 - Hello, World!
461.346 - 14
461.347 - >>> printf("Hello, %S", u"World!")
461.348 - Hello, World!
461.349 - 13
461.350 - >>> printf("%d bottles of beer\n", 42)
461.351 - 42 bottles of beer
461.352 - 19
461.353 - >>> printf("%f bottles of beer\n", 42.5)
461.354 - Traceback (most recent call last):
461.355 - File "<stdin>", line 1, in ?
461.356 - ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
461.357 - >>>
461.358 -
461.359 -As has been mentioned before, all Python types except integers, strings, and
461.360 -unicode strings have to be wrapped in their corresponding ``ctypes`` type, so
461.361 -that they can be converted to the required C data type::
461.362 -
461.363 - >>> printf("An int %d, a double %f\n", 1234, c_double(3.14))
461.364 - Integer 1234, double 3.1400001049
461.365 - 31
461.366 - >>>
461.367 -
461.368 -
461.369 -.. _ctypes-calling-functions-with-own-custom-data-types:
461.370 -
461.371 -Calling functions with your own custom data types
461.372 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
461.373 -
461.374 -You can also customize ``ctypes`` argument conversion to allow instances of your
461.375 -own classes be used as function arguments. ``ctypes`` looks for an
461.376 -:attr:`_as_parameter_` attribute and uses this as the function argument. Of
461.377 -course, it must be one of integer, string, or unicode::
461.378 -
461.379 - >>> class Bottles(object):
461.380 - ... def __init__(self, number):
461.381 - ... self._as_parameter_ = number
461.382 - ...
461.383 - >>> bottles = Bottles(42)
461.384 - >>> printf("%d bottles of beer\n", bottles)
461.385 - 42 bottles of beer
461.386 - 19
461.387 - >>>
461.388 -
461.389 -If you don't want to store the instance's data in the :attr:`_as_parameter_`
461.390 -instance variable, you could define a ``property`` which makes the data
461.391 -available.
461.392 -
461.393 -
461.394 -.. _ctypes-specifying-required-argument-types:
461.395 -
461.396 -Specifying the required argument types (function prototypes)
461.397 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
461.398 -
461.399 -It is possible to specify the required argument types of functions exported from
461.400 -DLLs by setting the :attr:`argtypes` attribute.
461.401 -
461.402 -:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
461.403 -probably not a good example here, because it takes a variable number and
461.404 -different types of parameters depending on the format string, on the other hand
461.405 -this is quite handy to experiment with this feature)::
461.406 -
461.407 - >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
461.408 - >>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2)
461.409 - String 'Hi', Int 10, Double 2.200000
461.410 - 37
461.411 - >>>
461.412 -
461.413 -Specifying a format protects against incompatible argument types (just as a
461.414 -prototype for a C function), and tries to convert the arguments to valid types::
461.415 -
461.416 - >>> printf("%d %d %d", 1, 2, 3)
461.417 - Traceback (most recent call last):
461.418 - File "<stdin>", line 1, in ?
461.419 - ArgumentError: argument 2: exceptions.TypeError: wrong type
461.420 - >>> printf("%s %d %f", "X", 2, 3)
461.421 - X 2 3.00000012
461.422 - 12
461.423 - >>>
461.424 -
461.425 -If you have defined your own classes which you pass to function calls, you have
461.426 -to implement a :meth:`from_param` class method for them to be able to use them
461.427 -in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
461.428 -the Python object passed to the function call, it should do a typecheck or
461.429 -whatever is needed to make sure this object is acceptable, and then return the
461.430 -object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
461.431 -pass as the C function argument in this case. Again, the result should be an
461.432 -integer, string, unicode, a ``ctypes`` instance, or an object with an
461.433 -:attr:`_as_parameter_` attribute.
461.434 -
461.435 -
461.436 -.. _ctypes-return-types:
461.437 -
461.438 -Return types
461.439 -^^^^^^^^^^^^
461.440 -
461.441 -By default functions are assumed to return the C ``int`` type. Other return
461.442 -types can be specified by setting the :attr:`restype` attribute of the function
461.443 -object.
461.444 -
461.445 -Here is a more advanced example, it uses the ``strchr`` function, which expects
461.446 -a string pointer and a char, and returns a pointer to a string::
461.447 -
461.448 - >>> strchr = libc.strchr
461.449 - >>> strchr("abcdef", ord("d")) # doctest: +SKIP
461.450 - 8059983
461.451 - >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
461.452 - >>> strchr("abcdef", ord("d"))
461.453 - 'def'
461.454 - >>> print strchr("abcdef", ord("x"))
461.455 - None
461.456 - >>>
461.457 -
461.458 -If you want to avoid the ``ord("x")`` calls above, you can set the
461.459 -:attr:`argtypes` attribute, and the second argument will be converted from a
461.460 -single character Python string into a C char::
461.461 -
461.462 - >>> strchr.restype = c_char_p
461.463 - >>> strchr.argtypes = [c_char_p, c_char]
461.464 - >>> strchr("abcdef", "d")
461.465 - 'def'
461.466 - >>> strchr("abcdef", "def")
461.467 - Traceback (most recent call last):
461.468 - File "<stdin>", line 1, in ?
461.469 - ArgumentError: argument 2: exceptions.TypeError: one character string expected
461.470 - >>> print strchr("abcdef", "x")
461.471 - None
461.472 - >>> strchr("abcdef", "d")
461.473 - 'def'
461.474 - >>>
461.475 -
461.476 -You can also use a callable Python object (a function or a class for example) as
461.477 -the :attr:`restype` attribute, if the foreign function returns an integer. The
461.478 -callable will be called with the ``integer`` the C function returns, and the
461.479 -result of this call will be used as the result of your function call. This is
461.480 -useful to check for error return values and automatically raise an exception::
461.481 -
461.482 - >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
461.483 - >>> def ValidHandle(value):
461.484 - ... if value == 0:
461.485 - ... raise WinError()
461.486 - ... return value
461.487 - ...
461.488 - >>>
461.489 - >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
461.490 - >>> GetModuleHandle(None) # doctest: +WINDOWS
461.491 - 486539264
461.492 - >>> GetModuleHandle("something silly") # doctest: +WINDOWS
461.493 - Traceback (most recent call last):
461.494 - File "<stdin>", line 1, in ?
461.495 - File "<stdin>", line 3, in ValidHandle
461.496 - WindowsError: [Errno 126] The specified module could not be found.
461.497 - >>>
461.498 -
461.499 -``WinError`` is a function which will call Windows ``FormatMessage()`` api to
461.500 -get the string representation of an error code, and *returns* an exception.
461.501 -``WinError`` takes an optional error code parameter, if no one is used, it calls
461.502 -:func:`GetLastError` to retrieve it.
461.503 -
461.504 -Please note that a much more powerful error checking mechanism is available
461.505 -through the :attr:`errcheck` attribute; see the reference manual for details.
461.506 -
461.507 -
461.508 -.. _ctypes-passing-pointers:
461.509 -
461.510 -Passing pointers (or: passing parameters by reference)
461.511 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
461.512 -
461.513 -Sometimes a C api function expects a *pointer* to a data type as parameter,
461.514 -probably to write into the corresponding location, or if the data is too large
461.515 -to be passed by value. This is also known as *passing parameters by reference*.
461.516 -
461.517 -``ctypes`` exports the :func:`byref` function which is used to pass parameters
461.518 -by reference. The same effect can be achieved with the ``pointer`` function,
461.519 -although ``pointer`` does a lot more work since it constructs a real pointer
461.520 -object, so it is faster to use :func:`byref` if you don't need the pointer
461.521 -object in Python itself::
461.522 -
461.523 - >>> i = c_int()
461.524 - >>> f = c_float()
461.525 - >>> s = create_string_buffer('\000' * 32)
461.526 - >>> print i.value, f.value, repr(s.value)
461.527 - 0 0.0 ''
461.528 - >>> libc.sscanf("1 3.14 Hello", "%d %f %s",
461.529 - ... byref(i), byref(f), s)
461.530 - 3
461.531 - >>> print i.value, f.value, repr(s.value)
461.532 - 1 3.1400001049 'Hello'
461.533 - >>>
461.534 -
461.535 -
461.536 -.. _ctypes-structures-unions:
461.537 -
461.538 -Structures and unions
461.539 -^^^^^^^^^^^^^^^^^^^^^
461.540 -
461.541 -Structures and unions must derive from the :class:`Structure` and :class:`Union`
461.542 -base classes which are defined in the ``ctypes`` module. Each subclass must
461.543 -define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of
461.544 -*2-tuples*, containing a *field name* and a *field type*.
461.545 -
461.546 -The field type must be a ``ctypes`` type like :class:`c_int`, or any other
461.547 -derived ``ctypes`` type: structure, union, array, pointer.
461.548 -
461.549 -Here is a simple example of a POINT structure, which contains two integers named
461.550 -``x`` and ``y``, and also shows how to initialize a structure in the
461.551 -constructor::
461.552 -
461.553 - >>> from ctypes import *
461.554 - >>> class POINT(Structure):
461.555 - ... _fields_ = [("x", c_int),
461.556 - ... ("y", c_int)]
461.557 - ...
461.558 - >>> point = POINT(10, 20)
461.559 - >>> print point.x, point.y
461.560 - 10 20
461.561 - >>> point = POINT(y=5)
461.562 - >>> print point.x, point.y
461.563 - 0 5
461.564 - >>> POINT(1, 2, 3)
461.565 - Traceback (most recent call last):
461.566 - File "<stdin>", line 1, in ?
461.567 - ValueError: too many initializers
461.568 - >>>
461.569 -
461.570 -You can, however, build much more complicated structures. Structures can itself
461.571 -contain other structures by using a structure as a field type.
461.572 -
461.573 -Here is a RECT structure which contains two POINTs named ``upperleft`` and
461.574 -``lowerright`` ::
461.575 -
461.576 - >>> class RECT(Structure):
461.577 - ... _fields_ = [("upperleft", POINT),
461.578 - ... ("lowerright", POINT)]
461.579 - ...
461.580 - >>> rc = RECT(point)
461.581 - >>> print rc.upperleft.x, rc.upperleft.y
461.582 - 0 5
461.583 - >>> print rc.lowerright.x, rc.lowerright.y
461.584 - 0 0
461.585 - >>>
461.586 -
461.587 -Nested structures can also be initialized in the constructor in several ways::
461.588 -
461.589 - >>> r = RECT(POINT(1, 2), POINT(3, 4))
461.590 - >>> r = RECT((1, 2), (3, 4))
461.591 -
461.592 -Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
461.593 -for debugging because they can provide useful information::
461.594 -
461.595 - >>> print POINT.x
461.596 - <Field type=c_long, ofs=0, size=4>
461.597 - >>> print POINT.y
461.598 - <Field type=c_long, ofs=4, size=4>
461.599 - >>>
461.600 -
461.601 -
461.602 -.. _ctypes-structureunion-alignment-byte-order:
461.603 -
461.604 -Structure/union alignment and byte order
461.605 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
461.606 -
461.607 -By default, Structure and Union fields are aligned in the same way the C
461.608 -compiler does it. It is possible to override this behavior be specifying a
461.609 -:attr:`_pack_` class attribute in the subclass definition. This must be set to a
461.610 -positive integer and specifies the maximum alignment for the fields. This is
461.611 -what ``#pragma pack(n)`` also does in MSVC.
461.612 -
461.613 -``ctypes`` uses the native byte order for Structures and Unions. To build
461.614 -structures with non-native byte order, you can use one of the
461.615 -BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion
461.616 -base classes. These classes cannot contain pointer fields.
461.617 -
461.618 -
461.619 -.. _ctypes-bit-fields-in-structures-unions:
461.620 -
461.621 -Bit fields in structures and unions
461.622 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
461.623 -
461.624 -It is possible to create structures and unions containing bit fields. Bit fields
461.625 -are only possible for integer fields, the bit width is specified as the third
461.626 -item in the :attr:`_fields_` tuples::
461.627 -
461.628 - >>> class Int(Structure):
461.629 - ... _fields_ = [("first_16", c_int, 16),
461.630 - ... ("second_16", c_int, 16)]
461.631 - ...
461.632 - >>> print Int.first_16
461.633 - <Field type=c_long, ofs=0:0, bits=16>
461.634 - >>> print Int.second_16
461.635 - <Field type=c_long, ofs=0:16, bits=16>
461.636 - >>>
461.637 -
461.638 -
461.639 -.. _ctypes-arrays:
461.640 -
461.641 -Arrays
461.642 -^^^^^^
461.643 -
461.644 -Arrays are sequences, containing a fixed number of instances of the same type.
461.645 -
461.646 -The recommended way to create array types is by multiplying a data type with a
461.647 -positive integer::
461.648 -
461.649 - TenPointsArrayType = POINT * 10
461.650 -
461.651 -Here is an example of an somewhat artificial data type, a structure containing 4
461.652 -POINTs among other stuff::
461.653 -
461.654 - >>> from ctypes import *
461.655 - >>> class POINT(Structure):
461.656 - ... _fields_ = ("x", c_int), ("y", c_int)
461.657 - ...
461.658 - >>> class MyStruct(Structure):
461.659 - ... _fields_ = [("a", c_int),
461.660 - ... ("b", c_float),
461.661 - ... ("point_array", POINT * 4)]
461.662 - >>>
461.663 - >>> print len(MyStruct().point_array)
461.664 - 4
461.665 - >>>
461.666 -
461.667 -Instances are created in the usual way, by calling the class::
461.668 -
461.669 - arr = TenPointsArrayType()
461.670 - for pt in arr:
461.671 - print pt.x, pt.y
461.672 -
461.673 -The above code print a series of ``0 0`` lines, because the array contents is
461.674 -initialized to zeros.
461.675 -
461.676 -Initializers of the correct type can also be specified::
461.677 -
461.678 - >>> from ctypes import *
461.679 - >>> TenIntegers = c_int * 10
461.680 - >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
461.681 - >>> print ii
461.682 - <c_long_Array_10 object at 0x...>
461.683 - >>> for i in ii: print i,
461.684 - ...
461.685 - 1 2 3 4 5 6 7 8 9 10
461.686 - >>>
461.687 -
461.688 -
461.689 -.. _ctypes-pointers:
461.690 -
461.691 -Pointers
461.692 -^^^^^^^^
461.693 -
461.694 -Pointer instances are created by calling the ``pointer`` function on a
461.695 -``ctypes`` type::
461.696 -
461.697 - >>> from ctypes import *
461.698 - >>> i = c_int(42)
461.699 - >>> pi = pointer(i)
461.700 - >>>
461.701 -
461.702 -Pointer instances have a ``contents`` attribute which returns the object to
461.703 -which the pointer points, the ``i`` object above::
461.704 -
461.705 - >>> pi.contents
461.706 - c_long(42)
461.707 - >>>
461.708 -
461.709 -Note that ``ctypes`` does not have OOR (original object return), it constructs a
461.710 -new, equivalent object each time you retrieve an attribute::
461.711 -
461.712 - >>> pi.contents is i
461.713 - False
461.714 - >>> pi.contents is pi.contents
461.715 - False
461.716 - >>>
461.717 -
461.718 -Assigning another :class:`c_int` instance to the pointer's contents attribute
461.719 -would cause the pointer to point to the memory location where this is stored::
461.720 -
461.721 - >>> i = c_int(99)
461.722 - >>> pi.contents = i
461.723 - >>> pi.contents
461.724 - c_long(99)
461.725 - >>>
461.726 -
461.727 -.. XXX Document dereferencing pointers, and that it is preferred over the .contents attribute.
461.728 -
461.729 -Pointer instances can also be indexed with integers::
461.730 -
461.731 - >>> pi[0]
461.732 - 99
461.733 - >>>
461.734 -
461.735 -Assigning to an integer index changes the pointed to value::
461.736 -
461.737 - >>> print i
461.738 - c_long(99)
461.739 - >>> pi[0] = 22
461.740 - >>> print i
461.741 - c_long(22)
461.742 - >>>
461.743 -
461.744 -It is also possible to use indexes different from 0, but you must know what
461.745 -you're doing, just as in C: You can access or change arbitrary memory locations.
461.746 -Generally you only use this feature if you receive a pointer from a C function,
461.747 -and you *know* that the pointer actually points to an array instead of a single
461.748 -item.
461.749 -
461.750 -Behind the scenes, the ``pointer`` function does more than simply create pointer
461.751 -instances, it has to create pointer *types* first. This is done with the
461.752 -``POINTER`` function, which accepts any ``ctypes`` type, and returns a new
461.753 -type::
461.754 -
461.755 - >>> PI = POINTER(c_int)
461.756 - >>> PI
461.757 - <class 'ctypes.LP_c_long'>
461.758 - >>> PI(42)
461.759 - Traceback (most recent call last):
461.760 - File "<stdin>", line 1, in ?
461.761 - TypeError: expected c_long instead of int
461.762 - >>> PI(c_int(42))
461.763 - <ctypes.LP_c_long object at 0x...>
461.764 - >>>
461.765 -
461.766 -Calling the pointer type without an argument creates a ``NULL`` pointer.
461.767 -``NULL`` pointers have a ``False`` boolean value::
461.768 -
461.769 - >>> null_ptr = POINTER(c_int)()
461.770 - >>> print bool(null_ptr)
461.771 - False
461.772 - >>>
461.773 -
461.774 -``ctypes`` checks for ``NULL`` when dereferencing pointers (but dereferencing
461.775 -invalid non-\ ``NULL`` pointers would crash Python)::
461.776 -
461.777 - >>> null_ptr[0]
461.778 - Traceback (most recent call last):
461.779 - ....
461.780 - ValueError: NULL pointer access
461.781 - >>>
461.782 -
461.783 - >>> null_ptr[0] = 1234
461.784 - Traceback (most recent call last):
461.785 - ....
461.786 - ValueError: NULL pointer access
461.787 - >>>
461.788 -
461.789 -
461.790 -.. _ctypes-type-conversions:
461.791 -
461.792 -Type conversions
461.793 -^^^^^^^^^^^^^^^^
461.794 -
461.795 -Usually, ctypes does strict type checking. This means, if you have
461.796 -``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
461.797 -a member field in a structure definition, only instances of exactly the same
461.798 -type are accepted. There are some exceptions to this rule, where ctypes accepts
461.799 -other objects. For example, you can pass compatible array instances instead of
461.800 -pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
461.801 -
461.802 - >>> class Bar(Structure):
461.803 - ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
461.804 - ...
461.805 - >>> bar = Bar()
461.806 - >>> bar.values = (c_int * 3)(1, 2, 3)
461.807 - >>> bar.count = 3
461.808 - >>> for i in range(bar.count):
461.809 - ... print bar.values[i]
461.810 - ...
461.811 - 1
461.812 - 2
461.813 - 3
461.814 - >>>
461.815 -
461.816 -To set a POINTER type field to ``NULL``, you can assign ``None``::
461.817 -
461.818 - >>> bar.values = None
461.819 - >>>
461.820 -
461.821 -.. XXX list other conversions...
461.822 -
461.823 -Sometimes you have instances of incompatible types. In C, you can cast one
461.824 -type into another type. ``ctypes`` provides a ``cast`` function which can be
461.825 -used in the same way. The ``Bar`` structure defined above accepts
461.826 -``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
461.827 -but not instances of other types::
461.828 -
461.829 - >>> bar.values = (c_byte * 4)()
461.830 - Traceback (most recent call last):
461.831 - File "<stdin>", line 1, in ?
461.832 - TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
461.833 - >>>
461.834 -
461.835 -For these cases, the ``cast`` function is handy.
461.836 -
461.837 -The ``cast`` function can be used to cast a ctypes instance into a pointer to a
461.838 -different ctypes data type. ``cast`` takes two parameters, a ctypes object that
461.839 -is or can be converted to a pointer of some kind, and a ctypes pointer type. It
461.840 -returns an instance of the second argument, which references the same memory
461.841 -block as the first argument::
461.842 -
461.843 - >>> a = (c_byte * 4)()
461.844 - >>> cast(a, POINTER(c_int))
461.845 - <ctypes.LP_c_long object at ...>
461.846 - >>>
461.847 -
461.848 -So, ``cast`` can be used to assign to the ``values`` field of ``Bar`` the
461.849 -structure::
461.850 -
461.851 - >>> bar = Bar()
461.852 - >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
461.853 - >>> print bar.values[0]
461.854 - 0
461.855 - >>>
461.856 -
461.857 -
461.858 -.. _ctypes-incomplete-types:
461.859 -
461.860 -Incomplete Types
461.861 -^^^^^^^^^^^^^^^^
461.862 -
461.863 -*Incomplete Types* are structures, unions or arrays whose members are not yet
461.864 -specified. In C, they are specified by forward declarations, which are defined
461.865 -later::
461.866 -
461.867 - struct cell; /* forward declaration */
461.868 -
461.869 - struct {
461.870 - char *name;
461.871 - struct cell *next;
461.872 - } cell;
461.873 -
461.874 -The straightforward translation into ctypes code would be this, but it does not
461.875 -work::
461.876 -
461.877 - >>> class cell(Structure):
461.878 - ... _fields_ = [("name", c_char_p),
461.879 - ... ("next", POINTER(cell))]
461.880 - ...
461.881 - Traceback (most recent call last):
461.882 - File "<stdin>", line 1, in ?
461.883 - File "<stdin>", line 2, in cell
461.884 - NameError: name 'cell' is not defined
461.885 - >>>
461.886 -
461.887 -because the new ``class cell`` is not available in the class statement itself.
461.888 -In ``ctypes``, we can define the ``cell`` class and set the :attr:`_fields_`
461.889 -attribute later, after the class statement::
461.890 -
461.891 - >>> from ctypes import *
461.892 - >>> class cell(Structure):
461.893 - ... pass
461.894 - ...
461.895 - >>> cell._fields_ = [("name", c_char_p),
461.896 - ... ("next", POINTER(cell))]
461.897 - >>>
461.898 -
461.899 -Lets try it. We create two instances of ``cell``, and let them point to each
461.900 -other, and finally follow the pointer chain a few times::
461.901 -
461.902 - >>> c1 = cell()
461.903 - >>> c1.name = "foo"
461.904 - >>> c2 = cell()
461.905 - >>> c2.name = "bar"
461.906 - >>> c1.next = pointer(c2)
461.907 - >>> c2.next = pointer(c1)
461.908 - >>> p = c1
461.909 - >>> for i in range(8):
461.910 - ... print p.name,
461.911 - ... p = p.next[0]
461.912 - ...
461.913 - foo bar foo bar foo bar foo bar
461.914 - >>>
461.915 -
461.916 -
461.917 -.. _ctypes-callback-functions:
461.918 -
461.919 -Callback functions
461.920 -^^^^^^^^^^^^^^^^^^
461.921 -
461.922 -``ctypes`` allows to create C callable function pointers from Python callables.
461.923 -These are sometimes called *callback functions*.
461.924 -
461.925 -First, you must create a class for the callback function, the class knows the
461.926 -calling convention, the return type, and the number and types of arguments this
461.927 -function will receive.
461.928 -
461.929 -The CFUNCTYPE factory function creates types for callback functions using the
461.930 -normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
461.931 -function creates types for callback functions using the stdcall calling
461.932 -convention.
461.933 -
461.934 -Both of these factory functions are called with the result type as first
461.935 -argument, and the callback functions expected argument types as the remaining
461.936 -arguments.
461.937 -
461.938 -I will present an example here which uses the standard C library's :func:`qsort`
461.939 -function, this is used to sort items with the help of a callback function.
461.940 -:func:`qsort` will be used to sort an array of integers::
461.941 -
461.942 - >>> IntArray5 = c_int * 5
461.943 - >>> ia = IntArray5(5, 1, 7, 33, 99)
461.944 - >>> qsort = libc.qsort
461.945 - >>> qsort.restype = None
461.946 - >>>
461.947 -
461.948 -:func:`qsort` must be called with a pointer to the data to sort, the number of
461.949 -items in the data array, the size of one item, and a pointer to the comparison
461.950 -function, the callback. The callback will then be called with two pointers to
461.951 -items, and it must return a negative integer if the first item is smaller than
461.952 -the second, a zero if they are equal, and a positive integer else.
461.953 -
461.954 -So our callback function receives pointers to integers, and must return an
461.955 -integer. First we create the ``type`` for the callback function::
461.956 -
461.957 - >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
461.958 - >>>
461.959 -
461.960 -For the first implementation of the callback function, we simply print the
461.961 -arguments we get, and return 0 (incremental development ;-)::
461.962 -
461.963 - >>> def py_cmp_func(a, b):
461.964 - ... print "py_cmp_func", a, b
461.965 - ... return 0
461.966 - ...
461.967 - >>>
461.968 -
461.969 -Create the C callable callback::
461.970 -
461.971 - >>> cmp_func = CMPFUNC(py_cmp_func)
461.972 - >>>
461.973 -
461.974 -And we're ready to go::
461.975 -
461.976 - >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
461.977 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
461.978 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
461.979 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
461.980 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
461.981 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
461.982 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
461.983 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
461.984 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
461.985 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
461.986 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
461.987 - >>>
461.988 -
461.989 -We know how to access the contents of a pointer, so lets redefine our callback::
461.990 -
461.991 - >>> def py_cmp_func(a, b):
461.992 - ... print "py_cmp_func", a[0], b[0]
461.993 - ... return 0
461.994 - ...
461.995 - >>> cmp_func = CMPFUNC(py_cmp_func)
461.996 - >>>
461.997 -
461.998 -Here is what we get on Windows::
461.999 -
461.1000 - >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
461.1001 - py_cmp_func 7 1
461.1002 - py_cmp_func 33 1
461.1003 - py_cmp_func 99 1
461.1004 - py_cmp_func 5 1
461.1005 - py_cmp_func 7 5
461.1006 - py_cmp_func 33 5
461.1007 - py_cmp_func 99 5
461.1008 - py_cmp_func 7 99
461.1009 - py_cmp_func 33 99
461.1010 - py_cmp_func 7 33
461.1011 - >>>
461.1012 -
461.1013 -It is funny to see that on linux the sort function seems to work much more
461.1014 -efficient, it is doing less comparisons::
461.1015 -
461.1016 - >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
461.1017 - py_cmp_func 5 1
461.1018 - py_cmp_func 33 99
461.1019 - py_cmp_func 7 33
461.1020 - py_cmp_func 5 7
461.1021 - py_cmp_func 1 7
461.1022 - >>>
461.1023 -
461.1024 -Ah, we're nearly done! The last step is to actually compare the two items and
461.1025 -return a useful result::
461.1026 -
461.1027 - >>> def py_cmp_func(a, b):
461.1028 - ... print "py_cmp_func", a[0], b[0]
461.1029 - ... return a[0] - b[0]
461.1030 - ...
461.1031 - >>>
461.1032 -
461.1033 -Final run on Windows::
461.1034 -
461.1035 - >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
461.1036 - py_cmp_func 33 7
461.1037 - py_cmp_func 99 33
461.1038 - py_cmp_func 5 99
461.1039 - py_cmp_func 1 99
461.1040 - py_cmp_func 33 7
461.1041 - py_cmp_func 1 33
461.1042 - py_cmp_func 5 33
461.1043 - py_cmp_func 5 7
461.1044 - py_cmp_func 1 7
461.1045 - py_cmp_func 5 1
461.1046 - >>>
461.1047 -
461.1048 -and on Linux::
461.1049 -
461.1050 - >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
461.1051 - py_cmp_func 5 1
461.1052 - py_cmp_func 33 99
461.1053 - py_cmp_func 7 33
461.1054 - py_cmp_func 1 7
461.1055 - py_cmp_func 5 7
461.1056 - >>>
461.1057 -
461.1058 -It is quite interesting to see that the Windows :func:`qsort` function needs
461.1059 -more comparisons than the linux version!
461.1060 -
461.1061 -As we can easily check, our array is sorted now::
461.1062 -
461.1063 - >>> for i in ia: print i,
461.1064 - ...
461.1065 - 1 5 7 33 99
461.1066 - >>>
461.1067 -
461.1068 -**Important note for callback functions:**
461.1069 -
461.1070 -Make sure you keep references to CFUNCTYPE objects as long as they are used from
461.1071 -C code. ``ctypes`` doesn't, and if you don't, they may be garbage collected,
461.1072 -crashing your program when a callback is made.
461.1073 -
461.1074 -
461.1075 -.. _ctypes-accessing-values-exported-from-dlls:
461.1076 -
461.1077 -Accessing values exported from dlls
461.1078 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
461.1079 -
461.1080 -Some shared libraries not only export functions, they also export variables. An
461.1081 -example in the Python library itself is the ``Py_OptimizeFlag``, an integer set
461.1082 -to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
461.1083 -startup.
461.1084 -
461.1085 -``ctypes`` can access values like this with the :meth:`in_dll` class methods of
461.1086 -the type. *pythonapi* is a predefined symbol giving access to the Python C
461.1087 -api::
461.1088 -
461.1089 - >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
461.1090 - >>> print opt_flag
461.1091 - c_long(0)
461.1092 - >>>
461.1093 -
461.1094 -If the interpreter would have been started with :option:`-O`, the sample would
461.1095 -have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
461.1096 -specified.
461.1097 -
461.1098 -An extended example which also demonstrates the use of pointers accesses the
461.1099 -``PyImport_FrozenModules`` pointer exported by Python.
461.1100 -
461.1101 -Quoting the Python docs: *This pointer is initialized to point to an array of
461.1102 -"struct _frozen" records, terminated by one whose members are all NULL or zero.
461.1103 -When a frozen module is imported, it is searched in this table. Third-party code
461.1104 -could play tricks with this to provide a dynamically created collection of
461.1105 -frozen modules.*
461.1106 -
461.1107 -So manipulating this pointer could even prove useful. To restrict the example
461.1108 -size, we show only how this table can be read with ``ctypes``::
461.1109 -
461.1110 - >>> from ctypes import *
461.1111 - >>>
461.1112 - >>> class struct_frozen(Structure):
461.1113 - ... _fields_ = [("name", c_char_p),
461.1114 - ... ("code", POINTER(c_ubyte)),
461.1115 - ... ("size", c_int)]
461.1116 - ...
461.1117 - >>>
461.1118 -
461.1119 -We have defined the ``struct _frozen`` data type, so we can get the pointer to
461.1120 -the table::
461.1121 -
461.1122 - >>> FrozenTable = POINTER(struct_frozen)
461.1123 - >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
461.1124 - >>>
461.1125 -
461.1126 -Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
461.1127 -can iterate over it, but we just have to make sure that our loop terminates,
461.1128 -because pointers have no size. Sooner or later it would probably crash with an
461.1129 -access violation or whatever, so it's better to break out of the loop when we
461.1130 -hit the NULL entry::
461.1131 -
461.1132 - >>> for item in table:
461.1133 - ... print item.name, item.size
461.1134 - ... if item.name is None:
461.1135 - ... break
461.1136 - ...
461.1137 - __hello__ 104
461.1138 - __phello__ -104
461.1139 - __phello__.spam 104
461.1140 - None 0
461.1141 - >>>
461.1142 -
461.1143 -The fact that standard Python has a frozen module and a frozen package
461.1144 -(indicated by the negative size member) is not well known, it is only used for
461.1145 -testing. Try it out with ``import __hello__`` for example.
461.1146 -
461.1147 -
461.1148 -.. _ctypes-surprises:
461.1149 -
461.1150 -Surprises
461.1151 -^^^^^^^^^
461.1152 -
461.1153 -There are some edges in ``ctypes`` where you may be expect something else than
461.1154 -what actually happens.
461.1155 -
461.1156 -Consider the following example::
461.1157 -
461.1158 - >>> from ctypes import *
461.1159 - >>> class POINT(Structure):
461.1160 - ... _fields_ = ("x", c_int), ("y", c_int)
461.1161 - ...
461.1162 - >>> class RECT(Structure):
461.1163 - ... _fields_ = ("a", POINT), ("b", POINT)
461.1164 - ...
461.1165 - >>> p1 = POINT(1, 2)
461.1166 - >>> p2 = POINT(3, 4)
461.1167 - >>> rc = RECT(p1, p2)
461.1168 - >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
461.1169 - 1 2 3 4
461.1170 - >>> # now swap the two points
461.1171 - >>> rc.a, rc.b = rc.b, rc.a
461.1172 - >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
461.1173 - 3 4 3 4
461.1174 - >>>
461.1175 -
461.1176 -Hm. We certainly expected the last statement to print ``3 4 1 2``. What
461.1177 -happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
461.1178 -
461.1179 - >>> temp0, temp1 = rc.b, rc.a
461.1180 - >>> rc.a = temp0
461.1181 - >>> rc.b = temp1
461.1182 - >>>
461.1183 -
461.1184 -Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
461.1185 -the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
461.1186 -contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
461.1187 -contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
461.1188 -the expected effect.
461.1189 -
461.1190 -Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
461.1191 -doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
461.1192 -the root-object's underlying buffer.
461.1193 -
461.1194 -Another example that may behave different from what one would expect is this::
461.1195 -
461.1196 - >>> s = c_char_p()
461.1197 - >>> s.value = "abc def ghi"
461.1198 - >>> s.value
461.1199 - 'abc def ghi'
461.1200 - >>> s.value is s.value
461.1201 - False
461.1202 - >>>
461.1203 -
461.1204 -Why is it printing ``False``? ctypes instances are objects containing a memory
461.1205 -block plus some :term:`descriptor`\s accessing the contents of the memory.
461.1206 -Storing a Python object in the memory block does not store the object itself,
461.1207 -instead the ``contents`` of the object is stored. Accessing the contents again
461.1208 -constructs a new Python object each time!
461.1209 -
461.1210 -
461.1211 -.. _ctypes-variable-sized-data-types:
461.1212 -
461.1213 -Variable-sized data types
461.1214 -^^^^^^^^^^^^^^^^^^^^^^^^^
461.1215 -
461.1216 -``ctypes`` provides some support for variable-sized arrays and structures (this
461.1217 -was added in version 0.9.9.7).
461.1218 -
461.1219 -The ``resize`` function can be used to resize the memory buffer of an existing
461.1220 -ctypes object. The function takes the object as first argument, and the
461.1221 -requested size in bytes as the second argument. The memory block cannot be made
461.1222 -smaller than the natural memory block specified by the objects type, a
461.1223 -``ValueError`` is raised if this is tried::
461.1224 -
461.1225 - >>> short_array = (c_short * 4)()
461.1226 - >>> print sizeof(short_array)
461.1227 - 8
461.1228 - >>> resize(short_array, 4)
461.1229 - Traceback (most recent call last):
461.1230 - ...
461.1231 - ValueError: minimum size is 8
461.1232 - >>> resize(short_array, 32)
461.1233 - >>> sizeof(short_array)
461.1234 - 32
461.1235 - >>> sizeof(type(short_array))
461.1236 - 8
461.1237 - >>>
461.1238 -
461.1239 -This is nice and fine, but how would one access the additional elements
461.1240 -contained in this array? Since the type still only knows about 4 elements, we
461.1241 -get errors accessing other elements::
461.1242 -
461.1243 - >>> short_array[:]
461.1244 - [0, 0, 0, 0]
461.1245 - >>> short_array[7]
461.1246 - Traceback (most recent call last):
461.1247 - ...
461.1248 - IndexError: invalid index
461.1249 - >>>
461.1250 -
461.1251 -Another way to use variable-sized data types with ``ctypes`` is to use the
461.1252 -dynamic nature of Python, and (re-)define the data type after the required size
461.1253 -is already known, on a case by case basis.
461.1254 -
461.1255 -
461.1256 -.. _ctypes-ctypes-reference:
461.1257 -
461.1258 -ctypes reference
461.1259 -----------------
461.1260 -
461.1261 -
461.1262 -.. _ctypes-finding-shared-libraries:
461.1263 -
461.1264 -Finding shared libraries
461.1265 -^^^^^^^^^^^^^^^^^^^^^^^^
461.1266 -
461.1267 -When programming in a compiled language, shared libraries are accessed when
461.1268 -compiling/linking a program, and when the program is run.
461.1269 -
461.1270 -The purpose of the ``find_library`` function is to locate a library in a way
461.1271 -similar to what the compiler does (on platforms with several versions of a
461.1272 -shared library the most recent should be loaded), while the ctypes library
461.1273 -loaders act like when a program is run, and call the runtime loader directly.
461.1274 -
461.1275 -The ``ctypes.util`` module provides a function which can help to determine the
461.1276 -library to load.
461.1277 -
461.1278 -
461.1279 -.. data:: find_library(name)
461.1280 - :noindex:
461.1281 -
461.1282 - Try to find a library and return a pathname. *name* is the library name without
461.1283 - any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
461.1284 - is the form used for the posix linker option :option:`-l`). If no library can
461.1285 - be found, returns ``None``.
461.1286 -
461.1287 -The exact functionality is system dependent.
461.1288 -
461.1289 -On Linux, ``find_library`` tries to run external programs (/sbin/ldconfig, gcc,
461.1290 -and objdump) to find the library file. It returns the filename of the library
461.1291 -file. Here are some examples::
461.1292 -
461.1293 - >>> from ctypes.util import find_library
461.1294 - >>> find_library("m")
461.1295 - 'libm.so.6'
461.1296 - >>> find_library("c")
461.1297 - 'libc.so.6'
461.1298 - >>> find_library("bz2")
461.1299 - 'libbz2.so.1.0'
461.1300 - >>>
461.1301 -
461.1302 -On OS X, ``find_library`` tries several predefined naming schemes and paths to
461.1303 -locate the library, and returns a full pathname if successful::
461.1304 -
461.1305 - >>> from ctypes.util import find_library
461.1306 - >>> find_library("c")
461.1307 - '/usr/lib/libc.dylib'
461.1308 - >>> find_library("m")
461.1309 - '/usr/lib/libm.dylib'
461.1310 - >>> find_library("bz2")
461.1311 - '/usr/lib/libbz2.dylib'
461.1312 - >>> find_library("AGL")
461.1313 - '/System/Library/Frameworks/AGL.framework/AGL'
461.1314 - >>>
461.1315 -
461.1316 -On Windows, ``find_library`` searches along the system search path, and returns
461.1317 -the full pathname, but since there is no predefined naming scheme a call like
461.1318 -``find_library("c")`` will fail and return ``None``.
461.1319 -
461.1320 -If wrapping a shared library with ``ctypes``, it *may* be better to determine
461.1321 -the shared library name at development type, and hardcode that into the wrapper
461.1322 -module instead of using ``find_library`` to locate the library at runtime.
461.1323 -
461.1324 -
461.1325 -.. _ctypes-loading-shared-libraries:
461.1326 -
461.1327 -Loading shared libraries
461.1328 -^^^^^^^^^^^^^^^^^^^^^^^^
461.1329 -
461.1330 -There are several ways to loaded shared libraries into the Python process. One
461.1331 -way is to instantiate one of the following classes:
461.1332 -
461.1333 -
461.1334 -.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
461.1335 -
461.1336 - Instances of this class represent loaded shared libraries. Functions in these
461.1337 - libraries use the standard C calling convention, and are assumed to return
461.1338 - ``int``.
461.1339 -
461.1340 -
461.1341 -.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
461.1342 -
461.1343 - Windows only: Instances of this class represent loaded shared libraries,
461.1344 - functions in these libraries use the ``stdcall`` calling convention, and are
461.1345 - assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
461.1346 - values contain information specifying whether the function call failed or
461.1347 - succeeded, together with additional error code. If the return value signals a
461.1348 - failure, an :class:`WindowsError` is automatically raised.
461.1349 -
461.1350 -
461.1351 -.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
461.1352 -
461.1353 - Windows only: Instances of this class represent loaded shared libraries,
461.1354 - functions in these libraries use the ``stdcall`` calling convention, and are
461.1355 - assumed to return ``int`` by default.
461.1356 -
461.1357 - On Windows CE only the standard calling convention is used, for convenience the
461.1358 - :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
461.1359 - platform.
461.1360 -
461.1361 -The Python :term:`global interpreter lock` is released before calling any
461.1362 -function exported by these libraries, and reacquired afterwards.
461.1363 -
461.1364 -
461.1365 -.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
461.1366 -
461.1367 - Instances of this class behave like :class:`CDLL` instances, except that the
461.1368 - Python GIL is *not* released during the function call, and after the function
461.1369 - execution the Python error flag is checked. If the error flag is set, a Python
461.1370 - exception is raised.
461.1371 -
461.1372 - Thus, this is only useful to call Python C api functions directly.
461.1373 -
461.1374 -All these classes can be instantiated by calling them with at least one
461.1375 -argument, the pathname of the shared library. If you have an existing handle to
461.1376 -an already loaded shard library, it can be passed as the ``handle`` named
461.1377 -parameter, otherwise the underlying platforms ``dlopen`` or :meth:`LoadLibrary`
461.1378 -function is used to load the library into the process, and to get a handle to
461.1379 -it.
461.1380 -
461.1381 -The *mode* parameter can be used to specify how the library is loaded. For
461.1382 -details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored.
461.1383 -
461.1384 -The *use_errno* parameter, when set to True, enables a ctypes
461.1385 -mechanism that allows to access the system `errno` error number in a
461.1386 -safe way. `ctypes` maintains a thread-local copy of the systems
461.1387 -`errno` variable; if you call foreign functions created with
461.1388 -`use_errno=True` then the `errno` value before the function call is
461.1389 -swapped with the ctypes private copy, the same happens immediately
461.1390 -after the function call.
461.1391 -
461.1392 -The function `ctypes.get_errno()` returns the value of the ctypes
461.1393 -private copy, and the function `ctypes.set_errno(value)` changes the
461.1394 -ctypes private copy to `value` and returns the former value.
461.1395 -
461.1396 -The *use_last_error* parameter, when set to True, enables the same
461.1397 -mechanism for the Windows error code which is managed by the
461.1398 -:func:`GetLastError` and :func:`SetLastError` Windows API functions;
461.1399 -`ctypes.get_last_error()` and `ctypes.set_last_error(value)` are used
461.1400 -to request and change the ctypes private copy of the windows error
461.1401 -code.
461.1402 -
461.1403 -.. versionadded:: 2.6
461.1404 - The ``use_last_error`` and ``use_errno`` optional parameters
461.1405 - were added.
461.1406 -
461.1407 -.. data:: RTLD_GLOBAL
461.1408 - :noindex:
461.1409 -
461.1410 - Flag to use as *mode* parameter. On platforms where this flag is not available,
461.1411 - it is defined as the integer zero.
461.1412 -
461.1413 -
461.1414 -.. data:: RTLD_LOCAL
461.1415 - :noindex:
461.1416 -
461.1417 - Flag to use as *mode* parameter. On platforms where this is not available, it
461.1418 - is the same as *RTLD_GLOBAL*.
461.1419 -
461.1420 -
461.1421 -.. data:: DEFAULT_MODE
461.1422 - :noindex:
461.1423 -
461.1424 - The default mode which is used to load shared libraries. On OSX 10.3, this is
461.1425 - *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
461.1426 -
461.1427 -Instances of these classes have no public methods, however :meth:`__getattr__`
461.1428 -and :meth:`__getitem__` have special behavior: functions exported by the shared
461.1429 -library can be accessed as attributes of by index. Please note that both
461.1430 -:meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
461.1431 -repeatedly returns the same object each time.
461.1432 -
461.1433 -The following public attributes are available, their name starts with an
461.1434 -underscore to not clash with exported function names:
461.1435 -
461.1436 -
461.1437 -.. attribute:: PyDLL._handle
461.1438 -
461.1439 - The system handle used to access the library.
461.1440 -
461.1441 -
461.1442 -.. attribute:: PyDLL._name
461.1443 -
461.1444 - The name of the library passed in the constructor.
461.1445 -
461.1446 -Shared libraries can also be loaded by using one of the prefabricated objects,
461.1447 -which are instances of the :class:`LibraryLoader` class, either by calling the
461.1448 -:meth:`LoadLibrary` method, or by retrieving the library as attribute of the
461.1449 -loader instance.
461.1450 -
461.1451 -
461.1452 -.. class:: LibraryLoader(dlltype)
461.1453 -
461.1454 - Class which loads shared libraries. ``dlltype`` should be one of the
461.1455 - :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
461.1456 -
461.1457 - :meth:`__getattr__` has special behavior: It allows to load a shared library by
461.1458 - accessing it as attribute of a library loader instance. The result is cached,
461.1459 - so repeated attribute accesses return the same library each time.
461.1460 -
461.1461 -
461.1462 - .. method:: LoadLibrary(name)
461.1463 -
461.1464 - Load a shared library into the process and return it. This method always
461.1465 - returns a new instance of the library.
461.1466 -
461.1467 -These prefabricated library loaders are available:
461.1468 -
461.1469 -
461.1470 -.. data:: cdll
461.1471 - :noindex:
461.1472 -
461.1473 - Creates :class:`CDLL` instances.
461.1474 -
461.1475 -
461.1476 -.. data:: windll
461.1477 - :noindex:
461.1478 -
461.1479 - Windows only: Creates :class:`WinDLL` instances.
461.1480 -
461.1481 -
461.1482 -.. data:: oledll
461.1483 - :noindex:
461.1484 -
461.1485 - Windows only: Creates :class:`OleDLL` instances.
461.1486 -
461.1487 -
461.1488 -.. data:: pydll
461.1489 - :noindex:
461.1490 -
461.1491 - Creates :class:`PyDLL` instances.
461.1492 -
461.1493 -For accessing the C Python api directly, a ready-to-use Python shared library
461.1494 -object is available:
461.1495 -
461.1496 -
461.1497 -.. data:: pythonapi
461.1498 - :noindex:
461.1499 -
461.1500 - An instance of :class:`PyDLL` that exposes Python C api functions as attributes.
461.1501 - Note that all these functions are assumed to return C ``int``, which is of
461.1502 - course not always the truth, so you have to assign the correct :attr:`restype`
461.1503 - attribute to use these functions.
461.1504 -
461.1505 -
461.1506 -.. _ctypes-foreign-functions:
461.1507 -
461.1508 -Foreign functions
461.1509 -^^^^^^^^^^^^^^^^^
461.1510 -
461.1511 -As explained in the previous section, foreign functions can be accessed as
461.1512 -attributes of loaded shared libraries. The function objects created in this way
461.1513 -by default accept any number of arguments, accept any ctypes data instances as
461.1514 -arguments, and return the default result type specified by the library loader.
461.1515 -They are instances of a private class:
461.1516 -
461.1517 -
461.1518 -.. class:: _FuncPtr
461.1519 -
461.1520 - Base class for C callable foreign functions.
461.1521 -
461.1522 - Instances of foreign functions are also C compatible data types; they
461.1523 - represent C function pointers.
461.1524 -
461.1525 - This behavior can be customized by assigning to special attributes of the
461.1526 - foreign function object.
461.1527 -
461.1528 -
461.1529 - .. attribute:: restype
461.1530 -
461.1531 - Assign a ctypes type to specify the result type of the foreign function.
461.1532 - Use ``None`` for ``void`` a function not returning anything.
461.1533 -
461.1534 - It is possible to assign a callable Python object that is not a ctypes
461.1535 - type, in this case the function is assumed to return a C ``int``, and the
461.1536 - callable will be called with this integer, allowing to do further
461.1537 - processing or error checking. Using this is deprecated, for more flexible
461.1538 - post processing or error checking use a ctypes data type as
461.1539 - :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
461.1540 -
461.1541 -
461.1542 - .. attribute:: argtypes
461.1543 -
461.1544 - Assign a tuple of ctypes types to specify the argument types that the
461.1545 - function accepts. Functions using the ``stdcall`` calling convention can
461.1546 - only be called with the same number of arguments as the length of this
461.1547 - tuple; functions using the C calling convention accept additional,
461.1548 - unspecified arguments as well.
461.1549 -
461.1550 - When a foreign function is called, each actual argument is passed to the
461.1551 - :meth:`from_param` class method of the items in the :attr:`argtypes`
461.1552 - tuple, this method allows to adapt the actual argument to an object that
461.1553 - the foreign function accepts. For example, a :class:`c_char_p` item in
461.1554 - the :attr:`argtypes` tuple will convert a unicode string passed as
461.1555 - argument into an byte string using ctypes conversion rules.
461.1556 -
461.1557 - New: It is now possible to put items in argtypes which are not ctypes
461.1558 - types, but each item must have a :meth:`from_param` method which returns a
461.1559 - value usable as argument (integer, string, ctypes instance). This allows
461.1560 - to define adapters that can adapt custom objects as function parameters.
461.1561 -
461.1562 -
461.1563 - .. attribute:: errcheck
461.1564 -
461.1565 - Assign a Python function or another callable to this attribute. The
461.1566 - callable will be called with three or more arguments:
461.1567 -
461.1568 - .. function:: callable(result, func, arguments)
461.1569 - :noindex:
461.1570 -
461.1571 - ``result`` is what the foreign function returns, as specified
461.1572 - by the :attr:`restype` attribute.
461.1573 -
461.1574 - ``func`` is the foreign function object itself, this allows
461.1575 - to reuse the same callable object to check or post process
461.1576 - the results of several functions.
461.1577 -
461.1578 - ``arguments`` is a tuple containing the parameters originally
461.1579 - passed to the function call, this allows to specialize the
461.1580 - behavior on the arguments used.
461.1581 -
461.1582 - The object that this function returns will be returned from the
461.1583 - foreign function call, but it can also check the result value
461.1584 - and raise an exception if the foreign function call failed.
461.1585 -
461.1586 -
461.1587 -.. exception:: ArgumentError()
461.1588 -
461.1589 - This exception is raised when a foreign function call cannot convert one of the
461.1590 - passed arguments.
461.1591 -
461.1592 -
461.1593 -.. _ctypes-function-prototypes:
461.1594 -
461.1595 -Function prototypes
461.1596 -^^^^^^^^^^^^^^^^^^^
461.1597 -
461.1598 -Foreign functions can also be created by instantiating function prototypes.
461.1599 -Function prototypes are similar to function prototypes in C; they describe a
461.1600 -function (return type, argument types, calling convention) without defining an
461.1601 -implementation. The factory functions must be called with the desired result
461.1602 -type and the argument types of the function.
461.1603 -
461.1604 -
461.1605 -.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
461.1606 -
461.1607 - The returned function prototype creates functions that use the standard C
461.1608 - calling convention. The function will release the GIL during the call.
461.1609 - If `use_errno` is set to True, the ctypes private copy of the system `errno`
461.1610 - variable is exchanged with the real `errno` value bafore and after the call;
461.1611 - `use_last_error` does the same for the Windows error code.
461.1612 -
461.1613 - .. versionchanged:: 2.6
461.1614 - The optional `use_errno` and `use_last_error` parameters were
461.1615 - added.
461.1616 -
461.1617 -
461.1618 -.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
461.1619 -
461.1620 - Windows only: The returned function prototype creates functions that use the
461.1621 - ``stdcall`` calling convention, except on Windows CE where :func:`WINFUNCTYPE`
461.1622 - is the same as :func:`CFUNCTYPE`. The function will release the GIL during the
461.1623 - call. `use_errno` and `use_last_error` have the same meaning as above.
461.1624 -
461.1625 -
461.1626 -.. function:: PYFUNCTYPE(restype, *argtypes)
461.1627 -
461.1628 - The returned function prototype creates functions that use the Python calling
461.1629 - convention. The function will *not* release the GIL during the call.
461.1630 -
461.1631 -Function prototypes created by these factory functions can be instantiated in
461.1632 -different ways, depending on the type and number of the parameters in the call:
461.1633 -
461.1634 -
461.1635 - .. function:: prototype(address)
461.1636 - :noindex:
461.1637 - :module:
461.1638 -
461.1639 - Returns a foreign function at the specified address which must be an integer.
461.1640 -
461.1641 -
461.1642 - .. function:: prototype(callable)
461.1643 - :noindex:
461.1644 - :module:
461.1645 -
461.1646 - Create a C callable function (a callback function) from a Python ``callable``.
461.1647 -
461.1648 -
461.1649 - .. function:: prototype(func_spec[, paramflags])
461.1650 - :noindex:
461.1651 - :module:
461.1652 -
461.1653 - Returns a foreign function exported by a shared library. ``func_spec`` must be a
461.1654 - 2-tuple ``(name_or_ordinal, library)``. The first item is the name of the
461.1655 - exported function as string, or the ordinal of the exported function as small
461.1656 - integer. The second item is the shared library instance.
461.1657 -
461.1658 -
461.1659 - .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
461.1660 - :noindex:
461.1661 - :module:
461.1662 -
461.1663 - Returns a foreign function that will call a COM method. ``vtbl_index`` is the
461.1664 - index into the virtual function table, a small non-negative integer. *name* is
461.1665 - name of the COM method. *iid* is an optional pointer to the interface identifier
461.1666 - which is used in extended error reporting.
461.1667 -
461.1668 - COM methods use a special calling convention: They require a pointer to the COM
461.1669 - interface as first argument, in addition to those parameters that are specified
461.1670 - in the :attr:`argtypes` tuple.
461.1671 -
461.1672 - The optional *paramflags* parameter creates foreign function wrappers with much
461.1673 - more functionality than the features described above.
461.1674 -
461.1675 - *paramflags* must be a tuple of the same length as :attr:`argtypes`.
461.1676 -
461.1677 - Each item in this tuple contains further information about a parameter, it must
461.1678 - be a tuple containing one, two, or three items.
461.1679 -
461.1680 - The first item is an integer containing a combination of direction
461.1681 - flags for the parameter:
461.1682 -
461.1683 - 1
461.1684 - Specifies an input parameter to the function.
461.1685 -
461.1686 - 2
461.1687 - Output parameter. The foreign function fills in a value.
461.1688 -
461.1689 - 4
461.1690 - Input parameter which defaults to the integer zero.
461.1691 -
461.1692 - The optional second item is the parameter name as string. If this is specified,
461.1693 - the foreign function can be called with named parameters.
461.1694 -
461.1695 - The optional third item is the default value for this parameter.
461.1696 -
461.1697 -This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
461.1698 -that it supports default parameters and named arguments. The C declaration from
461.1699 -the windows header file is this::
461.1700 -
461.1701 - WINUSERAPI int WINAPI
461.1702 - MessageBoxA(
461.1703 - HWND hWnd ,
461.1704 - LPCSTR lpText,
461.1705 - LPCSTR lpCaption,
461.1706 - UINT uType);
461.1707 -
461.1708 -Here is the wrapping with ``ctypes``::
461.1709 -
461.1710 - >>> from ctypes import c_int, WINFUNCTYPE, windll
461.1711 - >>> from ctypes.wintypes import HWND, LPCSTR, UINT
461.1712 - >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
461.1713 - >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
461.1714 - >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
461.1715 - >>>
461.1716 -
461.1717 -The MessageBox foreign function can now be called in these ways::
461.1718 -
461.1719 - >>> MessageBox()
461.1720 - >>> MessageBox(text="Spam, spam, spam")
461.1721 - >>> MessageBox(flags=2, text="foo bar")
461.1722 - >>>
461.1723 -
461.1724 -A second example demonstrates output parameters. The win32 ``GetWindowRect``
461.1725 -function retrieves the dimensions of a specified window by copying them into
461.1726 -``RECT`` structure that the caller has to supply. Here is the C declaration::
461.1727 -
461.1728 - WINUSERAPI BOOL WINAPI
461.1729 - GetWindowRect(
461.1730 - HWND hWnd,
461.1731 - LPRECT lpRect);
461.1732 -
461.1733 -Here is the wrapping with ``ctypes``::
461.1734 -
461.1735 - >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
461.1736 - >>> from ctypes.wintypes import BOOL, HWND, RECT
461.1737 - >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
461.1738 - >>> paramflags = (1, "hwnd"), (2, "lprect")
461.1739 - >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
461.1740 - >>>
461.1741 -
461.1742 -Functions with output parameters will automatically return the output parameter
461.1743 -value if there is a single one, or a tuple containing the output parameter
461.1744 -values when there are more than one, so the GetWindowRect function now returns a
461.1745 -RECT instance, when called.
461.1746 -
461.1747 -Output parameters can be combined with the :attr:`errcheck` protocol to do
461.1748 -further output processing and error checking. The win32 ``GetWindowRect`` api
461.1749 -function returns a ``BOOL`` to signal success or failure, so this function could
461.1750 -do the error checking, and raises an exception when the api call failed::
461.1751 -
461.1752 - >>> def errcheck(result, func, args):
461.1753 - ... if not result:
461.1754 - ... raise WinError()
461.1755 - ... return args
461.1756 - ...
461.1757 - >>> GetWindowRect.errcheck = errcheck
461.1758 - >>>
461.1759 -
461.1760 -If the :attr:`errcheck` function returns the argument tuple it receives
461.1761 -unchanged, ``ctypes`` continues the normal processing it does on the output
461.1762 -parameters. If you want to return a tuple of window coordinates instead of a
461.1763 -``RECT`` instance, you can retrieve the fields in the function and return them
461.1764 -instead, the normal processing will no longer take place::
461.1765 -
461.1766 - >>> def errcheck(result, func, args):
461.1767 - ... if not result:
461.1768 - ... raise WinError()
461.1769 - ... rc = args[1]
461.1770 - ... return rc.left, rc.top, rc.bottom, rc.right
461.1771 - ...
461.1772 - >>> GetWindowRect.errcheck = errcheck
461.1773 - >>>
461.1774 -
461.1775 -
461.1776 -.. _ctypes-utility-functions:
461.1777 -
461.1778 -Utility functions
461.1779 -^^^^^^^^^^^^^^^^^
461.1780 -
461.1781 -
461.1782 -.. function:: addressof(obj)
461.1783 -
461.1784 - Returns the address of the memory buffer as integer. ``obj`` must be an
461.1785 - instance of a ctypes type.
461.1786 -
461.1787 -
461.1788 -.. function:: alignment(obj_or_type)
461.1789 -
461.1790 - Returns the alignment requirements of a ctypes type. ``obj_or_type`` must be a
461.1791 - ctypes type or instance.
461.1792 -
461.1793 -
461.1794 -.. function:: byref(obj[, offset])
461.1795 -
461.1796 - Returns a light-weight pointer to ``obj``, which must be an
461.1797 - instance of a ctypes type. ``offset`` defaults to zero, and must be
461.1798 - an integer that will be added to the internal pointer value.
461.1799 -
461.1800 - ``byref(obj, offset)`` corresponds to this C code::
461.1801 -
461.1802 - (((char *)&obj) + offset)
461.1803 -
461.1804 - The returned object can only be used as a foreign function call
461.1805 - parameter. It behaves similar to ``pointer(obj)``, but the
461.1806 - construction is a lot faster.
461.1807 -
461.1808 - .. versionadded:: 2.6
461.1809 - The ``offset`` optional argument was added.
461.1810 -
461.1811 -.. function:: cast(obj, type)
461.1812 -
461.1813 - This function is similar to the cast operator in C. It returns a new instance of
461.1814 - ``type`` which points to the same memory block as ``obj``. ``type`` must be a
461.1815 - pointer type, and ``obj`` must be an object that can be interpreted as a
461.1816 - pointer.
461.1817 -
461.1818 -
461.1819 -.. function:: create_string_buffer(init_or_size[, size])
461.1820 -
461.1821 - This function creates a mutable character buffer. The returned object is a
461.1822 - ctypes array of :class:`c_char`.
461.1823 -
461.1824 - ``init_or_size`` must be an integer which specifies the size of the array, or a
461.1825 - string which will be used to initialize the array items.
461.1826 -
461.1827 - If a string is specified as first argument, the buffer is made one item larger
461.1828 - than the length of the string so that the last element in the array is a NUL
461.1829 - termination character. An integer can be passed as second argument which allows
461.1830 - to specify the size of the array if the length of the string should not be used.
461.1831 -
461.1832 - If the first parameter is a unicode string, it is converted into an 8-bit string
461.1833 - according to ctypes conversion rules.
461.1834 -
461.1835 -
461.1836 -.. function:: create_unicode_buffer(init_or_size[, size])
461.1837 -
461.1838 - This function creates a mutable unicode character buffer. The returned object is
461.1839 - a ctypes array of :class:`c_wchar`.
461.1840 -
461.1841 - ``init_or_size`` must be an integer which specifies the size of the array, or a
461.1842 - unicode string which will be used to initialize the array items.
461.1843 -
461.1844 - If a unicode string is specified as first argument, the buffer is made one item
461.1845 - larger than the length of the string so that the last element in the array is a
461.1846 - NUL termination character. An integer can be passed as second argument which
461.1847 - allows to specify the size of the array if the length of the string should not
461.1848 - be used.
461.1849 -
461.1850 - If the first parameter is a 8-bit string, it is converted into an unicode string
461.1851 - according to ctypes conversion rules.
461.1852 -
461.1853 -
461.1854 -.. function:: DllCanUnloadNow()
461.1855 -
461.1856 - Windows only: This function is a hook which allows to implement in-process COM
461.1857 - servers with ctypes. It is called from the DllCanUnloadNow function that the
461.1858 - _ctypes extension dll exports.
461.1859 -
461.1860 -
461.1861 -.. function:: DllGetClassObject()
461.1862 -
461.1863 - Windows only: This function is a hook which allows to implement in-process COM
461.1864 - servers with ctypes. It is called from the DllGetClassObject function that the
461.1865 - ``_ctypes`` extension dll exports.
461.1866 -
461.1867 -.. function:: find_library(name)
461.1868 - :module: ctypes.util
461.1869 -
461.1870 - Try to find a library and return a pathname. `name` is the library name without
461.1871 - any prefix like `lib`, suffix like ``.so``, ``.dylib`` or version number (this
461.1872 - is the form used for the posix linker option :option:`-l`). If no library can
461.1873 - be found, returns ``None``.
461.1874 -
461.1875 - The exact functionality is system dependent.
461.1876 -
461.1877 - .. versionchanged:: 2.6
461.1878 - Windows only: ``find_library("m")`` or
461.1879 - ``find_library("c")`` return the result of a call to
461.1880 - ``find_msvcrt()``.
461.1881 -
461.1882 -.. function:: find_msvcrt()
461.1883 - :module: ctypes.util
461.1884 -
461.1885 - Windows only: return the filename of the VC runtype library used
461.1886 - by Python, and by the extension modules. If the name of the
461.1887 - library cannot be determined, ``None`` is returned.
461.1888 -
461.1889 - If you need to free memory, for example, allocated by an extension
461.1890 - module with a call to the ``free(void *)``, it is important that you
461.1891 - use the function in the same library that allocated the memory.
461.1892 -
461.1893 - .. versionadded:: 2.6
461.1894 -
461.1895 -.. function:: FormatError([code])
461.1896 -
461.1897 - Windows only: Returns a textual description of the error code. If no error code
461.1898 - is specified, the last error code is used by calling the Windows api function
461.1899 - GetLastError.
461.1900 -
461.1901 -
461.1902 -.. function:: GetLastError()
461.1903 -
461.1904 - Windows only: Returns the last error code set by Windows in the calling thread.
461.1905 - This function calls the Windows `GetLastError()` function directly,
461.1906 - it does not return the ctypes-private copy of the error code.
461.1907 -
461.1908 -.. function:: get_errno()
461.1909 -
461.1910 - Returns the current value of the ctypes-private copy of the system
461.1911 - `errno` variable in the calling thread.
461.1912 -
461.1913 - .. versionadded:: 2.6
461.1914 -
461.1915 -.. function:: get_last_error()
461.1916 -
461.1917 - Windows only: returns the current value of the ctypes-private copy of the system
461.1918 - `LastError` variable in the calling thread.
461.1919 -
461.1920 - .. versionadded:: 2.6
461.1921 -
461.1922 -.. function:: memmove(dst, src, count)
461.1923 -
461.1924 - Same as the standard C memmove library function: copies *count* bytes from
461.1925 - ``src`` to *dst*. *dst* and ``src`` must be integers or ctypes instances that
461.1926 - can be converted to pointers.
461.1927 -
461.1928 -
461.1929 -.. function:: memset(dst, c, count)
461.1930 -
461.1931 - Same as the standard C memset library function: fills the memory block at
461.1932 - address *dst* with *count* bytes of value *c*. *dst* must be an integer
461.1933 - specifying an address, or a ctypes instance.
461.1934 -
461.1935 -
461.1936 -.. function:: POINTER(type)
461.1937 -
461.1938 - This factory function creates and returns a new ctypes pointer type. Pointer
461.1939 - types are cached an reused internally, so calling this function repeatedly is
461.1940 - cheap. type must be a ctypes type.
461.1941 -
461.1942 -
461.1943 -.. function:: pointer(obj)
461.1944 -
461.1945 - This function creates a new pointer instance, pointing to ``obj``. The returned
461.1946 - object is of the type POINTER(type(obj)).
461.1947 -
461.1948 - Note: If you just want to pass a pointer to an object to a foreign function
461.1949 - call, you should use ``byref(obj)`` which is much faster.
461.1950 -
461.1951 -
461.1952 -.. function:: resize(obj, size)
461.1953 -
461.1954 - This function resizes the internal memory buffer of obj, which must be an
461.1955 - instance of a ctypes type. It is not possible to make the buffer smaller than
461.1956 - the native size of the objects type, as given by sizeof(type(obj)), but it is
461.1957 - possible to enlarge the buffer.
461.1958 -
461.1959 -
461.1960 -.. function:: set_conversion_mode(encoding, errors)
461.1961 -
461.1962 - This function sets the rules that ctypes objects use when converting between
461.1963 - 8-bit strings and unicode strings. encoding must be a string specifying an
461.1964 - encoding, like ``'utf-8'`` or ``'mbcs'``, errors must be a string specifying the
461.1965 - error handling on encoding/decoding errors. Examples of possible values are
461.1966 - ``"strict"``, ``"replace"``, or ``"ignore"``.
461.1967 -
461.1968 - ``set_conversion_mode`` returns a 2-tuple containing the previous conversion
461.1969 - rules. On windows, the initial conversion rules are ``('mbcs', 'ignore')``, on
461.1970 - other systems ``('ascii', 'strict')``.
461.1971 -
461.1972 -
461.1973 -.. function:: set_errno(value)
461.1974 -
461.1975 - Set the current value of the ctypes-private copy of the system
461.1976 - `errno` variable in the calling thread to `value` and return the
461.1977 - previous value.
461.1978 -
461.1979 - .. versionadded:: 2.6
461.1980 -
461.1981 -.. function:: set_last_error(value)
461.1982 -
461.1983 - Windows only: set the current value of the ctypes-private copy of
461.1984 - the system `LastError` variable in the calling thread to `value`
461.1985 - and return the previous value.
461.1986 -
461.1987 - .. versionadded:: 2.6
461.1988 -
461.1989 -.. function:: sizeof(obj_or_type)
461.1990 -
461.1991 - Returns the size in bytes of a ctypes type or instance memory buffer. Does the
461.1992 - same as the C ``sizeof()`` function.
461.1993 -
461.1994 -
461.1995 -.. function:: string_at(address[, size])
461.1996 -
461.1997 - This function returns the string starting at memory address address. If size
461.1998 - is specified, it is used as size, otherwise the string is assumed to be
461.1999 - zero-terminated.
461.2000 -
461.2001 -
461.2002 -.. function:: WinError(code=None, descr=None)
461.2003 -
461.2004 - Windows only: this function is probably the worst-named thing in ctypes. It
461.2005 - creates an instance of WindowsError. If *code* is not specified,
461.2006 - ``GetLastError`` is called to determine the error code. If ``descr`` is not
461.2007 - specified, :func:`FormatError` is called to get a textual description of the
461.2008 - error.
461.2009 -
461.2010 -
461.2011 -.. function:: wstring_at(address)
461.2012 -
461.2013 - This function returns the wide character string starting at memory address
461.2014 - ``address`` as unicode string. If ``size`` is specified, it is used as the
461.2015 - number of characters of the string, otherwise the string is assumed to be
461.2016 - zero-terminated.
461.2017 -
461.2018 -
461.2019 -.. _ctypes-data-types:
461.2020 -
461.2021 -Data types
461.2022 -^^^^^^^^^^
461.2023 -
461.2024 -
461.2025 -.. class:: _CData
461.2026 -
461.2027 - This non-public class is the common base class of all ctypes data types. Among
461.2028 - other things, all ctypes type instances contain a memory block that hold C
461.2029 - compatible data; the address of the memory block is returned by the
461.2030 - ``addressof()`` helper function. Another instance variable is exposed as
461.2031 - :attr:`_objects`; this contains other Python objects that need to be kept alive
461.2032 - in case the memory block contains pointers.
461.2033 -
461.2034 - Common methods of ctypes data types, these are all class methods (to be
461.2035 - exact, they are methods of the :term:`metaclass`):
461.2036 -
461.2037 -
461.2038 - .. method:: _CData.from_buffer(source[, offset])
461.2039 -
461.2040 - This method returns a ctypes instance that shares the buffer of
461.2041 - the ``source`` object. The ``source`` object must support the
461.2042 - writeable buffer interface. The optional ``offset`` parameter
461.2043 - specifies an offset into the source buffer in bytes; the default
461.2044 - is zero. If the source buffer is not large enough a ValueError
461.2045 - is raised.
461.2046 -
461.2047 - .. versionadded:: 2.6
461.2048 -
461.2049 - .. method:: _CData.from_buffer_copy(source[, offset])
461.2050 -
461.2051 - This method creates a ctypes instance, copying the buffer from
461.2052 - the source object buffer which must be readable. The optional
461.2053 - ``offset`` parameter specifies an offset into the source buffer
461.2054 - in bytes; the default is zero. If the source buffer is not
461.2055 - large enough a ValueError is raised.
461.2056 -
461.2057 - .. versionadded:: 2.6
461.2058 -
461.2059 -
461.2060 - .. method:: from_address(address)
461.2061 -
461.2062 - This method returns a ctypes type instance using the memory specified by
461.2063 - address which must be an integer.
461.2064 -
461.2065 -
461.2066 - .. method:: from_param(obj)
461.2067 -
461.2068 - This method adapts *obj* to a ctypes type. It is called with the actual
461.2069 - object used in a foreign function call when the type is present in the
461.2070 - foreign function's :attr:`argtypes` tuple; it must return an object that
461.2071 - can be used as a function call parameter.
461.2072 -
461.2073 - All ctypes data types have a default implementation of this classmethod
461.2074 - that normally returns ``obj`` if that is an instance of the type. Some
461.2075 - types accept other objects as well.
461.2076 -
461.2077 -
461.2078 - .. method:: in_dll(library, name)
461.2079 -
461.2080 - This method returns a ctypes type instance exported by a shared
461.2081 - library. *name* is the name of the symbol that exports the data, *library*
461.2082 - is the loaded shared library.
461.2083 -
461.2084 -
461.2085 - Common instance variables of ctypes data types:
461.2086 -
461.2087 -
461.2088 - .. attribute:: _b_base_
461.2089 -
461.2090 - Sometimes ctypes data instances do not own the memory block they contain,
461.2091 - instead they share part of the memory block of a base object. The
461.2092 - :attr:`_b_base_` read-only member is the root ctypes object that owns the
461.2093 - memory block.
461.2094 -
461.2095 -
461.2096 - .. attribute:: _b_needsfree_
461.2097 -
461.2098 - This read-only variable is true when the ctypes data instance has
461.2099 - allocated the memory block itself, false otherwise.
461.2100 -
461.2101 -
461.2102 - .. attribute:: _objects
461.2103 -
461.2104 - This member is either ``None`` or a dictionary containing Python objects
461.2105 - that need to be kept alive so that the memory block contents is kept
461.2106 - valid. This object is only exposed for debugging; never modify the
461.2107 - contents of this dictionary.
461.2108 -
461.2109 -
461.2110 -.. _ctypes-fundamental-data-types-2:
461.2111 -
461.2112 -Fundamental data types
461.2113 -^^^^^^^^^^^^^^^^^^^^^^
461.2114 -
461.2115 -
461.2116 -.. class:: _SimpleCData
461.2117 -
461.2118 - This non-public class is the base class of all fundamental ctypes data types. It
461.2119 - is mentioned here because it contains the common attributes of the fundamental
461.2120 - ctypes data types. ``_SimpleCData`` is a subclass of ``_CData``, so it inherits
461.2121 - their methods and attributes.
461.2122 -
461.2123 - .. versionchanged:: 2.6
461.2124 - ctypes data types that are not and do not contain pointers can
461.2125 - now be pickled.
461.2126 -
461.2127 - Instances have a single attribute:
461.2128 -
461.2129 -
461.2130 - .. attribute:: value
461.2131 -
461.2132 - This attribute contains the actual value of the instance. For integer and
461.2133 - pointer types, it is an integer, for character types, it is a single
461.2134 - character string, for character pointer types it is a Python string or
461.2135 - unicode string.
461.2136 -
461.2137 - When the ``value`` attribute is retrieved from a ctypes instance, usually
461.2138 - a new object is returned each time. ``ctypes`` does *not* implement
461.2139 - original object return, always a new object is constructed. The same is
461.2140 - true for all other ctypes object instances.
461.2141 -
461.2142 -Fundamental data types, when returned as foreign function call results, or, for
461.2143 -example, by retrieving structure field members or array items, are transparently
461.2144 -converted to native Python types. In other words, if a foreign function has a
461.2145 -:attr:`restype` of :class:`c_char_p`, you will always receive a Python string,
461.2146 -*not* a :class:`c_char_p` instance.
461.2147 -
461.2148 -Subclasses of fundamental data types do *not* inherit this behavior. So, if a
461.2149 -foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
461.2150 -receive an instance of this subclass from the function call. Of course, you can
461.2151 -get the value of the pointer by accessing the ``value`` attribute.
461.2152 -
461.2153 -These are the fundamental ctypes data types:
461.2154 -
461.2155 -
461.2156 -.. class:: c_byte
461.2157 -
461.2158 - Represents the C signed char datatype, and interprets the value as small
461.2159 - integer. The constructor accepts an optional integer initializer; no overflow
461.2160 - checking is done.
461.2161 -
461.2162 -
461.2163 -.. class:: c_char
461.2164 -
461.2165 - Represents the C char datatype, and interprets the value as a single character.
461.2166 - The constructor accepts an optional string initializer, the length of the string
461.2167 - must be exactly one character.
461.2168 -
461.2169 -
461.2170 -.. class:: c_char_p
461.2171 -
461.2172 - Represents the C char \* datatype, which must be a pointer to a zero-terminated
461.2173 - string. The constructor accepts an integer address, or a string.
461.2174 -
461.2175 -
461.2176 -.. class:: c_double
461.2177 -
461.2178 - Represents the C double datatype. The constructor accepts an optional float
461.2179 - initializer.
461.2180 -
461.2181 -
461.2182 -.. class:: c_longdouble
461.2183 -
461.2184 - Represents the C long double datatype. The constructor accepts an
461.2185 - optional float initializer. On platforms where ``sizeof(long
461.2186 - double) == sizeof(double)`` it is an alias to :class:`c_double`.
461.2187 -
461.2188 - .. versionadded:: 2.6
461.2189 -
461.2190 -.. class:: c_float
461.2191 -
461.2192 - Represents the C float datatype. The constructor accepts an optional float
461.2193 - initializer.
461.2194 -
461.2195 -
461.2196 -.. class:: c_int
461.2197 -
461.2198 - Represents the C signed int datatype. The constructor accepts an optional
461.2199 - integer initializer; no overflow checking is done. On platforms where
461.2200 - ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
461.2201 -
461.2202 -
461.2203 -.. class:: c_int8
461.2204 -
461.2205 - Represents the C 8-bit ``signed int`` datatype. Usually an alias for
461.2206 - :class:`c_byte`.
461.2207 -
461.2208 -
461.2209 -.. class:: c_int16
461.2210 -
461.2211 - Represents the C 16-bit signed int datatype. Usually an alias for
461.2212 - :class:`c_short`.
461.2213 -
461.2214 -
461.2215 -.. class:: c_int32
461.2216 -
461.2217 - Represents the C 32-bit signed int datatype. Usually an alias for
461.2218 - :class:`c_int`.
461.2219 -
461.2220 -
461.2221 -.. class:: c_int64
461.2222 -
461.2223 - Represents the C 64-bit ``signed int`` datatype. Usually an alias for
461.2224 - :class:`c_longlong`.
461.2225 -
461.2226 -
461.2227 -.. class:: c_long
461.2228 -
461.2229 - Represents the C ``signed long`` datatype. The constructor accepts an optional
461.2230 - integer initializer; no overflow checking is done.
461.2231 -
461.2232 -
461.2233 -.. class:: c_longlong
461.2234 -
461.2235 - Represents the C ``signed long long`` datatype. The constructor accepts an
461.2236 - optional integer initializer; no overflow checking is done.
461.2237 -
461.2238 -
461.2239 -.. class:: c_short
461.2240 -
461.2241 - Represents the C ``signed short`` datatype. The constructor accepts an optional
461.2242 - integer initializer; no overflow checking is done.
461.2243 -
461.2244 -
461.2245 -.. class:: c_size_t
461.2246 -
461.2247 - Represents the C ``size_t`` datatype.
461.2248 -
461.2249 -
461.2250 -.. class:: c_ubyte
461.2251 -
461.2252 - Represents the C ``unsigned char`` datatype, it interprets the value as small
461.2253 - integer. The constructor accepts an optional integer initializer; no overflow
461.2254 - checking is done.
461.2255 -
461.2256 -
461.2257 -.. class:: c_uint
461.2258 -
461.2259 - Represents the C ``unsigned int`` datatype. The constructor accepts an optional
461.2260 - integer initializer; no overflow checking is done. On platforms where
461.2261 - ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
461.2262 -
461.2263 -
461.2264 -.. class:: c_uint8
461.2265 -
461.2266 - Represents the C 8-bit unsigned int datatype. Usually an alias for
461.2267 - :class:`c_ubyte`.
461.2268 -
461.2269 -
461.2270 -.. class:: c_uint16
461.2271 -
461.2272 - Represents the C 16-bit unsigned int datatype. Usually an alias for
461.2273 - :class:`c_ushort`.
461.2274 -
461.2275 -
461.2276 -.. class:: c_uint32
461.2277 -
461.2278 - Represents the C 32-bit unsigned int datatype. Usually an alias for
461.2279 - :class:`c_uint`.
461.2280 -
461.2281 -
461.2282 -.. class:: c_uint64
461.2283 -
461.2284 - Represents the C 64-bit unsigned int datatype. Usually an alias for
461.2285 - :class:`c_ulonglong`.
461.2286 -
461.2287 -
461.2288 -.. class:: c_ulong
461.2289 -
461.2290 - Represents the C ``unsigned long`` datatype. The constructor accepts an optional
461.2291 - integer initializer; no overflow checking is done.
461.2292 -
461.2293 -
461.2294 -.. class:: c_ulonglong
461.2295 -
461.2296 - Represents the C ``unsigned long long`` datatype. The constructor accepts an
461.2297 - optional integer initializer; no overflow checking is done.
461.2298 -
461.2299 -
461.2300 -.. class:: c_ushort
461.2301 -
461.2302 - Represents the C ``unsigned short`` datatype. The constructor accepts an
461.2303 - optional integer initializer; no overflow checking is done.
461.2304 -
461.2305 -
461.2306 -.. class:: c_void_p
461.2307 -
461.2308 - Represents the C ``void *`` type. The value is represented as integer. The
461.2309 - constructor accepts an optional integer initializer.
461.2310 -
461.2311 -
461.2312 -.. class:: c_wchar
461.2313 -
461.2314 - Represents the C ``wchar_t`` datatype, and interprets the value as a single
461.2315 - character unicode string. The constructor accepts an optional string
461.2316 - initializer, the length of the string must be exactly one character.
461.2317 -
461.2318 -
461.2319 -.. class:: c_wchar_p
461.2320 -
461.2321 - Represents the C ``wchar_t *`` datatype, which must be a pointer to a
461.2322 - zero-terminated wide character string. The constructor accepts an integer
461.2323 - address, or a string.
461.2324 -
461.2325 -
461.2326 -.. class:: c_bool
461.2327 -
461.2328 - Represent the C ``bool`` datatype (more accurately, _Bool from C99). Its value
461.2329 - can be True or False, and the constructor accepts any object that has a truth
461.2330 - value.
461.2331 -
461.2332 - .. versionadded:: 2.6
461.2333 -
461.2334 -
461.2335 -.. class:: HRESULT
461.2336 -
461.2337 - Windows only: Represents a :class:`HRESULT` value, which contains success or
461.2338 - error information for a function or method call.
461.2339 -
461.2340 -
461.2341 -.. class:: py_object
461.2342 -
461.2343 - Represents the C ``PyObject *`` datatype. Calling this without an argument
461.2344 - creates a ``NULL`` ``PyObject *`` pointer.
461.2345 -
461.2346 -The ``ctypes.wintypes`` module provides quite some other Windows specific data
461.2347 -types, for example ``HWND``, ``WPARAM``, or ``DWORD``. Some useful structures
461.2348 -like ``MSG`` or ``RECT`` are also defined.
461.2349 -
461.2350 -
461.2351 -.. _ctypes-structured-data-types:
461.2352 -
461.2353 -Structured data types
461.2354 -^^^^^^^^^^^^^^^^^^^^^
461.2355 -
461.2356 -
461.2357 -.. class:: Union(*args, **kw)
461.2358 -
461.2359 - Abstract base class for unions in native byte order.
461.2360 -
461.2361 -
461.2362 -.. class:: BigEndianStructure(*args, **kw)
461.2363 -
461.2364 - Abstract base class for structures in *big endian* byte order.
461.2365 -
461.2366 -
461.2367 -.. class:: LittleEndianStructure(*args, **kw)
461.2368 -
461.2369 - Abstract base class for structures in *little endian* byte order.
461.2370 -
461.2371 -Structures with non-native byte order cannot contain pointer type fields, or any
461.2372 -other data types containing pointer type fields.
461.2373 -
461.2374 -
461.2375 -.. class:: Structure(*args, **kw)
461.2376 -
461.2377 - Abstract base class for structures in *native* byte order.
461.2378 -
461.2379 - Concrete structure and union types must be created by subclassing one of these
461.2380 - types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will
461.2381 - create :term:`descriptor`\s which allow reading and writing the fields by direct
461.2382 - attribute accesses. These are the
461.2383 -
461.2384 -
461.2385 - .. attribute:: _fields_
461.2386 -
461.2387 - A sequence defining the structure fields. The items must be 2-tuples or
461.2388 - 3-tuples. The first item is the name of the field, the second item
461.2389 - specifies the type of the field; it can be any ctypes data type.
461.2390 -
461.2391 - For integer type fields like :class:`c_int`, a third optional item can be
461.2392 - given. It must be a small positive integer defining the bit width of the
461.2393 - field.
461.2394 -
461.2395 - Field names must be unique within one structure or union. This is not
461.2396 - checked, only one field can be accessed when names are repeated.
461.2397 -
461.2398 - It is possible to define the :attr:`_fields_` class variable *after* the
461.2399 - class statement that defines the Structure subclass, this allows to create
461.2400 - data types that directly or indirectly reference themselves::
461.2401 -
461.2402 - class List(Structure):
461.2403 - pass
461.2404 - List._fields_ = [("pnext", POINTER(List)),
461.2405 - ...
461.2406 - ]
461.2407 -
461.2408 - The :attr:`_fields_` class variable must, however, be defined before the
461.2409 - type is first used (an instance is created, ``sizeof()`` is called on it,
461.2410 - and so on). Later assignments to the :attr:`_fields_` class variable will
461.2411 - raise an AttributeError.
461.2412 -
461.2413 - Structure and union subclass constructors accept both positional and named
461.2414 - arguments. Positional arguments are used to initialize the fields in the
461.2415 - same order as they appear in the :attr:`_fields_` definition, named
461.2416 - arguments are used to initialize the fields with the corresponding name.
461.2417 -
461.2418 - It is possible to defined sub-subclasses of structure types, they inherit
461.2419 - the fields of the base class plus the :attr:`_fields_` defined in the
461.2420 - sub-subclass, if any.
461.2421 -
461.2422 -
461.2423 - .. attribute:: _pack_
461.2424 -
461.2425 - An optional small integer that allows to override the alignment of
461.2426 - structure fields in the instance. :attr:`_pack_` must already be defined
461.2427 - when :attr:`_fields_` is assigned, otherwise it will have no effect.
461.2428 -
461.2429 -
461.2430 - .. attribute:: _anonymous_
461.2431 -
461.2432 - An optional sequence that lists the names of unnamed (anonymous) fields.
461.2433 - ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned,
461.2434 - otherwise it will have no effect.
461.2435 -
461.2436 - The fields listed in this variable must be structure or union type fields.
461.2437 - ``ctypes`` will create descriptors in the structure type that allows to
461.2438 - access the nested fields directly, without the need to create the
461.2439 - structure or union field.
461.2440 -
461.2441 - Here is an example type (Windows)::
461.2442 -
461.2443 - class _U(Union):
461.2444 - _fields_ = [("lptdesc", POINTER(TYPEDESC)),
461.2445 - ("lpadesc", POINTER(ARRAYDESC)),
461.2446 - ("hreftype", HREFTYPE)]
461.2447 -
461.2448 - class TYPEDESC(Structure):
461.2449 - _fields_ = [("u", _U),
461.2450 - ("vt", VARTYPE)]
461.2451 -
461.2452 - _anonymous_ = ("u",)
461.2453 -
461.2454 - The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
461.2455 - specifies which one of the union fields is valid. Since the ``u`` field
461.2456 - is defined as anonymous field, it is now possible to access the members
461.2457 - directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
461.2458 - are equivalent, but the former is faster since it does not need to create
461.2459 - a temporary union instance::
461.2460 -
461.2461 - td = TYPEDESC()
461.2462 - td.vt = VT_PTR
461.2463 - td.lptdesc = POINTER(some_type)
461.2464 - td.u.lptdesc = POINTER(some_type)
461.2465 -
461.2466 -It is possible to defined sub-subclasses of structures, they inherit the fields
461.2467 -of the base class. If the subclass definition has a separate :attr:`_fields_`
461.2468 -variable, the fields specified in this are appended to the fields of the base
461.2469 -class.
461.2470 -
461.2471 -Structure and union constructors accept both positional and keyword arguments.
461.2472 -Positional arguments are used to initialize member fields in the same order as
461.2473 -they are appear in :attr:`_fields_`. Keyword arguments in the constructor are
461.2474 -interpreted as attribute assignments, so they will initialize :attr:`_fields_`
461.2475 -with the same name, or create new attributes for names not present in
461.2476 -:attr:`_fields_`.
461.2477 -
461.2478 -
461.2479 -.. _ctypes-arrays-pointers:
461.2480 -
461.2481 -Arrays and pointers
461.2482 -^^^^^^^^^^^^^^^^^^^
461.2483 -
461.2484 -Not yet written - please see the sections :ref:`ctypes-pointers` and
461.2485 -section :ref:`ctypes-arrays` in the tutorial.
461.2486 -
462.1 --- a/python.editor/test/unit/data/testfiles/rst/ctypes.rst.indexed Sun Jan 04 13:11:53 2015 -0600
462.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
462.3 @@ -1,553 +0,0 @@
462.4 -
462.5 -
462.6 -Document 0
462.7 -Searchable Keys:
462.8 - class : ArgumentError
462.9 - class-ig : argumenterror
462.10 - extends : Exception
462.11 - in : ctypes
462.12 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
462.13 -
462.14 -Not Searchable Keys:
462.15 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.16 -
462.17 -
462.18 -Document 1
462.19 -Searchable Keys:
462.20 - class : BigEndianStructure
462.21 - class-ig : bigendianstructure
462.22 - in : ctypes
462.23 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;*args,**kw;
462.24 -
462.25 -Not Searchable Keys:
462.26 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.27 -
462.28 -
462.29 -Document 2
462.30 -Searchable Keys:
462.31 - class : CDLL
462.32 - class-ig : cdll
462.33 - in : ctypes
462.34 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;name,mode,handle,use_errno,use_last_error;
462.35 -
462.36 -Not Searchable Keys:
462.37 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.38 -
462.39 -
462.40 -Document 3
462.41 -Searchable Keys:
462.42 - class : HRESULT
462.43 - class-ig : hresult
462.44 - in : ctypes
462.45 -
462.46 -Not Searchable Keys:
462.47 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.48 -
462.49 -
462.50 -Document 4
462.51 -Searchable Keys:
462.52 - class : LibraryLoader
462.53 - class-ig : libraryloader
462.54 - in : ctypes
462.55 - member : LoadLibrary;F;|DOCUMENTED|DOC_ONLY|;name;
462.56 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;dlltype;
462.57 -
462.58 -Not Searchable Keys:
462.59 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.60 -
462.61 -
462.62 -Document 5
462.63 -Searchable Keys:
462.64 - class : LittleEndianStructure
462.65 - class-ig : littleendianstructure
462.66 - in : ctypes
462.67 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;*args,**kw;
462.68 -
462.69 -Not Searchable Keys:
462.70 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.71 -
462.72 -
462.73 -Document 6
462.74 -Searchable Keys:
462.75 - class : OleDLL
462.76 - class-ig : oledll
462.77 - in : ctypes
462.78 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;name,mode,handle,use_errno,use_last_error;
462.79 -
462.80 -Not Searchable Keys:
462.81 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.82 -
462.83 -
462.84 -Document 7
462.85 -Searchable Keys:
462.86 - class : PyDLL
462.87 - class-ig : pydll
462.88 - in : ctypes
462.89 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;name,mode,handle;
462.90 - member : _handle;A;|DOCUMENTED|PRIVATE|DOC_ONLY|;
462.91 - member : _name;A;|DOCUMENTED|PRIVATE|DOC_ONLY|;
462.92 -
462.93 -Not Searchable Keys:
462.94 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.95 -
462.96 -
462.97 -Document 8
462.98 -Searchable Keys:
462.99 - class : Structure
462.100 - class-ig : structure
462.101 - in : ctypes
462.102 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;*args,**kw;
462.103 - member : _anonymous_;A;|DOCUMENTED|DOC_ONLY|;
462.104 - member : _fields_;A;|DOCUMENTED|DOC_ONLY|;
462.105 - member : _pack_;A;|DOCUMENTED|DOC_ONLY|;
462.106 -
462.107 -Not Searchable Keys:
462.108 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.109 -
462.110 -
462.111 -Document 9
462.112 -Searchable Keys:
462.113 - class : Union
462.114 - class-ig : union
462.115 - in : ctypes
462.116 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;*args,**kw;
462.117 -
462.118 -Not Searchable Keys:
462.119 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.120 -
462.121 -
462.122 -Document 10
462.123 -Searchable Keys:
462.124 - class : WinDLL
462.125 - class-ig : windll
462.126 - in : ctypes
462.127 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;name,mode,handle,use_errno,use_last_error;
462.128 -
462.129 -Not Searchable Keys:
462.130 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.131 -
462.132 -
462.133 -Document 11
462.134 -Searchable Keys:
462.135 - class : _CData
462.136 - class-ig : _cdata
462.137 - in : ctypes
462.138 - member : _b_base_;A;|DOCUMENTED|DOC_ONLY|;
462.139 - member : _b_needsfree_;A;|DOCUMENTED|DOC_ONLY|;
462.140 - member : _objects;A;|DOCUMENTED|PRIVATE|DOC_ONLY|;
462.141 - member : from_address;F;|DOCUMENTED|DOC_ONLY|;address;
462.142 - member : from_buffer;F;|DOCUMENTED|DOC_ONLY|;source,offset;
462.143 - member : from_buffer_copy;F;|DOCUMENTED|DOC_ONLY|;source,offset;
462.144 - member : from_param;F;|DOCUMENTED|DOC_ONLY|;obj;
462.145 - member : in_dll;F;|DOCUMENTED|DOC_ONLY|;library,name;
462.146 -
462.147 -Not Searchable Keys:
462.148 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.149 -
462.150 -
462.151 -Document 12
462.152 -Searchable Keys:
462.153 - class : _FuncPtr
462.154 - class-ig : _funcptr
462.155 - in : ctypes
462.156 - member : argtypes;A;|DOCUMENTED|DOC_ONLY|;
462.157 - member : errcheck;A;|DOCUMENTED|DOC_ONLY|;
462.158 - member : restype;A;|DOCUMENTED|DOC_ONLY|;
462.159 -
462.160 -Not Searchable Keys:
462.161 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.162 -
462.163 -
462.164 -Document 13
462.165 -Searchable Keys:
462.166 - class : _SimpleCData
462.167 - class-ig : _simplecdata
462.168 - in : ctypes
462.169 - member : value;A;|DOCUMENTED|DOC_ONLY|;
462.170 -
462.171 -Not Searchable Keys:
462.172 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.173 -
462.174 -
462.175 -Document 14
462.176 -Searchable Keys:
462.177 - class : c_bool
462.178 - class-ig : c_bool
462.179 - in : ctypes
462.180 -
462.181 -Not Searchable Keys:
462.182 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.183 -
462.184 -
462.185 -Document 15
462.186 -Searchable Keys:
462.187 - class : c_byte
462.188 - class-ig : c_byte
462.189 - in : ctypes
462.190 -
462.191 -Not Searchable Keys:
462.192 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.193 -
462.194 -
462.195 -Document 16
462.196 -Searchable Keys:
462.197 - class : c_char
462.198 - class-ig : c_char
462.199 - in : ctypes
462.200 -
462.201 -Not Searchable Keys:
462.202 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.203 -
462.204 -
462.205 -Document 17
462.206 -Searchable Keys:
462.207 - class : c_char_p
462.208 - class-ig : c_char_p
462.209 - in : ctypes
462.210 -
462.211 -Not Searchable Keys:
462.212 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.213 -
462.214 -
462.215 -Document 18
462.216 -Searchable Keys:
462.217 - class : c_double
462.218 - class-ig : c_double
462.219 - in : ctypes
462.220 -
462.221 -Not Searchable Keys:
462.222 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.223 -
462.224 -
462.225 -Document 19
462.226 -Searchable Keys:
462.227 - class : c_float
462.228 - class-ig : c_float
462.229 - in : ctypes
462.230 -
462.231 -Not Searchable Keys:
462.232 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.233 -
462.234 -
462.235 -Document 20
462.236 -Searchable Keys:
462.237 - class : c_int
462.238 - class-ig : c_int
462.239 - in : ctypes
462.240 -
462.241 -Not Searchable Keys:
462.242 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.243 -
462.244 -
462.245 -Document 21
462.246 -Searchable Keys:
462.247 - class : c_int16
462.248 - class-ig : c_int16
462.249 - in : ctypes
462.250 -
462.251 -Not Searchable Keys:
462.252 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.253 -
462.254 -
462.255 -Document 22
462.256 -Searchable Keys:
462.257 - class : c_int32
462.258 - class-ig : c_int32
462.259 - in : ctypes
462.260 -
462.261 -Not Searchable Keys:
462.262 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.263 -
462.264 -
462.265 -Document 23
462.266 -Searchable Keys:
462.267 - class : c_int64
462.268 - class-ig : c_int64
462.269 - in : ctypes
462.270 -
462.271 -Not Searchable Keys:
462.272 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.273 -
462.274 -
462.275 -Document 24
462.276 -Searchable Keys:
462.277 - class : c_int8
462.278 - class-ig : c_int8
462.279 - in : ctypes
462.280 -
462.281 -Not Searchable Keys:
462.282 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.283 -
462.284 -
462.285 -Document 25
462.286 -Searchable Keys:
462.287 - class : c_long
462.288 - class-ig : c_long
462.289 - in : ctypes
462.290 -
462.291 -Not Searchable Keys:
462.292 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.293 -
462.294 -
462.295 -Document 26
462.296 -Searchable Keys:
462.297 - class : c_longdouble
462.298 - class-ig : c_longdouble
462.299 - in : ctypes
462.300 -
462.301 -Not Searchable Keys:
462.302 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.303 -
462.304 -
462.305 -Document 27
462.306 -Searchable Keys:
462.307 - class : c_longlong
462.308 - class-ig : c_longlong
462.309 - in : ctypes
462.310 -
462.311 -Not Searchable Keys:
462.312 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.313 -
462.314 -
462.315 -Document 28
462.316 -Searchable Keys:
462.317 - class : c_short
462.318 - class-ig : c_short
462.319 - in : ctypes
462.320 -
462.321 -Not Searchable Keys:
462.322 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.323 -
462.324 -
462.325 -Document 29
462.326 -Searchable Keys:
462.327 - class : c_size_t
462.328 - class-ig : c_size_t
462.329 - in : ctypes
462.330 -
462.331 -Not Searchable Keys:
462.332 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.333 -
462.334 -
462.335 -Document 30
462.336 -Searchable Keys:
462.337 - class : c_ubyte
462.338 - class-ig : c_ubyte
462.339 - in : ctypes
462.340 -
462.341 -Not Searchable Keys:
462.342 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.343 -
462.344 -
462.345 -Document 31
462.346 -Searchable Keys:
462.347 - class : c_uint
462.348 - class-ig : c_uint
462.349 - in : ctypes
462.350 -
462.351 -Not Searchable Keys:
462.352 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.353 -
462.354 -
462.355 -Document 32
462.356 -Searchable Keys:
462.357 - class : c_uint16
462.358 - class-ig : c_uint16
462.359 - in : ctypes
462.360 -
462.361 -Not Searchable Keys:
462.362 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.363 -
462.364 -
462.365 -Document 33
462.366 -Searchable Keys:
462.367 - class : c_uint32
462.368 - class-ig : c_uint32
462.369 - in : ctypes
462.370 -
462.371 -Not Searchable Keys:
462.372 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.373 -
462.374 -
462.375 -Document 34
462.376 -Searchable Keys:
462.377 - class : c_uint64
462.378 - class-ig : c_uint64
462.379 - in : ctypes
462.380 -
462.381 -Not Searchable Keys:
462.382 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.383 -
462.384 -
462.385 -Document 35
462.386 -Searchable Keys:
462.387 - class : c_uint8
462.388 - class-ig : c_uint8
462.389 - in : ctypes
462.390 -
462.391 -Not Searchable Keys:
462.392 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.393 -
462.394 -
462.395 -Document 36
462.396 -Searchable Keys:
462.397 - class : c_ulong
462.398 - class-ig : c_ulong
462.399 - in : ctypes
462.400 -
462.401 -Not Searchable Keys:
462.402 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.403 -
462.404 -
462.405 -Document 37
462.406 -Searchable Keys:
462.407 - class : c_ulonglong
462.408 - class-ig : c_ulonglong
462.409 - in : ctypes
462.410 -
462.411 -Not Searchable Keys:
462.412 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.413 -
462.414 -
462.415 -Document 38
462.416 -Searchable Keys:
462.417 - class : c_ushort
462.418 - class-ig : c_ushort
462.419 - in : ctypes
462.420 -
462.421 -Not Searchable Keys:
462.422 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.423 -
462.424 -
462.425 -Document 39
462.426 -Searchable Keys:
462.427 - class : c_void_p
462.428 - class-ig : c_void_p
462.429 - in : ctypes
462.430 -
462.431 -Not Searchable Keys:
462.432 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.433 -
462.434 -
462.435 -Document 40
462.436 -Searchable Keys:
462.437 - class : c_wchar
462.438 - class-ig : c_wchar
462.439 - in : ctypes
462.440 -
462.441 -Not Searchable Keys:
462.442 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.443 -
462.444 -
462.445 -Document 41
462.446 -Searchable Keys:
462.447 - class : c_wchar_p
462.448 - class-ig : c_wchar_p
462.449 - in : ctypes
462.450 -
462.451 -Not Searchable Keys:
462.452 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.453 -
462.454 -
462.455 -Document 42
462.456 -Searchable Keys:
462.457 - class : py_object
462.458 - class-ig : py_object
462.459 - in : ctypes
462.460 -
462.461 -Not Searchable Keys:
462.462 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
462.463 -
462.464 -
462.465 -Document 43
462.466 -Searchable Keys:
462.467 - item : ArgumentError;C;|DOCUMENTED|DOC_ONLY|;
462.468 - item : BigEndianStructure;C;|DOCUMENTED|DOC_ONLY|;
462.469 - item : CDLL;C;|DOCUMENTED|DOC_ONLY|;
462.470 - item : CFUNCTYPE;F;|DOCUMENTED|DOC_ONLY|;restype,*argtypes,use_errno,use_last_error;
462.471 - item : DEFAULT_MODE;D;|DOCUMENTED|DOC_ONLY|;
462.472 - item : DllCanUnloadNow;F;|DOCUMENTED|DOC_ONLY|;;
462.473 - item : DllGetClassObject;F;|DOCUMENTED|DOC_ONLY|;;
462.474 - item : FormatError;F;|DOCUMENTED|DOC_ONLY|;code;
462.475 - item : GetLastError;F;|DOCUMENTED|DOC_ONLY|;;
462.476 - item : HRESULT;C;|DOCUMENTED|DOC_ONLY|;
462.477 - item : LibraryLoader;C;|DOCUMENTED|DOC_ONLY|;
462.478 - item : LittleEndianStructure;C;|DOCUMENTED|DOC_ONLY|;
462.479 - item : OleDLL;C;|DOCUMENTED|DOC_ONLY|;
462.480 - item : POINTER;F;|DOCUMENTED|DOC_ONLY|;type;
462.481 - item : PYFUNCTYPE;F;|DOCUMENTED|DOC_ONLY|;restype,*argtypes;
462.482 - item : PyDLL;C;|DOCUMENTED|DOC_ONLY|;
462.483 - item : RTLD_GLOBAL;D;|DOCUMENTED|DOC_ONLY|;
462.484 - item : RTLD_LOCAL;D;|DOCUMENTED|DOC_ONLY|;
462.485 - item : Structure;C;|DOCUMENTED|DOC_ONLY|;
462.486 - item : Union;C;|DOCUMENTED|DOC_ONLY|;
462.487 - item : WINFUNCTYPE;F;|DOCUMENTED|DOC_ONLY|;restype,*argtypes,use_errno,use_last_error;
462.488 - item : WinDLL;C;|DOCUMENTED|DOC_ONLY|;
462.489 - item : WinError;F;|DOCUMENTED|DOC_ONLY|;code,descr;
462.490 - item : _CData;C;|DOCUMENTED|PRIVATE|DOC_ONLY|;
462.491 - item : _FuncPtr;C;|DOCUMENTED|PRIVATE|DOC_ONLY|;
462.492 - item : _SimpleCData;C;|DOCUMENTED|PRIVATE|DOC_ONLY|;
462.493 - item : addressof;F;|DOCUMENTED|DOC_ONLY|;obj;
462.494 - item : alignment;F;|DOCUMENTED|DOC_ONLY|;obj_or_type;
462.495 - item : byref;F;|DOCUMENTED|DOC_ONLY|;obj,offset;
462.496 - item : c_bool;C;|DOCUMENTED|DOC_ONLY|;
462.497 - item : c_byte;C;|DOCUMENTED|DOC_ONLY|;
462.498 - item : c_char;C;|DOCUMENTED|DOC_ONLY|;
462.499 - item : c_char_p;C;|DOCUMENTED|DOC_ONLY|;
462.500 - item : c_double;C;|DOCUMENTED|DOC_ONLY|;
462.501 - item : c_float;C;|DOCUMENTED|DOC_ONLY|;
462.502 - item : c_int16;C;|DOCUMENTED|DOC_ONLY|;
462.503 - item : c_int32;C;|DOCUMENTED|DOC_ONLY|;
462.504 - item : c_int64;C;|DOCUMENTED|DOC_ONLY|;
462.505 - item : c_int8;C;|DOCUMENTED|DOC_ONLY|;
462.506 - item : c_int;C;|DOCUMENTED|DOC_ONLY|;
462.507 - item : c_long;C;|DOCUMENTED|DOC_ONLY|;
462.508 - item : c_longdouble;C;|DOCUMENTED|DOC_ONLY|;
462.509 - item : c_longlong;C;|DOCUMENTED|DOC_ONLY|;
462.510 - item : c_short;C;|DOCUMENTED|DOC_ONLY|;
462.511 - item : c_size_t;C;|DOCUMENTED|DOC_ONLY|;
462.512 - item : c_ubyte;C;|DOCUMENTED|DOC_ONLY|;
462.513 - item : c_uint16;C;|DOCUMENTED|DOC_ONLY|;
462.514 - item : c_uint32;C;|DOCUMENTED|DOC_ONLY|;
462.515 - item : c_uint64;C;|DOCUMENTED|DOC_ONLY|;
462.516 - item : c_uint8;C;|DOCUMENTED|DOC_ONLY|;
462.517 - item : c_uint;C;|DOCUMENTED|DOC_ONLY|;
462.518 - item : c_ulong;C;|DOCUMENTED|DOC_ONLY|;
462.519 - item : c_ulonglong;C;|DOCUMENTED|DOC_ONLY|;
462.520 - item : c_ushort;C;|DOCUMENTED|DOC_ONLY|;
462.521 - item : c_void_p;C;|DOCUMENTED|DOC_ONLY|;
462.522 - item : c_wchar;C;|DOCUMENTED|DOC_ONLY|;
462.523 - item : c_wchar_p;C;|DOCUMENTED|DOC_ONLY|;
462.524 - item : callable;F;|DOCUMENTED|DOC_ONLY|;result,func,arguments;
462.525 - item : cast;F;|DOCUMENTED|DOC_ONLY|;obj,type;
462.526 - item : cdll;D;|DOCUMENTED|DOC_ONLY|;
462.527 - item : create_string_buffer;F;|DOCUMENTED|DOC_ONLY|;init_or_size,size;
462.528 - item : create_unicode_buffer;F;|DOCUMENTED|DOC_ONLY|;init_or_size,size;
462.529 - item : find_library;F;|DOCUMENTED|DOC_ONLY|;name;
462.530 - item : find_library;F;|DOCUMENTED|DOC_ONLY|;name;
462.531 - item : find_msvcrt;F;|DOCUMENTED|DOC_ONLY|;;
462.532 - item : get_errno;F;|DOCUMENTED|DOC_ONLY|;;
462.533 - item : get_last_error;F;|DOCUMENTED|DOC_ONLY|;;
462.534 - item : memmove;F;|DOCUMENTED|DOC_ONLY|;dst,src,count;
462.535 - item : memset;F;|DOCUMENTED|DOC_ONLY|;dst,c,count;
462.536 - item : oledll;D;|DOCUMENTED|DOC_ONLY|;
462.537 - item : pointer;F;|DOCUMENTED|DOC_ONLY|;obj;
462.538 - item : prototype;F;|DOCUMENTED|DOC_ONLY|;address;
462.539 - item : prototype;F;|DOCUMENTED|DOC_ONLY|;callable;
462.540 - item : prototype;F;|DOCUMENTED|DOC_ONLY|;func_spec,paramflags;
462.541 - item : prototype;F;|DOCUMENTED|DOC_ONLY|;vtbl_index,name,paramflags,iid;
462.542 - item : py_object;C;|DOCUMENTED|DOC_ONLY|;
462.543 - item : pydll;D;|DOCUMENTED|DOC_ONLY|;
462.544 - item : pythonapi;D;|DOCUMENTED|DOC_ONLY|;
462.545 - item : resize;F;|DOCUMENTED|DOC_ONLY|;obj,size;
462.546 - item : set_conversion_mode;F;|DOCUMENTED|DOC_ONLY|;encoding,errors;
462.547 - item : set_errno;F;|DOCUMENTED|DOC_ONLY|;value;
462.548 - item : set_last_error;F;|DOCUMENTED|DOC_ONLY|;value;
462.549 - item : sizeof;F;|DOCUMENTED|DOC_ONLY|;obj_or_type;
462.550 - item : string_at;F;|DOCUMENTED|DOC_ONLY|;address,size;
462.551 - item : windll;D;|DOCUMENTED|DOC_ONLY|;
462.552 - item : wstring_at;F;|DOCUMENTED|DOC_ONLY|;address;
462.553 - module : ctypes
462.554 -
462.555 -Not Searchable Keys:
462.556 - modattrs : S
463.1 --- a/python.editor/test/unit/data/testfiles/rst/exceptions.rst Sun Jan 04 13:11:53 2015 -0600
463.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
463.3 @@ -1,478 +0,0 @@
463.4 -.. _bltin-exceptions:
463.5 -
463.6 -Built-in Exceptions
463.7 -===================
463.8 -
463.9 -.. module:: exceptions
463.10 - :synopsis: Standard exception classes.
463.11 -
463.12 -
463.13 -Exceptions should be class objects. The exceptions are defined in the module
463.14 -:mod:`exceptions`. This module never needs to be imported explicitly: the
463.15 -exceptions are provided in the built-in namespace as well as the
463.16 -:mod:`exceptions` module.
463.17 -
463.18 -.. index::
463.19 - statement: try
463.20 - statement: except
463.21 -
463.22 -For class exceptions, in a :keyword:`try` statement with an :keyword:`except`
463.23 -clause that mentions a particular class, that clause also handles any exception
463.24 -classes derived from that class (but not exception classes from which *it* is
463.25 -derived). Two exception classes that are not related via subclassing are never
463.26 -equivalent, even if they have the same name.
463.27 -
463.28 -.. index:: statement: raise
463.29 -
463.30 -The built-in exceptions listed below can be generated by the interpreter or
463.31 -built-in functions. Except where mentioned, they have an "associated value"
463.32 -indicating the detailed cause of the error. This may be a string or a tuple
463.33 -containing several items of information (e.g., an error code and a string
463.34 -explaining the code). The associated value is the second argument to the
463.35 -:keyword:`raise` statement. If the exception class is derived from the standard
463.36 -root class :exc:`BaseException`, the associated value is present as the
463.37 -exception instance's :attr:`args` attribute.
463.38 -
463.39 -User code can raise built-in exceptions. This can be used to test an exception
463.40 -handler or to report an error condition "just like" the situation in which the
463.41 -interpreter raises the same exception; but beware that there is nothing to
463.42 -prevent user code from raising an inappropriate error.
463.43 -
463.44 -The built-in exception classes can be sub-classed to define new exceptions;
463.45 -programmers are encouraged to at least derive new exceptions from the
463.46 -:exc:`Exception` class and not :exc:`BaseException`. More information on
463.47 -defining exceptions is available in the Python Tutorial under
463.48 -:ref:`tut-userexceptions`.
463.49 -
463.50 -The following exceptions are only used as base classes for other exceptions.
463.51 -
463.52 -
463.53 -.. exception:: BaseException
463.54 -
463.55 - The base class for all built-in exceptions. It is not meant to be directly
463.56 - inherited by user-defined classes (for that use :exc:`Exception`). If
463.57 - :func:`str` or :func:`unicode` is called on an instance of this class, the
463.58 - representation of the argument(s) to the instance are returned or the emptry
463.59 - string when there were no arguments. All arguments are stored in :attr:`args`
463.60 - as a tuple.
463.61 -
463.62 - .. versionadded:: 2.5
463.63 -
463.64 -
463.65 -.. exception:: Exception
463.66 -
463.67 - All built-in, non-system-exiting exceptions are derived from this class. All
463.68 - user-defined exceptions should also be derived from this class.
463.69 -
463.70 - .. versionchanged:: 2.5
463.71 - Changed to inherit from :exc:`BaseException`.
463.72 -
463.73 -
463.74 -.. exception:: StandardError
463.75 -
463.76 - The base class for all built-in exceptions except :exc:`StopIteration`,
463.77 - :exc:`GeneratorExit`, :exc:`KeyboardInterrupt` and :exc:`SystemExit`.
463.78 - :exc:`StandardError` itself is derived from :exc:`Exception`.
463.79 -
463.80 -
463.81 -.. exception:: ArithmeticError
463.82 -
463.83 - The base class for those built-in exceptions that are raised for various
463.84 - arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`,
463.85 - :exc:`FloatingPointError`.
463.86 -
463.87 -
463.88 -.. exception:: LookupError
463.89 -
463.90 - The base class for the exceptions that are raised when a key or index used on a
463.91 - mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This can be
463.92 - raised directly by :func:`sys.setdefaultencoding`.
463.93 -
463.94 -
463.95 -.. exception:: EnvironmentError
463.96 -
463.97 - The base class for exceptions that can occur outside the Python system:
463.98 - :exc:`IOError`, :exc:`OSError`. When exceptions of this type are created with a
463.99 - 2-tuple, the first item is available on the instance's :attr:`errno` attribute
463.100 - (it is assumed to be an error number), and the second item is available on the
463.101 - :attr:`strerror` attribute (it is usually the associated error message). The
463.102 - tuple itself is also available on the :attr:`args` attribute.
463.103 -
463.104 - .. versionadded:: 1.5.2
463.105 -
463.106 - When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
463.107 - first two items are available as above, while the third item is available on the
463.108 - :attr:`filename` attribute. However, for backwards compatibility, the
463.109 - :attr:`args` attribute contains only a 2-tuple of the first two constructor
463.110 - arguments.
463.111 -
463.112 - The :attr:`filename` attribute is ``None`` when this exception is created with
463.113 - other than 3 arguments. The :attr:`errno` and :attr:`strerror` attributes are
463.114 - also ``None`` when the instance was created with other than 2 or 3 arguments.
463.115 - In this last case, :attr:`args` contains the verbatim constructor arguments as a
463.116 - tuple.
463.117 -
463.118 -The following exceptions are the exceptions that are actually raised.
463.119 -
463.120 -
463.121 -.. exception:: AssertionError
463.122 -
463.123 - .. index:: statement: assert
463.124 -
463.125 - Raised when an :keyword:`assert` statement fails.
463.126 -
463.127 -
463.128 -.. exception:: AttributeError
463.129 -
463.130 - Raised when an attribute reference (see :ref:`attribute-references`) or
463.131 - assignment fails. (When an object does not support attribute references or
463.132 - attribute assignments at all, :exc:`TypeError` is raised.)
463.133 -
463.134 -
463.135 -.. exception:: EOFError
463.136 -
463.137 - Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
463.138 - hits an end-of-file condition (EOF) without reading any data. (N.B.: the
463.139 - :meth:`file.read` and :meth:`file.readline` methods return an empty string
463.140 - when they hit EOF.)
463.141 -
463.142 -
463.143 -.. exception:: FloatingPointError
463.144 -
463.145 - Raised when a floating point operation fails. This exception is always defined,
463.146 - but can only be raised when Python is configured with the
463.147 - :option:`--with-fpectl` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
463.148 - defined in the :file:`pyconfig.h` file.
463.149 -
463.150 -
463.151 -.. exception:: GeneratorExit
463.152 -
463.153 - Raise when a :term:`generator`\'s :meth:`close` method is called. It
463.154 - directly inherits from :exc:`BaseException` instead of :exc:`StandardError` since
463.155 - it is technically not an error.
463.156 -
463.157 - .. versionadded:: 2.5
463.158 -
463.159 - .. versionchanged:: 2.6
463.160 - Changed to inherit from :exc:`BaseException`.
463.161 -
463.162 -.. exception:: IOError
463.163 -
463.164 - Raised when an I/O operation (such as a :keyword:`print` statement, the built-in
463.165 - :func:`open` function or a method of a file object) fails for an I/O-related
463.166 - reason, e.g., "file not found" or "disk full".
463.167 -
463.168 - This class is derived from :exc:`EnvironmentError`. See the discussion above
463.169 - for more information on exception instance attributes.
463.170 -
463.171 - .. versionchanged:: 2.6
463.172 - Changed :exc:`socket.error` to use this as a base class.
463.173 -
463.174 -
463.175 -.. exception:: ImportError
463.176 -
463.177 - Raised when an :keyword:`import` statement fails to find the module definition
463.178 - or when a ``from ... import`` fails to find a name that is to be imported.
463.179 -
463.180 -
463.181 -.. exception:: IndexError
463.182 -
463.183 - Raised when a sequence subscript is out of range. (Slice indices are silently
463.184 - truncated to fall in the allowed range; if an index is not a plain integer,
463.185 - :exc:`TypeError` is raised.)
463.186 -
463.187 - .. XXX xref to sequences
463.188 -
463.189 -
463.190 -.. exception:: KeyError
463.191 -
463.192 - Raised when a mapping (dictionary) key is not found in the set of existing keys.
463.193 -
463.194 - .. XXX xref to mapping objects?
463.195 -
463.196 -
463.197 -.. exception:: KeyboardInterrupt
463.198 -
463.199 - Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
463.200 - :kbd:`Delete`). During execution, a check for interrupts is made regularly.
463.201 - Interrupts typed when a built-in function :func:`input` or :func:`raw_input` is
463.202 - waiting for input also raise this exception. The exception inherits from
463.203 - :exc:`BaseException` so as to not be accidentally caught by code that catches
463.204 - :exc:`Exception` and thus prevent the interpreter from exiting.
463.205 -
463.206 - .. versionchanged:: 2.5
463.207 - Changed to inherit from :exc:`BaseException`.
463.208 -
463.209 -
463.210 -.. exception:: MemoryError
463.211 -
463.212 - Raised when an operation runs out of memory but the situation may still be
463.213 - rescued (by deleting some objects). The associated value is a string indicating
463.214 - what kind of (internal) operation ran out of memory. Note that because of the
463.215 - underlying memory management architecture (C's :cfunc:`malloc` function), the
463.216 - interpreter may not always be able to completely recover from this situation; it
463.217 - nevertheless raises an exception so that a stack traceback can be printed, in
463.218 - case a run-away program was the cause.
463.219 -
463.220 -
463.221 -.. exception:: NameError
463.222 -
463.223 - Raised when a local or global name is not found. This applies only to
463.224 - unqualified names. The associated value is an error message that includes the
463.225 - name that could not be found.
463.226 -
463.227 -
463.228 -.. exception:: NotImplementedError
463.229 -
463.230 - This exception is derived from :exc:`RuntimeError`. In user defined base
463.231 - classes, abstract methods should raise this exception when they require derived
463.232 - classes to override the method.
463.233 -
463.234 - .. versionadded:: 1.5.2
463.235 -
463.236 -
463.237 -.. exception:: OSError
463.238 -
463.239 - .. index:: module: errno
463.240 -
463.241 - This exception is derived from :exc:`EnvironmentError`. It is raised when a
463.242 - function returns a system-related error (not for illegal argument types or
463.243 - other incidental errors). The :attr:`errno` attribute is a numeric error
463.244 - code from :cdata:`errno`, and the :attr:`strerror` attribute is the
463.245 - corresponding string, as would be printed by the C function :cfunc:`perror`.
463.246 - See the module :mod:`errno`, which contains names for the error codes defined
463.247 - by the underlying operating system.
463.248 -
463.249 - For exceptions that involve a file system path (such as :func:`chdir` or
463.250 - :func:`unlink`), the exception instance will contain a third attribute,
463.251 - :attr:`filename`, which is the file name passed to the function.
463.252 -
463.253 - .. versionadded:: 1.5.2
463.254 -
463.255 -
463.256 -.. exception:: OverflowError
463.257 -
463.258 - Raised when the result of an arithmetic operation is too large to be
463.259 - represented. This cannot occur for long integers (which would rather raise
463.260 - :exc:`MemoryError` than give up) and for most operations with plain integers,
463.261 - which return a long integer instead. Because of the lack of standardization
463.262 - of floating point exception handling in C, most floating point operations
463.263 - also aren't checked.
463.264 -
463.265 -
463.266 -.. exception:: ReferenceError
463.267 -
463.268 - This exception is raised when a weak reference proxy, created by the
463.269 - :func:`weakref.proxy` function, is used to access an attribute of the referent
463.270 - after it has been garbage collected. For more information on weak references,
463.271 - see the :mod:`weakref` module.
463.272 -
463.273 - .. versionadded:: 2.2
463.274 - Previously known as the :exc:`weakref.ReferenceError` exception.
463.275 -
463.276 -
463.277 -.. exception:: RuntimeError
463.278 -
463.279 - Raised when an error is detected that doesn't fall in any of the other
463.280 - categories. The associated value is a string indicating what precisely went
463.281 - wrong. (This exception is mostly a relic from a previous version of the
463.282 - interpreter; it is not used very much any more.)
463.283 -
463.284 -
463.285 -.. exception:: StopIteration
463.286 -
463.287 - Raised by an :term:`iterator`\'s :meth:`next` method to signal that there are
463.288 - no further values. This is derived from :exc:`Exception` rather than
463.289 - :exc:`StandardError`, since this is not considered an error in its normal
463.290 - application.
463.291 -
463.292 - .. versionadded:: 2.2
463.293 -
463.294 -
463.295 -.. exception:: SyntaxError
463.296 -
463.297 - Raised when the parser encounters a syntax error. This may occur in an
463.298 - :keyword:`import` statement, in an :keyword:`exec` statement, in a call to the
463.299 - built-in function :func:`eval` or :func:`input`, or when reading the initial
463.300 - script or standard input (also interactively).
463.301 -
463.302 - Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
463.303 - :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
463.304 - of the exception instance returns only the message.
463.305 -
463.306 -
463.307 -.. exception:: SystemError
463.308 -
463.309 - Raised when the interpreter finds an internal error, but the situation does not
463.310 - look so serious to cause it to abandon all hope. The associated value is a
463.311 - string indicating what went wrong (in low-level terms).
463.312 -
463.313 - You should report this to the author or maintainer of your Python interpreter.
463.314 - Be sure to report the version of the Python interpreter (``sys.version``; it is
463.315 - also printed at the start of an interactive Python session), the exact error
463.316 - message (the exception's associated value) and if possible the source of the
463.317 - program that triggered the error.
463.318 -
463.319 -
463.320 -.. exception:: SystemExit
463.321 -
463.322 - This exception is raised by the :func:`sys.exit` function. When it is not
463.323 - handled, the Python interpreter exits; no stack traceback is printed. If the
463.324 - associated value is a plain integer, it specifies the system exit status (passed
463.325 - to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; if
463.326 - it has another type (such as a string), the object's value is printed and the
463.327 - exit status is one.
463.328 -
463.329 - Instances have an attribute :attr:`code` which is set to the proposed exit
463.330 - status or error message (defaulting to ``None``). Also, this exception derives
463.331 - directly from :exc:`BaseException` and not :exc:`StandardError`, since it is not
463.332 - technically an error.
463.333 -
463.334 - A call to :func:`sys.exit` is translated into an exception so that clean-up
463.335 - handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
463.336 - executed, and so that a debugger can execute a script without running the risk
463.337 - of losing control. The :func:`os._exit` function can be used if it is
463.338 - absolutely positively necessary to exit immediately (for example, in the child
463.339 - process after a call to :func:`fork`).
463.340 -
463.341 - The exception inherits from :exc:`BaseException` instead of :exc:`StandardError`
463.342 - or :exc:`Exception` so that it is not accidentally caught by code that catches
463.343 - :exc:`Exception`. This allows the exception to properly propagate up and cause
463.344 - the interpreter to exit.
463.345 -
463.346 - .. versionchanged:: 2.5
463.347 - Changed to inherit from :exc:`BaseException`.
463.348 -
463.349 -
463.350 -.. exception:: TypeError
463.351 -
463.352 - Raised when an operation or function is applied to an object of inappropriate
463.353 - type. The associated value is a string giving details about the type mismatch.
463.354 -
463.355 -
463.356 -.. exception:: UnboundLocalError
463.357 -
463.358 - Raised when a reference is made to a local variable in a function or method, but
463.359 - no value has been bound to that variable. This is a subclass of
463.360 - :exc:`NameError`.
463.361 -
463.362 - .. versionadded:: 2.0
463.363 -
463.364 -
463.365 -.. exception:: UnicodeError
463.366 -
463.367 - Raised when a Unicode-related encoding or decoding error occurs. It is a
463.368 - subclass of :exc:`ValueError`.
463.369 -
463.370 - .. versionadded:: 2.0
463.371 -
463.372 -
463.373 -.. exception:: UnicodeEncodeError
463.374 -
463.375 - Raised when a Unicode-related error occurs during encoding. It is a subclass of
463.376 - :exc:`UnicodeError`.
463.377 -
463.378 - .. versionadded:: 2.3
463.379 -
463.380 -
463.381 -.. exception:: UnicodeDecodeError
463.382 -
463.383 - Raised when a Unicode-related error occurs during decoding. It is a subclass of
463.384 - :exc:`UnicodeError`.
463.385 -
463.386 - .. versionadded:: 2.3
463.387 -
463.388 -
463.389 -.. exception:: UnicodeTranslateError
463.390 -
463.391 - Raised when a Unicode-related error occurs during translating. It is a subclass
463.392 - of :exc:`UnicodeError`.
463.393 -
463.394 - .. versionadded:: 2.3
463.395 -
463.396 -
463.397 -.. exception:: ValueError
463.398 -
463.399 - Raised when a built-in operation or function receives an argument that has the
463.400 - right type but an inappropriate value, and the situation is not described by a
463.401 - more precise exception such as :exc:`IndexError`.
463.402 -
463.403 -
463.404 -.. exception:: WindowsError
463.405 -
463.406 - Raised when a Windows-specific error occurs or when the error number does not
463.407 - correspond to an :cdata:`errno` value. The :attr:`winerror` and
463.408 - :attr:`strerror` values are created from the return values of the
463.409 - :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows
463.410 - Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
463.411 - corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
463.412 -
463.413 - .. versionadded:: 2.0
463.414 -
463.415 - .. versionchanged:: 2.5
463.416 - Previous versions put the :cfunc:`GetLastError` codes into :attr:`errno`.
463.417 -
463.418 -
463.419 -.. exception:: ZeroDivisionError
463.420 -
463.421 - Raised when the second argument of a division or modulo operation is zero. The
463.422 - associated value is a string indicating the type of the operands and the
463.423 - operation.
463.424 -
463.425 -The following exceptions are used as warning categories; see the :mod:`warnings`
463.426 -module for more information.
463.427 -
463.428 -
463.429 -.. exception:: Warning
463.430 -
463.431 - Base class for warning categories.
463.432 -
463.433 -
463.434 -.. exception:: UserWarning
463.435 -
463.436 - Base class for warnings generated by user code.
463.437 -
463.438 -
463.439 -.. exception:: DeprecationWarning
463.440 -
463.441 - Base class for warnings about deprecated features.
463.442 -
463.443 -
463.444 -.. exception:: PendingDeprecationWarning
463.445 -
463.446 - Base class for warnings about features which will be deprecated in the future.
463.447 -
463.448 -
463.449 -.. exception:: SyntaxWarning
463.450 -
463.451 - Base class for warnings about dubious syntax
463.452 -
463.453 -
463.454 -.. exception:: RuntimeWarning
463.455 -
463.456 - Base class for warnings about dubious runtime behavior.
463.457 -
463.458 -
463.459 -.. exception:: FutureWarning
463.460 -
463.461 - Base class for warnings about constructs that will change semantically in the
463.462 - future.
463.463 -
463.464 -
463.465 -.. exception:: ImportWarning
463.466 -
463.467 - Base class for warnings about probable mistakes in module imports.
463.468 -
463.469 - .. versionadded:: 2.5
463.470 -
463.471 -
463.472 -.. exception:: UnicodeWarning
463.473 -
463.474 - Base class for warnings related to Unicode.
463.475 -
463.476 - .. versionadded:: 2.5
463.477 -
463.478 -The class hierarchy for built-in exceptions is:
463.479 -
463.480 -
463.481 -.. literalinclude:: ../../Lib/test/exception_hierarchy.txt
464.1 --- a/python.editor/test/unit/data/testfiles/rst/exceptions.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,547 +0,0 @@
464.4 -
464.5 -
464.6 -Document 0
464.7 -Searchable Keys:
464.8 - class : ArithmeticError
464.9 - class-ig : arithmeticerror
464.10 - extends : Exception
464.11 - in : exceptions
464.12 -
464.13 -Not Searchable Keys:
464.14 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.15 -
464.16 -
464.17 -Document 1
464.18 -Searchable Keys:
464.19 - class : AssertionError
464.20 - class-ig : assertionerror
464.21 - extends : Exception
464.22 - in : exceptions
464.23 -
464.24 -Not Searchable Keys:
464.25 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.26 -
464.27 -
464.28 -Document 2
464.29 -Searchable Keys:
464.30 - class : AttributeError
464.31 - class-ig : attributeerror
464.32 - extends : Exception
464.33 - in : exceptions
464.34 -
464.35 -Not Searchable Keys:
464.36 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.37 -
464.38 -
464.39 -Document 3
464.40 -Searchable Keys:
464.41 - class : BaseException
464.42 - class-ig : baseexception
464.43 - extends : Exception
464.44 - in : exceptions
464.45 -
464.46 -Not Searchable Keys:
464.47 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.48 -
464.49 -
464.50 -Document 4
464.51 -Searchable Keys:
464.52 - class : DeprecationWarning
464.53 - class-ig : deprecationwarning
464.54 - extends : Exception
464.55 - in : exceptions
464.56 -
464.57 -Not Searchable Keys:
464.58 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.59 -
464.60 -
464.61 -Document 5
464.62 -Searchable Keys:
464.63 - class : EOFError
464.64 - class-ig : eoferror
464.65 - extends : Exception
464.66 - in : exceptions
464.67 -
464.68 -Not Searchable Keys:
464.69 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.70 -
464.71 -
464.72 -Document 6
464.73 -Searchable Keys:
464.74 - class : EnvironmentError
464.75 - class-ig : environmenterror
464.76 - extends : Exception
464.77 - in : exceptions
464.78 -
464.79 -Not Searchable Keys:
464.80 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.81 -
464.82 -
464.83 -Document 7
464.84 -Searchable Keys:
464.85 - class : Exception
464.86 - class-ig : exception
464.87 - in : exceptions
464.88 -
464.89 -Not Searchable Keys:
464.90 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.91 -
464.92 -
464.93 -Document 8
464.94 -Searchable Keys:
464.95 - class : FloatingPointError
464.96 - class-ig : floatingpointerror
464.97 - extends : Exception
464.98 - in : exceptions
464.99 -
464.100 -Not Searchable Keys:
464.101 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.102 -
464.103 -
464.104 -Document 9
464.105 -Searchable Keys:
464.106 - class : FutureWarning
464.107 - class-ig : futurewarning
464.108 - extends : Exception
464.109 - in : exceptions
464.110 -
464.111 -Not Searchable Keys:
464.112 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.113 -
464.114 -
464.115 -Document 10
464.116 -Searchable Keys:
464.117 - class : GeneratorExit
464.118 - class-ig : generatorexit
464.119 - extends : Exception
464.120 - in : exceptions
464.121 -
464.122 -Not Searchable Keys:
464.123 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.124 -
464.125 -
464.126 -Document 11
464.127 -Searchable Keys:
464.128 - class : IOError
464.129 - class-ig : ioerror
464.130 - extends : Exception
464.131 - in : exceptions
464.132 -
464.133 -Not Searchable Keys:
464.134 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.135 -
464.136 -
464.137 -Document 12
464.138 -Searchable Keys:
464.139 - class : ImportError
464.140 - class-ig : importerror
464.141 - extends : Exception
464.142 - in : exceptions
464.143 -
464.144 -Not Searchable Keys:
464.145 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.146 -
464.147 -
464.148 -Document 13
464.149 -Searchable Keys:
464.150 - class : ImportWarning
464.151 - class-ig : importwarning
464.152 - extends : Exception
464.153 - in : exceptions
464.154 -
464.155 -Not Searchable Keys:
464.156 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.157 -
464.158 -
464.159 -Document 14
464.160 -Searchable Keys:
464.161 - class : IndexError
464.162 - class-ig : indexerror
464.163 - extends : Exception
464.164 - in : exceptions
464.165 -
464.166 -Not Searchable Keys:
464.167 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.168 -
464.169 -
464.170 -Document 15
464.171 -Searchable Keys:
464.172 - class : KeyError
464.173 - class-ig : keyerror
464.174 - extends : Exception
464.175 - in : exceptions
464.176 -
464.177 -Not Searchable Keys:
464.178 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.179 -
464.180 -
464.181 -Document 16
464.182 -Searchable Keys:
464.183 - class : KeyboardInterrupt
464.184 - class-ig : keyboardinterrupt
464.185 - extends : Exception
464.186 - in : exceptions
464.187 -
464.188 -Not Searchable Keys:
464.189 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.190 -
464.191 -
464.192 -Document 17
464.193 -Searchable Keys:
464.194 - class : LookupError
464.195 - class-ig : lookuperror
464.196 - extends : Exception
464.197 - in : exceptions
464.198 -
464.199 -Not Searchable Keys:
464.200 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.201 -
464.202 -
464.203 -Document 18
464.204 -Searchable Keys:
464.205 - class : MemoryError
464.206 - class-ig : memoryerror
464.207 - extends : Exception
464.208 - in : exceptions
464.209 -
464.210 -Not Searchable Keys:
464.211 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.212 -
464.213 -
464.214 -Document 19
464.215 -Searchable Keys:
464.216 - class : NameError
464.217 - class-ig : nameerror
464.218 - extends : Exception
464.219 - in : exceptions
464.220 -
464.221 -Not Searchable Keys:
464.222 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.223 -
464.224 -
464.225 -Document 20
464.226 -Searchable Keys:
464.227 - class : NotImplementedError
464.228 - class-ig : notimplementederror
464.229 - extends : Exception
464.230 - in : exceptions
464.231 -
464.232 -Not Searchable Keys:
464.233 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.234 -
464.235 -
464.236 -Document 21
464.237 -Searchable Keys:
464.238 - class : OSError
464.239 - class-ig : oserror
464.240 - extends : Exception
464.241 - in : exceptions
464.242 -
464.243 -Not Searchable Keys:
464.244 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.245 -
464.246 -
464.247 -Document 22
464.248 -Searchable Keys:
464.249 - class : OverflowError
464.250 - class-ig : overflowerror
464.251 - extends : Exception
464.252 - in : exceptions
464.253 -
464.254 -Not Searchable Keys:
464.255 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.256 -
464.257 -
464.258 -Document 23
464.259 -Searchable Keys:
464.260 - class : PendingDeprecationWarning
464.261 - class-ig : pendingdeprecationwarning
464.262 - extends : Exception
464.263 - in : exceptions
464.264 -
464.265 -Not Searchable Keys:
464.266 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.267 -
464.268 -
464.269 -Document 24
464.270 -Searchable Keys:
464.271 - class : ReferenceError
464.272 - class-ig : referenceerror
464.273 - extends : Exception
464.274 - in : exceptions
464.275 -
464.276 -Not Searchable Keys:
464.277 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.278 -
464.279 -
464.280 -Document 25
464.281 -Searchable Keys:
464.282 - class : RuntimeError
464.283 - class-ig : runtimeerror
464.284 - extends : Exception
464.285 - in : exceptions
464.286 -
464.287 -Not Searchable Keys:
464.288 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.289 -
464.290 -
464.291 -Document 26
464.292 -Searchable Keys:
464.293 - class : RuntimeWarning
464.294 - class-ig : runtimewarning
464.295 - extends : Exception
464.296 - in : exceptions
464.297 -
464.298 -Not Searchable Keys:
464.299 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.300 -
464.301 -
464.302 -Document 27
464.303 -Searchable Keys:
464.304 - class : StandardError
464.305 - class-ig : standarderror
464.306 - extends : Exception
464.307 - in : exceptions
464.308 -
464.309 -Not Searchable Keys:
464.310 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.311 -
464.312 -
464.313 -Document 28
464.314 -Searchable Keys:
464.315 - class : StopIteration
464.316 - class-ig : stopiteration
464.317 - extends : Exception
464.318 - in : exceptions
464.319 -
464.320 -Not Searchable Keys:
464.321 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.322 -
464.323 -
464.324 -Document 29
464.325 -Searchable Keys:
464.326 - class : SyntaxError
464.327 - class-ig : syntaxerror
464.328 - extends : Exception
464.329 - in : exceptions
464.330 -
464.331 -Not Searchable Keys:
464.332 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.333 -
464.334 -
464.335 -Document 30
464.336 -Searchable Keys:
464.337 - class : SyntaxWarning
464.338 - class-ig : syntaxwarning
464.339 - extends : Exception
464.340 - in : exceptions
464.341 -
464.342 -Not Searchable Keys:
464.343 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.344 -
464.345 -
464.346 -Document 31
464.347 -Searchable Keys:
464.348 - class : SystemError
464.349 - class-ig : systemerror
464.350 - extends : Exception
464.351 - in : exceptions
464.352 -
464.353 -Not Searchable Keys:
464.354 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.355 -
464.356 -
464.357 -Document 32
464.358 -Searchable Keys:
464.359 - class : SystemExit
464.360 - class-ig : systemexit
464.361 - extends : Exception
464.362 - in : exceptions
464.363 -
464.364 -Not Searchable Keys:
464.365 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.366 -
464.367 -
464.368 -Document 33
464.369 -Searchable Keys:
464.370 - class : TypeError
464.371 - class-ig : typeerror
464.372 - extends : Exception
464.373 - in : exceptions
464.374 -
464.375 -Not Searchable Keys:
464.376 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.377 -
464.378 -
464.379 -Document 34
464.380 -Searchable Keys:
464.381 - class : UnboundLocalError
464.382 - class-ig : unboundlocalerror
464.383 - extends : Exception
464.384 - in : exceptions
464.385 -
464.386 -Not Searchable Keys:
464.387 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.388 -
464.389 -
464.390 -Document 35
464.391 -Searchable Keys:
464.392 - class : UnicodeDecodeError
464.393 - class-ig : unicodedecodeerror
464.394 - extends : Exception
464.395 - in : exceptions
464.396 -
464.397 -Not Searchable Keys:
464.398 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.399 -
464.400 -
464.401 -Document 36
464.402 -Searchable Keys:
464.403 - class : UnicodeEncodeError
464.404 - class-ig : unicodeencodeerror
464.405 - extends : Exception
464.406 - in : exceptions
464.407 -
464.408 -Not Searchable Keys:
464.409 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.410 -
464.411 -
464.412 -Document 37
464.413 -Searchable Keys:
464.414 - class : UnicodeError
464.415 - class-ig : unicodeerror
464.416 - extends : Exception
464.417 - in : exceptions
464.418 -
464.419 -Not Searchable Keys:
464.420 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.421 -
464.422 -
464.423 -Document 38
464.424 -Searchable Keys:
464.425 - class : UnicodeTranslateError
464.426 - class-ig : unicodetranslateerror
464.427 - extends : Exception
464.428 - in : exceptions
464.429 -
464.430 -Not Searchable Keys:
464.431 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.432 -
464.433 -
464.434 -Document 39
464.435 -Searchable Keys:
464.436 - class : UnicodeWarning
464.437 - class-ig : unicodewarning
464.438 - extends : Exception
464.439 - in : exceptions
464.440 -
464.441 -Not Searchable Keys:
464.442 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.443 -
464.444 -
464.445 -Document 40
464.446 -Searchable Keys:
464.447 - class : UserWarning
464.448 - class-ig : userwarning
464.449 - extends : Exception
464.450 - in : exceptions
464.451 -
464.452 -Not Searchable Keys:
464.453 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.454 -
464.455 -
464.456 -Document 41
464.457 -Searchable Keys:
464.458 - class : ValueError
464.459 - class-ig : valueerror
464.460 - extends : Exception
464.461 - in : exceptions
464.462 -
464.463 -Not Searchable Keys:
464.464 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.465 -
464.466 -
464.467 -Document 42
464.468 -Searchable Keys:
464.469 - class : Warning
464.470 - class-ig : warning
464.471 - extends : Exception
464.472 - in : exceptions
464.473 -
464.474 -Not Searchable Keys:
464.475 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.476 -
464.477 -
464.478 -Document 43
464.479 -Searchable Keys:
464.480 - class : WindowsError
464.481 - class-ig : windowserror
464.482 - extends : Exception
464.483 - in : exceptions
464.484 -
464.485 -Not Searchable Keys:
464.486 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.487 -
464.488 -
464.489 -Document 44
464.490 -Searchable Keys:
464.491 - class : ZeroDivisionError
464.492 - class-ig : zerodivisionerror
464.493 - extends : Exception
464.494 - in : exceptions
464.495 -
464.496 -Not Searchable Keys:
464.497 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.498 -
464.499 -
464.500 -Document 45
464.501 -Searchable Keys:
464.502 - item : ArithmeticError;C;|DOCUMENTED|DOC_ONLY|;
464.503 - item : AssertionError;C;|DOCUMENTED|DOC_ONLY|;
464.504 - item : AttributeError;C;|DOCUMENTED|DOC_ONLY|;
464.505 - item : BaseException;C;|DOCUMENTED|DOC_ONLY|;
464.506 - item : DeprecationWarning;C;|DOCUMENTED|DOC_ONLY|;
464.507 - item : EOFError;C;|DOCUMENTED|DOC_ONLY|;
464.508 - item : EnvironmentError;C;|DOCUMENTED|DOC_ONLY|;
464.509 - item : Exception;C;|DOCUMENTED|DOC_ONLY|;
464.510 - item : FloatingPointError;C;|DOCUMENTED|DOC_ONLY|;
464.511 - item : FutureWarning;C;|DOCUMENTED|DOC_ONLY|;
464.512 - item : GeneratorExit;C;|DOCUMENTED|DOC_ONLY|;
464.513 - item : IOError;C;|DOCUMENTED|DOC_ONLY|;
464.514 - item : ImportError;C;|DOCUMENTED|DOC_ONLY|;
464.515 - item : ImportWarning;C;|DOCUMENTED|DOC_ONLY|;
464.516 - item : IndexError;C;|DOCUMENTED|DOC_ONLY|;
464.517 - item : KeyError;C;|DOCUMENTED|DOC_ONLY|;
464.518 - item : KeyboardInterrupt;C;|DOCUMENTED|DOC_ONLY|;
464.519 - item : LookupError;C;|DOCUMENTED|DOC_ONLY|;
464.520 - item : MemoryError;C;|DOCUMENTED|DOC_ONLY|;
464.521 - item : NameError;C;|DOCUMENTED|DOC_ONLY|;
464.522 - item : NotImplementedError;C;|DOCUMENTED|DOC_ONLY|;
464.523 - item : OSError;C;|DOCUMENTED|DOC_ONLY|;
464.524 - item : OverflowError;C;|DOCUMENTED|DOC_ONLY|;
464.525 - item : PendingDeprecationWarning;C;|DOCUMENTED|DOC_ONLY|;
464.526 - item : ReferenceError;C;|DOCUMENTED|DOC_ONLY|;
464.527 - item : RuntimeError;C;|DOCUMENTED|DOC_ONLY|;
464.528 - item : RuntimeWarning;C;|DOCUMENTED|DOC_ONLY|;
464.529 - item : StandardError;C;|DOCUMENTED|DOC_ONLY|;
464.530 - item : StopIteration;C;|DOCUMENTED|DOC_ONLY|;
464.531 - item : SyntaxError;C;|DOCUMENTED|DOC_ONLY|;
464.532 - item : SyntaxWarning;C;|DOCUMENTED|DOC_ONLY|;
464.533 - item : SystemError;C;|DOCUMENTED|DOC_ONLY|;
464.534 - item : SystemExit;C;|DOCUMENTED|DOC_ONLY|;
464.535 - item : TypeError;C;|DOCUMENTED|DOC_ONLY|;
464.536 - item : UnboundLocalError;C;|DOCUMENTED|DOC_ONLY|;
464.537 - item : UnicodeDecodeError;C;|DOCUMENTED|DOC_ONLY|;
464.538 - item : UnicodeEncodeError;C;|DOCUMENTED|DOC_ONLY|;
464.539 - item : UnicodeError;C;|DOCUMENTED|DOC_ONLY|;
464.540 - item : UnicodeTranslateError;C;|DOCUMENTED|DOC_ONLY|;
464.541 - item : UnicodeWarning;C;|DOCUMENTED|DOC_ONLY|;
464.542 - item : UserWarning;C;|DOCUMENTED|DOC_ONLY|;
464.543 - item : ValueError;C;|DOCUMENTED|DOC_ONLY|;
464.544 - item : Warning;C;|DOCUMENTED|DOC_ONLY|;
464.545 - item : WindowsError;C;|DOCUMENTED|DOC_ONLY|;
464.546 - item : ZeroDivisionError;C;|DOCUMENTED|DOC_ONLY|;
464.547 - module : exceptions
464.548 -
464.549 -Not Searchable Keys:
464.550 - modattrs : S
465.1 --- a/python.editor/test/unit/data/testfiles/rst/logging.rst Sun Jan 04 13:11:53 2015 -0600
465.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
465.3 @@ -1,2668 +0,0 @@
465.4 -:mod:`logging` --- Logging facility for Python
465.5 -==============================================
465.6 -
465.7 -.. module:: logging
465.8 - :synopsis: Flexible error logging system for applications.
465.9 -
465.10 -
465.11 -.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
465.12 -.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
465.13 -
465.14 -
465.15 -.. index:: pair: Errors; logging
465.16 -
465.17 -.. versionadded:: 2.3
465.18 -
465.19 -This module defines functions and classes which implement a flexible error
465.20 -logging system for applications.
465.21 -
465.22 -Logging is performed by calling methods on instances of the :class:`Logger`
465.23 -class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
465.24 -conceptually arranged in a namespace hierarchy using dots (periods) as
465.25 -separators. For example, a logger named "scan" is the parent of loggers
465.26 -"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
465.27 -and indicate the area of an application in which a logged message originates.
465.28 -
465.29 -Logged messages also have levels of importance associated with them. The default
465.30 -levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
465.31 -:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
465.32 -importance of a logged message by calling an appropriate method of
465.33 -:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
465.34 -:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
465.35 -constrained to use these levels: you can specify your own and use a more general
465.36 -:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
465.37 -
465.38 -
465.39 -Logging tutorial
465.40 -----------------
465.41 -
465.42 -The key benefit of having the logging API provided by a standard library module
465.43 -is that all Python modules can participate in logging, so your application log
465.44 -can include messages from third-party modules.
465.45 -
465.46 -It is, of course, possible to log messages with different verbosity levels or to
465.47 -different destinations. Support for writing log messages to files, HTTP
465.48 -GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
465.49 -mechanisms are all supported by the standard module. You can also create your
465.50 -own log destination class if you have special requirements not met by any of the
465.51 -built-in classes.
465.52 -
465.53 -Simple examples
465.54 -^^^^^^^^^^^^^^^
465.55 -
465.56 -.. sectionauthor:: Doug Hellmann
465.57 -.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
465.58 -
465.59 -Most applications are probably going to want to log to a file, so let's start
465.60 -with that case. Using the :func:`basicConfig` function, we can set up the
465.61 -default handler so that debug messages are written to a file::
465.62 -
465.63 - import logging
465.64 - LOG_FILENAME = '/tmp/logging_example.out'
465.65 - logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
465.66 -
465.67 - logging.debug('This message should go to the log file')
465.68 -
465.69 -And now if we open the file and look at what we have, we should find the log
465.70 -message::
465.71 -
465.72 - DEBUG:root:This message should go to the log file
465.73 -
465.74 -If you run the script repeatedly, the additional log messages are appended to
465.75 -the file. To create a new file each time, you can pass a filemode argument to
465.76 -:func:`basicConfig` with a value of ``'w'``. Rather than managing the file size
465.77 -yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
465.78 -
465.79 - import glob
465.80 - import logging
465.81 - import logging.handlers
465.82 -
465.83 - LOG_FILENAME = '/tmp/logging_rotatingfile_example.out'
465.84 -
465.85 - # Set up a specific logger with our desired output level
465.86 - my_logger = logging.getLogger('MyLogger')
465.87 - my_logger.setLevel(logging.DEBUG)
465.88 -
465.89 - # Add the log message handler to the logger
465.90 - handler = logging.handlers.RotatingFileHandler(
465.91 - LOG_FILENAME, maxBytes=20, backupCount=5)
465.92 -
465.93 - my_logger.addHandler(handler)
465.94 -
465.95 - # Log some messages
465.96 - for i in range(20):
465.97 - my_logger.debug('i = %d' % i)
465.98 -
465.99 - # See what files are created
465.100 - logfiles = glob.glob('%s*' % LOG_FILENAME)
465.101 -
465.102 - for filename in logfiles:
465.103 - print filename
465.104 -
465.105 -The result should be 6 separate files, each with part of the log history for the
465.106 -application::
465.107 -
465.108 - /tmp/logging_rotatingfile_example.out
465.109 - /tmp/logging_rotatingfile_example.out.1
465.110 - /tmp/logging_rotatingfile_example.out.2
465.111 - /tmp/logging_rotatingfile_example.out.3
465.112 - /tmp/logging_rotatingfile_example.out.4
465.113 - /tmp/logging_rotatingfile_example.out.5
465.114 -
465.115 -The most current file is always :file:`/tmp/logging_rotatingfile_example.out`,
465.116 -and each time it reaches the size limit it is renamed with the suffix
465.117 -``.1``. Each of the existing backup files is renamed to increment the suffix
465.118 -(``.1`` becomes ``.2``, etc.) and the ``.5`` file is erased.
465.119 -
465.120 -Obviously this example sets the log length much much too small as an extreme
465.121 -example. You would want to set *maxBytes* to an appropriate value.
465.122 -
465.123 -Another useful feature of the logging API is the ability to produce different
465.124 -messages at different log levels. This allows you to instrument your code with
465.125 -debug messages, for example, but turning the log level down so that those debug
465.126 -messages are not written for your production system. The default levels are
465.127 -``CRITICAL``, ``ERROR``, ``WARNING``, ``INFO``, ``DEBUG`` and ``UNSET``.
465.128 -
465.129 -The logger, handler, and log message call each specify a level. The log message
465.130 -is only emitted if the handler and logger are configured to emit messages of
465.131 -that level or lower. For example, if a message is ``CRITICAL``, and the logger
465.132 -is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
465.133 -the logger is set to produce only ``ERROR``\s, the message is not emitted::
465.134 -
465.135 - import logging
465.136 - import sys
465.137 -
465.138 - LEVELS = {'debug': logging.DEBUG,
465.139 - 'info': logging.INFO,
465.140 - 'warning': logging.WARNING,
465.141 - 'error': logging.ERROR,
465.142 - 'critical': logging.CRITICAL}
465.143 -
465.144 - if len(sys.argv) > 1:
465.145 - level_name = sys.argv[1]
465.146 - level = LEVELS.get(level_name, logging.NOTSET)
465.147 - logging.basicConfig(level=level)
465.148 -
465.149 - logging.debug('This is a debug message')
465.150 - logging.info('This is an info message')
465.151 - logging.warning('This is a warning message')
465.152 - logging.error('This is an error message')
465.153 - logging.critical('This is a critical error message')
465.154 -
465.155 -Run the script with an argument like 'debug' or 'warning' to see which messages
465.156 -show up at different levels::
465.157 -
465.158 - $ python logging_level_example.py debug
465.159 - DEBUG:root:This is a debug message
465.160 - INFO:root:This is an info message
465.161 - WARNING:root:This is a warning message
465.162 - ERROR:root:This is an error message
465.163 - CRITICAL:root:This is a critical error message
465.164 -
465.165 - $ python logging_level_example.py info
465.166 - INFO:root:This is an info message
465.167 - WARNING:root:This is a warning message
465.168 - ERROR:root:This is an error message
465.169 - CRITICAL:root:This is a critical error message
465.170 -
465.171 -You will notice that these log messages all have ``root`` embedded in them. The
465.172 -logging module supports a hierarchy of loggers with different names. An easy
465.173 -way to tell where a specific log message comes from is to use a separate logger
465.174 -object for each of your modules. Each new logger "inherits" the configuration
465.175 -of its parent, and log messages sent to a logger include the name of that
465.176 -logger. Optionally, each logger can be configured differently, so that messages
465.177 -from different modules are handled in different ways. Let's look at a simple
465.178 -example of how to log from different modules so it is easy to trace the source
465.179 -of the message::
465.180 -
465.181 - import logging
465.182 -
465.183 - logging.basicConfig(level=logging.WARNING)
465.184 -
465.185 - logger1 = logging.getLogger('package1.module1')
465.186 - logger2 = logging.getLogger('package2.module2')
465.187 -
465.188 - logger1.warning('This message comes from one module')
465.189 - logger2.warning('And this message comes from another module')
465.190 -
465.191 -And the output::
465.192 -
465.193 - $ python logging_modules_example.py
465.194 - WARNING:package1.module1:This message comes from one module
465.195 - WARNING:package2.module2:And this message comes from another module
465.196 -
465.197 -There are many more options for configuring logging, including different log
465.198 -message formatting options, having messages delivered to multiple destinations,
465.199 -and changing the configuration of a long-running application on the fly using a
465.200 -socket interface. All of these options are covered in depth in the library
465.201 -module documentation.
465.202 -
465.203 -Loggers
465.204 -^^^^^^^
465.205 -
465.206 -The logging library takes a modular approach and offers the several categories
465.207 -of components: loggers, handlers, filters, and formatters. Loggers expose the
465.208 -interface that application code directly uses. Handlers send the log records to
465.209 -the appropriate destination. Filters provide a finer grained facility for
465.210 -determining which log records to send on to a handler. Formatters specify the
465.211 -layout of the resultant log record.
465.212 -
465.213 -:class:`Logger` objects have a threefold job. First, they expose several
465.214 -methods to application code so that applications can log messages at runtime.
465.215 -Second, logger objects determine which log messages to act upon based upon
465.216 -severity (the default filtering facility) or filter objects. Third, logger
465.217 -objects pass along relevant log messages to all interested log handlers.
465.218 -
465.219 -The most widely used methods on logger objects fall into two categories:
465.220 -configuration and message sending.
465.221 -
465.222 -* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
465.223 - will handle, where debug is the lowest built-in severity level and critical is
465.224 - the highest built-in severity. For example, if the severity level is info,
465.225 - the logger will handle only info, warning, error, and critical messages and
465.226 - will ignore debug messages.
465.227 -
465.228 -* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
465.229 - objects from the logger object. This tutorial does not address filters.
465.230 -
465.231 -With the logger object configured, the following methods create log messages:
465.232 -
465.233 -* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
465.234 - :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
465.235 - a message and a level that corresponds to their respective method names. The
465.236 - message is actually a format string, which may contain the standard string
465.237 - substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
465.238 - rest of their arguments is a list of objects that correspond with the
465.239 - substitution fields in the message. With regard to :const:`**kwargs`, the
465.240 - logging methods care only about a keyword of :const:`exc_info` and use it to
465.241 - determine whether to log exception information.
465.242 -
465.243 -* :meth:`Logger.exception` creates a log message similar to
465.244 - :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
465.245 - stack trace along with it. Call this method only from an exception handler.
465.246 -
465.247 -* :meth:`Logger.log` takes a log level as an explicit argument. This is a
465.248 - little more verbose for logging messages than using the log level convenience
465.249 - methods listed above, but this is how to log at custom log levels.
465.250 -
465.251 -:func:`getLogger` returns a reference to a logger instance with the specified
465.252 -if it it is provided, or ``root`` if not. The names are period-separated
465.253 -hierarchical structures. Multiple calls to :func:`getLogger` with the same name
465.254 -will return a reference to the same logger object. Loggers that are further
465.255 -down in the hierarchical list are children of loggers higher up in the list.
465.256 -For example, given a logger with a name of ``foo``, loggers with names of
465.257 -``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all children of ``foo``.
465.258 -Child loggers propagate messages up to their parent loggers. Because of this,
465.259 -it is unnecessary to define and configure all the loggers an application uses.
465.260 -It is sufficient to configure a top-level logger and create child loggers as
465.261 -needed.
465.262 -
465.263 -
465.264 -Handlers
465.265 -^^^^^^^^
465.266 -
465.267 -:class:`Handler` objects are responsible for dispatching the appropriate log
465.268 -messages (based on the log messages' severity) to the handler's specified
465.269 -destination. Logger objects can add zero or more handler objects to themselves
465.270 -with an :func:`addHandler` method. As an example scenario, an application may
465.271 -want to send all log messages to a log file, all log messages of error or higher
465.272 -to stdout, and all messages of critical to an email address. This scenario
465.273 -requires three individual handlers where each handler is responsible for sending
465.274 -messages of a specific severity to a specific location.
465.275 -
465.276 -The standard library includes quite a few handler types; this tutorial uses only
465.277 -:class:`StreamHandler` and :class:`FileHandler` in its examples.
465.278 -
465.279 -There are very few methods in a handler for application developers to concern
465.280 -themselves with. The only handler methods that seem relevant for application
465.281 -developers who are using the built-in handler objects (that is, not creating
465.282 -custom handlers) are the following configuration methods:
465.283 -
465.284 -* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
465.285 - lowest severity that will be dispatched to the appropriate destination. Why
465.286 - are there two :func:`setLevel` methods? The level set in the logger
465.287 - determines which severity of messages it will pass to its handlers. The level
465.288 - set in each handler determines which messages that handler will send on.
465.289 - :func:`setFormatter` selects a Formatter object for this handler to use.
465.290 -
465.291 -* :func:`addFilter` and :func:`removeFilter` respectively configure and
465.292 - deconfigure filter objects on handlers.
465.293 -
465.294 -Application code should not directly instantiate and use handlers. Instead, the
465.295 -:class:`Handler` class is a base class that defines the interface that all
465.296 -Handlers should have and establishes some default behavior that child classes
465.297 -can use (or override).
465.298 -
465.299 -
465.300 -Formatters
465.301 -^^^^^^^^^^
465.302 -
465.303 -Formatter objects configure the final order, structure, and contents of the log
465.304 -message. Unlike the base :class:`logging.Handler` class, application code may
465.305 -instantiate formatter classes, although you could likely subclass the formatter
465.306 -if your application needs special behavior. The constructor takes two optional
465.307 -arguments: a message format string and a date format string. If there is no
465.308 -message format string, the default is to use the raw message. If there is no
465.309 -date format string, the default date format is::
465.310 -
465.311 - %Y-%m-%d %H:%M:%S
465.312 -
465.313 -with the milliseconds tacked on at the end.
465.314 -
465.315 -The message format string uses ``%(<dictionary key>)s`` styled string
465.316 -substitution; the possible keys are documented in :ref:`formatter-objects`.
465.317 -
465.318 -The following message format string will log the time in a human-readable
465.319 -format, the severity of the message, and the contents of the message, in that
465.320 -order::
465.321 -
465.322 - "%(asctime)s - %(levelname)s - %(message)s"
465.323 -
465.324 -
465.325 -Configuring Logging
465.326 -^^^^^^^^^^^^^^^^^^^
465.327 -
465.328 -Programmers can configure logging either by creating loggers, handlers, and
465.329 -formatters explicitly in a main module with the configuration methods listed
465.330 -above (using Python code), or by creating a logging config file. The following
465.331 -code is an example of configuring a very simple logger, a console handler, and a
465.332 -simple formatter in a Python module::
465.333 -
465.334 - import logging
465.335 -
465.336 - # create logger
465.337 - logger = logging.getLogger("simple_example")
465.338 - logger.setLevel(logging.DEBUG)
465.339 - # create console handler and set level to debug
465.340 - ch = logging.StreamHandler()
465.341 - ch.setLevel(logging.DEBUG)
465.342 - # create formatter
465.343 - formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
465.344 - # add formatter to ch
465.345 - ch.setFormatter(formatter)
465.346 - # add ch to logger
465.347 - logger.addHandler(ch)
465.348 -
465.349 - # "application" code
465.350 - logger.debug("debug message")
465.351 - logger.info("info message")
465.352 - logger.warn("warn message")
465.353 - logger.error("error message")
465.354 - logger.critical("critical message")
465.355 -
465.356 -Running this module from the command line produces the following output::
465.357 -
465.358 - $ python simple_logging_module.py
465.359 - 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
465.360 - 2005-03-19 15:10:26,620 - simple_example - INFO - info message
465.361 - 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
465.362 - 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
465.363 - 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
465.364 -
465.365 -The following Python module creates a logger, handler, and formatter nearly
465.366 -identical to those in the example listed above, with the only difference being
465.367 -the names of the objects::
465.368 -
465.369 - import logging
465.370 - import logging.config
465.371 -
465.372 - logging.config.fileConfig("logging.conf")
465.373 -
465.374 - # create logger
465.375 - logger = logging.getLogger("simpleExample")
465.376 -
465.377 - # "application" code
465.378 - logger.debug("debug message")
465.379 - logger.info("info message")
465.380 - logger.warn("warn message")
465.381 - logger.error("error message")
465.382 - logger.critical("critical message")
465.383 -
465.384 -Here is the logging.conf file::
465.385 -
465.386 - [loggers]
465.387 - keys=root,simpleExample
465.388 -
465.389 - [handlers]
465.390 - keys=consoleHandler
465.391 -
465.392 - [formatters]
465.393 - keys=simpleFormatter
465.394 -
465.395 - [logger_root]
465.396 - level=DEBUG
465.397 - handlers=consoleHandler
465.398 -
465.399 - [logger_simpleExample]
465.400 - level=DEBUG
465.401 - handlers=consoleHandler
465.402 - qualname=simpleExample
465.403 - propagate=0
465.404 -
465.405 - [handler_consoleHandler]
465.406 - class=StreamHandler
465.407 - level=DEBUG
465.408 - formatter=simpleFormatter
465.409 - args=(sys.stdout,)
465.410 -
465.411 - [formatter_simpleFormatter]
465.412 - format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
465.413 - datefmt=
465.414 -
465.415 -The output is nearly identical to that of the non-config-file-based example::
465.416 -
465.417 - $ python simple_logging_config.py
465.418 - 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
465.419 - 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
465.420 - 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
465.421 - 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
465.422 - 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
465.423 -
465.424 -You can see that the config file approach has a few advantages over the Python
465.425 -code approach, mainly separation of configuration and code and the ability of
465.426 -noncoders to easily modify the logging properties.
465.427 -
465.428 -Configuring Logging for a Library
465.429 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
465.430 -
465.431 -When developing a library which uses logging, some consideration needs to be
465.432 -given to its configuration. If the using application does not use logging, and
465.433 -library code makes logging calls, then a one-off message "No handlers could be
465.434 -found for logger X.Y.Z" is printed to the console. This message is intended
465.435 -to catch mistakes in logging configuration, but will confuse an application
465.436 -developer who is not aware of logging by the library.
465.437 -
465.438 -In addition to documenting how a library uses logging, a good way to configure
465.439 -library logging so that it does not cause a spurious message is to add a
465.440 -handler which does nothing. This avoids the message being printed, since a
465.441 -handler will be found: it just doesn't produce any output. If the library user
465.442 -configures logging for application use, presumably that configuration will add
465.443 -some handlers, and if levels are suitably configured then logging calls made
465.444 -in library code will send output to those handlers, as normal.
465.445 -
465.446 -A do-nothing handler can be simply defined as follows::
465.447 -
465.448 - import logging
465.449 -
465.450 - class NullHandler(logging.Handler):
465.451 - def emit(self, record):
465.452 - pass
465.453 -
465.454 -An instance of this handler should be added to the top-level logger of the
465.455 -logging namespace used by the library. If all logging by a library *foo* is
465.456 -done using loggers with names matching "foo.x.y", then the code::
465.457 -
465.458 - import logging
465.459 -
465.460 - h = NullHandler()
465.461 - logging.getLogger("foo").addHandler(h)
465.462 -
465.463 -should have the desired effect. If an organisation produces a number of
465.464 -libraries, then the logger name specified can be "orgname.foo" rather than
465.465 -just "foo".
465.466 -
465.467 -
465.468 -Logging Levels
465.469 ---------------
465.470 -
465.471 -The numeric values of logging levels are given in the following table. These are
465.472 -primarily of interest if you want to define your own levels, and need them to
465.473 -have specific values relative to the predefined levels. If you define a level
465.474 -with the same numeric value, it overwrites the predefined value; the predefined
465.475 -name is lost.
465.476 -
465.477 -+--------------+---------------+
465.478 -| Level | Numeric value |
465.479 -+==============+===============+
465.480 -| ``CRITICAL`` | 50 |
465.481 -+--------------+---------------+
465.482 -| ``ERROR`` | 40 |
465.483 -+--------------+---------------+
465.484 -| ``WARNING`` | 30 |
465.485 -+--------------+---------------+
465.486 -| ``INFO`` | 20 |
465.487 -+--------------+---------------+
465.488 -| ``DEBUG`` | 10 |
465.489 -+--------------+---------------+
465.490 -| ``NOTSET`` | 0 |
465.491 -+--------------+---------------+
465.492 -
465.493 -Levels can also be associated with loggers, being set either by the developer or
465.494 -through loading a saved logging configuration. When a logging method is called
465.495 -on a logger, the logger compares its own level with the level associated with
465.496 -the method call. If the logger's level is higher than the method call's, no
465.497 -logging message is actually generated. This is the basic mechanism controlling
465.498 -the verbosity of logging output.
465.499 -
465.500 -Logging messages are encoded as instances of the :class:`LogRecord` class. When
465.501 -a logger decides to actually log an event, a :class:`LogRecord` instance is
465.502 -created from the logging message.
465.503 -
465.504 -Logging messages are subjected to a dispatch mechanism through the use of
465.505 -:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
465.506 -class. Handlers are responsible for ensuring that a logged message (in the form
465.507 -of a :class:`LogRecord`) ends up in a particular location (or set of locations)
465.508 -which is useful for the target audience for that message (such as end users,
465.509 -support desk staff, system administrators, developers). Handlers are passed
465.510 -:class:`LogRecord` instances intended for particular destinations. Each logger
465.511 -can have zero, one or more handlers associated with it (via the
465.512 -:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
465.513 -directly associated with a logger, *all handlers associated with all ancestors
465.514 -of the logger* are called to dispatch the message.
465.515 -
465.516 -Just as for loggers, handlers can have levels associated with them. A handler's
465.517 -level acts as a filter in the same way as a logger's level does. If a handler
465.518 -decides to actually dispatch an event, the :meth:`emit` method is used to send
465.519 -the message to its destination. Most user-defined subclasses of :class:`Handler`
465.520 -will need to override this :meth:`emit`.
465.521 -
465.522 -In addition to the base :class:`Handler` class, many useful subclasses are
465.523 -provided:
465.524 -
465.525 -#. :class:`StreamHandler` instances send error messages to streams (file-like
465.526 - objects).
465.527 -
465.528 -#. :class:`FileHandler` instances send error messages to disk files.
465.529 -
465.530 -#. :class:`BaseRotatingHandler` is the base class for handlers that rotate log
465.531 - files at a certain point. It is not meant to be instantiated directly. Instead,
465.532 - use :class:`RotatingFileHandler` or :class:`TimedRotatingFileHandler`.
465.533 -
465.534 -#. :class:`RotatingFileHandler` instances send error messages to disk files,
465.535 - with support for maximum log file sizes and log file rotation.
465.536 -
465.537 -#. :class:`TimedRotatingFileHandler` instances send error messages to disk files
465.538 - rotating the log file at certain timed intervals.
465.539 -
465.540 -#. :class:`SocketHandler` instances send error messages to TCP/IP sockets.
465.541 -
465.542 -#. :class:`DatagramHandler` instances send error messages to UDP sockets.
465.543 -
465.544 -#. :class:`SMTPHandler` instances send error messages to a designated email
465.545 - address.
465.546 -
465.547 -#. :class:`SysLogHandler` instances send error messages to a Unix syslog daemon,
465.548 - possibly on a remote machine.
465.549 -
465.550 -#. :class:`NTEventLogHandler` instances send error messages to a Windows
465.551 - NT/2000/XP event log.
465.552 -
465.553 -#. :class:`MemoryHandler` instances send error messages to a buffer in memory,
465.554 - which is flushed whenever specific criteria are met.
465.555 -
465.556 -#. :class:`HTTPHandler` instances send error messages to an HTTP server using
465.557 - either ``GET`` or ``POST`` semantics.
465.558 -
465.559 -The :class:`StreamHandler` and :class:`FileHandler` classes are defined in the
465.560 -core logging package. The other handlers are defined in a sub- module,
465.561 -:mod:`logging.handlers`. (There is also another sub-module,
465.562 -:mod:`logging.config`, for configuration functionality.)
465.563 -
465.564 -Logged messages are formatted for presentation through instances of the
465.565 -:class:`Formatter` class. They are initialized with a format string suitable for
465.566 -use with the % operator and a dictionary.
465.567 -
465.568 -For formatting multiple messages in a batch, instances of
465.569 -:class:`BufferingFormatter` can be used. In addition to the format string (which
465.570 -is applied to each message in the batch), there is provision for header and
465.571 -trailer format strings.
465.572 -
465.573 -When filtering based on logger level and/or handler level is not enough,
465.574 -instances of :class:`Filter` can be added to both :class:`Logger` and
465.575 -:class:`Handler` instances (through their :meth:`addFilter` method). Before
465.576 -deciding to process a message further, both loggers and handlers consult all
465.577 -their filters for permission. If any filter returns a false value, the message
465.578 -is not processed further.
465.579 -
465.580 -The basic :class:`Filter` functionality allows filtering by specific logger
465.581 -name. If this feature is used, messages sent to the named logger and its
465.582 -children are allowed through the filter, and all others dropped.
465.583 -
465.584 -In addition to the classes described above, there are a number of module- level
465.585 -functions.
465.586 -
465.587 -
465.588 -.. function:: getLogger([name])
465.589 -
465.590 - Return a logger with the specified name or, if no name is specified, return a
465.591 - logger which is the root logger of the hierarchy. If specified, the name is
465.592 - typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
465.593 - Choice of these names is entirely up to the developer who is using logging.
465.594 -
465.595 - All calls to this function with a given name return the same logger instance.
465.596 - This means that logger instances never need to be passed between different parts
465.597 - of an application.
465.598 -
465.599 -
465.600 -.. function:: getLoggerClass()
465.601 -
465.602 - Return either the standard :class:`Logger` class, or the last class passed to
465.603 - :func:`setLoggerClass`. This function may be called from within a new class
465.604 - definition, to ensure that installing a customised :class:`Logger` class will
465.605 - not undo customisations already applied by other code. For example::
465.606 -
465.607 - class MyLogger(logging.getLoggerClass()):
465.608 - # ... override behaviour here
465.609 -
465.610 -
465.611 -.. function:: debug(msg[, *args[, **kwargs]])
465.612 -
465.613 - Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
465.614 - message format string, and the *args* are the arguments which are merged into
465.615 - *msg* using the string formatting operator. (Note that this means that you can
465.616 - use keywords in the format string, together with a single dictionary argument.)
465.617 -
465.618 - There are two keyword arguments in *kwargs* which are inspected: *exc_info*
465.619 - which, if it does not evaluate as false, causes exception information to be
465.620 - added to the logging message. If an exception tuple (in the format returned by
465.621 - :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
465.622 - is called to get the exception information.
465.623 -
465.624 - The other optional keyword argument is *extra* which can be used to pass a
465.625 - dictionary which is used to populate the __dict__ of the LogRecord created for
465.626 - the logging event with user-defined attributes. These custom attributes can then
465.627 - be used as you like. For example, they could be incorporated into logged
465.628 - messages. For example::
465.629 -
465.630 - FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
465.631 - logging.basicConfig(format=FORMAT)
465.632 - d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
465.633 - logging.warning("Protocol problem: %s", "connection reset", extra=d)
465.634 -
465.635 - would print something like ::
465.636 -
465.637 - 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
465.638 -
465.639 - The keys in the dictionary passed in *extra* should not clash with the keys used
465.640 - by the logging system. (See the :class:`Formatter` documentation for more
465.641 - information on which keys are used by the logging system.)
465.642 -
465.643 - If you choose to use these attributes in logged messages, you need to exercise
465.644 - some care. In the above example, for instance, the :class:`Formatter` has been
465.645 - set up with a format string which expects 'clientip' and 'user' in the attribute
465.646 - dictionary of the LogRecord. If these are missing, the message will not be
465.647 - logged because a string formatting exception will occur. So in this case, you
465.648 - always need to pass the *extra* dictionary with these keys.
465.649 -
465.650 - While this might be annoying, this feature is intended for use in specialized
465.651 - circumstances, such as multi-threaded servers where the same code executes in
465.652 - many contexts, and interesting conditions which arise are dependent on this
465.653 - context (such as remote client IP address and authenticated user name, in the
465.654 - above example). In such circumstances, it is likely that specialized
465.655 - :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
465.656 -
465.657 - .. versionchanged:: 2.5
465.658 - *extra* was added.
465.659 -
465.660 -
465.661 -.. function:: info(msg[, *args[, **kwargs]])
465.662 -
465.663 - Logs a message with level :const:`INFO` on the root logger. The arguments are
465.664 - interpreted as for :func:`debug`.
465.665 -
465.666 -
465.667 -.. function:: warning(msg[, *args[, **kwargs]])
465.668 -
465.669 - Logs a message with level :const:`WARNING` on the root logger. The arguments are
465.670 - interpreted as for :func:`debug`.
465.671 -
465.672 -
465.673 -.. function:: error(msg[, *args[, **kwargs]])
465.674 -
465.675 - Logs a message with level :const:`ERROR` on the root logger. The arguments are
465.676 - interpreted as for :func:`debug`.
465.677 -
465.678 -
465.679 -.. function:: critical(msg[, *args[, **kwargs]])
465.680 -
465.681 - Logs a message with level :const:`CRITICAL` on the root logger. The arguments
465.682 - are interpreted as for :func:`debug`.
465.683 -
465.684 -
465.685 -.. function:: exception(msg[, *args])
465.686 -
465.687 - Logs a message with level :const:`ERROR` on the root logger. The arguments are
465.688 - interpreted as for :func:`debug`. Exception info is added to the logging
465.689 - message. This function should only be called from an exception handler.
465.690 -
465.691 -
465.692 -.. function:: log(level, msg[, *args[, **kwargs]])
465.693 -
465.694 - Logs a message with level *level* on the root logger. The other arguments are
465.695 - interpreted as for :func:`debug`.
465.696 -
465.697 -
465.698 -.. function:: disable(lvl)
465.699 -
465.700 - Provides an overriding level *lvl* for all loggers which takes precedence over
465.701 - the logger's own level. When the need arises to temporarily throttle logging
465.702 - output down across the whole application, this function can be useful.
465.703 -
465.704 -
465.705 -.. function:: addLevelName(lvl, levelName)
465.706 -
465.707 - Associates level *lvl* with text *levelName* in an internal dictionary, which is
465.708 - used to map numeric levels to a textual representation, for example when a
465.709 - :class:`Formatter` formats a message. This function can also be used to define
465.710 - your own levels. The only constraints are that all levels used must be
465.711 - registered using this function, levels should be positive integers and they
465.712 - should increase in increasing order of severity.
465.713 -
465.714 -
465.715 -.. function:: getLevelName(lvl)
465.716 -
465.717 - Returns the textual representation of logging level *lvl*. If the level is one
465.718 - of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
465.719 - :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
465.720 - have associated levels with names using :func:`addLevelName` then the name you
465.721 - have associated with *lvl* is returned. If a numeric value corresponding to one
465.722 - of the defined levels is passed in, the corresponding string representation is
465.723 - returned. Otherwise, the string "Level %s" % lvl is returned.
465.724 -
465.725 -
465.726 -.. function:: makeLogRecord(attrdict)
465.727 -
465.728 - Creates and returns a new :class:`LogRecord` instance whose attributes are
465.729 - defined by *attrdict*. This function is useful for taking a pickled
465.730 - :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
465.731 - it as a :class:`LogRecord` instance at the receiving end.
465.732 -
465.733 -
465.734 -.. function:: basicConfig([**kwargs])
465.735 -
465.736 - Does basic configuration for the logging system by creating a
465.737 - :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
465.738 - root logger. The function does nothing if any handlers have been defined for
465.739 - the root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
465.740 - :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
465.741 - if no handlers are defined for the root logger.
465.742 -
465.743 - This function does nothing if the root logger already has handlers configured.
465.744 -
465.745 - .. versionchanged:: 2.4
465.746 - Formerly, :func:`basicConfig` did not take any keyword arguments.
465.747 -
465.748 - The following keyword arguments are supported.
465.749 -
465.750 - +--------------+---------------------------------------------+
465.751 - | Format | Description |
465.752 - +==============+=============================================+
465.753 - | ``filename`` | Specifies that a FileHandler be created, |
465.754 - | | using the specified filename, rather than a |
465.755 - | | StreamHandler. |
465.756 - +--------------+---------------------------------------------+
465.757 - | ``filemode`` | Specifies the mode to open the file, if |
465.758 - | | filename is specified (if filemode is |
465.759 - | | unspecified, it defaults to 'a'). |
465.760 - +--------------+---------------------------------------------+
465.761 - | ``format`` | Use the specified format string for the |
465.762 - | | handler. |
465.763 - +--------------+---------------------------------------------+
465.764 - | ``datefmt`` | Use the specified date/time format. |
465.765 - +--------------+---------------------------------------------+
465.766 - | ``level`` | Set the root logger level to the specified |
465.767 - | | level. |
465.768 - +--------------+---------------------------------------------+
465.769 - | ``stream`` | Use the specified stream to initialize the |
465.770 - | | StreamHandler. Note that this argument is |
465.771 - | | incompatible with 'filename' - if both are |
465.772 - | | present, 'stream' is ignored. |
465.773 - +--------------+---------------------------------------------+
465.774 -
465.775 -
465.776 -.. function:: shutdown()
465.777 -
465.778 - Informs the logging system to perform an orderly shutdown by flushing and
465.779 - closing all handlers. This should be called at application exit and no
465.780 - further use of the logging system should be made after this call.
465.781 -
465.782 -
465.783 -.. function:: setLoggerClass(klass)
465.784 -
465.785 - Tells the logging system to use the class *klass* when instantiating a logger.
465.786 - The class should define :meth:`__init__` such that only a name argument is
465.787 - required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
465.788 - function is typically called before any loggers are instantiated by applications
465.789 - which need to use custom logger behavior.
465.790 -
465.791 -
465.792 -.. seealso::
465.793 -
465.794 - :pep:`282` - A Logging System
465.795 - The proposal which described this feature for inclusion in the Python standard
465.796 - library.
465.797 -
465.798 - `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
465.799 - This is the original source for the :mod:`logging` package. The version of the
465.800 - package available from this site is suitable for use with Python 1.5.2, 2.1.x
465.801 - and 2.2.x, which do not include the :mod:`logging` package in the standard
465.802 - library.
465.803 -
465.804 -
465.805 -Logger Objects
465.806 ---------------
465.807 -
465.808 -Loggers have the following attributes and methods. Note that Loggers are never
465.809 -instantiated directly, but always through the module-level function
465.810 -``logging.getLogger(name)``.
465.811 -
465.812 -
465.813 -.. attribute:: Logger.propagate
465.814 -
465.815 - If this evaluates to false, logging messages are not passed by this logger or by
465.816 - child loggers to higher level (ancestor) loggers. The constructor sets this
465.817 - attribute to 1.
465.818 -
465.819 -
465.820 -.. method:: Logger.setLevel(lvl)
465.821 -
465.822 - Sets the threshold for this logger to *lvl*. Logging messages which are less
465.823 - severe than *lvl* will be ignored. When a logger is created, the level is set to
465.824 - :const:`NOTSET` (which causes all messages to be processed when the logger is
465.825 - the root logger, or delegation to the parent when the logger is a non-root
465.826 - logger). Note that the root logger is created with level :const:`WARNING`.
465.827 -
465.828 - The term "delegation to the parent" means that if a logger has a level of
465.829 - NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
465.830 - a level other than NOTSET is found, or the root is reached.
465.831 -
465.832 - If an ancestor is found with a level other than NOTSET, then that ancestor's
465.833 - level is treated as the effective level of the logger where the ancestor search
465.834 - began, and is used to determine how a logging event is handled.
465.835 -
465.836 - If the root is reached, and it has a level of NOTSET, then all messages will be
465.837 - processed. Otherwise, the root's level will be used as the effective level.
465.838 -
465.839 -
465.840 -.. method:: Logger.isEnabledFor(lvl)
465.841 -
465.842 - Indicates if a message of severity *lvl* would be processed by this logger.
465.843 - This method checks first the module-level level set by
465.844 - ``logging.disable(lvl)`` and then the logger's effective level as determined
465.845 - by :meth:`getEffectiveLevel`.
465.846 -
465.847 -
465.848 -.. method:: Logger.getEffectiveLevel()
465.849 -
465.850 - Indicates the effective level for this logger. If a value other than
465.851 - :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
465.852 - the hierarchy is traversed towards the root until a value other than
465.853 - :const:`NOTSET` is found, and that value is returned.
465.854 -
465.855 -
465.856 -.. method:: Logger.debug(msg[, *args[, **kwargs]])
465.857 -
465.858 - Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
465.859 - message format string, and the *args* are the arguments which are merged into
465.860 - *msg* using the string formatting operator. (Note that this means that you can
465.861 - use keywords in the format string, together with a single dictionary argument.)
465.862 -
465.863 - There are two keyword arguments in *kwargs* which are inspected: *exc_info*
465.864 - which, if it does not evaluate as false, causes exception information to be
465.865 - added to the logging message. If an exception tuple (in the format returned by
465.866 - :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
465.867 - is called to get the exception information.
465.868 -
465.869 - The other optional keyword argument is *extra* which can be used to pass a
465.870 - dictionary which is used to populate the __dict__ of the LogRecord created for
465.871 - the logging event with user-defined attributes. These custom attributes can then
465.872 - be used as you like. For example, they could be incorporated into logged
465.873 - messages. For example::
465.874 -
465.875 - FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
465.876 - logging.basicConfig(format=FORMAT)
465.877 - d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
465.878 - logger = logging.getLogger("tcpserver")
465.879 - logger.warning("Protocol problem: %s", "connection reset", extra=d)
465.880 -
465.881 - would print something like ::
465.882 -
465.883 - 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
465.884 -
465.885 - The keys in the dictionary passed in *extra* should not clash with the keys used
465.886 - by the logging system. (See the :class:`Formatter` documentation for more
465.887 - information on which keys are used by the logging system.)
465.888 -
465.889 - If you choose to use these attributes in logged messages, you need to exercise
465.890 - some care. In the above example, for instance, the :class:`Formatter` has been
465.891 - set up with a format string which expects 'clientip' and 'user' in the attribute
465.892 - dictionary of the LogRecord. If these are missing, the message will not be
465.893 - logged because a string formatting exception will occur. So in this case, you
465.894 - always need to pass the *extra* dictionary with these keys.
465.895 -
465.896 - While this might be annoying, this feature is intended for use in specialized
465.897 - circumstances, such as multi-threaded servers where the same code executes in
465.898 - many contexts, and interesting conditions which arise are dependent on this
465.899 - context (such as remote client IP address and authenticated user name, in the
465.900 - above example). In such circumstances, it is likely that specialized
465.901 - :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
465.902 -
465.903 - .. versionchanged:: 2.5
465.904 - *extra* was added.
465.905 -
465.906 -
465.907 -.. method:: Logger.info(msg[, *args[, **kwargs]])
465.908 -
465.909 - Logs a message with level :const:`INFO` on this logger. The arguments are
465.910 - interpreted as for :meth:`debug`.
465.911 -
465.912 -
465.913 -.. method:: Logger.warning(msg[, *args[, **kwargs]])
465.914 -
465.915 - Logs a message with level :const:`WARNING` on this logger. The arguments are
465.916 - interpreted as for :meth:`debug`.
465.917 -
465.918 -
465.919 -.. method:: Logger.error(msg[, *args[, **kwargs]])
465.920 -
465.921 - Logs a message with level :const:`ERROR` on this logger. The arguments are
465.922 - interpreted as for :meth:`debug`.
465.923 -
465.924 -
465.925 -.. method:: Logger.critical(msg[, *args[, **kwargs]])
465.926 -
465.927 - Logs a message with level :const:`CRITICAL` on this logger. The arguments are
465.928 - interpreted as for :meth:`debug`.
465.929 -
465.930 -
465.931 -.. method:: Logger.log(lvl, msg[, *args[, **kwargs]])
465.932 -
465.933 - Logs a message with integer level *lvl* on this logger. The other arguments are
465.934 - interpreted as for :meth:`debug`.
465.935 -
465.936 -
465.937 -.. method:: Logger.exception(msg[, *args])
465.938 -
465.939 - Logs a message with level :const:`ERROR` on this logger. The arguments are
465.940 - interpreted as for :meth:`debug`. Exception info is added to the logging
465.941 - message. This method should only be called from an exception handler.
465.942 -
465.943 -
465.944 -.. method:: Logger.addFilter(filt)
465.945 -
465.946 - Adds the specified filter *filt* to this logger.
465.947 -
465.948 -
465.949 -.. method:: Logger.removeFilter(filt)
465.950 -
465.951 - Removes the specified filter *filt* from this logger.
465.952 -
465.953 -
465.954 -.. method:: Logger.filter(record)
465.955 -
465.956 - Applies this logger's filters to the record and returns a true value if the
465.957 - record is to be processed.
465.958 -
465.959 -
465.960 -.. method:: Logger.addHandler(hdlr)
465.961 -
465.962 - Adds the specified handler *hdlr* to this logger.
465.963 -
465.964 -
465.965 -.. method:: Logger.removeHandler(hdlr)
465.966 -
465.967 - Removes the specified handler *hdlr* from this logger.
465.968 -
465.969 -
465.970 -.. method:: Logger.findCaller()
465.971 -
465.972 - Finds the caller's source filename and line number. Returns the filename, line
465.973 - number and function name as a 3-element tuple.
465.974 -
465.975 - .. versionchanged:: 2.4
465.976 - The function name was added. In earlier versions, the filename and line number
465.977 - were returned as a 2-element tuple..
465.978 -
465.979 -
465.980 -.. method:: Logger.handle(record)
465.981 -
465.982 - Handles a record by passing it to all handlers associated with this logger and
465.983 - its ancestors (until a false value of *propagate* is found). This method is used
465.984 - for unpickled records received from a socket, as well as those created locally.
465.985 - Logger-level filtering is applied using :meth:`filter`.
465.986 -
465.987 -
465.988 -.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info [, func, extra])
465.989 -
465.990 - This is a factory method which can be overridden in subclasses to create
465.991 - specialized :class:`LogRecord` instances.
465.992 -
465.993 - .. versionchanged:: 2.5
465.994 - *func* and *extra* were added.
465.995 -
465.996 -
465.997 -.. _minimal-example:
465.998 -
465.999 -Basic example
465.1000 --------------
465.1001 -
465.1002 -.. versionchanged:: 2.4
465.1003 - formerly :func:`basicConfig` did not take any keyword arguments.
465.1004 -
465.1005 -The :mod:`logging` package provides a lot of flexibility, and its configuration
465.1006 -can appear daunting. This section demonstrates that simple use of the logging
465.1007 -package is possible.
465.1008 -
465.1009 -The simplest example shows logging to the console::
465.1010 -
465.1011 - import logging
465.1012 -
465.1013 - logging.debug('A debug message')
465.1014 - logging.info('Some information')
465.1015 - logging.warning('A shot across the bows')
465.1016 -
465.1017 -If you run the above script, you'll see this::
465.1018 -
465.1019 - WARNING:root:A shot across the bows
465.1020 -
465.1021 -Because no particular logger was specified, the system used the root logger. The
465.1022 -debug and info messages didn't appear because by default, the root logger is
465.1023 -configured to only handle messages with a severity of WARNING or above. The
465.1024 -message format is also a configuration default, as is the output destination of
465.1025 -the messages - ``sys.stderr``. The severity level, the message format and
465.1026 -destination can be easily changed, as shown in the example below::
465.1027 -
465.1028 - import logging
465.1029 -
465.1030 - logging.basicConfig(level=logging.DEBUG,
465.1031 - format='%(asctime)s %(levelname)s %(message)s',
465.1032 - filename='/tmp/myapp.log',
465.1033 - filemode='w')
465.1034 - logging.debug('A debug message')
465.1035 - logging.info('Some information')
465.1036 - logging.warning('A shot across the bows')
465.1037 -
465.1038 -The :meth:`basicConfig` method is used to change the configuration defaults,
465.1039 -which results in output (written to ``/tmp/myapp.log``) which should look
465.1040 -something like the following::
465.1041 -
465.1042 - 2004-07-02 13:00:08,743 DEBUG A debug message
465.1043 - 2004-07-02 13:00:08,743 INFO Some information
465.1044 - 2004-07-02 13:00:08,743 WARNING A shot across the bows
465.1045 -
465.1046 -This time, all messages with a severity of DEBUG or above were handled, and the
465.1047 -format of the messages was also changed, and output went to the specified file
465.1048 -rather than the console.
465.1049 -
465.1050 -Formatting uses standard Python string formatting - see section
465.1051 -:ref:`string-formatting`. The format string takes the following common
465.1052 -specifiers. For a complete list of specifiers, consult the :class:`Formatter`
465.1053 -documentation.
465.1054 -
465.1055 -+-------------------+-----------------------------------------------+
465.1056 -| Format | Description |
465.1057 -+===================+===============================================+
465.1058 -| ``%(name)s`` | Name of the logger (logging channel). |
465.1059 -+-------------------+-----------------------------------------------+
465.1060 -| ``%(levelname)s`` | Text logging level for the message |
465.1061 -| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
465.1062 -| | ``'ERROR'``, ``'CRITICAL'``). |
465.1063 -+-------------------+-----------------------------------------------+
465.1064 -| ``%(asctime)s`` | Human-readable time when the |
465.1065 -| | :class:`LogRecord` was created. By default |
465.1066 -| | this is of the form "2003-07-08 16:49:45,896" |
465.1067 -| | (the numbers after the comma are millisecond |
465.1068 -| | portion of the time). |
465.1069 -+-------------------+-----------------------------------------------+
465.1070 -| ``%(message)s`` | The logged message. |
465.1071 -+-------------------+-----------------------------------------------+
465.1072 -
465.1073 -To change the date/time format, you can pass an additional keyword parameter,
465.1074 -*datefmt*, as in the following::
465.1075 -
465.1076 - import logging
465.1077 -
465.1078 - logging.basicConfig(level=logging.DEBUG,
465.1079 - format='%(asctime)s %(levelname)-8s %(message)s',
465.1080 - datefmt='%a, %d %b %Y %H:%M:%S',
465.1081 - filename='/temp/myapp.log',
465.1082 - filemode='w')
465.1083 - logging.debug('A debug message')
465.1084 - logging.info('Some information')
465.1085 - logging.warning('A shot across the bows')
465.1086 -
465.1087 -which would result in output like ::
465.1088 -
465.1089 - Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
465.1090 - Fri, 02 Jul 2004 13:06:18 INFO Some information
465.1091 - Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
465.1092 -
465.1093 -The date format string follows the requirements of :func:`strftime` - see the
465.1094 -documentation for the :mod:`time` module.
465.1095 -
465.1096 -If, instead of sending logging output to the console or a file, you'd rather use
465.1097 -a file-like object which you have created separately, you can pass it to
465.1098 -:func:`basicConfig` using the *stream* keyword argument. Note that if both
465.1099 -*stream* and *filename* keyword arguments are passed, the *stream* argument is
465.1100 -ignored.
465.1101 -
465.1102 -Of course, you can put variable information in your output. To do this, simply
465.1103 -have the message be a format string and pass in additional arguments containing
465.1104 -the variable information, as in the following example::
465.1105 -
465.1106 - import logging
465.1107 -
465.1108 - logging.basicConfig(level=logging.DEBUG,
465.1109 - format='%(asctime)s %(levelname)-8s %(message)s',
465.1110 - datefmt='%a, %d %b %Y %H:%M:%S',
465.1111 - filename='/temp/myapp.log',
465.1112 - filemode='w')
465.1113 - logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
465.1114 -
465.1115 -which would result in ::
465.1116 -
465.1117 - Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
465.1118 -
465.1119 -
465.1120 -.. _multiple-destinations:
465.1121 -
465.1122 -Logging to multiple destinations
465.1123 ---------------------------------
465.1124 -
465.1125 -Let's say you want to log to console and file with different message formats and
465.1126 -in differing circumstances. Say you want to log messages with levels of DEBUG
465.1127 -and higher to file, and those messages at level INFO and higher to the console.
465.1128 -Let's also assume that the file should contain timestamps, but the console
465.1129 -messages should not. Here's how you can achieve this::
465.1130 -
465.1131 - import logging
465.1132 -
465.1133 - # set up logging to file - see previous section for more details
465.1134 - logging.basicConfig(level=logging.DEBUG,
465.1135 - format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
465.1136 - datefmt='%m-%d %H:%M',
465.1137 - filename='/temp/myapp.log',
465.1138 - filemode='w')
465.1139 - # define a Handler which writes INFO messages or higher to the sys.stderr
465.1140 - console = logging.StreamHandler()
465.1141 - console.setLevel(logging.INFO)
465.1142 - # set a format which is simpler for console use
465.1143 - formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
465.1144 - # tell the handler to use this format
465.1145 - console.setFormatter(formatter)
465.1146 - # add the handler to the root logger
465.1147 - logging.getLogger('').addHandler(console)
465.1148 -
465.1149 - # Now, we can log to the root logger, or any other logger. First the root...
465.1150 - logging.info('Jackdaws love my big sphinx of quartz.')
465.1151 -
465.1152 - # Now, define a couple of other loggers which might represent areas in your
465.1153 - # application:
465.1154 -
465.1155 - logger1 = logging.getLogger('myapp.area1')
465.1156 - logger2 = logging.getLogger('myapp.area2')
465.1157 -
465.1158 - logger1.debug('Quick zephyrs blow, vexing daft Jim.')
465.1159 - logger1.info('How quickly daft jumping zebras vex.')
465.1160 - logger2.warning('Jail zesty vixen who grabbed pay from quack.')
465.1161 - logger2.error('The five boxing wizards jump quickly.')
465.1162 -
465.1163 -When you run this, on the console you will see ::
465.1164 -
465.1165 - root : INFO Jackdaws love my big sphinx of quartz.
465.1166 - myapp.area1 : INFO How quickly daft jumping zebras vex.
465.1167 - myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
465.1168 - myapp.area2 : ERROR The five boxing wizards jump quickly.
465.1169 -
465.1170 -and in the file you will see something like ::
465.1171 -
465.1172 - 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
465.1173 - 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
465.1174 - 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
465.1175 - 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
465.1176 - 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
465.1177 -
465.1178 -As you can see, the DEBUG message only shows up in the file. The other messages
465.1179 -are sent to both destinations.
465.1180 -
465.1181 -This example uses console and file handlers, but you can use any number and
465.1182 -combination of handlers you choose.
465.1183 -
465.1184 -
465.1185 -.. _context-info:
465.1186 -
465.1187 -Adding contextual information to your logging output
465.1188 -----------------------------------------------------
465.1189 -
465.1190 -Sometimes you want logging output to contain contextual information in
465.1191 -addition to the parameters passed to the logging call. For example, in a
465.1192 -networked application, it may be desirable to log client-specific information
465.1193 -in the log (e.g. remote client's username, or IP address). Although you could
465.1194 -use the *extra* parameter to achieve this, it's not always convenient to pass
465.1195 -the information in this way. While it might be tempting to create
465.1196 -:class:`Logger` instances on a per-connection basis, this is not a good idea
465.1197 -because these instances are not garbage collected. While this is not a problem
465.1198 -in practice, when the number of :class:`Logger` instances is dependent on the
465.1199 -level of granularity you want to use in logging an application, it could
465.1200 -be hard to manage if the number of :class:`Logger` instances becomes
465.1201 -effectively unbounded.
465.1202 -
465.1203 -An easy way in which you can pass contextual information to be output along
465.1204 -with logging event information is to use the :class:`LoggerAdapter` class.
465.1205 -This class is designed to look like a :class:`Logger`, so that you can call
465.1206 -:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
465.1207 -:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
465.1208 -same signatures as their counterparts in :class:`Logger`, so you can use the
465.1209 -two types of instances interchangeably.
465.1210 -
465.1211 -When you create an instance of :class:`LoggerAdapter`, you pass it a
465.1212 -:class:`Logger` instance and a dict-like object which contains your contextual
465.1213 -information. When you call one of the logging methods on an instance of
465.1214 -:class:`LoggerAdapter`, it delegates the call to the underlying instance of
465.1215 -:class:`Logger` passed to its constructor, and arranges to pass the contextual
465.1216 -information in the delegated call. Here's a snippet from the code of
465.1217 -:class:`LoggerAdapter`::
465.1218 -
465.1219 - def debug(self, msg, *args, **kwargs):
465.1220 - """
465.1221 - Delegate a debug call to the underlying logger, after adding
465.1222 - contextual information from this adapter instance.
465.1223 - """
465.1224 - msg, kwargs = self.process(msg, kwargs)
465.1225 - self.logger.debug(msg, *args, **kwargs)
465.1226 -
465.1227 -The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
465.1228 -information is added to the logging output. It's passed the message and
465.1229 -keyword arguments of the logging call, and it passes back (potentially)
465.1230 -modified versions of these to use in the call to the underlying logger. The
465.1231 -default implementation of this method leaves the message alone, but inserts
465.1232 -an "extra" key in the keyword argument whose value is the dict-like object
465.1233 -passed to the constructor. Of course, if you had passed an "extra" keyword
465.1234 -argument in the call to the adapter, it will be silently overwritten.
465.1235 -
465.1236 -The advantage of using "extra" is that the values in the dict-like object are
465.1237 -merged into the :class:`LogRecord` instance's __dict__, allowing you to use
465.1238 -customized strings with your :class:`Formatter` instances which know about
465.1239 -the keys of the dict-like object. If you need a different method, e.g. if you
465.1240 -want to prepend or append the contextual information to the message string,
465.1241 -you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
465.1242 -to do what you need. Here's an example script which uses this class, which
465.1243 -also illustrates what dict-like behaviour is needed from an arbitrary
465.1244 -"dict-like" object for use in the constructor::
465.1245 -
465.1246 - import logging
465.1247 -
465.1248 - class ConnInfo:
465.1249 - """
465.1250 - An example class which shows how an arbitrary class can be used as
465.1251 - the 'extra' context information repository passed to a LoggerAdapter.
465.1252 - """
465.1253 -
465.1254 - def __getitem__(self, name):
465.1255 - """
465.1256 - To allow this instance to look like a dict.
465.1257 - """
465.1258 - from random import choice
465.1259 - if name == "ip":
465.1260 - result = choice(["127.0.0.1", "192.168.0.1"])
465.1261 - elif name == "user":
465.1262 - result = choice(["jim", "fred", "sheila"])
465.1263 - else:
465.1264 - result = self.__dict__.get(name, "?")
465.1265 - return result
465.1266 -
465.1267 - def __iter__(self):
465.1268 - """
465.1269 - To allow iteration over keys, which will be merged into
465.1270 - the LogRecord dict before formatting and output.
465.1271 - """
465.1272 - keys = ["ip", "user"]
465.1273 - keys.extend(self.__dict__.keys())
465.1274 - return keys.__iter__()
465.1275 -
465.1276 - if __name__ == "__main__":
465.1277 - from random import choice
465.1278 - levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
465.1279 - a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
465.1280 - { "ip" : "123.231.231.123", "user" : "sheila" })
465.1281 - logging.basicConfig(level=logging.DEBUG,
465.1282 - format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
465.1283 - a1.debug("A debug message")
465.1284 - a1.info("An info message with %s", "some parameters")
465.1285 - a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
465.1286 - for x in range(10):
465.1287 - lvl = choice(levels)
465.1288 - lvlname = logging.getLevelName(lvl)
465.1289 - a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
465.1290 -
465.1291 -When this script is run, the output should look something like this::
465.1292 -
465.1293 - 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
465.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
465.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
465.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
465.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
465.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
465.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
465.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
465.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
465.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
465.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
465.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
465.1305 -
465.1306 -.. versionadded:: 2.6
465.1307 -
465.1308 -The :class:`LoggerAdapter` class was not present in previous versions.
465.1309 -
465.1310 -
465.1311 -.. _network-logging:
465.1312 -
465.1313 -Sending and receiving logging events across a network
465.1314 ------------------------------------------------------
465.1315 -
465.1316 -Let's say you want to send logging events across a network, and handle them at
465.1317 -the receiving end. A simple way of doing this is attaching a
465.1318 -:class:`SocketHandler` instance to the root logger at the sending end::
465.1319 -
465.1320 - import logging, logging.handlers
465.1321 -
465.1322 - rootLogger = logging.getLogger('')
465.1323 - rootLogger.setLevel(logging.DEBUG)
465.1324 - socketHandler = logging.handlers.SocketHandler('localhost',
465.1325 - logging.handlers.DEFAULT_TCP_LOGGING_PORT)
465.1326 - # don't bother with a formatter, since a socket handler sends the event as
465.1327 - # an unformatted pickle
465.1328 - rootLogger.addHandler(socketHandler)
465.1329 -
465.1330 - # Now, we can log to the root logger, or any other logger. First the root...
465.1331 - logging.info('Jackdaws love my big sphinx of quartz.')
465.1332 -
465.1333 - # Now, define a couple of other loggers which might represent areas in your
465.1334 - # application:
465.1335 -
465.1336 - logger1 = logging.getLogger('myapp.area1')
465.1337 - logger2 = logging.getLogger('myapp.area2')
465.1338 -
465.1339 - logger1.debug('Quick zephyrs blow, vexing daft Jim.')
465.1340 - logger1.info('How quickly daft jumping zebras vex.')
465.1341 - logger2.warning('Jail zesty vixen who grabbed pay from quack.')
465.1342 - logger2.error('The five boxing wizards jump quickly.')
465.1343 -
465.1344 -At the receiving end, you can set up a receiver using the :mod:`SocketServer`
465.1345 -module. Here is a basic working example::
465.1346 -
465.1347 - import cPickle
465.1348 - import logging
465.1349 - import logging.handlers
465.1350 - import SocketServer
465.1351 - import struct
465.1352 -
465.1353 -
465.1354 - class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
465.1355 - """Handler for a streaming logging request.
465.1356 -
465.1357 - This basically logs the record using whatever logging policy is
465.1358 - configured locally.
465.1359 - """
465.1360 -
465.1361 - def handle(self):
465.1362 - """
465.1363 - Handle multiple requests - each expected to be a 4-byte length,
465.1364 - followed by the LogRecord in pickle format. Logs the record
465.1365 - according to whatever policy is configured locally.
465.1366 - """
465.1367 - while 1:
465.1368 - chunk = self.connection.recv(4)
465.1369 - if len(chunk) < 4:
465.1370 - break
465.1371 - slen = struct.unpack(">L", chunk)[0]
465.1372 - chunk = self.connection.recv(slen)
465.1373 - while len(chunk) < slen:
465.1374 - chunk = chunk + self.connection.recv(slen - len(chunk))
465.1375 - obj = self.unPickle(chunk)
465.1376 - record = logging.makeLogRecord(obj)
465.1377 - self.handleLogRecord(record)
465.1378 -
465.1379 - def unPickle(self, data):
465.1380 - return cPickle.loads(data)
465.1381 -
465.1382 - def handleLogRecord(self, record):
465.1383 - # if a name is specified, we use the named logger rather than the one
465.1384 - # implied by the record.
465.1385 - if self.server.logname is not None:
465.1386 - name = self.server.logname
465.1387 - else:
465.1388 - name = record.name
465.1389 - logger = logging.getLogger(name)
465.1390 - # N.B. EVERY record gets logged. This is because Logger.handle
465.1391 - # is normally called AFTER logger-level filtering. If you want
465.1392 - # to do filtering, do it at the client end to save wasting
465.1393 - # cycles and network bandwidth!
465.1394 - logger.handle(record)
465.1395 -
465.1396 - class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
465.1397 - """simple TCP socket-based logging receiver suitable for testing.
465.1398 - """
465.1399 -
465.1400 - allow_reuse_address = 1
465.1401 -
465.1402 - def __init__(self, host='localhost',
465.1403 - port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
465.1404 - handler=LogRecordStreamHandler):
465.1405 - SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
465.1406 - self.abort = 0
465.1407 - self.timeout = 1
465.1408 - self.logname = None
465.1409 -
465.1410 - def serve_until_stopped(self):
465.1411 - import select
465.1412 - abort = 0
465.1413 - while not abort:
465.1414 - rd, wr, ex = select.select([self.socket.fileno()],
465.1415 - [], [],
465.1416 - self.timeout)
465.1417 - if rd:
465.1418 - self.handle_request()
465.1419 - abort = self.abort
465.1420 -
465.1421 - def main():
465.1422 - logging.basicConfig(
465.1423 - format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
465.1424 - tcpserver = LogRecordSocketReceiver()
465.1425 - print "About to start TCP server..."
465.1426 - tcpserver.serve_until_stopped()
465.1427 -
465.1428 - if __name__ == "__main__":
465.1429 - main()
465.1430 -
465.1431 -First run the server, and then the client. On the client side, nothing is
465.1432 -printed on the console; on the server side, you should see something like::
465.1433 -
465.1434 - About to start TCP server...
465.1435 - 59 root INFO Jackdaws love my big sphinx of quartz.
465.1436 - 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
465.1437 - 69 myapp.area1 INFO How quickly daft jumping zebras vex.
465.1438 - 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
465.1439 - 69 myapp.area2 ERROR The five boxing wizards jump quickly.
465.1440 -
465.1441 -
465.1442 -Handler Objects
465.1443 ----------------
465.1444 -
465.1445 -Handlers have the following attributes and methods. Note that :class:`Handler`
465.1446 -is never instantiated directly; this class acts as a base for more useful
465.1447 -subclasses. However, the :meth:`__init__` method in subclasses needs to call
465.1448 -:meth:`Handler.__init__`.
465.1449 -
465.1450 -
465.1451 -.. method:: Handler.__init__(level=NOTSET)
465.1452 -
465.1453 - Initializes the :class:`Handler` instance by setting its level, setting the list
465.1454 - of filters to the empty list and creating a lock (using :meth:`createLock`) for
465.1455 - serializing access to an I/O mechanism.
465.1456 -
465.1457 -
465.1458 -.. method:: Handler.createLock()
465.1459 -
465.1460 - Initializes a thread lock which can be used to serialize access to underlying
465.1461 - I/O functionality which may not be threadsafe.
465.1462 -
465.1463 -
465.1464 -.. method:: Handler.acquire()
465.1465 -
465.1466 - Acquires the thread lock created with :meth:`createLock`.
465.1467 -
465.1468 -
465.1469 -.. method:: Handler.release()
465.1470 -
465.1471 - Releases the thread lock acquired with :meth:`acquire`.
465.1472 -
465.1473 -
465.1474 -.. method:: Handler.setLevel(lvl)
465.1475 -
465.1476 - Sets the threshold for this handler to *lvl*. Logging messages which are less
465.1477 - severe than *lvl* will be ignored. When a handler is created, the level is set
465.1478 - to :const:`NOTSET` (which causes all messages to be processed).
465.1479 -
465.1480 -
465.1481 -.. method:: Handler.setFormatter(form)
465.1482 -
465.1483 - Sets the :class:`Formatter` for this handler to *form*.
465.1484 -
465.1485 -
465.1486 -.. method:: Handler.addFilter(filt)
465.1487 -
465.1488 - Adds the specified filter *filt* to this handler.
465.1489 -
465.1490 -
465.1491 -.. method:: Handler.removeFilter(filt)
465.1492 -
465.1493 - Removes the specified filter *filt* from this handler.
465.1494 -
465.1495 -
465.1496 -.. method:: Handler.filter(record)
465.1497 -
465.1498 - Applies this handler's filters to the record and returns a true value if the
465.1499 - record is to be processed.
465.1500 -
465.1501 -
465.1502 -.. method:: Handler.flush()
465.1503 -
465.1504 - Ensure all logging output has been flushed. This version does nothing and is
465.1505 - intended to be implemented by subclasses.
465.1506 -
465.1507 -
465.1508 -.. method:: Handler.close()
465.1509 -
465.1510 - Tidy up any resources used by the handler. This version does no output but
465.1511 - removes the handler from an internal list of handlers which is closed when
465.1512 - :func:`shutdown` is called. Subclasses should ensure that this gets called
465.1513 - from overridden :meth:`close` methods.
465.1514 -
465.1515 -
465.1516 -.. method:: Handler.handle(record)
465.1517 -
465.1518 - Conditionally emits the specified logging record, depending on filters which may
465.1519 - have been added to the handler. Wraps the actual emission of the record with
465.1520 - acquisition/release of the I/O thread lock.
465.1521 -
465.1522 -
465.1523 -.. method:: Handler.handleError(record)
465.1524 -
465.1525 - This method should be called from handlers when an exception is encountered
465.1526 - during an :meth:`emit` call. By default it does nothing, which means that
465.1527 - exceptions get silently ignored. This is what is mostly wanted for a logging
465.1528 - system - most users will not care about errors in the logging system, they are
465.1529 - more interested in application errors. You could, however, replace this with a
465.1530 - custom handler if you wish. The specified record is the one which was being
465.1531 - processed when the exception occurred.
465.1532 -
465.1533 -
465.1534 -.. method:: Handler.format(record)
465.1535 -
465.1536 - Do formatting for a record - if a formatter is set, use it. Otherwise, use the
465.1537 - default formatter for the module.
465.1538 -
465.1539 -
465.1540 -.. method:: Handler.emit(record)
465.1541 -
465.1542 - Do whatever it takes to actually log the specified logging record. This version
465.1543 - is intended to be implemented by subclasses and so raises a
465.1544 - :exc:`NotImplementedError`.
465.1545 -
465.1546 -
465.1547 -StreamHandler
465.1548 -^^^^^^^^^^^^^
465.1549 -
465.1550 -The :class:`StreamHandler` class, located in the core :mod:`logging` package,
465.1551 -sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
465.1552 -file-like object (or, more precisely, any object which supports :meth:`write`
465.1553 -and :meth:`flush` methods).
465.1554 -
465.1555 -
465.1556 -.. class:: StreamHandler([strm])
465.1557 -
465.1558 - Returns a new instance of the :class:`StreamHandler` class. If *strm* is
465.1559 - specified, the instance will use it for logging output; otherwise, *sys.stderr*
465.1560 - will be used.
465.1561 -
465.1562 -
465.1563 - .. method:: emit(record)
465.1564 -
465.1565 - If a formatter is specified, it is used to format the record. The record
465.1566 - is then written to the stream with a trailing newline. If exception
465.1567 - information is present, it is formatted using
465.1568 - :func:`traceback.print_exception` and appended to the stream.
465.1569 -
465.1570 -
465.1571 - .. method:: flush()
465.1572 -
465.1573 - Flushes the stream by calling its :meth:`flush` method. Note that the
465.1574 - :meth:`close` method is inherited from :class:`Handler` and so does
465.1575 - no output, so an explicit :meth:`flush` call may be needed at times.
465.1576 -
465.1577 -
465.1578 -FileHandler
465.1579 -^^^^^^^^^^^
465.1580 -
465.1581 -The :class:`FileHandler` class, located in the core :mod:`logging` package,
465.1582 -sends logging output to a disk file. It inherits the output functionality from
465.1583 -:class:`StreamHandler`.
465.1584 -
465.1585 -
465.1586 -.. class:: FileHandler(filename[, mode[, encoding[, delay]]])
465.1587 -
465.1588 - Returns a new instance of the :class:`FileHandler` class. The specified file is
465.1589 - opened and used as the stream for logging. If *mode* is not specified,
465.1590 - :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
465.1591 - with that encoding. If *delay* is true, then file opening is deferred until the
465.1592 - first call to :meth:`emit`. By default, the file grows indefinitely.
465.1593 -
465.1594 -
465.1595 - .. method:: close()
465.1596 -
465.1597 - Closes the file.
465.1598 -
465.1599 -
465.1600 - .. method:: emit(record)
465.1601 -
465.1602 - Outputs the record to the file.
465.1603 -
465.1604 -
465.1605 -WatchedFileHandler
465.1606 -^^^^^^^^^^^^^^^^^^
465.1607 -
465.1608 -.. versionadded:: 2.6
465.1609 -
465.1610 -The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
465.1611 -module, is a :class:`FileHandler` which watches the file it is logging to. If
465.1612 -the file changes, it is closed and reopened using the file name.
465.1613 -
465.1614 -A file change can happen because of usage of programs such as *newsyslog* and
465.1615 -*logrotate* which perform log file rotation. This handler, intended for use
465.1616 -under Unix/Linux, watches the file to see if it has changed since the last emit.
465.1617 -(A file is deemed to have changed if its device or inode have changed.) If the
465.1618 -file has changed, the old file stream is closed, and the file opened to get a
465.1619 -new stream.
465.1620 -
465.1621 -This handler is not appropriate for use under Windows, because under Windows
465.1622 -open log files cannot be moved or renamed - logging opens the files with
465.1623 -exclusive locks - and so there is no need for such a handler. Furthermore,
465.1624 -*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
465.1625 -this value.
465.1626 -
465.1627 -
465.1628 -.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
465.1629 -
465.1630 - Returns a new instance of the :class:`WatchedFileHandler` class. The specified
465.1631 - file is opened and used as the stream for logging. If *mode* is not specified,
465.1632 - :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
465.1633 - with that encoding. If *delay* is true, then file opening is deferred until the
465.1634 - first call to :meth:`emit`. By default, the file grows indefinitely.
465.1635 -
465.1636 -
465.1637 - .. method:: emit(record)
465.1638 -
465.1639 - Outputs the record to the file, but first checks to see if the file has
465.1640 - changed. If it has, the existing stream is flushed and closed and the
465.1641 - file opened again, before outputting the record to the file.
465.1642 -
465.1643 -
465.1644 -RotatingFileHandler
465.1645 -^^^^^^^^^^^^^^^^^^^
465.1646 -
465.1647 -The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
465.1648 -module, supports rotation of disk log files.
465.1649 -
465.1650 -
465.1651 -.. class:: RotatingFileHandler(filename[, mode[, maxBytes[, backupCount[, encoding[, delay]]]]])
465.1652 -
465.1653 - Returns a new instance of the :class:`RotatingFileHandler` class. The specified
465.1654 - file is opened and used as the stream for logging. If *mode* is not specified,
465.1655 - ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
465.1656 - with that encoding. If *delay* is true, then file opening is deferred until the
465.1657 - first call to :meth:`emit`. By default, the file grows indefinitely.
465.1658 -
465.1659 - You can use the *maxBytes* and *backupCount* values to allow the file to
465.1660 - :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
465.1661 - the file is closed and a new file is silently opened for output. Rollover occurs
465.1662 - whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
465.1663 - zero, rollover never occurs. If *backupCount* is non-zero, the system will save
465.1664 - old log files by appending the extensions ".1", ".2" etc., to the filename. For
465.1665 - example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
465.1666 - would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
465.1667 - :file:`app.log.5`. The file being written to is always :file:`app.log`. When
465.1668 - this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
465.1669 - :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
465.1670 - :file:`app.log.2`, :file:`app.log.3` etc. respectively.
465.1671 -
465.1672 -
465.1673 - .. method:: doRollover()
465.1674 -
465.1675 - Does a rollover, as described above.
465.1676 -
465.1677 -
465.1678 - .. method:: emit(record)
465.1679 -
465.1680 - Outputs the record to the file, catering for rollover as described
465.1681 - previously.
465.1682 -
465.1683 -
465.1684 -TimedRotatingFileHandler
465.1685 -^^^^^^^^^^^^^^^^^^^^^^^^
465.1686 -
465.1687 -The :class:`TimedRotatingFileHandler` class, located in the
465.1688 -:mod:`logging.handlers` module, supports rotation of disk log files at certain
465.1689 -timed intervals.
465.1690 -
465.1691 -
465.1692 -.. class:: TimedRotatingFileHandler(filename [,when [,interval [,backupCount[, encoding[, delay[, utc]]]]]])
465.1693 -
465.1694 - Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
465.1695 - specified file is opened and used as the stream for logging. On rotating it also
465.1696 - sets the filename suffix. Rotating happens based on the product of *when* and
465.1697 - *interval*.
465.1698 -
465.1699 - You can use the *when* to specify the type of *interval*. The list of possible
465.1700 - values is below. Note that they are not case sensitive.
465.1701 -
465.1702 - +----------------+-----------------------+
465.1703 - | Value | Type of interval |
465.1704 - +================+=======================+
465.1705 - | ``'S'`` | Seconds |
465.1706 - +----------------+-----------------------+
465.1707 - | ``'M'`` | Minutes |
465.1708 - +----------------+-----------------------+
465.1709 - | ``'H'`` | Hours |
465.1710 - +----------------+-----------------------+
465.1711 - | ``'D'`` | Days |
465.1712 - +----------------+-----------------------+
465.1713 - | ``'W'`` | Week day (0=Monday) |
465.1714 - +----------------+-----------------------+
465.1715 - | ``'midnight'`` | Roll over at midnight |
465.1716 - +----------------+-----------------------+
465.1717 -
465.1718 - The system will save old log files by appending extensions to the filename.
465.1719 - The extensions are date-and-time based, using the strftime format
465.1720 - ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
465.1721 - rollover interval.
465.1722 - If the *utc* argument is true, times in UTC will be used; otherwise
465.1723 - local time is used.
465.1724 -
465.1725 - If *backupCount* is nonzero, at most *backupCount* files
465.1726 - will be kept, and if more would be created when rollover occurs, the oldest
465.1727 - one is deleted. The deletion logic uses the interval to determine which
465.1728 - files to delete, so changing the interval may leave old files lying around.
465.1729 -
465.1730 -
465.1731 - .. method:: doRollover()
465.1732 -
465.1733 - Does a rollover, as described above.
465.1734 -
465.1735 -
465.1736 - .. method:: emit(record)
465.1737 -
465.1738 - Outputs the record to the file, catering for rollover as described above.
465.1739 -
465.1740 -
465.1741 -SocketHandler
465.1742 -^^^^^^^^^^^^^
465.1743 -
465.1744 -The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
465.1745 -sends logging output to a network socket. The base class uses a TCP socket.
465.1746 -
465.1747 -
465.1748 -.. class:: SocketHandler(host, port)
465.1749 -
465.1750 - Returns a new instance of the :class:`SocketHandler` class intended to
465.1751 - communicate with a remote machine whose address is given by *host* and *port*.
465.1752 -
465.1753 -
465.1754 - .. method:: close()
465.1755 -
465.1756 - Closes the socket.
465.1757 -
465.1758 -
465.1759 - .. method:: emit()
465.1760 -
465.1761 - Pickles the record's attribute dictionary and writes it to the socket in
465.1762 - binary format. If there is an error with the socket, silently drops the
465.1763 - packet. If the connection was previously lost, re-establishes the
465.1764 - connection. To unpickle the record at the receiving end into a
465.1765 - :class:`LogRecord`, use the :func:`makeLogRecord` function.
465.1766 -
465.1767 -
465.1768 - .. method:: handleError()
465.1769 -
465.1770 - Handles an error which has occurred during :meth:`emit`. The most likely
465.1771 - cause is a lost connection. Closes the socket so that we can retry on the
465.1772 - next event.
465.1773 -
465.1774 -
465.1775 - .. method:: makeSocket()
465.1776 -
465.1777 - This is a factory method which allows subclasses to define the precise
465.1778 - type of socket they want. The default implementation creates a TCP socket
465.1779 - (:const:`socket.SOCK_STREAM`).
465.1780 -
465.1781 -
465.1782 - .. method:: makePickle(record)
465.1783 -
465.1784 - Pickles the record's attribute dictionary in binary format with a length
465.1785 - prefix, and returns it ready for transmission across the socket.
465.1786 -
465.1787 -
465.1788 - .. method:: send(packet)
465.1789 -
465.1790 - Send a pickled string *packet* to the socket. This function allows for
465.1791 - partial sends which can happen when the network is busy.
465.1792 -
465.1793 -
465.1794 -DatagramHandler
465.1795 -^^^^^^^^^^^^^^^
465.1796 -
465.1797 -The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
465.1798 -module, inherits from :class:`SocketHandler` to support sending logging messages
465.1799 -over UDP sockets.
465.1800 -
465.1801 -
465.1802 -.. class:: DatagramHandler(host, port)
465.1803 -
465.1804 - Returns a new instance of the :class:`DatagramHandler` class intended to
465.1805 - communicate with a remote machine whose address is given by *host* and *port*.
465.1806 -
465.1807 -
465.1808 - .. method:: emit()
465.1809 -
465.1810 - Pickles the record's attribute dictionary and writes it to the socket in
465.1811 - binary format. If there is an error with the socket, silently drops the
465.1812 - packet. To unpickle the record at the receiving end into a
465.1813 - :class:`LogRecord`, use the :func:`makeLogRecord` function.
465.1814 -
465.1815 -
465.1816 - .. method:: makeSocket()
465.1817 -
465.1818 - The factory method of :class:`SocketHandler` is here overridden to create
465.1819 - a UDP socket (:const:`socket.SOCK_DGRAM`).
465.1820 -
465.1821 -
465.1822 - .. method:: send(s)
465.1823 -
465.1824 - Send a pickled string to a socket.
465.1825 -
465.1826 -
465.1827 -SysLogHandler
465.1828 -^^^^^^^^^^^^^
465.1829 -
465.1830 -The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
465.1831 -supports sending logging messages to a remote or local Unix syslog.
465.1832 -
465.1833 -
465.1834 -.. class:: SysLogHandler([address[, facility]])
465.1835 -
465.1836 - Returns a new instance of the :class:`SysLogHandler` class intended to
465.1837 - communicate with a remote Unix machine whose address is given by *address* in
465.1838 - the form of a ``(host, port)`` tuple. If *address* is not specified,
465.1839 - ``('localhost', 514)`` is used. The address is used to open a UDP socket. An
465.1840 - alternative to providing a ``(host, port)`` tuple is providing an address as a
465.1841 - string, for example "/dev/log". In this case, a Unix domain socket is used to
465.1842 - send the message to the syslog. If *facility* is not specified,
465.1843 - :const:`LOG_USER` is used.
465.1844 -
465.1845 -
465.1846 - .. method:: close()
465.1847 -
465.1848 - Closes the socket to the remote host.
465.1849 -
465.1850 -
465.1851 - .. method:: emit(record)
465.1852 -
465.1853 - The record is formatted, and then sent to the syslog server. If exception
465.1854 - information is present, it is *not* sent to the server.
465.1855 -
465.1856 -
465.1857 - .. method:: encodePriority(facility, priority)
465.1858 -
465.1859 - Encodes the facility and priority into an integer. You can pass in strings
465.1860 - or integers - if strings are passed, internal mapping dictionaries are
465.1861 - used to convert them to integers.
465.1862 -
465.1863 -
465.1864 -NTEventLogHandler
465.1865 -^^^^^^^^^^^^^^^^^
465.1866 -
465.1867 -The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
465.1868 -module, supports sending logging messages to a local Windows NT, Windows 2000 or
465.1869 -Windows XP event log. Before you can use it, you need Mark Hammond's Win32
465.1870 -extensions for Python installed.
465.1871 -
465.1872 -
465.1873 -.. class:: NTEventLogHandler(appname[, dllname[, logtype]])
465.1874 -
465.1875 - Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
465.1876 - used to define the application name as it appears in the event log. An
465.1877 - appropriate registry entry is created using this name. The *dllname* should give
465.1878 - the fully qualified pathname of a .dll or .exe which contains message
465.1879 - definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
465.1880 - - this is installed with the Win32 extensions and contains some basic
465.1881 - placeholder message definitions. Note that use of these placeholders will make
465.1882 - your event logs big, as the entire message source is held in the log. If you
465.1883 - want slimmer logs, you have to pass in the name of your own .dll or .exe which
465.1884 - contains the message definitions you want to use in the event log). The
465.1885 - *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
465.1886 - defaults to ``'Application'``.
465.1887 -
465.1888 -
465.1889 - .. method:: close()
465.1890 -
465.1891 - At this point, you can remove the application name from the registry as a
465.1892 - source of event log entries. However, if you do this, you will not be able
465.1893 - to see the events as you intended in the Event Log Viewer - it needs to be
465.1894 - able to access the registry to get the .dll name. The current version does
465.1895 - not do this.
465.1896 -
465.1897 -
465.1898 - .. method:: emit(record)
465.1899 -
465.1900 - Determines the message ID, event category and event type, and then logs
465.1901 - the message in the NT event log.
465.1902 -
465.1903 -
465.1904 - .. method:: getEventCategory(record)
465.1905 -
465.1906 - Returns the event category for the record. Override this if you want to
465.1907 - specify your own categories. This version returns 0.
465.1908 -
465.1909 -
465.1910 - .. method:: getEventType(record)
465.1911 -
465.1912 - Returns the event type for the record. Override this if you want to
465.1913 - specify your own types. This version does a mapping using the handler's
465.1914 - typemap attribute, which is set up in :meth:`__init__` to a dictionary
465.1915 - which contains mappings for :const:`DEBUG`, :const:`INFO`,
465.1916 - :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
465.1917 - your own levels, you will either need to override this method or place a
465.1918 - suitable dictionary in the handler's *typemap* attribute.
465.1919 -
465.1920 -
465.1921 - .. method:: getMessageID(record)
465.1922 -
465.1923 - Returns the message ID for the record. If you are using your own messages,
465.1924 - you could do this by having the *msg* passed to the logger being an ID
465.1925 - rather than a format string. Then, in here, you could use a dictionary
465.1926 - lookup to get the message ID. This version returns 1, which is the base
465.1927 - message ID in :file:`win32service.pyd`.
465.1928 -
465.1929 -
465.1930 -SMTPHandler
465.1931 -^^^^^^^^^^^
465.1932 -
465.1933 -The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
465.1934 -supports sending logging messages to an email address via SMTP.
465.1935 -
465.1936 -
465.1937 -.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject[, credentials])
465.1938 -
465.1939 - Returns a new instance of the :class:`SMTPHandler` class. The instance is
465.1940 - initialized with the from and to addresses and subject line of the email. The
465.1941 - *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
465.1942 - the (host, port) tuple format for the *mailhost* argument. If you use a string,
465.1943 - the standard SMTP port is used. If your SMTP server requires authentication, you
465.1944 - can specify a (username, password) tuple for the *credentials* argument.
465.1945 -
465.1946 - .. versionchanged:: 2.6
465.1947 - *credentials* was added.
465.1948 -
465.1949 -
465.1950 - .. method:: emit(record)
465.1951 -
465.1952 - Formats the record and sends it to the specified addressees.
465.1953 -
465.1954 -
465.1955 - .. method:: getSubject(record)
465.1956 -
465.1957 - If you want to specify a subject line which is record-dependent, override
465.1958 - this method.
465.1959 -
465.1960 -
465.1961 -MemoryHandler
465.1962 -^^^^^^^^^^^^^
465.1963 -
465.1964 -The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
465.1965 -supports buffering of logging records in memory, periodically flushing them to a
465.1966 -:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
465.1967 -event of a certain severity or greater is seen.
465.1968 -
465.1969 -:class:`MemoryHandler` is a subclass of the more general
465.1970 -:class:`BufferingHandler`, which is an abstract class. This buffers logging
465.1971 -records in memory. Whenever each record is added to the buffer, a check is made
465.1972 -by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
465.1973 -should, then :meth:`flush` is expected to do the needful.
465.1974 -
465.1975 -
465.1976 -.. class:: BufferingHandler(capacity)
465.1977 -
465.1978 - Initializes the handler with a buffer of the specified capacity.
465.1979 -
465.1980 -
465.1981 - .. method:: emit(record)
465.1982 -
465.1983 - Appends the record to the buffer. If :meth:`shouldFlush` returns true,
465.1984 - calls :meth:`flush` to process the buffer.
465.1985 -
465.1986 -
465.1987 - .. method:: flush()
465.1988 -
465.1989 - You can override this to implement custom flushing behavior. This version
465.1990 - just zaps the buffer to empty.
465.1991 -
465.1992 -
465.1993 - .. method:: shouldFlush(record)
465.1994 -
465.1995 - Returns true if the buffer is up to capacity. This method can be
465.1996 - overridden to implement custom flushing strategies.
465.1997 -
465.1998 -
465.1999 -.. class:: MemoryHandler(capacity[, flushLevel [, target]])
465.2000 -
465.2001 - Returns a new instance of the :class:`MemoryHandler` class. The instance is
465.2002 - initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
465.2003 - :const:`ERROR` is used. If no *target* is specified, the target will need to be
465.2004 - set using :meth:`setTarget` before this handler does anything useful.
465.2005 -
465.2006 -
465.2007 - .. method:: close()
465.2008 -
465.2009 - Calls :meth:`flush`, sets the target to :const:`None` and clears the
465.2010 - buffer.
465.2011 -
465.2012 -
465.2013 - .. method:: flush()
465.2014 -
465.2015 - For a :class:`MemoryHandler`, flushing means just sending the buffered
465.2016 - records to the target, if there is one. Override if you want different
465.2017 - behavior.
465.2018 -
465.2019 -
465.2020 - .. method:: setTarget(target)
465.2021 -
465.2022 - Sets the target handler for this handler.
465.2023 -
465.2024 -
465.2025 - .. method:: shouldFlush(record)
465.2026 -
465.2027 - Checks for buffer full or a record at the *flushLevel* or higher.
465.2028 -
465.2029 -
465.2030 -HTTPHandler
465.2031 -^^^^^^^^^^^
465.2032 -
465.2033 -The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
465.2034 -supports sending logging messages to a Web server, using either ``GET`` or
465.2035 -``POST`` semantics.
465.2036 -
465.2037 -
465.2038 -.. class:: HTTPHandler(host, url[, method])
465.2039 -
465.2040 - Returns a new instance of the :class:`HTTPHandler` class. The instance is
465.2041 - initialized with a host address, url and HTTP method. The *host* can be of the
465.2042 - form ``host:port``, should you need to use a specific port number. If no
465.2043 - *method* is specified, ``GET`` is used.
465.2044 -
465.2045 -
465.2046 - .. method:: emit(record)
465.2047 -
465.2048 - Sends the record to the Web server as an URL-encoded dictionary.
465.2049 -
465.2050 -
465.2051 -.. _formatter-objects:
465.2052 -
465.2053 -Formatter Objects
465.2054 ------------------
465.2055 -
465.2056 -:class:`Formatter`\ s have the following attributes and methods. They are
465.2057 -responsible for converting a :class:`LogRecord` to (usually) a string which can
465.2058 -be interpreted by either a human or an external system. The base
465.2059 -:class:`Formatter` allows a formatting string to be specified. If none is
465.2060 -supplied, the default value of ``'%(message)s'`` is used.
465.2061 -
465.2062 -A Formatter can be initialized with a format string which makes use of knowledge
465.2063 -of the :class:`LogRecord` attributes - such as the default value mentioned above
465.2064 -making use of the fact that the user's message and arguments are pre-formatted
465.2065 -into a :class:`LogRecord`'s *message* attribute. This format string contains
465.2066 -standard python %-style mapping keys. See section :ref:`string-formatting`
465.2067 -for more information on string formatting.
465.2068 -
465.2069 -Currently, the useful mapping keys in a :class:`LogRecord` are:
465.2070 -
465.2071 -+-------------------------+-----------------------------------------------+
465.2072 -| Format | Description |
465.2073 -+=========================+===============================================+
465.2074 -| ``%(name)s`` | Name of the logger (logging channel). |
465.2075 -+-------------------------+-----------------------------------------------+
465.2076 -| ``%(levelno)s`` | Numeric logging level for the message |
465.2077 -| | (:const:`DEBUG`, :const:`INFO`, |
465.2078 -| | :const:`WARNING`, :const:`ERROR`, |
465.2079 -| | :const:`CRITICAL`). |
465.2080 -+-------------------------+-----------------------------------------------+
465.2081 -| ``%(levelname)s`` | Text logging level for the message |
465.2082 -| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
465.2083 -| | ``'ERROR'``, ``'CRITICAL'``). |
465.2084 -+-------------------------+-----------------------------------------------+
465.2085 -| ``%(pathname)s`` | Full pathname of the source file where the |
465.2086 -| | logging call was issued (if available). |
465.2087 -+-------------------------+-----------------------------------------------+
465.2088 -| ``%(filename)s`` | Filename portion of pathname. |
465.2089 -+-------------------------+-----------------------------------------------+
465.2090 -| ``%(module)s`` | Module (name portion of filename). |
465.2091 -+-------------------------+-----------------------------------------------+
465.2092 -| ``%(funcName)s`` | Name of function containing the logging call. |
465.2093 -+-------------------------+-----------------------------------------------+
465.2094 -| ``%(lineno)d`` | Source line number where the logging call was |
465.2095 -| | issued (if available). |
465.2096 -+-------------------------+-----------------------------------------------+
465.2097 -| ``%(created)f`` | Time when the :class:`LogRecord` was created |
465.2098 -| | (as returned by :func:`time.time`). |
465.2099 -+-------------------------+-----------------------------------------------+
465.2100 -| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
465.2101 -| | created, relative to the time the logging |
465.2102 -| | module was loaded. |
465.2103 -+-------------------------+-----------------------------------------------+
465.2104 -| ``%(asctime)s`` | Human-readable time when the |
465.2105 -| | :class:`LogRecord` was created. By default |
465.2106 -| | this is of the form "2003-07-08 16:49:45,896" |
465.2107 -| | (the numbers after the comma are millisecond |
465.2108 -| | portion of the time). |
465.2109 -+-------------------------+-----------------------------------------------+
465.2110 -| ``%(msecs)d`` | Millisecond portion of the time when the |
465.2111 -| | :class:`LogRecord` was created. |
465.2112 -+-------------------------+-----------------------------------------------+
465.2113 -| ``%(thread)d`` | Thread ID (if available). |
465.2114 -+-------------------------+-----------------------------------------------+
465.2115 -| ``%(threadName)s`` | Thread name (if available). |
465.2116 -+-------------------------+-----------------------------------------------+
465.2117 -| ``%(process)d`` | Process ID (if available). |
465.2118 -+-------------------------+-----------------------------------------------+
465.2119 -| ``%(message)s`` | The logged message, computed as ``msg % |
465.2120 -| | args``. |
465.2121 -+-------------------------+-----------------------------------------------+
465.2122 -
465.2123 -.. versionchanged:: 2.5
465.2124 - *funcName* was added.
465.2125 -
465.2126 -
465.2127 -.. class:: Formatter([fmt[, datefmt]])
465.2128 -
465.2129 - Returns a new instance of the :class:`Formatter` class. The instance is
465.2130 - initialized with a format string for the message as a whole, as well as a format
465.2131 - string for the date/time portion of a message. If no *fmt* is specified,
465.2132 - ``'%(message)s'`` is used. If no *datefmt* is specified, the ISO8601 date format
465.2133 - is used.
465.2134 -
465.2135 -
465.2136 - .. method:: format(record)
465.2137 -
465.2138 - The record's attribute dictionary is used as the operand to a string
465.2139 - formatting operation. Returns the resulting string. Before formatting the
465.2140 - dictionary, a couple of preparatory steps are carried out. The *message*
465.2141 - attribute of the record is computed using *msg* % *args*. If the
465.2142 - formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
465.2143 - to format the event time. If there is exception information, it is
465.2144 - formatted using :meth:`formatException` and appended to the message. Note
465.2145 - that the formatted exception information is cached in attribute
465.2146 - *exc_text*. This is useful because the exception information can be
465.2147 - pickled and sent across the wire, but you should be careful if you have
465.2148 - more than one :class:`Formatter` subclass which customizes the formatting
465.2149 - of exception information. In this case, you will have to clear the cached
465.2150 - value after a formatter has done its formatting, so that the next
465.2151 - formatter to handle the event doesn't use the cached value but
465.2152 - recalculates it afresh.
465.2153 -
465.2154 -
465.2155 - .. method:: formatTime(record[, datefmt])
465.2156 -
465.2157 - This method should be called from :meth:`format` by a formatter which
465.2158 - wants to make use of a formatted time. This method can be overridden in
465.2159 - formatters to provide for any specific requirement, but the basic behavior
465.2160 - is as follows: if *datefmt* (a string) is specified, it is used with
465.2161 - :func:`time.strftime` to format the creation time of the
465.2162 - record. Otherwise, the ISO8601 format is used. The resulting string is
465.2163 - returned.
465.2164 -
465.2165 -
465.2166 - .. method:: formatException(exc_info)
465.2167 -
465.2168 - Formats the specified exception information (a standard exception tuple as
465.2169 - returned by :func:`sys.exc_info`) as a string. This default implementation
465.2170 - just uses :func:`traceback.print_exception`. The resulting string is
465.2171 - returned.
465.2172 -
465.2173 -
465.2174 -Filter Objects
465.2175 ---------------
465.2176 -
465.2177 -:class:`Filter`\ s can be used by :class:`Handler`\ s and :class:`Logger`\ s for
465.2178 -more sophisticated filtering than is provided by levels. The base filter class
465.2179 -only allows events which are below a certain point in the logger hierarchy. For
465.2180 -example, a filter initialized with "A.B" will allow events logged by loggers
465.2181 -"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
465.2182 -initialized with the empty string, all events are passed.
465.2183 -
465.2184 -
465.2185 -.. class:: Filter([name])
465.2186 -
465.2187 - Returns an instance of the :class:`Filter` class. If *name* is specified, it
465.2188 - names a logger which, together with its children, will have its events allowed
465.2189 - through the filter. If no name is specified, allows every event.
465.2190 -
465.2191 -
465.2192 - .. method:: filter(record)
465.2193 -
465.2194 - Is the specified record to be logged? Returns zero for no, nonzero for
465.2195 - yes. If deemed appropriate, the record may be modified in-place by this
465.2196 - method.
465.2197 -
465.2198 -
465.2199 -LogRecord Objects
465.2200 ------------------
465.2201 -
465.2202 -:class:`LogRecord` instances are created every time something is logged. They
465.2203 -contain all the information pertinent to the event being logged. The main
465.2204 -information passed in is in msg and args, which are combined using msg % args to
465.2205 -create the message field of the record. The record also includes information
465.2206 -such as when the record was created, the source line where the logging call was
465.2207 -made, and any exception information to be logged.
465.2208 -
465.2209 -
465.2210 -.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info [, func])
465.2211 -
465.2212 - Returns an instance of :class:`LogRecord` initialized with interesting
465.2213 - information. The *name* is the logger name; *lvl* is the numeric level;
465.2214 - *pathname* is the absolute pathname of the source file in which the logging
465.2215 - call was made; *lineno* is the line number in that file where the logging
465.2216 - call is found; *msg* is the user-supplied message (a format string); *args*
465.2217 - is the tuple which, together with *msg*, makes up the user message; and
465.2218 - *exc_info* is the exception tuple obtained by calling :func:`sys.exc_info`
465.2219 - (or :const:`None`, if no exception information is available). The *func* is
465.2220 - the name of the function from which the logging call was made. If not
465.2221 - specified, it defaults to ``None``.
465.2222 -
465.2223 - .. versionchanged:: 2.5
465.2224 - *func* was added.
465.2225 -
465.2226 -
465.2227 - .. method:: getMessage()
465.2228 -
465.2229 - Returns the message for this :class:`LogRecord` instance after merging any
465.2230 - user-supplied arguments with the message.
465.2231 -
465.2232 -
465.2233 -LoggerAdapter Objects
465.2234 ----------------------
465.2235 -
465.2236 -.. versionadded:: 2.6
465.2237 -
465.2238 -:class:`LoggerAdapter` instances are used to conveniently pass contextual
465.2239 -information into logging calls. For a usage example , see the section on
465.2240 -`adding contextual information to your logging output`__.
465.2241 -
465.2242 -__ context-info_
465.2243 -
465.2244 -.. class:: LoggerAdapter(logger, extra)
465.2245 -
465.2246 - Returns an instance of :class:`LoggerAdapter` initialized with an
465.2247 - underlying :class:`Logger` instance and a dict-like object.
465.2248 -
465.2249 - .. method:: process(msg, kwargs)
465.2250 -
465.2251 - Modifies the message and/or keyword arguments passed to a logging call in
465.2252 - order to insert contextual information. This implementation takes the object
465.2253 - passed as *extra* to the constructor and adds it to *kwargs* using key
465.2254 - 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
465.2255 - (possibly modified) versions of the arguments passed in.
465.2256 -
465.2257 -In addition to the above, :class:`LoggerAdapter` supports all the logging
465.2258 -methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
465.2259 -:meth:`error`, :meth:`exception`, :meth:`critical` and :meth:`log`. These
465.2260 -methods have the same signatures as their counterparts in :class:`Logger`, so
465.2261 -you can use the two types of instances interchangeably.
465.2262 -
465.2263 -
465.2264 -Thread Safety
465.2265 --------------
465.2266 -
465.2267 -The logging module is intended to be thread-safe without any special work
465.2268 -needing to be done by its clients. It achieves this though using threading
465.2269 -locks; there is one lock to serialize access to the module's shared data, and
465.2270 -each handler also creates a lock to serialize access to its underlying I/O.
465.2271 -
465.2272 -
465.2273 -Configuration
465.2274 --------------
465.2275 -
465.2276 -
465.2277 -.. _logging-config-api:
465.2278 -
465.2279 -Configuration functions
465.2280 -^^^^^^^^^^^^^^^^^^^^^^^
465.2281 -
465.2282 -The following functions configure the logging module. They are located in the
465.2283 -:mod:`logging.config` module. Their use is optional --- you can configure the
465.2284 -logging module using these functions or by making calls to the main API (defined
465.2285 -in :mod:`logging` itself) and defining handlers which are declared either in
465.2286 -:mod:`logging` or :mod:`logging.handlers`.
465.2287 -
465.2288 -
465.2289 -.. function:: fileConfig(fname[, defaults])
465.2290 -
465.2291 - Reads the logging configuration from a ConfigParser-format file named *fname*.
465.2292 - This function can be called several times from an application, allowing an end
465.2293 - user the ability to select from various pre-canned configurations (if the
465.2294 - developer provides a mechanism to present the choices and load the chosen
465.2295 - configuration). Defaults to be passed to ConfigParser can be specified in the
465.2296 - *defaults* argument.
465.2297 -
465.2298 -
465.2299 -.. function:: listen([port])
465.2300 -
465.2301 - Starts up a socket server on the specified port, and listens for new
465.2302 - configurations. If no port is specified, the module's default
465.2303 - :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
465.2304 - sent as a file suitable for processing by :func:`fileConfig`. Returns a
465.2305 - :class:`Thread` instance on which you can call :meth:`start` to start the
465.2306 - server, and which you can :meth:`join` when appropriate. To stop the server,
465.2307 - call :func:`stopListening`.
465.2308 -
465.2309 - To send a configuration to the socket, read in the configuration file and
465.2310 - send it to the socket as a string of bytes preceded by a four-byte length
465.2311 - string packed in binary using ``struct.pack('>L', n)``.
465.2312 -
465.2313 -
465.2314 -.. function:: stopListening()
465.2315 -
465.2316 - Stops the listening server which was created with a call to :func:`listen`.
465.2317 - This is typically called before calling :meth:`join` on the return value from
465.2318 - :func:`listen`.
465.2319 -
465.2320 -
465.2321 -.. _logging-config-fileformat:
465.2322 -
465.2323 -Configuration file format
465.2324 -^^^^^^^^^^^^^^^^^^^^^^^^^
465.2325 -
465.2326 -The configuration file format understood by :func:`fileConfig` is based on
465.2327 -ConfigParser functionality. The file must contain sections called ``[loggers]``,
465.2328 -``[handlers]`` and ``[formatters]`` which identify by name the entities of each
465.2329 -type which are defined in the file. For each such entity, there is a separate
465.2330 -section which identified how that entity is configured. Thus, for a logger named
465.2331 -``log01`` in the ``[loggers]`` section, the relevant configuration details are
465.2332 -held in a section ``[logger_log01]``. Similarly, a handler called ``hand01`` in
465.2333 -the ``[handlers]`` section will have its configuration held in a section called
465.2334 -``[handler_hand01]``, while a formatter called ``form01`` in the
465.2335 -``[formatters]`` section will have its configuration specified in a section
465.2336 -called ``[formatter_form01]``. The root logger configuration must be specified
465.2337 -in a section called ``[logger_root]``.
465.2338 -
465.2339 -Examples of these sections in the file are given below. ::
465.2340 -
465.2341 - [loggers]
465.2342 - keys=root,log02,log03,log04,log05,log06,log07
465.2343 -
465.2344 - [handlers]
465.2345 - keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
465.2346 -
465.2347 - [formatters]
465.2348 - keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
465.2349 -
465.2350 -The root logger must specify a level and a list of handlers. An example of a
465.2351 -root logger section is given below. ::
465.2352 -
465.2353 - [logger_root]
465.2354 - level=NOTSET
465.2355 - handlers=hand01
465.2356 -
465.2357 -The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
465.2358 -``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
465.2359 -logged. Level values are :func:`eval`\ uated in the context of the ``logging``
465.2360 -package's namespace.
465.2361 -
465.2362 -The ``handlers`` entry is a comma-separated list of handler names, which must
465.2363 -appear in the ``[handlers]`` section. These names must appear in the
465.2364 -``[handlers]`` section and have corresponding sections in the configuration
465.2365 -file.
465.2366 -
465.2367 -For loggers other than the root logger, some additional information is required.
465.2368 -This is illustrated by the following example. ::
465.2369 -
465.2370 - [logger_parser]
465.2371 - level=DEBUG
465.2372 - handlers=hand01
465.2373 - propagate=1
465.2374 - qualname=compiler.parser
465.2375 -
465.2376 -The ``level`` and ``handlers`` entries are interpreted as for the root logger,
465.2377 -except that if a non-root logger's level is specified as ``NOTSET``, the system
465.2378 -consults loggers higher up the hierarchy to determine the effective level of the
465.2379 -logger. The ``propagate`` entry is set to 1 to indicate that messages must
465.2380 -propagate to handlers higher up the logger hierarchy from this logger, or 0 to
465.2381 -indicate that messages are **not** propagated to handlers up the hierarchy. The
465.2382 -``qualname`` entry is the hierarchical channel name of the logger, that is to
465.2383 -say the name used by the application to get the logger.
465.2384 -
465.2385 -Sections which specify handler configuration are exemplified by the following.
465.2386 -::
465.2387 -
465.2388 - [handler_hand01]
465.2389 - class=StreamHandler
465.2390 - level=NOTSET
465.2391 - formatter=form01
465.2392 - args=(sys.stdout,)
465.2393 -
465.2394 -The ``class`` entry indicates the handler's class (as determined by :func:`eval`
465.2395 -in the ``logging`` package's namespace). The ``level`` is interpreted as for
465.2396 -loggers, and ``NOTSET`` is taken to mean "log everything".
465.2397 -
465.2398 -.. versionchanged:: 2.6
465.2399 - Added support for resolving the handler's class as a dotted module and class
465.2400 - name.
465.2401 -
465.2402 -The ``formatter`` entry indicates the key name of the formatter for this
465.2403 -handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
465.2404 -If a name is specified, it must appear in the ``[formatters]`` section and have
465.2405 -a corresponding section in the configuration file.
465.2406 -
465.2407 -The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
465.2408 -package's namespace, is the list of arguments to the constructor for the handler
465.2409 -class. Refer to the constructors for the relevant handlers, or to the examples
465.2410 -below, to see how typical entries are constructed. ::
465.2411 -
465.2412 - [handler_hand02]
465.2413 - class=FileHandler
465.2414 - level=DEBUG
465.2415 - formatter=form02
465.2416 - args=('python.log', 'w')
465.2417 -
465.2418 - [handler_hand03]
465.2419 - class=handlers.SocketHandler
465.2420 - level=INFO
465.2421 - formatter=form03
465.2422 - args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
465.2423 -
465.2424 - [handler_hand04]
465.2425 - class=handlers.DatagramHandler
465.2426 - level=WARN
465.2427 - formatter=form04
465.2428 - args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
465.2429 -
465.2430 - [handler_hand05]
465.2431 - class=handlers.SysLogHandler
465.2432 - level=ERROR
465.2433 - formatter=form05
465.2434 - args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
465.2435 -
465.2436 - [handler_hand06]
465.2437 - class=handlers.NTEventLogHandler
465.2438 - level=CRITICAL
465.2439 - formatter=form06
465.2440 - args=('Python Application', '', 'Application')
465.2441 -
465.2442 - [handler_hand07]
465.2443 - class=handlers.SMTPHandler
465.2444 - level=WARN
465.2445 - formatter=form07
465.2446 - args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
465.2447 -
465.2448 - [handler_hand08]
465.2449 - class=handlers.MemoryHandler
465.2450 - level=NOTSET
465.2451 - formatter=form08
465.2452 - target=
465.2453 - args=(10, ERROR)
465.2454 -
465.2455 - [handler_hand09]
465.2456 - class=handlers.HTTPHandler
465.2457 - level=NOTSET
465.2458 - formatter=form09
465.2459 - args=('localhost:9022', '/log', 'GET')
465.2460 -
465.2461 -Sections which specify formatter configuration are typified by the following. ::
465.2462 -
465.2463 - [formatter_form01]
465.2464 - format=F1 %(asctime)s %(levelname)s %(message)s
465.2465 - datefmt=
465.2466 - class=logging.Formatter
465.2467 -
465.2468 -The ``format`` entry is the overall format string, and the ``datefmt`` entry is
465.2469 -the :func:`strftime`\ -compatible date/time format string. If empty, the
465.2470 -package substitutes ISO8601 format date/times, which is almost equivalent to
465.2471 -specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
465.2472 -also specifies milliseconds, which are appended to the result of using the above
465.2473 -format string, with a comma separator. An example time in ISO8601 format is
465.2474 -``2003-01-23 00:29:50,411``.
465.2475 -
465.2476 -The ``class`` entry is optional. It indicates the name of the formatter's class
465.2477 -(as a dotted module and class name.) This option is useful for instantiating a
465.2478 -:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
465.2479 -exception tracebacks in an expanded or condensed format.
465.2480 -
465.2481 -
465.2482 -Configuration server example
465.2483 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^
465.2484 -
465.2485 -Here is an example of a module using the logging configuration server::
465.2486 -
465.2487 - import logging
465.2488 - import logging.config
465.2489 - import time
465.2490 - import os
465.2491 -
465.2492 - # read initial config file
465.2493 - logging.config.fileConfig("logging.conf")
465.2494 -
465.2495 - # create and start listener on port 9999
465.2496 - t = logging.config.listen(9999)
465.2497 - t.start()
465.2498 -
465.2499 - logger = logging.getLogger("simpleExample")
465.2500 -
465.2501 - try:
465.2502 - # loop through logging calls to see the difference
465.2503 - # new configurations make, until Ctrl+C is pressed
465.2504 - while True:
465.2505 - logger.debug("debug message")
465.2506 - logger.info("info message")
465.2507 - logger.warn("warn message")
465.2508 - logger.error("error message")
465.2509 - logger.critical("critical message")
465.2510 - time.sleep(5)
465.2511 - except KeyboardInterrupt:
465.2512 - # cleanup
465.2513 - logging.config.stopListening()
465.2514 - t.join()
465.2515 -
465.2516 -And here is a script that takes a filename and sends that file to the server,
465.2517 -properly preceded with the binary-encoded length, as the new logging
465.2518 -configuration::
465.2519 -
465.2520 - #!/usr/bin/env python
465.2521 - import socket, sys, struct
465.2522 -
465.2523 - data_to_send = open(sys.argv[1], "r").read()
465.2524 -
465.2525 - HOST = 'localhost'
465.2526 - PORT = 9999
465.2527 - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
465.2528 - print "connecting..."
465.2529 - s.connect((HOST, PORT))
465.2530 - print "sending config..."
465.2531 - s.send(struct.pack(">L", len(data_to_send)))
465.2532 - s.send(data_to_send)
465.2533 - s.close()
465.2534 - print "complete"
465.2535 -
465.2536 -
465.2537 -More examples
465.2538 --------------
465.2539 -
465.2540 -Multiple handlers and formatters
465.2541 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
465.2542 -
465.2543 -Loggers are plain Python objects. The :func:`addHandler` method has no minimum
465.2544 -or maximum quota for the number of handlers you may add. Sometimes it will be
465.2545 -beneficial for an application to log all messages of all severities to a text
465.2546 -file while simultaneously logging errors or above to the console. To set this
465.2547 -up, simply configure the appropriate handlers. The logging calls in the
465.2548 -application code will remain unchanged. Here is a slight modification to the
465.2549 -previous simple module-based configuration example::
465.2550 -
465.2551 - import logging
465.2552 -
465.2553 - logger = logging.getLogger("simple_example")
465.2554 - logger.setLevel(logging.DEBUG)
465.2555 - # create file handler which logs even debug messages
465.2556 - fh = logging.FileHandler("spam.log")
465.2557 - fh.setLevel(logging.DEBUG)
465.2558 - # create console handler with a higher log level
465.2559 - ch = logging.StreamHandler()
465.2560 - ch.setLevel(logging.ERROR)
465.2561 - # create formatter and add it to the handlers
465.2562 - formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
465.2563 - ch.setFormatter(formatter)
465.2564 - fh.setFormatter(formatter)
465.2565 - # add the handlers to logger
465.2566 - logger.addHandler(ch)
465.2567 - logger.addHandler(fh)
465.2568 -
465.2569 - # "application" code
465.2570 - logger.debug("debug message")
465.2571 - logger.info("info message")
465.2572 - logger.warn("warn message")
465.2573 - logger.error("error message")
465.2574 - logger.critical("critical message")
465.2575 -
465.2576 -Notice that the "application" code does not care about multiple handlers. All
465.2577 -that changed was the addition and configuration of a new handler named *fh*.
465.2578 -
465.2579 -The ability to create new handlers with higher- or lower-severity filters can be
465.2580 -very helpful when writing and testing an application. Instead of using many
465.2581 -``print`` statements for debugging, use ``logger.debug``: Unlike the print
465.2582 -statements, which you will have to delete or comment out later, the logger.debug
465.2583 -statements can remain intact in the source code and remain dormant until you
465.2584 -need them again. At that time, the only change that needs to happen is to
465.2585 -modify the severity level of the logger and/or handler to debug.
465.2586 -
465.2587 -
465.2588 -Using logging in multiple modules
465.2589 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
465.2590 -
465.2591 -It was mentioned above that multiple calls to
465.2592 -``logging.getLogger('someLogger')`` return a reference to the same logger
465.2593 -object. This is true not only within the same module, but also across modules
465.2594 -as long as it is in the same Python interpreter process. It is true for
465.2595 -references to the same object; additionally, application code can define and
465.2596 -configure a parent logger in one module and create (but not configure) a child
465.2597 -logger in a separate module, and all logger calls to the child will pass up to
465.2598 -the parent. Here is a main module::
465.2599 -
465.2600 - import logging
465.2601 - import auxiliary_module
465.2602 -
465.2603 - # create logger with "spam_application"
465.2604 - logger = logging.getLogger("spam_application")
465.2605 - logger.setLevel(logging.DEBUG)
465.2606 - # create file handler which logs even debug messages
465.2607 - fh = logging.FileHandler("spam.log")
465.2608 - fh.setLevel(logging.DEBUG)
465.2609 - # create console handler with a higher log level
465.2610 - ch = logging.StreamHandler()
465.2611 - ch.setLevel(logging.ERROR)
465.2612 - # create formatter and add it to the handlers
465.2613 - formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
465.2614 - fh.setFormatter(formatter)
465.2615 - ch.setFormatter(formatter)
465.2616 - # add the handlers to the logger
465.2617 - logger.addHandler(fh)
465.2618 - logger.addHandler(ch)
465.2619 -
465.2620 - logger.info("creating an instance of auxiliary_module.Auxiliary")
465.2621 - a = auxiliary_module.Auxiliary()
465.2622 - logger.info("created an instance of auxiliary_module.Auxiliary")
465.2623 - logger.info("calling auxiliary_module.Auxiliary.do_something")
465.2624 - a.do_something()
465.2625 - logger.info("finished auxiliary_module.Auxiliary.do_something")
465.2626 - logger.info("calling auxiliary_module.some_function()")
465.2627 - auxiliary_module.some_function()
465.2628 - logger.info("done with auxiliary_module.some_function()")
465.2629 -
465.2630 -Here is the auxiliary module::
465.2631 -
465.2632 - import logging
465.2633 -
465.2634 - # create logger
465.2635 - module_logger = logging.getLogger("spam_application.auxiliary")
465.2636 -
465.2637 - class Auxiliary:
465.2638 - def __init__(self):
465.2639 - self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
465.2640 - self.logger.info("creating an instance of Auxiliary")
465.2641 - def do_something(self):
465.2642 - self.logger.info("doing something")
465.2643 - a = 1 + 1
465.2644 - self.logger.info("done doing something")
465.2645 -
465.2646 - def some_function():
465.2647 - module_logger.info("received a call to \"some_function\"")
465.2648 -
465.2649 -The output looks like this::
465.2650 -
465.2651 - 2005-03-23 23:47:11,663 - spam_application - INFO -
465.2652 - creating an instance of auxiliary_module.Auxiliary
465.2653 - 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
465.2654 - creating an instance of Auxiliary
465.2655 - 2005-03-23 23:47:11,665 - spam_application - INFO -
465.2656 - created an instance of auxiliary_module.Auxiliary
465.2657 - 2005-03-23 23:47:11,668 - spam_application - INFO -
465.2658 - calling auxiliary_module.Auxiliary.do_something
465.2659 - 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
465.2660 - doing something
465.2661 - 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
465.2662 - done doing something
465.2663 - 2005-03-23 23:47:11,670 - spam_application - INFO -
465.2664 - finished auxiliary_module.Auxiliary.do_something
465.2665 - 2005-03-23 23:47:11,671 - spam_application - INFO -
465.2666 - calling auxiliary_module.some_function()
465.2667 - 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
465.2668 - received a call to "some_function"
465.2669 - 2005-03-23 23:47:11,673 - spam_application - INFO -
465.2670 - done with auxiliary_module.some_function()
465.2671 -
466.1 --- a/python.editor/test/unit/data/testfiles/rst/logging.rst.indexed Sun Jan 04 13:11:53 2015 -0600
466.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
466.3 @@ -1,327 +0,0 @@
466.4 -
466.5 -
466.6 -Document 0
466.7 -Searchable Keys:
466.8 - class : BufferingHandler
466.9 - class-ig : bufferinghandler
466.10 - in : logging
466.11 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;capacity;
466.12 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
466.13 - member : flush;F;|DOCUMENTED|DOC_ONLY|;;
466.14 - member : shouldFlush;F;|DOCUMENTED|DOC_ONLY|;record;
466.15 -
466.16 -Not Searchable Keys:
466.17 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.18 -
466.19 -
466.20 -Document 1
466.21 -Searchable Keys:
466.22 - class : DatagramHandler
466.23 - class-ig : datagramhandler
466.24 - in : logging
466.25 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;host,port;
466.26 - member : emit;F;|DOCUMENTED|DOC_ONLY|;;
466.27 - member : makeSocket;F;|DOCUMENTED|DOC_ONLY|;;
466.28 - member : send;F;|DOCUMENTED|DOC_ONLY|;s;
466.29 -
466.30 -Not Searchable Keys:
466.31 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.32 -
466.33 -
466.34 -Document 2
466.35 -Searchable Keys:
466.36 - class : FileHandler
466.37 - class-ig : filehandler
466.38 - in : logging
466.39 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;filename,mode,encoding,delay;
466.40 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
466.41 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
466.42 -
466.43 -Not Searchable Keys:
466.44 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.45 -
466.46 -
466.47 -Document 3
466.48 -Searchable Keys:
466.49 - class : Filter
466.50 - class-ig : filter
466.51 - in : logging
466.52 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;name;
466.53 - member : filter;F;|DOCUMENTED|DOC_ONLY|;record;
466.54 -
466.55 -Not Searchable Keys:
466.56 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.57 -
466.58 -
466.59 -Document 4
466.60 -Searchable Keys:
466.61 - class : Formatter
466.62 - class-ig : formatter
466.63 - in : logging
466.64 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;fmt,datefmt;
466.65 - member : format;F;|DOCUMENTED|DOC_ONLY|;record;
466.66 - member : formatException;F;|DOCUMENTED|DOC_ONLY|;exc_info;
466.67 - member : formatTime;F;|DOCUMENTED|DOC_ONLY|;record,datefmt;
466.68 -
466.69 -Not Searchable Keys:
466.70 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.71 -
466.72 -
466.73 -Document 5
466.74 -Searchable Keys:
466.75 - class : HTTPHandler
466.76 - class-ig : httphandler
466.77 - in : logging
466.78 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;host,url,method;
466.79 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
466.80 -
466.81 -Not Searchable Keys:
466.82 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.83 -
466.84 -
466.85 -Document 6
466.86 -Searchable Keys:
466.87 - class : Handler
466.88 - class-ig : handler
466.89 - in : logging
466.90 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;level;
466.91 - member : acquire;F;|DOCUMENTED|DOC_ONLY|;;
466.92 - member : addFilter;F;|DOCUMENTED|DOC_ONLY|;filt;
466.93 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
466.94 - member : createLock;F;|DOCUMENTED|DOC_ONLY|;;
466.95 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
466.96 - member : filter;F;|DOCUMENTED|DOC_ONLY|;record;
466.97 - member : flush;F;|DOCUMENTED|DOC_ONLY|;;
466.98 - member : format;F;|DOCUMENTED|DOC_ONLY|;record;
466.99 - member : handle;F;|DOCUMENTED|DOC_ONLY|;record;
466.100 - member : handleError;F;|DOCUMENTED|DOC_ONLY|;record;
466.101 - member : release;F;|DOCUMENTED|DOC_ONLY|;;
466.102 - member : removeFilter;F;|DOCUMENTED|DOC_ONLY|;filt;
466.103 - member : setFormatter;F;|DOCUMENTED|DOC_ONLY|;form;
466.104 - member : setLevel;F;|DOCUMENTED|DOC_ONLY|;lvl;
466.105 -
466.106 -Not Searchable Keys:
466.107 -
466.108 -
466.109 -Document 7
466.110 -Searchable Keys:
466.111 - class : LogRecord
466.112 - class-ig : logrecord
466.113 - in : logging
466.114 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;name,lvl,pathname,lineno,msg,args,exc_info,func;
466.115 - member : getMessage;F;|DOCUMENTED|DOC_ONLY|;;
466.116 -
466.117 -Not Searchable Keys:
466.118 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.119 -
466.120 -
466.121 -Document 8
466.122 -Searchable Keys:
466.123 - class : Logger
466.124 - class-ig : logger
466.125 - in : logging
466.126 - member : addFilter;F;|DOCUMENTED|DOC_ONLY|;filt;
466.127 - member : addHandler;F;|DOCUMENTED|DOC_ONLY|;hdlr;
466.128 - member : critical;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
466.129 - member : debug;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
466.130 - member : error;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
466.131 - member : exception;F;|DOCUMENTED|DOC_ONLY|;msg,*args;
466.132 - member : filter;F;|DOCUMENTED|DOC_ONLY|;record;
466.133 - member : findCaller;F;|DOCUMENTED|DOC_ONLY|;;
466.134 - member : getEffectiveLevel;F;|DOCUMENTED|DOC_ONLY|;;
466.135 - member : handle;F;|DOCUMENTED|DOC_ONLY|;record;
466.136 - member : info;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
466.137 - member : isEnabledFor;F;|DOCUMENTED|DOC_ONLY|;lvl;
466.138 - member : log;F;|DOCUMENTED|DOC_ONLY|;lvl,msg,*args,**kwargs;
466.139 - member : makeRecord;F;|DOCUMENTED|DOC_ONLY|;name,lvl,fn,lno,msg,args,exc_info,func,extra;
466.140 - member : propagate;A;|DOCUMENTED|DOC_ONLY|;
466.141 - member : removeFilter;F;|DOCUMENTED|DOC_ONLY|;filt;
466.142 - member : removeHandler;F;|DOCUMENTED|DOC_ONLY|;hdlr;
466.143 - member : setLevel;F;|DOCUMENTED|DOC_ONLY|;lvl;
466.144 - member : warning;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
466.145 -
466.146 -Not Searchable Keys:
466.147 -
466.148 -
466.149 -Document 9
466.150 -Searchable Keys:
466.151 - class : LoggerAdapter
466.152 - class-ig : loggeradapter
466.153 - in : logging
466.154 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;logger,extra;
466.155 - member : process;F;|DOCUMENTED|DOC_ONLY|;msg,kwargs;
466.156 -
466.157 -Not Searchable Keys:
466.158 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.159 -
466.160 -
466.161 -Document 10
466.162 -Searchable Keys:
466.163 - class : MemoryHandler
466.164 - class-ig : memoryhandler
466.165 - in : logging
466.166 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;capacity,flushLevel,target;
466.167 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
466.168 - member : flush;F;|DOCUMENTED|DOC_ONLY|;;
466.169 - member : setTarget;F;|DOCUMENTED|DOC_ONLY|;target;
466.170 - member : shouldFlush;F;|DOCUMENTED|DOC_ONLY|;record;
466.171 -
466.172 -Not Searchable Keys:
466.173 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.174 -
466.175 -
466.176 -Document 11
466.177 -Searchable Keys:
466.178 - class : NTEventLogHandler
466.179 - class-ig : nteventloghandler
466.180 - in : logging
466.181 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;appname,dllname,logtype;
466.182 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
466.183 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
466.184 - member : getEventCategory;F;|DOCUMENTED|DOC_ONLY|;record;
466.185 - member : getEventType;F;|DOCUMENTED|DOC_ONLY|;record;
466.186 - member : getMessageID;F;|DOCUMENTED|DOC_ONLY|;record;
466.187 -
466.188 -Not Searchable Keys:
466.189 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.190 -
466.191 -
466.192 -Document 12
466.193 -Searchable Keys:
466.194 - class : RotatingFileHandler
466.195 - class-ig : rotatingfilehandler
466.196 - in : logging
466.197 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;filename,mode,maxBytes,backupCount,encoding,delay;
466.198 - member : doRollover;F;|DOCUMENTED|DOC_ONLY|;;
466.199 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
466.200 -
466.201 -Not Searchable Keys:
466.202 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.203 -
466.204 -
466.205 -Document 13
466.206 -Searchable Keys:
466.207 - class : SMTPHandler
466.208 - class-ig : smtphandler
466.209 - in : logging
466.210 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;mailhost,fromaddr,toaddrs,subject,credentials;
466.211 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
466.212 - member : getSubject;F;|DOCUMENTED|DOC_ONLY|;record;
466.213 -
466.214 -Not Searchable Keys:
466.215 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.216 -
466.217 -
466.218 -Document 14
466.219 -Searchable Keys:
466.220 - class : SocketHandler
466.221 - class-ig : sockethandler
466.222 - in : logging
466.223 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;host,port;
466.224 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
466.225 - member : emit;F;|DOCUMENTED|DOC_ONLY|;;
466.226 - member : handleError;F;|DOCUMENTED|DOC_ONLY|;;
466.227 - member : makePickle;F;|DOCUMENTED|DOC_ONLY|;record;
466.228 - member : makeSocket;F;|DOCUMENTED|DOC_ONLY|;;
466.229 - member : send;F;|DOCUMENTED|DOC_ONLY|;packet;
466.230 -
466.231 -Not Searchable Keys:
466.232 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.233 -
466.234 -
466.235 -Document 15
466.236 -Searchable Keys:
466.237 - class : StreamHandler
466.238 - class-ig : streamhandler
466.239 - in : logging
466.240 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;strm;
466.241 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
466.242 - member : flush;F;|DOCUMENTED|DOC_ONLY|;;
466.243 -
466.244 -Not Searchable Keys:
466.245 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.246 -
466.247 -
466.248 -Document 16
466.249 -Searchable Keys:
466.250 - class : SysLogHandler
466.251 - class-ig : sysloghandler
466.252 - in : logging
466.253 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;address,facility;
466.254 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
466.255 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
466.256 - member : encodePriority;F;|DOCUMENTED|DOC_ONLY|;facility,priority;
466.257 -
466.258 -Not Searchable Keys:
466.259 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.260 -
466.261 -
466.262 -Document 17
466.263 -Searchable Keys:
466.264 - class : TimedRotatingFileHandler
466.265 - class-ig : timedrotatingfilehandler
466.266 - in : logging
466.267 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;filename,when,interval,backupCount,encoding,delay,utc;
466.268 - member : doRollover;F;|DOCUMENTED|DOC_ONLY|;;
466.269 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
466.270 -
466.271 -Not Searchable Keys:
466.272 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.273 -
466.274 -
466.275 -Document 18
466.276 -Searchable Keys:
466.277 - class : WatchedFileHandler
466.278 - class-ig : watchedfilehandler
466.279 - in : logging
466.280 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;filename,mode,encoding,delay;
466.281 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
466.282 -
466.283 -Not Searchable Keys:
466.284 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
466.285 -
466.286 -
466.287 -Document 19
466.288 -Searchable Keys:
466.289 - item : BufferingHandler;C;|DOCUMENTED|DOC_ONLY|;
466.290 - item : DatagramHandler;C;|DOCUMENTED|DOC_ONLY|;
466.291 - item : FileHandler;C;|DOCUMENTED|DOC_ONLY|;
466.292 - item : Filter;C;|DOCUMENTED|DOC_ONLY|;
466.293 - item : Formatter;C;|DOCUMENTED|DOC_ONLY|;
466.294 - item : HTTPHandler;C;|DOCUMENTED|DOC_ONLY|;
466.295 - item : Handler;C;|DOCUMENTED|DOC_ONLY|;
466.296 - item : LogRecord;C;|DOCUMENTED|DOC_ONLY|;
466.297 - item : Logger;C;|DOCUMENTED|DOC_ONLY|;
466.298 - item : LoggerAdapter;C;|DOCUMENTED|DOC_ONLY|;
466.299 - item : MemoryHandler;C;|DOCUMENTED|DOC_ONLY|;
466.300 - item : NTEventLogHandler;C;|DOCUMENTED|DOC_ONLY|;
466.301 - item : RotatingFileHandler;C;|DOCUMENTED|DOC_ONLY|;
466.302 - item : SMTPHandler;C;|DOCUMENTED|DOC_ONLY|;
466.303 - item : SocketHandler;C;|DOCUMENTED|DOC_ONLY|;
466.304 - item : StreamHandler;C;|DOCUMENTED|DOC_ONLY|;
466.305 - item : SysLogHandler;C;|DOCUMENTED|DOC_ONLY|;
466.306 - item : TimedRotatingFileHandler;C;|DOCUMENTED|DOC_ONLY|;
466.307 - item : WatchedFileHandler;C;|DOCUMENTED|DOC_ONLY|;
466.308 - item : addLevelName;F;|DOCUMENTED|DOC_ONLY|;lvl,levelName;
466.309 - item : basicConfig;F;|DOCUMENTED|DOC_ONLY|;**kwargs;
466.310 - item : critical;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
466.311 - item : debug;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
466.312 - item : disable;F;|DOCUMENTED|DOC_ONLY|;lvl;
466.313 - item : error;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
466.314 - item : exception;F;|DOCUMENTED|DOC_ONLY|;msg,*args;
466.315 - item : fileConfig;F;|DOCUMENTED|DOC_ONLY|;fname,defaults;
466.316 - item : getLevelName;F;|DOCUMENTED|DOC_ONLY|;lvl;
466.317 - item : getLogger;F;|DOCUMENTED|DOC_ONLY|;name;
466.318 - item : getLoggerClass;F;|DOCUMENTED|DOC_ONLY|;;
466.319 - item : info;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
466.320 - item : listen;F;|DOCUMENTED|DOC_ONLY|;port;
466.321 - item : log;F;|DOCUMENTED|DOC_ONLY|;level,msg,*args,**kwargs;
466.322 - item : makeLogRecord;F;|DOCUMENTED|DOC_ONLY|;attrdict;
466.323 - item : setLoggerClass;F;|DOCUMENTED|DOC_ONLY|;klass;
466.324 - item : shutdown;F;|DOCUMENTED|DOC_ONLY|;;
466.325 - item : stopListening;F;|DOCUMENTED|DOC_ONLY|;;
466.326 - item : warning;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
466.327 - module : logging
466.328 -
466.329 -Not Searchable Keys:
466.330 - modattrs : S
467.1 --- a/python.editor/test/unit/data/testfiles/rst/operator.rst Sun Jan 04 13:11:53 2015 -0600
467.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
467.3 @@ -1,659 +0,0 @@
467.4 -:mod:`operator` --- Standard operators as functions
467.5 -===================================================
467.6 -
467.7 -.. module:: operator
467.8 - :synopsis: Functions corresponding to the standard operators.
467.9 -.. sectionauthor:: Skip Montanaro <skip@automatrix.com>
467.10 -
467.11 -
467.12 -.. testsetup::
467.13 -
467.14 - import operator
467.15 - from operator import itemgetter
467.16 -
467.17 -
467.18 -The :mod:`operator` module exports a set of functions implemented in C
467.19 -corresponding to the intrinsic operators of Python. For example,
467.20 -``operator.add(x, y)`` is equivalent to the expression ``x+y``. The function
467.21 -names are those used for special class methods; variants without leading and
467.22 -trailing ``__`` are also provided for convenience.
467.23 -
467.24 -The functions fall into categories that perform object comparisons, logical
467.25 -operations, mathematical operations, sequence operations, and abstract type
467.26 -tests.
467.27 -
467.28 -The object comparison functions are useful for all objects, and are named after
467.29 -the rich comparison operators they support:
467.30 -
467.31 -
467.32 -.. function:: lt(a, b)
467.33 - le(a, b)
467.34 - eq(a, b)
467.35 - ne(a, b)
467.36 - ge(a, b)
467.37 - gt(a, b)
467.38 - __lt__(a, b)
467.39 - __le__(a, b)
467.40 - __eq__(a, b)
467.41 - __ne__(a, b)
467.42 - __ge__(a, b)
467.43 - __gt__(a, b)
467.44 -
467.45 - Perform "rich comparisons" between *a* and *b*. Specifically, ``lt(a, b)`` is
467.46 - equivalent to ``a < b``, ``le(a, b)`` is equivalent to ``a <= b``, ``eq(a,
467.47 - b)`` is equivalent to ``a == b``, ``ne(a, b)`` is equivalent to ``a != b``,
467.48 - ``gt(a, b)`` is equivalent to ``a > b`` and ``ge(a, b)`` is equivalent to ``a
467.49 - >= b``. Note that unlike the built-in :func:`cmp`, these functions can
467.50 - return any value, which may or may not be interpretable as a Boolean value.
467.51 - See :ref:`comparisons` for more information about rich comparisons.
467.52 -
467.53 - .. versionadded:: 2.2
467.54 -
467.55 -The logical operations are also generally applicable to all objects, and support
467.56 -truth tests, identity tests, and boolean operations:
467.57 -
467.58 -
467.59 -.. function:: not_(obj)
467.60 - __not__(obj)
467.61 -
467.62 - Return the outcome of :keyword:`not` *obj*. (Note that there is no
467.63 - :meth:`__not__` method for object instances; only the interpreter core defines
467.64 - this operation. The result is affected by the :meth:`__nonzero__` and
467.65 - :meth:`__len__` methods.)
467.66 -
467.67 -
467.68 -.. function:: truth(obj)
467.69 -
467.70 - Return :const:`True` if *obj* is true, and :const:`False` otherwise. This is
467.71 - equivalent to using the :class:`bool` constructor.
467.72 -
467.73 -
467.74 -.. function:: is_(a, b)
467.75 -
467.76 - Return ``a is b``. Tests object identity.
467.77 -
467.78 - .. versionadded:: 2.3
467.79 -
467.80 -
467.81 -.. function:: is_not(a, b)
467.82 -
467.83 - Return ``a is not b``. Tests object identity.
467.84 -
467.85 - .. versionadded:: 2.3
467.86 -
467.87 -The mathematical and bitwise operations are the most numerous:
467.88 -
467.89 -
467.90 -.. function:: abs(obj)
467.91 - __abs__(obj)
467.92 -
467.93 - Return the absolute value of *obj*.
467.94 -
467.95 -
467.96 -.. function:: add(a, b)
467.97 - __add__(a, b)
467.98 -
467.99 - Return ``a + b``, for *a* and *b* numbers.
467.100 -
467.101 -
467.102 -.. function:: and_(a, b)
467.103 - __and__(a, b)
467.104 -
467.105 - Return the bitwise and of *a* and *b*.
467.106 -
467.107 -
467.108 -.. function:: div(a, b)
467.109 - __div__(a, b)
467.110 -
467.111 - Return ``a / b`` when ``__future__.division`` is not in effect. This is
467.112 - also known as "classic" division.
467.113 -
467.114 -
467.115 -.. function:: floordiv(a, b)
467.116 - __floordiv__(a, b)
467.117 -
467.118 - Return ``a // b``.
467.119 -
467.120 - .. versionadded:: 2.2
467.121 -
467.122 -
467.123 -.. function:: inv(obj)
467.124 - invert(obj)
467.125 - __inv__(obj)
467.126 - __invert__(obj)
467.127 -
467.128 - Return the bitwise inverse of the number *obj*. This is equivalent to ``~obj``.
467.129 -
467.130 - .. versionadded:: 2.0
467.131 - The names :func:`invert` and :func:`__invert__`.
467.132 -
467.133 -
467.134 -.. function:: lshift(a, b)
467.135 - __lshift__(a, b)
467.136 -
467.137 - Return *a* shifted left by *b*.
467.138 -
467.139 -
467.140 -.. function:: mod(a, b)
467.141 - __mod__(a, b)
467.142 -
467.143 - Return ``a % b``.
467.144 -
467.145 -
467.146 -.. function:: mul(a, b)
467.147 - __mul__(a, b)
467.148 -
467.149 - Return ``a * b``, for *a* and *b* numbers.
467.150 -
467.151 -
467.152 -.. function:: neg(obj)
467.153 - __neg__(obj)
467.154 -
467.155 - Return *obj* negated.
467.156 -
467.157 -
467.158 -.. function:: or_(a, b)
467.159 - __or__(a, b)
467.160 -
467.161 - Return the bitwise or of *a* and *b*.
467.162 -
467.163 -
467.164 -.. function:: pos(obj)
467.165 - __pos__(obj)
467.166 -
467.167 - Return *obj* positive.
467.168 -
467.169 -
467.170 -.. function:: pow(a, b)
467.171 - __pow__(a, b)
467.172 -
467.173 - Return ``a ** b``, for *a* and *b* numbers.
467.174 -
467.175 - .. versionadded:: 2.3
467.176 -
467.177 -
467.178 -.. function:: rshift(a, b)
467.179 - __rshift__(a, b)
467.180 -
467.181 - Return *a* shifted right by *b*.
467.182 -
467.183 -
467.184 -.. function:: sub(a, b)
467.185 - __sub__(a, b)
467.186 -
467.187 - Return ``a - b``.
467.188 -
467.189 -
467.190 -.. function:: truediv(a, b)
467.191 - __truediv__(a, b)
467.192 -
467.193 - Return ``a / b`` when ``__future__.division`` is in effect. This is also
467.194 - known as "true" division.
467.195 -
467.196 - .. versionadded:: 2.2
467.197 -
467.198 -
467.199 -.. function:: xor(a, b)
467.200 - __xor__(a, b)
467.201 -
467.202 - Return the bitwise exclusive or of *a* and *b*.
467.203 -
467.204 -
467.205 -.. function:: index(a)
467.206 - __index__(a)
467.207 -
467.208 - Return *a* converted to an integer. Equivalent to ``a.__index__()``.
467.209 -
467.210 - .. versionadded:: 2.5
467.211 -
467.212 -
467.213 -Operations which work with sequences include:
467.214 -
467.215 -.. function:: concat(a, b)
467.216 - __concat__(a, b)
467.217 -
467.218 - Return ``a + b`` for *a* and *b* sequences.
467.219 -
467.220 -
467.221 -.. function:: contains(a, b)
467.222 - __contains__(a, b)
467.223 -
467.224 - Return the outcome of the test ``b in a``. Note the reversed operands.
467.225 -
467.226 - .. versionadded:: 2.0
467.227 - The name :func:`__contains__`.
467.228 -
467.229 -
467.230 -.. function:: countOf(a, b)
467.231 -
467.232 - Return the number of occurrences of *b* in *a*.
467.233 -
467.234 -
467.235 -.. function:: delitem(a, b)
467.236 - __delitem__(a, b)
467.237 -
467.238 - Remove the value of *a* at index *b*.
467.239 -
467.240 -
467.241 -.. function:: delslice(a, b, c)
467.242 - __delslice__(a, b, c)
467.243 -
467.244 - Delete the slice of *a* from index *b* to index *c-1*.
467.245 -
467.246 -
467.247 -.. function:: getitem(a, b)
467.248 - __getitem__(a, b)
467.249 -
467.250 - Return the value of *a* at index *b*.
467.251 -
467.252 -
467.253 -.. function:: getslice(a, b, c)
467.254 - __getslice__(a, b, c)
467.255 -
467.256 - Return the slice of *a* from index *b* to index *c-1*.
467.257 -
467.258 -
467.259 -.. function:: indexOf(a, b)
467.260 -
467.261 - Return the index of the first of occurrence of *b* in *a*.
467.262 -
467.263 -
467.264 -.. function:: repeat(a, b)
467.265 - __repeat__(a, b)
467.266 -
467.267 - Return ``a * b`` where *a* is a sequence and *b* is an integer.
467.268 -
467.269 -
467.270 -.. function:: sequenceIncludes(...)
467.271 -
467.272 - .. deprecated:: 2.0
467.273 - Use :func:`contains` instead.
467.274 -
467.275 - Alias for :func:`contains`.
467.276 -
467.277 -
467.278 -.. function:: setitem(a, b, c)
467.279 - __setitem__(a, b, c)
467.280 -
467.281 - Set the value of *a* at index *b* to *c*.
467.282 -
467.283 -
467.284 -.. function:: setslice(a, b, c, v)
467.285 - __setslice__(a, b, c, v)
467.286 -
467.287 - Set the slice of *a* from index *b* to index *c-1* to the sequence *v*.
467.288 -
467.289 -Many operations have an "in-place" version. The following functions provide a
467.290 -more primitive access to in-place operators than the usual syntax does; for
467.291 -example, the :term:`statement` ``x += y`` is equivalent to
467.292 -``x = operator.iadd(x, y)``. Another way to put it is to say that
467.293 -``z = operator.iadd(x, y)`` is equivalent to the compound statement
467.294 -``z = x; z += y``.
467.295 -
467.296 -.. function:: iadd(a, b)
467.297 - __iadd__(a, b)
467.298 -
467.299 - ``a = iadd(a, b)`` is equivalent to ``a += b``.
467.300 -
467.301 - .. versionadded:: 2.5
467.302 -
467.303 -
467.304 -.. function:: iand(a, b)
467.305 - __iand__(a, b)
467.306 -
467.307 - ``a = iand(a, b)`` is equivalent to ``a &= b``.
467.308 -
467.309 - .. versionadded:: 2.5
467.310 -
467.311 -
467.312 -.. function:: iconcat(a, b)
467.313 - __iconcat__(a, b)
467.314 -
467.315 - ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
467.316 -
467.317 - .. versionadded:: 2.5
467.318 -
467.319 -
467.320 -.. function:: idiv(a, b)
467.321 - __idiv__(a, b)
467.322 -
467.323 - ``a = idiv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division`` is
467.324 - not in effect.
467.325 -
467.326 - .. versionadded:: 2.5
467.327 -
467.328 -
467.329 -.. function:: ifloordiv(a, b)
467.330 - __ifloordiv__(a, b)
467.331 -
467.332 - ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
467.333 -
467.334 - .. versionadded:: 2.5
467.335 -
467.336 -
467.337 -.. function:: ilshift(a, b)
467.338 - __ilshift__(a, b)
467.339 -
467.340 - ``a = ilshift(a, b)`` is equivalent to ``a <``\ ``<= b``.
467.341 -
467.342 - .. versionadded:: 2.5
467.343 -
467.344 -
467.345 -.. function:: imod(a, b)
467.346 - __imod__(a, b)
467.347 -
467.348 - ``a = imod(a, b)`` is equivalent to ``a %= b``.
467.349 -
467.350 - .. versionadded:: 2.5
467.351 -
467.352 -
467.353 -.. function:: imul(a, b)
467.354 - __imul__(a, b)
467.355 -
467.356 - ``a = imul(a, b)`` is equivalent to ``a *= b``.
467.357 -
467.358 - .. versionadded:: 2.5
467.359 -
467.360 -
467.361 -.. function:: ior(a, b)
467.362 - __ior__(a, b)
467.363 -
467.364 - ``a = ior(a, b)`` is equivalent to ``a |= b``.
467.365 -
467.366 - .. versionadded:: 2.5
467.367 -
467.368 -
467.369 -.. function:: ipow(a, b)
467.370 - __ipow__(a, b)
467.371 -
467.372 - ``a = ipow(a, b)`` is equivalent to ``a **= b``.
467.373 -
467.374 - .. versionadded:: 2.5
467.375 -
467.376 -
467.377 -.. function:: irepeat(a, b)
467.378 - __irepeat__(a, b)
467.379 -
467.380 - ``a = irepeat(a, b)`` is equivalent to ``a *= b`` where *a* is a sequence and
467.381 - *b* is an integer.
467.382 -
467.383 - .. versionadded:: 2.5
467.384 -
467.385 -
467.386 -.. function:: irshift(a, b)
467.387 - __irshift__(a, b)
467.388 -
467.389 - ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
467.390 -
467.391 - .. versionadded:: 2.5
467.392 -
467.393 -
467.394 -.. function:: isub(a, b)
467.395 - __isub__(a, b)
467.396 -
467.397 - ``a = isub(a, b)`` is equivalent to ``a -= b``.
467.398 -
467.399 - .. versionadded:: 2.5
467.400 -
467.401 -
467.402 -.. function:: itruediv(a, b)
467.403 - __itruediv__(a, b)
467.404 -
467.405 - ``a = itruediv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division``
467.406 - is in effect.
467.407 -
467.408 - .. versionadded:: 2.5
467.409 -
467.410 -
467.411 -.. function:: ixor(a, b)
467.412 - __ixor__(a, b)
467.413 -
467.414 - ``a = ixor(a, b)`` is equivalent to ``a ^= b``.
467.415 -
467.416 - .. versionadded:: 2.5
467.417 -
467.418 -
467.419 -The :mod:`operator` module also defines a few predicates to test the type of
467.420 -objects.
467.421 -
467.422 -.. note::
467.423 -
467.424 - Be careful not to misinterpret the results of these functions; only
467.425 - :func:`isCallable` has any measure of reliability with instance objects.
467.426 - For example:
467.427 -
467.428 - >>> class C:
467.429 - ... pass
467.430 - ...
467.431 - >>> import operator
467.432 - >>> obj = C()
467.433 - >>> operator.isMappingType(obj)
467.434 - True
467.435 -
467.436 -.. note::
467.437 -
467.438 - Python 3 is expected to introduce abstract base classes for
467.439 - collection types, so it should be possible to write, for example,
467.440 - ``isinstance(obj, collections.Mapping)`` and ``isinstance(obj,
467.441 - collections.Sequence)``.
467.442 -
467.443 -.. function:: isCallable(obj)
467.444 -
467.445 - .. deprecated:: 2.0
467.446 - Use the :func:`callable` built-in function instead.
467.447 -
467.448 - Returns true if the object *obj* can be called like a function, otherwise it
467.449 - returns false. True is returned for functions, bound and unbound methods, class
467.450 - objects, and instance objects which support the :meth:`__call__` method.
467.451 -
467.452 -
467.453 -.. function:: isMappingType(obj)
467.454 -
467.455 - Returns true if the object *obj* supports the mapping interface. This is true for
467.456 - dictionaries and all instance objects defining :meth:`__getitem__`.
467.457 -
467.458 - .. warning::
467.459 -
467.460 - There is no reliable way to test if an instance supports the complete mapping
467.461 - protocol since the interface itself is ill-defined. This makes this test less
467.462 - useful than it otherwise might be.
467.463 -
467.464 -
467.465 -.. function:: isNumberType(obj)
467.466 -
467.467 - Returns true if the object *obj* represents a number. This is true for all
467.468 - numeric types implemented in C.
467.469 -
467.470 - .. warning::
467.471 -
467.472 - There is no reliable way to test if an instance supports the complete numeric
467.473 - interface since the interface itself is ill-defined. This makes this test less
467.474 - useful than it otherwise might be.
467.475 -
467.476 -
467.477 -.. function:: isSequenceType(obj)
467.478 -
467.479 - Returns true if the object *obj* supports the sequence protocol. This returns true
467.480 - for all objects which define sequence methods in C, and for all instance objects
467.481 - defining :meth:`__getitem__`.
467.482 -
467.483 - .. warning::
467.484 -
467.485 - There is no reliable way to test if an instance supports the complete sequence
467.486 - interface since the interface itself is ill-defined. This makes this test less
467.487 - useful than it otherwise might be.
467.488 -
467.489 -Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to
467.490 -their character equivalents.
467.491 -
467.492 - >>> d = {}
467.493 - >>> keys = range(256)
467.494 - >>> vals = map(chr, keys)
467.495 - >>> map(operator.setitem, [d]*len(keys), keys, vals) # doctest: +SKIP
467.496 -
467.497 -.. XXX: find a better, readable, example
467.498 -
467.499 -The :mod:`operator` module also defines tools for generalized attribute and item
467.500 -lookups. These are useful for making fast field extractors as arguments for
467.501 -:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
467.502 -expect a function argument.
467.503 -
467.504 -
467.505 -.. function:: attrgetter(attr[, args...])
467.506 -
467.507 - Return a callable object that fetches *attr* from its operand. If more than one
467.508 - attribute is requested, returns a tuple of attributes. After,
467.509 - ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
467.510 - ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
467.511 - b.date)``.
467.512 -
467.513 - The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
467.514 - the call ``f(b)`` returns ``b.date.month``.
467.515 -
467.516 - .. versionadded:: 2.4
467.517 -
467.518 - .. versionchanged:: 2.5
467.519 - Added support for multiple attributes.
467.520 -
467.521 - .. versionchanged:: 2.6
467.522 - Added support for dotted attributes.
467.523 -
467.524 -
467.525 -.. function:: itemgetter(item[, args...])
467.526 -
467.527 - Return a callable object that fetches *item* from its operand using the
467.528 - operand's :meth:`__getitem__` method. If multiple items are specified,
467.529 - returns a tuple of lookup values. Equivalent to::
467.530 -
467.531 - def itemgetter(*items):
467.532 - if len(items) == 1:
467.533 - item = items[0]
467.534 - def g(obj):
467.535 - return obj[item]
467.536 - else:
467.537 - def g(obj):
467.538 - return tuple(obj[item] for item in items)
467.539 - return g
467.540 -
467.541 - The items can be any type accepted by the operand's :meth:`__getitem__`
467.542 - method. Dictionaries accept any hashable value. Lists, tuples, and
467.543 - strings accept an index or a slice:
467.544 -
467.545 - >>> itemgetter(1)('ABCDEFG')
467.546 - 'B'
467.547 - >>> itemgetter(1,3,5)('ABCDEFG')
467.548 - ('B', 'D', 'F')
467.549 - >>> itemgetter(slice(2,None))('ABCDEFG')
467.550 - 'CDEFG'
467.551 -
467.552 - .. versionadded:: 2.4
467.553 -
467.554 - .. versionchanged:: 2.5
467.555 - Added support for multiple item extraction.
467.556 -
467.557 - Example of using :func:`itemgetter` to retrieve specific fields from a
467.558 - tuple record:
467.559 -
467.560 - >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
467.561 - >>> getcount = itemgetter(1)
467.562 - >>> map(getcount, inventory)
467.563 - [3, 2, 5, 1]
467.564 - >>> sorted(inventory, key=getcount)
467.565 - [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
467.566 -
467.567 -
467.568 -.. function:: methodcaller(name[, args...])
467.569 -
467.570 - Return a callable object that calls the method *name* on its operand. If
467.571 - additional arguments and/or keyword arguments are given, they will be given
467.572 - to the method as well. After ``f = methodcaller('name')``, the call ``f(b)``
467.573 - returns ``b.name()``. After ``f = methodcaller('name', 'foo', bar=1)``, the
467.574 - call ``f(b)`` returns ``b.name('foo', bar=1)``.
467.575 -
467.576 - .. versionadded:: 2.6
467.577 -
467.578 -
467.579 -.. _operator-map:
467.580 -
467.581 -Mapping Operators to Functions
467.582 -------------------------------
467.583 -
467.584 -This table shows how abstract operations correspond to operator symbols in the
467.585 -Python syntax and the functions in the :mod:`operator` module.
467.586 -
467.587 -+-----------------------+-------------------------+---------------------------------+
467.588 -| Operation | Syntax | Function |
467.589 -+=======================+=========================+=================================+
467.590 -| Addition | ``a + b`` | ``add(a, b)`` |
467.591 -+-----------------------+-------------------------+---------------------------------+
467.592 -| Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
467.593 -+-----------------------+-------------------------+---------------------------------+
467.594 -| Containment Test | ``obj in seq`` | ``contains(seq, obj)`` |
467.595 -+-----------------------+-------------------------+---------------------------------+
467.596 -| Division | ``a / b`` | ``div(a, b)`` (without |
467.597 -| | | ``__future__.division``) |
467.598 -+-----------------------+-------------------------+---------------------------------+
467.599 -| Division | ``a / b`` | ``truediv(a, b)`` (with |
467.600 -| | | ``__future__.division``) |
467.601 -+-----------------------+-------------------------+---------------------------------+
467.602 -| Division | ``a // b`` | ``floordiv(a, b)`` |
467.603 -+-----------------------+-------------------------+---------------------------------+
467.604 -| Bitwise And | ``a & b`` | ``and_(a, b)`` |
467.605 -+-----------------------+-------------------------+---------------------------------+
467.606 -| Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
467.607 -+-----------------------+-------------------------+---------------------------------+
467.608 -| Bitwise Inversion | ``~ a`` | ``invert(a)`` |
467.609 -+-----------------------+-------------------------+---------------------------------+
467.610 -| Bitwise Or | ``a | b`` | ``or_(a, b)`` |
467.611 -+-----------------------+-------------------------+---------------------------------+
467.612 -| Exponentiation | ``a ** b`` | ``pow(a, b)`` |
467.613 -+-----------------------+-------------------------+---------------------------------+
467.614 -| Identity | ``a is b`` | ``is_(a, b)`` |
467.615 -+-----------------------+-------------------------+---------------------------------+
467.616 -| Identity | ``a is not b`` | ``is_not(a, b)`` |
467.617 -+-----------------------+-------------------------+---------------------------------+
467.618 -| Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
467.619 -+-----------------------+-------------------------+---------------------------------+
467.620 -| Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
467.621 -+-----------------------+-------------------------+---------------------------------+
467.622 -| Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
467.623 -+-----------------------+-------------------------+---------------------------------+
467.624 -| Left Shift | ``a << b`` | ``lshift(a, b)`` |
467.625 -+-----------------------+-------------------------+---------------------------------+
467.626 -| Modulo | ``a % b`` | ``mod(a, b)`` |
467.627 -+-----------------------+-------------------------+---------------------------------+
467.628 -| Multiplication | ``a * b`` | ``mul(a, b)`` |
467.629 -+-----------------------+-------------------------+---------------------------------+
467.630 -| Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
467.631 -+-----------------------+-------------------------+---------------------------------+
467.632 -| Negation (Logical) | ``not a`` | ``not_(a)`` |
467.633 -+-----------------------+-------------------------+---------------------------------+
467.634 -| Right Shift | ``a >> b`` | ``rshift(a, b)`` |
467.635 -+-----------------------+-------------------------+---------------------------------+
467.636 -| Sequence Repetition | ``seq * i`` | ``repeat(seq, i)`` |
467.637 -+-----------------------+-------------------------+---------------------------------+
467.638 -| Slice Assignment | ``seq[i:j] = values`` | ``setslice(seq, i, j, values)`` |
467.639 -+-----------------------+-------------------------+---------------------------------+
467.640 -| Slice Deletion | ``del seq[i:j]`` | ``delslice(seq, i, j)`` |
467.641 -+-----------------------+-------------------------+---------------------------------+
467.642 -| Slicing | ``seq[i:j]`` | ``getslice(seq, i, j)`` |
467.643 -+-----------------------+-------------------------+---------------------------------+
467.644 -| String Formatting | ``s % obj`` | ``mod(s, obj)`` |
467.645 -+-----------------------+-------------------------+---------------------------------+
467.646 -| Subtraction | ``a - b`` | ``sub(a, b)`` |
467.647 -+-----------------------+-------------------------+---------------------------------+
467.648 -| Truth Test | ``obj`` | ``truth(obj)`` |
467.649 -+-----------------------+-------------------------+---------------------------------+
467.650 -| Ordering | ``a < b`` | ``lt(a, b)`` |
467.651 -+-----------------------+-------------------------+---------------------------------+
467.652 -| Ordering | ``a <= b`` | ``le(a, b)`` |
467.653 -+-----------------------+-------------------------+---------------------------------+
467.654 -| Equality | ``a == b`` | ``eq(a, b)`` |
467.655 -+-----------------------+-------------------------+---------------------------------+
467.656 -| Difference | ``a != b`` | ``ne(a, b)`` |
467.657 -+-----------------------+-------------------------+---------------------------------+
467.658 -| Ordering | ``a >= b`` | ``ge(a, b)`` |
467.659 -+-----------------------+-------------------------+---------------------------------+
467.660 -| Ordering | ``a > b`` | ``gt(a, b)`` |
467.661 -+-----------------------+-------------------------+---------------------------------+
467.662 -
468.1 --- a/python.editor/test/unit/data/testfiles/rst/operator.rst.indexed Sun Jan 04 13:11:53 2015 -0600
468.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
468.3 @@ -1,365 +0,0 @@
468.4 -
468.5 -
468.6 -Document 0
468.7 -Searchable Keys:
468.8 - class : bool
468.9 - class-ig : bool
468.10 - in : operator
468.11 - member : __abs__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.12 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.13 - member : __and__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.14 - member : __div__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.15 - member : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.16 - member : __index__;F;|DOCUMENTED|DOC_ONLY|;a;
468.17 - member : __invert__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.18 - member : __lshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.19 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.20 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.21 - member : __neg__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.22 - member : __or__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.23 - member : __pos__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.24 - member : __pow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.25 - member : __rshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.26 - member : __sub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.27 - member : __truediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.28 - member : __xor__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.29 -
468.30 -Not Searchable Keys:
468.31 -
468.32 -
468.33 -Document 1
468.34 -Searchable Keys:
468.35 - class : complex
468.36 - class-ig : complex
468.37 - in : operator
468.38 - member : __abs__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.39 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.40 - member : __div__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.41 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.42 - member : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.43 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.44 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.45 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.46 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.47 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.48 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.49 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.50 - member : __neg__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.51 - member : __pos__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.52 - member : __pow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.53 - member : __sub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.54 - member : __truediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.55 -
468.56 -Not Searchable Keys:
468.57 -
468.58 -
468.59 -Document 2
468.60 -Searchable Keys:
468.61 - class : dict
468.62 - class-ig : dict
468.63 - in : operator
468.64 - member : __contains__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.65 - member : __delitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.66 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.67 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.68 - member : __getitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.69 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.70 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.71 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.72 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.73 - member : __setitem__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
468.74 -
468.75 -Not Searchable Keys:
468.76 -
468.77 -
468.78 -Document 3
468.79 -Searchable Keys:
468.80 - class : float
468.81 - class-ig : float
468.82 - in : operator
468.83 - member : __abs__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.84 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.85 - member : __div__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.86 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.87 - member : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.88 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.89 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.90 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.91 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.92 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.93 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.94 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.95 - member : __neg__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.96 - member : __pos__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.97 - member : __pow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.98 - member : __sub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.99 - member : __truediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.100 -
468.101 -Not Searchable Keys:
468.102 -
468.103 -
468.104 -Document 4
468.105 -Searchable Keys:
468.106 - class : int
468.107 - class-ig : int
468.108 - in : operator
468.109 - member : __abs__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.110 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.111 - member : __and__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.112 - member : __div__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.113 - member : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.114 - member : __index__;F;|DOCUMENTED|DOC_ONLY|;a;
468.115 - member : __invert__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.116 - member : __lshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.117 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.118 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.119 - member : __neg__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.120 - member : __or__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.121 - member : __pos__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.122 - member : __pow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.123 - member : __rshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.124 - member : __sub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.125 - member : __truediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.126 - member : __xor__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.127 -
468.128 -Not Searchable Keys:
468.129 -
468.130 -
468.131 -Document 5
468.132 -Searchable Keys:
468.133 - class : list
468.134 - class-ig : list
468.135 - in : operator
468.136 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.137 - member : __contains__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.138 - member : __delitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.139 - member : __delslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
468.140 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.141 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.142 - member : __getitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.143 - member : __getslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
468.144 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.145 - member : __iadd__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.146 - member : __imul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.147 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.148 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.149 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.150 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.151 - member : __setitem__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
468.152 - member : __setslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c,v;
468.153 - member : index;F;|DOCUMENTED|DOC_ONLY|;a;
468.154 -
468.155 -Not Searchable Keys:
468.156 -
468.157 -
468.158 -Document 6
468.159 -Searchable Keys:
468.160 - class : long
468.161 - class-ig : long
468.162 - in : operator
468.163 - member : __abs__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.164 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.165 - member : __and__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.166 - member : __div__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.167 - member : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.168 - member : __index__;F;|DOCUMENTED|DOC_ONLY|;a;
468.169 - member : __invert__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.170 - member : __lshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.171 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.172 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.173 - member : __neg__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.174 - member : __or__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.175 - member : __pos__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.176 - member : __pow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.177 - member : __rshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.178 - member : __sub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.179 - member : __truediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.180 - member : __xor__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.181 -
468.182 -Not Searchable Keys:
468.183 -
468.184 -
468.185 -Document 7
468.186 -Searchable Keys:
468.187 - class : str
468.188 - class-ig : str
468.189 - in : operator
468.190 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.191 - member : __contains__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.192 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.193 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.194 - member : __getitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.195 - member : __getslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
468.196 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.197 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.198 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.199 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.200 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.201 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.202 - member : index;F;|DOCUMENTED|DOC_ONLY|;a;
468.203 -
468.204 -Not Searchable Keys:
468.205 -
468.206 -
468.207 -Document 8
468.208 -Searchable Keys:
468.209 - class : tuple
468.210 - class-ig : tuple
468.211 - in : operator
468.212 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.213 - member : __contains__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.214 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.215 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.216 - member : __getitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.217 - member : __getslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
468.218 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.219 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.220 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.221 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.222 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.223 - member : index;F;|DOCUMENTED|DOC_ONLY|;a;
468.224 -
468.225 -Not Searchable Keys:
468.226 -
468.227 -
468.228 -Document 9
468.229 -Searchable Keys:
468.230 - class : unicode
468.231 - class-ig : unicode
468.232 - in : operator
468.233 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.234 - member : __contains__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.235 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.236 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.237 - member : __getitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.238 - member : __getslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
468.239 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.240 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.241 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.242 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.243 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.244 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.245 - member : index;F;|DOCUMENTED|DOC_ONLY|;a;
468.246 -
468.247 -Not Searchable Keys:
468.248 -
468.249 -
468.250 -Document 10
468.251 -Searchable Keys:
468.252 - item : __abs__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.253 - item : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.254 - item : __and__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.255 - item : __concat__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.256 - item : __contains__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.257 - item : __delitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.258 - item : __delslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
468.259 - item : __div__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.260 - item : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.261 - item : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.262 - item : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.263 - item : __getitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.264 - item : __getslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
468.265 - item : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.266 - item : __iadd__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.267 - item : __iand__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.268 - item : __iconcat__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.269 - item : __idiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.270 - item : __ifloordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.271 - item : __ilshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.272 - item : __imod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.273 - item : __imul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.274 - item : __index__;F;|DOCUMENTED|DOC_ONLY|;a;
468.275 - item : __inv__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.276 - item : __invert__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.277 - item : __ior__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.278 - item : __ipow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.279 - item : __irepeat__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.280 - item : __irshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.281 - item : __isub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.282 - item : __itruediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.283 - item : __ixor__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.284 - item : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.285 - item : __lshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.286 - item : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.287 - item : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.288 - item : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.289 - item : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.290 - item : __neg__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.291 - item : __not__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.292 - item : __or__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.293 - item : __pos__;F;|DOCUMENTED|DOC_ONLY|;obj;
468.294 - item : __pow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.295 - item : __repeat__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.296 - item : __rshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.297 - item : __setitem__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
468.298 - item : __setslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c,v;
468.299 - item : __sub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.300 - item : __truediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.301 - item : __xor__;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.302 - item : abs;F;|DOCUMENTED|DOC_ONLY|;obj;
468.303 - item : add;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.304 - item : and_;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.305 - item : attrgetter;F;|DOCUMENTED|DOC_ONLY|;attr,args;
468.306 - item : concat;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.307 - item : contains;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.308 - item : countOf;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.309 - item : delitem;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.310 - item : delslice;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
468.311 - item : div;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.312 - item : eq;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.313 - item : floordiv;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.314 - item : ge;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.315 - item : getitem;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.316 - item : getslice;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
468.317 - item : gt;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.318 - item : iadd;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.319 - item : iand;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.320 - item : iconcat;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.321 - item : idiv;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.322 - item : ifloordiv;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.323 - item : ilshift;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.324 - item : imod;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.325 - item : imul;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.326 - item : index;F;|DOCUMENTED|DOC_ONLY|;a;
468.327 - item : indexOf;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.328 - item : inv;F;|DOCUMENTED|DOC_ONLY|;obj;
468.329 - item : invert;F;|DOCUMENTED|DOC_ONLY|;obj;
468.330 - item : ior;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.331 - item : ipow;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.332 - item : irepeat;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.333 - item : irshift;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.334 - item : isCallable;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;obj;
468.335 - item : isMappingType;F;|DOCUMENTED|DOC_ONLY|;obj;
468.336 - item : isNumberType;F;|DOCUMENTED|DOC_ONLY|;obj;
468.337 - item : isSequenceType;F;|DOCUMENTED|DOC_ONLY|;obj;
468.338 - item : is_;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.339 - item : is_not;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.340 - item : isub;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.341 - item : itemgetter;F;|DOCUMENTED|DOC_ONLY|;item,args;
468.342 - item : itruediv;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.343 - item : ixor;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.344 - item : le;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.345 - item : lshift;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.346 - item : lt;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.347 - item : methodcaller;F;|DOCUMENTED|DOC_ONLY|;name,args;
468.348 - item : mod;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.349 - item : mul;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.350 - item : ne;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.351 - item : neg;F;|DOCUMENTED|DOC_ONLY|;obj;
468.352 - item : not_;F;|DOCUMENTED|DOC_ONLY|;obj;
468.353 - item : or_;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.354 - item : pos;F;|DOCUMENTED|DOC_ONLY|;obj;
468.355 - item : pow;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.356 - item : repeat;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.357 - item : rshift;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.358 - item : sequenceIncludes;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;;
468.359 - item : setitem;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
468.360 - item : setslice;F;|DOCUMENTED|DOC_ONLY|;a,b,c,v;
468.361 - item : sub;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.362 - item : truediv;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.363 - item : truth;F;|DOCUMENTED|DOC_ONLY|;obj;
468.364 - item : xor;F;|DOCUMENTED|DOC_ONLY|;a,b;
468.365 - module : operator
468.366 -
468.367 -Not Searchable Keys:
468.368 - modattrs : S
469.1 --- a/python.editor/test/unit/data/testfiles/rst/operator.rst.testGetDoc5.html Sun Jan 04 13:11:53 2015 -0600
469.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
469.3 @@ -1,7 +0,0 @@
469.4 -<html><body><pre><b>delitem</b><font color="#808080">(a, b)</font></pre>
469.5 -<hr>
469.6 - __delitem__(a, b)
469.7 -
469.8 -<br><br>
469.9 - Remove the value of <b>a</b> at index <b>b</b>.
469.10 -</body></html>
470.1 --- a/python.editor/test/unit/data/testfiles/rst/pickle.rst Sun Jan 04 13:11:53 2015 -0600
470.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
470.3 @@ -1,879 +0,0 @@
470.4 -:mod:`pickle` --- Python object serialization
470.5 -=============================================
470.6 -
470.7 -.. index::
470.8 - single: persistence
470.9 - pair: persistent; objects
470.10 - pair: serializing; objects
470.11 - pair: marshalling; objects
470.12 - pair: flattening; objects
470.13 - pair: pickling; objects
470.14 -
470.15 -.. module:: pickle
470.16 - :synopsis: Convert Python objects to streams of bytes and back.
470.17 -.. sectionauthor:: Jim Kerr <jbkerr@sr.hp.com>.
470.18 -.. sectionauthor:: Barry Warsaw <barry@zope.com>
470.19 -
470.20 -The :mod:`pickle` module implements a fundamental, but powerful algorithm for
470.21 -serializing and de-serializing a Python object structure. "Pickling" is the
470.22 -process whereby a Python object hierarchy is converted into a byte stream, and
470.23 -"unpickling" is the inverse operation, whereby a byte stream is converted back
470.24 -into an object hierarchy. Pickling (and unpickling) is alternatively known as
470.25 -"serialization", "marshalling," [#]_ or "flattening", however, to avoid
470.26 -confusion, the terms used here are "pickling" and "unpickling".
470.27 -
470.28 -This documentation describes both the :mod:`pickle` module and the
470.29 -:mod:`cPickle` module.
470.30 -
470.31 -
470.32 -Relationship to other Python modules
470.33 -------------------------------------
470.34 -
470.35 -The :mod:`pickle` module has an optimized cousin called the :mod:`cPickle`
470.36 -module. As its name implies, :mod:`cPickle` is written in C, so it can be up to
470.37 -1000 times faster than :mod:`pickle`. However it does not support subclassing
470.38 -of the :func:`Pickler` and :func:`Unpickler` classes, because in :mod:`cPickle`
470.39 -these are functions, not classes. Most applications have no need for this
470.40 -functionality, and can benefit from the improved performance of :mod:`cPickle`.
470.41 -Other than that, the interfaces of the two modules are nearly identical; the
470.42 -common interface is described in this manual and differences are pointed out
470.43 -where necessary. In the following discussions, we use the term "pickle" to
470.44 -collectively describe the :mod:`pickle` and :mod:`cPickle` modules.
470.45 -
470.46 -The data streams the two modules produce are guaranteed to be interchangeable.
470.47 -
470.48 -Python has a more primitive serialization module called :mod:`marshal`, but in
470.49 -general :mod:`pickle` should always be the preferred way to serialize Python
470.50 -objects. :mod:`marshal` exists primarily to support Python's :file:`.pyc`
470.51 -files.
470.52 -
470.53 -The :mod:`pickle` module differs from :mod:`marshal` several significant ways:
470.54 -
470.55 -* The :mod:`pickle` module keeps track of the objects it has already serialized,
470.56 - so that later references to the same object won't be serialized again.
470.57 - :mod:`marshal` doesn't do this.
470.58 -
470.59 - This has implications both for recursive objects and object sharing. Recursive
470.60 - objects are objects that contain references to themselves. These are not
470.61 - handled by marshal, and in fact, attempting to marshal recursive objects will
470.62 - crash your Python interpreter. Object sharing happens when there are multiple
470.63 - references to the same object in different places in the object hierarchy being
470.64 - serialized. :mod:`pickle` stores such objects only once, and ensures that all
470.65 - other references point to the master copy. Shared objects remain shared, which
470.66 - can be very important for mutable objects.
470.67 -
470.68 -* :mod:`marshal` cannot be used to serialize user-defined classes and their
470.69 - instances. :mod:`pickle` can save and restore class instances transparently,
470.70 - however the class definition must be importable and live in the same module as
470.71 - when the object was stored.
470.72 -
470.73 -* The :mod:`marshal` serialization format is not guaranteed to be portable
470.74 - across Python versions. Because its primary job in life is to support
470.75 - :file:`.pyc` files, the Python implementers reserve the right to change the
470.76 - serialization format in non-backwards compatible ways should the need arise.
470.77 - The :mod:`pickle` serialization format is guaranteed to be backwards compatible
470.78 - across Python releases.
470.79 -
470.80 -.. warning::
470.81 -
470.82 - The :mod:`pickle` module is not intended to be secure against erroneous or
470.83 - maliciously constructed data. Never unpickle data received from an untrusted or
470.84 - unauthenticated source.
470.85 -
470.86 -Note that serialization is a more primitive notion than persistence; although
470.87 -:mod:`pickle` reads and writes file objects, it does not handle the issue of
470.88 -naming persistent objects, nor the (even more complicated) issue of concurrent
470.89 -access to persistent objects. The :mod:`pickle` module can transform a complex
470.90 -object into a byte stream and it can transform the byte stream into an object
470.91 -with the same internal structure. Perhaps the most obvious thing to do with
470.92 -these byte streams is to write them onto a file, but it is also conceivable to
470.93 -send them across a network or store them in a database. The module
470.94 -:mod:`shelve` provides a simple interface to pickle and unpickle objects on
470.95 -DBM-style database files.
470.96 -
470.97 -
470.98 -Data stream format
470.99 -------------------
470.100 -
470.101 -.. index::
470.102 - single: XDR
470.103 - single: External Data Representation
470.104 -
470.105 -The data format used by :mod:`pickle` is Python-specific. This has the
470.106 -advantage that there are no restrictions imposed by external standards such as
470.107 -XDR (which can't represent pointer sharing); however it means that non-Python
470.108 -programs may not be able to reconstruct pickled Python objects.
470.109 -
470.110 -By default, the :mod:`pickle` data format uses a printable ASCII representation.
470.111 -This is slightly more voluminous than a binary representation. The big
470.112 -advantage of using printable ASCII (and of some other characteristics of
470.113 -:mod:`pickle`'s representation) is that for debugging or recovery purposes it is
470.114 -possible for a human to read the pickled file with a standard text editor.
470.115 -
470.116 -There are currently 3 different protocols which can be used for pickling.
470.117 -
470.118 -* Protocol version 0 is the original ASCII protocol and is backwards compatible
470.119 - with earlier versions of Python.
470.120 -
470.121 -* Protocol version 1 is the old binary format which is also compatible with
470.122 - earlier versions of Python.
470.123 -
470.124 -* Protocol version 2 was introduced in Python 2.3. It provides much more
470.125 - efficient pickling of :term:`new-style class`\es.
470.126 -
470.127 -Refer to :pep:`307` for more information.
470.128 -
470.129 -If a *protocol* is not specified, protocol 0 is used. If *protocol* is specified
470.130 -as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version
470.131 -available will be used.
470.132 -
470.133 -.. versionchanged:: 2.3
470.134 - Introduced the *protocol* parameter.
470.135 -
470.136 -A binary format, which is slightly more efficient, can be chosen by specifying a
470.137 -*protocol* version >= 1.
470.138 -
470.139 -
470.140 -Usage
470.141 ------
470.142 -
470.143 -To serialize an object hierarchy, you first create a pickler, then you call the
470.144 -pickler's :meth:`dump` method. To de-serialize a data stream, you first create
470.145 -an unpickler, then you call the unpickler's :meth:`load` method. The
470.146 -:mod:`pickle` module provides the following constant:
470.147 -
470.148 -
470.149 -.. data:: HIGHEST_PROTOCOL
470.150 -
470.151 - The highest protocol version available. This value can be passed as a
470.152 - *protocol* value.
470.153 -
470.154 - .. versionadded:: 2.3
470.155 -
470.156 -.. note::
470.157 -
470.158 - Be sure to always open pickle files created with protocols >= 1 in binary mode.
470.159 - For the old ASCII-based pickle protocol 0 you can use either text mode or binary
470.160 - mode as long as you stay consistent.
470.161 -
470.162 - A pickle file written with protocol 0 in binary mode will contain lone linefeeds
470.163 - as line terminators and therefore will look "funny" when viewed in Notepad or
470.164 - other editors which do not support this format.
470.165 -
470.166 -The :mod:`pickle` module provides the following functions to make the pickling
470.167 -process more convenient:
470.168 -
470.169 -
470.170 -.. function:: dump(obj, file[, protocol])
470.171 -
470.172 - Write a pickled representation of *obj* to the open file object *file*. This is
470.173 - equivalent to ``Pickler(file, protocol).dump(obj)``.
470.174 -
470.175 - If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is
470.176 - specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol
470.177 - version will be used.
470.178 -
470.179 - .. versionchanged:: 2.3
470.180 - Introduced the *protocol* parameter.
470.181 -
470.182 - *file* must have a :meth:`write` method that accepts a single string argument.
470.183 - It can thus be a file object opened for writing, a :mod:`StringIO` object, or
470.184 - any other custom object that meets this interface.
470.185 -
470.186 -
470.187 -.. function:: load(file)
470.188 -
470.189 - Read a string from the open file object *file* and interpret it as a pickle data
470.190 - stream, reconstructing and returning the original object hierarchy. This is
470.191 - equivalent to ``Unpickler(file).load()``.
470.192 -
470.193 - *file* must have two methods, a :meth:`read` method that takes an integer
470.194 - argument, and a :meth:`readline` method that requires no arguments. Both
470.195 - methods should return a string. Thus *file* can be a file object opened for
470.196 - reading, a :mod:`StringIO` object, or any other custom object that meets this
470.197 - interface.
470.198 -
470.199 - This function automatically determines whether the data stream was written in
470.200 - binary mode or not.
470.201 -
470.202 -
470.203 -.. function:: dumps(obj[, protocol])
470.204 -
470.205 - Return the pickled representation of the object as a string, instead of writing
470.206 - it to a file.
470.207 -
470.208 - If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is
470.209 - specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol
470.210 - version will be used.
470.211 -
470.212 - .. versionchanged:: 2.3
470.213 - The *protocol* parameter was added.
470.214 -
470.215 -
470.216 -.. function:: loads(string)
470.217 -
470.218 - Read a pickled object hierarchy from a string. Characters in the string past
470.219 - the pickled object's representation are ignored.
470.220 -
470.221 -The :mod:`pickle` module also defines three exceptions:
470.222 -
470.223 -
470.224 -.. exception:: PickleError
470.225 -
470.226 - A common base class for the other exceptions defined below. This inherits from
470.227 - :exc:`Exception`.
470.228 -
470.229 -
470.230 -.. exception:: PicklingError
470.231 -
470.232 - This exception is raised when an unpicklable object is passed to the
470.233 - :meth:`dump` method.
470.234 -
470.235 -
470.236 -.. exception:: UnpicklingError
470.237 -
470.238 - This exception is raised when there is a problem unpickling an object. Note that
470.239 - other exceptions may also be raised during unpickling, including (but not
470.240 - necessarily limited to) :exc:`AttributeError`, :exc:`EOFError`,
470.241 - :exc:`ImportError`, and :exc:`IndexError`.
470.242 -
470.243 -The :mod:`pickle` module also exports two callables [#]_, :class:`Pickler` and
470.244 -:class:`Unpickler`:
470.245 -
470.246 -
470.247 -.. class:: Pickler(file[, protocol])
470.248 -
470.249 - This takes a file-like object to which it will write a pickle data stream.
470.250 -
470.251 - If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is
470.252 - specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest
470.253 - protocol version will be used.
470.254 -
470.255 - .. versionchanged:: 2.3
470.256 - Introduced the *protocol* parameter.
470.257 -
470.258 - *file* must have a :meth:`write` method that accepts a single string argument.
470.259 - It can thus be an open file object, a :mod:`StringIO` object, or any other
470.260 - custom object that meets this interface.
470.261 -
470.262 - :class:`Pickler` objects define one (or two) public methods:
470.263 -
470.264 -
470.265 - .. method:: dump(obj)
470.266 -
470.267 - Write a pickled representation of *obj* to the open file object given in the
470.268 - constructor. Either the binary or ASCII format will be used, depending on the
470.269 - value of the *protocol* argument passed to the constructor.
470.270 -
470.271 -
470.272 - .. method:: clear_memo()
470.273 -
470.274 - Clears the pickler's "memo". The memo is the data structure that remembers
470.275 - which objects the pickler has already seen, so that shared or recursive objects
470.276 - pickled by reference and not by value. This method is useful when re-using
470.277 - picklers.
470.278 -
470.279 - .. note::
470.280 -
470.281 - Prior to Python 2.3, :meth:`clear_memo` was only available on the picklers
470.282 - created by :mod:`cPickle`. In the :mod:`pickle` module, picklers have an
470.283 - instance variable called :attr:`memo` which is a Python dictionary. So to clear
470.284 - the memo for a :mod:`pickle` module pickler, you could do the following::
470.285 -
470.286 - mypickler.memo.clear()
470.287 -
470.288 - Code that does not need to support older versions of Python should simply use
470.289 - :meth:`clear_memo`.
470.290 -
470.291 -It is possible to make multiple calls to the :meth:`dump` method of the same
470.292 -:class:`Pickler` instance. These must then be matched to the same number of
470.293 -calls to the :meth:`load` method of the corresponding :class:`Unpickler`
470.294 -instance. If the same object is pickled by multiple :meth:`dump` calls, the
470.295 -:meth:`load` will all yield references to the same object. [#]_
470.296 -
470.297 -:class:`Unpickler` objects are defined as:
470.298 -
470.299 -
470.300 -.. class:: Unpickler(file)
470.301 -
470.302 - This takes a file-like object from which it will read a pickle data stream.
470.303 - This class automatically determines whether the data stream was written in
470.304 - binary mode or not, so it does not need a flag as in the :class:`Pickler`
470.305 - factory.
470.306 -
470.307 - *file* must have two methods, a :meth:`read` method that takes an integer
470.308 - argument, and a :meth:`readline` method that requires no arguments. Both
470.309 - methods should return a string. Thus *file* can be a file object opened for
470.310 - reading, a :mod:`StringIO` object, or any other custom object that meets this
470.311 - interface.
470.312 -
470.313 - :class:`Unpickler` objects have one (or two) public methods:
470.314 -
470.315 -
470.316 - .. method:: load()
470.317 -
470.318 - Read a pickled object representation from the open file object given in
470.319 - the constructor, and return the reconstituted object hierarchy specified
470.320 - therein.
470.321 -
470.322 - This method automatically determines whether the data stream was written
470.323 - in binary mode or not.
470.324 -
470.325 -
470.326 - .. method:: noload()
470.327 -
470.328 - This is just like :meth:`load` except that it doesn't actually create any
470.329 - objects. This is useful primarily for finding what's called "persistent
470.330 - ids" that may be referenced in a pickle data stream. See section
470.331 - :ref:`pickle-protocol` below for more details.
470.332 -
470.333 - **Note:** the :meth:`noload` method is currently only available on
470.334 - :class:`Unpickler` objects created with the :mod:`cPickle` module.
470.335 - :mod:`pickle` module :class:`Unpickler`\ s do not have the :meth:`noload`
470.336 - method.
470.337 -
470.338 -
470.339 -What can be pickled and unpickled?
470.340 -----------------------------------
470.341 -
470.342 -The following types can be pickled:
470.343 -
470.344 -* ``None``, ``True``, and ``False``
470.345 -
470.346 -* integers, long integers, floating point numbers, complex numbers
470.347 -
470.348 -* normal and Unicode strings
470.349 -
470.350 -* tuples, lists, sets, and dictionaries containing only picklable objects
470.351 -
470.352 -* functions defined at the top level of a module
470.353 -
470.354 -* built-in functions defined at the top level of a module
470.355 -
470.356 -* classes that are defined at the top level of a module
470.357 -
470.358 -* instances of such classes whose :attr:`__dict__` or :meth:`__setstate__` is
470.359 - picklable (see section :ref:`pickle-protocol` for details)
470.360 -
470.361 -Attempts to pickle unpicklable objects will raise the :exc:`PicklingError`
470.362 -exception; when this happens, an unspecified number of bytes may have already
470.363 -been written to the underlying file. Trying to pickle a highly recursive data
470.364 -structure may exceed the maximum recursion depth, a :exc:`RuntimeError` will be
470.365 -raised in this case. You can carefully raise this limit with
470.366 -:func:`sys.setrecursionlimit`.
470.367 -
470.368 -Note that functions (built-in and user-defined) are pickled by "fully qualified"
470.369 -name reference, not by value. This means that only the function name is
470.370 -pickled, along with the name of module the function is defined in. Neither the
470.371 -function's code, nor any of its function attributes are pickled. Thus the
470.372 -defining module must be importable in the unpickling environment, and the module
470.373 -must contain the named object, otherwise an exception will be raised. [#]_
470.374 -
470.375 -Similarly, classes are pickled by named reference, so the same restrictions in
470.376 -the unpickling environment apply. Note that none of the class's code or data is
470.377 -pickled, so in the following example the class attribute ``attr`` is not
470.378 -restored in the unpickling environment::
470.379 -
470.380 - class Foo:
470.381 - attr = 'a class attr'
470.382 -
470.383 - picklestring = pickle.dumps(Foo)
470.384 -
470.385 -These restrictions are why picklable functions and classes must be defined in
470.386 -the top level of a module.
470.387 -
470.388 -Similarly, when class instances are pickled, their class's code and data are not
470.389 -pickled along with them. Only the instance data are pickled. This is done on
470.390 -purpose, so you can fix bugs in a class or add methods to the class and still
470.391 -load objects that were created with an earlier version of the class. If you
470.392 -plan to have long-lived objects that will see many versions of a class, it may
470.393 -be worthwhile to put a version number in the objects so that suitable
470.394 -conversions can be made by the class's :meth:`__setstate__` method.
470.395 -
470.396 -
470.397 -.. _pickle-protocol:
470.398 -
470.399 -The pickle protocol
470.400 --------------------
470.401 -
470.402 -.. currentmodule:: None
470.403 -
470.404 -This section describes the "pickling protocol" that defines the interface
470.405 -between the pickler/unpickler and the objects that are being serialized. This
470.406 -protocol provides a standard way for you to define, customize, and control how
470.407 -your objects are serialized and de-serialized. The description in this section
470.408 -doesn't cover specific customizations that you can employ to make the unpickling
470.409 -environment slightly safer from untrusted pickle data streams; see section
470.410 -:ref:`pickle-sub` for more details.
470.411 -
470.412 -
470.413 -.. _pickle-inst:
470.414 -
470.415 -Pickling and unpickling normal class instances
470.416 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
470.417 -
470.418 -.. method:: object.__getinitargs__()
470.419 -
470.420 - When a pickled class instance is unpickled, its :meth:`__init__` method is
470.421 - normally *not* invoked. If it is desirable that the :meth:`__init__` method
470.422 - be called on unpickling, an old-style class can define a method
470.423 - :meth:`__getinitargs__`, which should return a *tuple* containing the
470.424 - arguments to be passed to the class constructor (:meth:`__init__` for
470.425 - example). The :meth:`__getinitargs__` method is called at pickle time; the
470.426 - tuple it returns is incorporated in the pickle for the instance.
470.427 -
470.428 -.. method:: object.__getnewargs__()
470.429 -
470.430 - New-style types can provide a :meth:`__getnewargs__` method that is used for
470.431 - protocol 2. Implementing this method is needed if the type establishes some
470.432 - internal invariants when the instance is created, or if the memory allocation
470.433 - is affected by the values passed to the :meth:`__new__` method for the type
470.434 - (as it is for tuples and strings). Instances of a :term:`new-style class`
470.435 - ``C`` are created using ::
470.436 -
470.437 - obj = C.__new__(C, *args)
470.438 -
470.439 - where *args* is the result of calling :meth:`__getnewargs__` on the original
470.440 - object; if there is no :meth:`__getnewargs__`, an empty tuple is assumed.
470.441 -
470.442 -.. method:: object.__getstate__()
470.443 -
470.444 - Classes can further influence how their instances are pickled; if the class
470.445 - defines the method :meth:`__getstate__`, it is called and the return state is
470.446 - pickled as the contents for the instance, instead of the contents of the
470.447 - instance's dictionary. If there is no :meth:`__getstate__` method, the
470.448 - instance's :attr:`__dict__` is pickled.
470.449 -
470.450 -.. method:: object.__setstate__()
470.451 -
470.452 - Upon unpickling, if the class also defines the method :meth:`__setstate__`,
470.453 - it is called with the unpickled state. [#]_ If there is no
470.454 - :meth:`__setstate__` method, the pickled state must be a dictionary and its
470.455 - items are assigned to the new instance's dictionary. If a class defines both
470.456 - :meth:`__getstate__` and :meth:`__setstate__`, the state object needn't be a
470.457 - dictionary and these methods can do what they want. [#]_
470.458 -
470.459 - .. warning::
470.460 -
470.461 - For :term:`new-style class`\es, if :meth:`__getstate__` returns a false
470.462 - value, the :meth:`__setstate__` method will not be called.
470.463 -
470.464 -
470.465 -Pickling and unpickling extension types
470.466 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
470.467 -
470.468 -.. method:: object.__reduce__()
470.469 -
470.470 - When the :class:`Pickler` encounters an object of a type it knows nothing
470.471 - about --- such as an extension type --- it looks in two places for a hint of
470.472 - how to pickle it. One alternative is for the object to implement a
470.473 - :meth:`__reduce__` method. If provided, at pickling time :meth:`__reduce__`
470.474 - will be called with no arguments, and it must return either a string or a
470.475 - tuple.
470.476 -
470.477 - If a string is returned, it names a global variable whose contents are
470.478 - pickled as normal. The string returned by :meth:`__reduce__` should be the
470.479 - object's local name relative to its module; the pickle module searches the
470.480 - module namespace to determine the object's module.
470.481 -
470.482 - When a tuple is returned, it must be between two and five elements long.
470.483 - Optional elements can either be omitted, or ``None`` can be provided as their
470.484 - value. The contents of this tuple are pickled as normal and used to
470.485 - reconstruct the object at unpickling time. The semantics of each element
470.486 - are:
470.487 -
470.488 - * A callable object that will be called to create the initial version of the
470.489 - object. The next element of the tuple will provide arguments for this
470.490 - callable, and later elements provide additional state information that will
470.491 - subsequently be used to fully reconstruct the pickled data.
470.492 -
470.493 - In the unpickling environment this object must be either a class, a
470.494 - callable registered as a "safe constructor" (see below), or it must have an
470.495 - attribute :attr:`__safe_for_unpickling__` with a true value. Otherwise, an
470.496 - :exc:`UnpicklingError` will be raised in the unpickling environment. Note
470.497 - that as usual, the callable itself is pickled by name.
470.498 -
470.499 - * A tuple of arguments for the callable object.
470.500 -
470.501 - .. versionchanged:: 2.5
470.502 - Formerly, this argument could also be ``None``.
470.503 -
470.504 - * Optionally, the object's state, which will be passed to the object's
470.505 - :meth:`__setstate__` method as described in section :ref:`pickle-inst`. If
470.506 - the object has no :meth:`__setstate__` method, then, as above, the value
470.507 - must be a dictionary and it will be added to the object's :attr:`__dict__`.
470.508 -
470.509 - * Optionally, an iterator (and not a sequence) yielding successive list
470.510 - items. These list items will be pickled, and appended to the object using
470.511 - either ``obj.append(item)`` or ``obj.extend(list_of_items)``. This is
470.512 - primarily used for list subclasses, but may be used by other classes as
470.513 - long as they have :meth:`append` and :meth:`extend` methods with the
470.514 - appropriate signature. (Whether :meth:`append` or :meth:`extend` is used
470.515 - depends on which pickle protocol version is used as well as the number of
470.516 - items to append, so both must be supported.)
470.517 -
470.518 - * Optionally, an iterator (not a sequence) yielding successive dictionary
470.519 - items, which should be tuples of the form ``(key, value)``. These items
470.520 - will be pickled and stored to the object using ``obj[key] = value``. This
470.521 - is primarily used for dictionary subclasses, but may be used by other
470.522 - classes as long as they implement :meth:`__setitem__`.
470.523 -
470.524 -.. method:: object.__reduce_ex__(protocol)
470.525 -
470.526 - It is sometimes useful to know the protocol version when implementing
470.527 - :meth:`__reduce__`. This can be done by implementing a method named
470.528 - :meth:`__reduce_ex__` instead of :meth:`__reduce__`. :meth:`__reduce_ex__`,
470.529 - when it exists, is called in preference over :meth:`__reduce__` (you may
470.530 - still provide :meth:`__reduce__` for backwards compatibility). The
470.531 - :meth:`__reduce_ex__` method will be called with a single integer argument,
470.532 - the protocol version.
470.533 -
470.534 - The :class:`object` class implements both :meth:`__reduce__` and
470.535 - :meth:`__reduce_ex__`; however, if a subclass overrides :meth:`__reduce__`
470.536 - but not :meth:`__reduce_ex__`, the :meth:`__reduce_ex__` implementation
470.537 - detects this and calls :meth:`__reduce__`.
470.538 -
470.539 -An alternative to implementing a :meth:`__reduce__` method on the object to be
470.540 -pickled, is to register the callable with the :mod:`copy_reg` module. This
470.541 -module provides a way for programs to register "reduction functions" and
470.542 -constructors for user-defined types. Reduction functions have the same
470.543 -semantics and interface as the :meth:`__reduce__` method described above, except
470.544 -that they are called with a single argument, the object to be pickled.
470.545 -
470.546 -The registered constructor is deemed a "safe constructor" for purposes of
470.547 -unpickling as described above.
470.548 -
470.549 -
470.550 -Pickling and unpickling external objects
470.551 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
470.552 -
470.553 -.. index::
470.554 - single: persistent_id (pickle protocol)
470.555 - single: persistent_load (pickle protocol)
470.556 -
470.557 -For the benefit of object persistence, the :mod:`pickle` module supports the
470.558 -notion of a reference to an object outside the pickled data stream. Such
470.559 -objects are referenced by a "persistent id", which is just an arbitrary string
470.560 -of printable ASCII characters. The resolution of such names is not defined by
470.561 -the :mod:`pickle` module; it will delegate this resolution to user defined
470.562 -functions on the pickler and unpickler. [#]_
470.563 -
470.564 -To define external persistent id resolution, you need to set the
470.565 -:attr:`persistent_id` attribute of the pickler object and the
470.566 -:attr:`persistent_load` attribute of the unpickler object.
470.567 -
470.568 -To pickle objects that have an external persistent id, the pickler must have a
470.569 -custom :func:`persistent_id` method that takes an object as an argument and
470.570 -returns either ``None`` or the persistent id for that object. When ``None`` is
470.571 -returned, the pickler simply pickles the object as normal. When a persistent id
470.572 -string is returned, the pickler will pickle that string, along with a marker so
470.573 -that the unpickler will recognize the string as a persistent id.
470.574 -
470.575 -To unpickle external objects, the unpickler must have a custom
470.576 -:func:`persistent_load` function that takes a persistent id string and returns
470.577 -the referenced object.
470.578 -
470.579 -Here's a silly example that *might* shed more light::
470.580 -
470.581 - import pickle
470.582 - from cStringIO import StringIO
470.583 -
470.584 - src = StringIO()
470.585 - p = pickle.Pickler(src)
470.586 -
470.587 - def persistent_id(obj):
470.588 - if hasattr(obj, 'x'):
470.589 - return 'the value %d' % obj.x
470.590 - else:
470.591 - return None
470.592 -
470.593 - p.persistent_id = persistent_id
470.594 -
470.595 - class Integer:
470.596 - def __init__(self, x):
470.597 - self.x = x
470.598 - def __str__(self):
470.599 - return 'My name is integer %d' % self.x
470.600 -
470.601 - i = Integer(7)
470.602 - print i
470.603 - p.dump(i)
470.604 -
470.605 - datastream = src.getvalue()
470.606 - print repr(datastream)
470.607 - dst = StringIO(datastream)
470.608 -
470.609 - up = pickle.Unpickler(dst)
470.610 -
470.611 - class FancyInteger(Integer):
470.612 - def __str__(self):
470.613 - return 'I am the integer %d' % self.x
470.614 -
470.615 - def persistent_load(persid):
470.616 - if persid.startswith('the value '):
470.617 - value = int(persid.split()[2])
470.618 - return FancyInteger(value)
470.619 - else:
470.620 - raise pickle.UnpicklingError, 'Invalid persistent id'
470.621 -
470.622 - up.persistent_load = persistent_load
470.623 -
470.624 - j = up.load()
470.625 - print j
470.626 -
470.627 -In the :mod:`cPickle` module, the unpickler's :attr:`persistent_load` attribute
470.628 -can also be set to a Python list, in which case, when the unpickler reaches a
470.629 -persistent id, the persistent id string will simply be appended to this list.
470.630 -This functionality exists so that a pickle data stream can be "sniffed" for
470.631 -object references without actually instantiating all the objects in a pickle.
470.632 -[#]_ Setting :attr:`persistent_load` to a list is usually used in conjunction
470.633 -with the :meth:`noload` method on the Unpickler.
470.634 -
470.635 -.. BAW: Both pickle and cPickle support something called inst_persistent_id()
470.636 - which appears to give unknown types a second shot at producing a persistent
470.637 - id. Since Jim Fulton can't remember why it was added or what it's for, I'm
470.638 - leaving it undocumented.
470.639 -
470.640 -
470.641 -.. _pickle-sub:
470.642 -
470.643 -Subclassing Unpicklers
470.644 -----------------------
470.645 -
470.646 -.. index::
470.647 - single: load_global() (pickle protocol)
470.648 - single: find_global() (pickle protocol)
470.649 -
470.650 -By default, unpickling will import any class that it finds in the pickle data.
470.651 -You can control exactly what gets unpickled and what gets called by customizing
470.652 -your unpickler. Unfortunately, exactly how you do this is different depending
470.653 -on whether you're using :mod:`pickle` or :mod:`cPickle`. [#]_
470.654 -
470.655 -In the :mod:`pickle` module, you need to derive a subclass from
470.656 -:class:`Unpickler`, overriding the :meth:`load_global` method.
470.657 -:meth:`load_global` should read two lines from the pickle data stream where the
470.658 -first line will the name of the module containing the class and the second line
470.659 -will be the name of the instance's class. It then looks up the class, possibly
470.660 -importing the module and digging out the attribute, then it appends what it
470.661 -finds to the unpickler's stack. Later on, this class will be assigned to the
470.662 -:attr:`__class__` attribute of an empty class, as a way of magically creating an
470.663 -instance without calling its class's :meth:`__init__`. Your job (should you
470.664 -choose to accept it), would be to have :meth:`load_global` push onto the
470.665 -unpickler's stack, a known safe version of any class you deem safe to unpickle.
470.666 -It is up to you to produce such a class. Or you could raise an error if you
470.667 -want to disallow all unpickling of instances. If this sounds like a hack,
470.668 -you're right. Refer to the source code to make this work.
470.669 -
470.670 -Things are a little cleaner with :mod:`cPickle`, but not by much. To control
470.671 -what gets unpickled, you can set the unpickler's :attr:`find_global` attribute
470.672 -to a function or ``None``. If it is ``None`` then any attempts to unpickle
470.673 -instances will raise an :exc:`UnpicklingError`. If it is a function, then it
470.674 -should accept a module name and a class name, and return the corresponding class
470.675 -object. It is responsible for looking up the class and performing any necessary
470.676 -imports, and it may raise an error to prevent instances of the class from being
470.677 -unpickled.
470.678 -
470.679 -The moral of the story is that you should be really careful about the source of
470.680 -the strings your application unpickles.
470.681 -
470.682 -
470.683 -.. _pickle-example:
470.684 -
470.685 -Example
470.686 --------
470.687 -
470.688 -For the simplest code, use the :func:`dump` and :func:`load` functions. Note
470.689 -that a self-referencing list is pickled and restored correctly. ::
470.690 -
470.691 - import pickle
470.692 -
470.693 - data1 = {'a': [1, 2.0, 3, 4+6j],
470.694 - 'b': ('string', u'Unicode string'),
470.695 - 'c': None}
470.696 -
470.697 - selfref_list = [1, 2, 3]
470.698 - selfref_list.append(selfref_list)
470.699 -
470.700 - output = open('data.pkl', 'wb')
470.701 -
470.702 - # Pickle dictionary using protocol 0.
470.703 - pickle.dump(data1, output)
470.704 -
470.705 - # Pickle the list using the highest protocol available.
470.706 - pickle.dump(selfref_list, output, -1)
470.707 -
470.708 - output.close()
470.709 -
470.710 -The following example reads the resulting pickled data. When reading a
470.711 -pickle-containing file, you should open the file in binary mode because you
470.712 -can't be sure if the ASCII or binary format was used. ::
470.713 -
470.714 - import pprint, pickle
470.715 -
470.716 - pkl_file = open('data.pkl', 'rb')
470.717 -
470.718 - data1 = pickle.load(pkl_file)
470.719 - pprint.pprint(data1)
470.720 -
470.721 - data2 = pickle.load(pkl_file)
470.722 - pprint.pprint(data2)
470.723 -
470.724 - pkl_file.close()
470.725 -
470.726 -Here's a larger example that shows how to modify pickling behavior for a class.
470.727 -The :class:`TextReader` class opens a text file, and returns the line number and
470.728 -line contents each time its :meth:`readline` method is called. If a
470.729 -:class:`TextReader` instance is pickled, all attributes *except* the file object
470.730 -member are saved. When the instance is unpickled, the file is reopened, and
470.731 -reading resumes from the last location. The :meth:`__setstate__` and
470.732 -:meth:`__getstate__` methods are used to implement this behavior. ::
470.733 -
470.734 - #!/usr/local/bin/python
470.735 -
470.736 - class TextReader:
470.737 - """Print and number lines in a text file."""
470.738 - def __init__(self, file):
470.739 - self.file = file
470.740 - self.fh = open(file)
470.741 - self.lineno = 0
470.742 -
470.743 - def readline(self):
470.744 - self.lineno = self.lineno + 1
470.745 - line = self.fh.readline()
470.746 - if not line:
470.747 - return None
470.748 - if line.endswith("\n"):
470.749 - line = line[:-1]
470.750 - return "%d: %s" % (self.lineno, line)
470.751 -
470.752 - def __getstate__(self):
470.753 - odict = self.__dict__.copy() # copy the dict since we change it
470.754 - del odict['fh'] # remove filehandle entry
470.755 - return odict
470.756 -
470.757 - def __setstate__(self, dict):
470.758 - fh = open(dict['file']) # reopen file
470.759 - count = dict['lineno'] # read from file...
470.760 - while count: # until line count is restored
470.761 - fh.readline()
470.762 - count = count - 1
470.763 - self.__dict__.update(dict) # update attributes
470.764 - self.fh = fh # save the file object
470.765 -
470.766 -A sample usage might be something like this::
470.767 -
470.768 - >>> import TextReader
470.769 - >>> obj = TextReader.TextReader("TextReader.py")
470.770 - >>> obj.readline()
470.771 - '1: #!/usr/local/bin/python'
470.772 - >>> obj.readline()
470.773 - '2: '
470.774 - >>> obj.readline()
470.775 - '3: class TextReader:'
470.776 - >>> import pickle
470.777 - >>> pickle.dump(obj, open('save.p', 'wb'))
470.778 -
470.779 -If you want to see that :mod:`pickle` works across Python processes, start
470.780 -another Python session, before continuing. What follows can happen from either
470.781 -the same process or a new process. ::
470.782 -
470.783 - >>> import pickle
470.784 - >>> reader = pickle.load(open('save.p', 'rb'))
470.785 - >>> reader.readline()
470.786 - '4: """Print and number lines in a text file."""'
470.787 -
470.788 -
470.789 -.. seealso::
470.790 -
470.791 - Module :mod:`copy_reg`
470.792 - Pickle interface constructor registration for extension types.
470.793 -
470.794 - Module :mod:`shelve`
470.795 - Indexed databases of objects; uses :mod:`pickle`.
470.796 -
470.797 - Module :mod:`copy`
470.798 - Shallow and deep object copying.
470.799 -
470.800 - Module :mod:`marshal`
470.801 - High-performance serialization of built-in types.
470.802 -
470.803 -
470.804 -:mod:`cPickle` --- A faster :mod:`pickle`
470.805 -=========================================
470.806 -
470.807 -.. module:: cPickle
470.808 - :synopsis: Faster version of pickle, but not subclassable.
470.809 -.. moduleauthor:: Jim Fulton <jim@zope.com>
470.810 -.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
470.811 -
470.812 -
470.813 -.. index:: module: pickle
470.814 -
470.815 -The :mod:`cPickle` module supports serialization and de-serialization of Python
470.816 -objects, providing an interface and functionality nearly identical to the
470.817 -:mod:`pickle` module. There are several differences, the most important being
470.818 -performance and subclassability.
470.819 -
470.820 -First, :mod:`cPickle` can be up to 1000 times faster than :mod:`pickle` because
470.821 -the former is implemented in C. Second, in the :mod:`cPickle` module the
470.822 -callables :func:`Pickler` and :func:`Unpickler` are functions, not classes.
470.823 -This means that you cannot use them to derive custom pickling and unpickling
470.824 -subclasses. Most applications have no need for this functionality and should
470.825 -benefit from the greatly improved performance of the :mod:`cPickle` module.
470.826 -
470.827 -The pickle data stream produced by :mod:`pickle` and :mod:`cPickle` are
470.828 -identical, so it is possible to use :mod:`pickle` and :mod:`cPickle`
470.829 -interchangeably with existing pickles. [#]_
470.830 -
470.831 -There are additional minor differences in API between :mod:`cPickle` and
470.832 -:mod:`pickle`, however for most applications, they are interchangeable. More
470.833 -documentation is provided in the :mod:`pickle` module documentation, which
470.834 -includes a list of the documented differences.
470.835 -
470.836 -.. rubric:: Footnotes
470.837 -
470.838 -.. [#] Don't confuse this with the :mod:`marshal` module
470.839 -
470.840 -.. [#] In the :mod:`pickle` module these callables are classes, which you could
470.841 - subclass to customize the behavior. However, in the :mod:`cPickle` module these
470.842 - callables are factory functions and so cannot be subclassed. One common reason
470.843 - to subclass is to control what objects can actually be unpickled. See section
470.844 - :ref:`pickle-sub` for more details.
470.845 -
470.846 -.. [#] *Warning*: this is intended for pickling multiple objects without intervening
470.847 - modifications to the objects or their parts. If you modify an object and then
470.848 - pickle it again using the same :class:`Pickler` instance, the object is not
470.849 - pickled again --- a reference to it is pickled and the :class:`Unpickler` will
470.850 - return the old value, not the modified one. There are two problems here: (1)
470.851 - detecting changes, and (2) marshalling a minimal set of changes. Garbage
470.852 - Collection may also become a problem here.
470.853 -
470.854 -.. [#] The exception raised will likely be an :exc:`ImportError` or an
470.855 - :exc:`AttributeError` but it could be something else.
470.856 -
470.857 -.. [#] These methods can also be used to implement copying class instances.
470.858 -
470.859 -.. [#] This protocol is also used by the shallow and deep copying operations defined in
470.860 - the :mod:`copy` module.
470.861 -
470.862 -.. [#] The actual mechanism for associating these user defined functions is slightly
470.863 - different for :mod:`pickle` and :mod:`cPickle`. The description given here
470.864 - works the same for both implementations. Users of the :mod:`pickle` module
470.865 - could also use subclassing to effect the same results, overriding the
470.866 - :meth:`persistent_id` and :meth:`persistent_load` methods in the derived
470.867 - classes.
470.868 -
470.869 -.. [#] We'll leave you with the image of Guido and Jim sitting around sniffing pickles
470.870 - in their living rooms.
470.871 -
470.872 -.. [#] A word of caution: the mechanisms described here use internal attributes and
470.873 - methods, which are subject to change in future versions of Python. We intend to
470.874 - someday provide a common interface for controlling this behavior, which will
470.875 - work in either :mod:`pickle` or :mod:`cPickle`.
470.876 -
470.877 -.. [#] Since the pickle data format is actually a tiny stack-oriented programming
470.878 - language, and some freedom is taken in the encodings of certain objects, it is
470.879 - possible that the two modules produce different data streams for the same input
470.880 - objects. However it is guaranteed that they will always be able to read each
470.881 - other's data streams.
470.882 -
471.1 --- a/python.editor/test/unit/data/testfiles/rst/pickle.rst.indexed Sun Jan 04 13:11:53 2015 -0600
471.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
471.3 @@ -1,109 +0,0 @@
471.4 -
471.5 -
471.6 -Document 0
471.7 -Searchable Keys:
471.8 - class : PickleError
471.9 - class-ig : pickleerror
471.10 - extends : Exception
471.11 - in : pickle
471.12 -
471.13 -Not Searchable Keys:
471.14 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
471.15 -
471.16 -
471.17 -Document 1
471.18 -Searchable Keys:
471.19 - class : Pickler
471.20 - class-ig : pickler
471.21 - in : pickle
471.22 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;file,protocol;
471.23 - member : clear_memo;F;|DOCUMENTED|DOC_ONLY|;;
471.24 - member : dump;F;|DOCUMENTED|DOC_ONLY|;obj;
471.25 -
471.26 -Not Searchable Keys:
471.27 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
471.28 -
471.29 -
471.30 -Document 2
471.31 -Searchable Keys:
471.32 - class : PicklingError
471.33 - class-ig : picklingerror
471.34 - extends : Exception
471.35 - in : pickle
471.36 -
471.37 -Not Searchable Keys:
471.38 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
471.39 -
471.40 -
471.41 -Document 3
471.42 -Searchable Keys:
471.43 - class : Unpickler
471.44 - class-ig : unpickler
471.45 - in : pickle
471.46 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;file;
471.47 - member : load;F;|DOCUMENTED|DOC_ONLY|;;
471.48 - member : noload;F;|DOCUMENTED|DOC_ONLY|;;
471.49 -
471.50 -Not Searchable Keys:
471.51 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
471.52 -
471.53 -
471.54 -Document 4
471.55 -Searchable Keys:
471.56 - class : UnpicklingError
471.57 - class-ig : unpicklingerror
471.58 - extends : Exception
471.59 - in : pickle
471.60 -
471.61 -Not Searchable Keys:
471.62 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
471.63 -
471.64 -
471.65 -Document 5
471.66 -Searchable Keys:
471.67 - class : object
471.68 - class-ig : object
471.69 - in : None
471.70 - member : __getinitargs__;F;|DOCUMENTED|DOC_ONLY|;;
471.71 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
471.72 - member : __getstate__;F;|DOCUMENTED|DOC_ONLY|;;
471.73 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
471.74 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;protocol;
471.75 - member : __setstate__;F;|DOCUMENTED|DOC_ONLY|;;
471.76 -
471.77 -Not Searchable Keys:
471.78 -
471.79 -
471.80 -Document 6
471.81 -Searchable Keys:
471.82 - item : HIGHEST_PROTOCOL;D;|DOCUMENTED|DOC_ONLY|;
471.83 - item : dump;F;|DOCUMENTED|DOC_ONLY|;obj,file,protocol;
471.84 - item : dumps;F;|DOCUMENTED|DOC_ONLY|;obj,protocol;
471.85 - item : load;F;|DOCUMENTED|DOC_ONLY|;file;
471.86 - item : loads;F;|DOCUMENTED|DOC_ONLY|;string;
471.87 - module : pickle
471.88 -
471.89 -Not Searchable Keys:
471.90 - modattrs : S
471.91 -
471.92 -
471.93 -Document 7
471.94 -Searchable Keys:
471.95 - item : PickleError;C;|DOCUMENTED|DOC_ONLY|;
471.96 - item : Pickler;C;|DOCUMENTED|DOC_ONLY|;
471.97 - item : PicklingError;C;|DOCUMENTED|DOC_ONLY|;
471.98 - item : Unpickler;C;|DOCUMENTED|DOC_ONLY|;
471.99 - item : UnpicklingError;C;|DOCUMENTED|DOC_ONLY|;
471.100 - item : object;C;|DOCUMENTED|DOC_ONLY|;
471.101 - module : cPickle
471.102 -
471.103 -Not Searchable Keys:
471.104 - modattrs : S
471.105 -
471.106 -
471.107 -Document 8
471.108 -Searchable Keys:
471.109 - module : None
471.110 -
471.111 -Not Searchable Keys:
471.112 - modattrs : S
472.1 --- a/python.editor/test/unit/data/testfiles/rst/platform.rst Sun Jan 04 13:11:53 2015 -0600
472.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
472.3 @@ -1,266 +0,0 @@
472.4 -
472.5 -:mod:`platform` --- Access to underlying platform's identifying data.
472.6 -======================================================================
472.7 -
472.8 -.. module:: platform
472.9 - :synopsis: Retrieves as much platform identifying data as possible.
472.10 -.. moduleauthor:: Marc-Andre Lemburg <mal@egenix.com>
472.11 -.. sectionauthor:: Bjorn Pettersen <bpettersen@corp.fairisaac.com>
472.12 -
472.13 -
472.14 -.. versionadded:: 2.3
472.15 -
472.16 -.. note::
472.17 -
472.18 - Specific platforms listed alphabetically, with Linux included in the Unix
472.19 - section.
472.20 -
472.21 -
472.22 -Cross Platform
472.23 ---------------
472.24 -
472.25 -
472.26 -.. function:: architecture(executable=sys.executable, bits='', linkage='')
472.27 -
472.28 - Queries the given executable (defaults to the Python interpreter binary) for
472.29 - various architecture information.
472.30 -
472.31 - Returns a tuple ``(bits, linkage)`` which contain information about the bit
472.32 - architecture and the linkage format used for the executable. Both values are
472.33 - returned as strings.
472.34 -
472.35 - Values that cannot be determined are returned as given by the parameter presets.
472.36 - If bits is given as ``''``, the :cfunc:`sizeof(pointer)` (or
472.37 - :cfunc:`sizeof(long)` on Python version < 1.5.2) is used as indicator for the
472.38 - supported pointer size.
472.39 -
472.40 - The function relies on the system's :file:`file` command to do the actual work.
472.41 - This is available on most if not all Unix platforms and some non-Unix platforms
472.42 - and then only if the executable points to the Python interpreter. Reasonable
472.43 - defaults are used when the above needs are not met.
472.44 -
472.45 -
472.46 -.. function:: machine()
472.47 -
472.48 - Returns the machine type, e.g. ``'i386'``. An empty string is returned if the
472.49 - value cannot be determined.
472.50 -
472.51 -
472.52 -.. function:: node()
472.53 -
472.54 - Returns the computer's network name (may not be fully qualified!). An empty
472.55 - string is returned if the value cannot be determined.
472.56 -
472.57 -
472.58 -.. function:: platform(aliased=0, terse=0)
472.59 -
472.60 - Returns a single string identifying the underlying platform with as much useful
472.61 - information as possible.
472.62 -
472.63 - The output is intended to be *human readable* rather than machine parseable. It
472.64 - may look different on different platforms and this is intended.
472.65 -
472.66 - If *aliased* is true, the function will use aliases for various platforms that
472.67 - report system names which differ from their common names, for example SunOS will
472.68 - be reported as Solaris. The :func:`system_alias` function is used to implement
472.69 - this.
472.70 -
472.71 - Setting *terse* to true causes the function to return only the absolute minimum
472.72 - information needed to identify the platform.
472.73 -
472.74 -
472.75 -.. function:: processor()
472.76 -
472.77 - Returns the (real) processor name, e.g. ``'amdk6'``.
472.78 -
472.79 - An empty string is returned if the value cannot be determined. Note that many
472.80 - platforms do not provide this information or simply return the same value as for
472.81 - :func:`machine`. NetBSD does this.
472.82 -
472.83 -
472.84 -.. function:: python_build()
472.85 -
472.86 - Returns a tuple ``(buildno, builddate)`` stating the Python build number and
472.87 - date as strings.
472.88 -
472.89 -
472.90 -.. function:: python_compiler()
472.91 -
472.92 - Returns a string identifying the compiler used for compiling Python.
472.93 -
472.94 -
472.95 -.. function:: python_branch()
472.96 -
472.97 - Returns a string identifying the Python implementation SCM branch.
472.98 -
472.99 - .. versionadded:: 2.6
472.100 -
472.101 -
472.102 -.. function:: python_implementation()
472.103 -
472.104 - Returns a string identifying the Python implementation. Possible return values
472.105 - are: 'CPython', 'IronPython', 'Jython'
472.106 -
472.107 - .. versionadded:: 2.6
472.108 -
472.109 -
472.110 -.. function:: python_revision()
472.111 -
472.112 - Returns a string identifying the Python implementation SCM revision.
472.113 -
472.114 - .. versionadded:: 2.6
472.115 -
472.116 -
472.117 -.. function:: python_version()
472.118 -
472.119 - Returns the Python version as string ``'major.minor.patchlevel'``
472.120 -
472.121 - Note that unlike the Python ``sys.version``, the returned value will always
472.122 - include the patchlevel (it defaults to 0).
472.123 -
472.124 -
472.125 -.. function:: python_version_tuple()
472.126 -
472.127 - Returns the Python version as tuple ``(major, minor, patchlevel)`` of strings.
472.128 -
472.129 - Note that unlike the Python ``sys.version``, the returned value will always
472.130 - include the patchlevel (it defaults to ``'0'``).
472.131 -
472.132 -
472.133 -.. function:: release()
472.134 -
472.135 - Returns the system's release, e.g. ``'2.2.0'`` or ``'NT'`` An empty string is
472.136 - returned if the value cannot be determined.
472.137 -
472.138 -
472.139 -.. function:: system()
472.140 -
472.141 - Returns the system/OS name, e.g. ``'Linux'``, ``'Windows'``, or ``'Java'``. An
472.142 - empty string is returned if the value cannot be determined.
472.143 -
472.144 -
472.145 -.. function:: system_alias(system, release, version)
472.146 -
472.147 - Returns ``(system, release, version)`` aliased to common marketing names used
472.148 - for some systems. It also does some reordering of the information in some cases
472.149 - where it would otherwise cause confusion.
472.150 -
472.151 -
472.152 -.. function:: version()
472.153 -
472.154 - Returns the system's release version, e.g. ``'#3 on degas'``. An empty string is
472.155 - returned if the value cannot be determined.
472.156 -
472.157 -
472.158 -.. function:: uname()
472.159 -
472.160 - Fairly portable uname interface. Returns a tuple of strings ``(system, node,
472.161 - release, version, machine, processor)`` identifying the underlying platform.
472.162 -
472.163 - Note that unlike the :func:`os.uname` function this also returns possible
472.164 - processor information as additional tuple entry.
472.165 -
472.166 - Entries which cannot be determined are set to ``''``.
472.167 -
472.168 -
472.169 -Java Platform
472.170 --------------
472.171 -
472.172 -
472.173 -.. function:: java_ver(release='', vendor='', vminfo=('','',''), osinfo=('','',''))
472.174 -
472.175 - Version interface for JPython.
472.176 -
472.177 - Returns a tuple ``(release, vendor, vminfo, osinfo)`` with *vminfo* being a
472.178 - tuple ``(vm_name, vm_release, vm_vendor)`` and *osinfo* being a tuple
472.179 - ``(os_name, os_version, os_arch)``. Values which cannot be determined are set to
472.180 - the defaults given as parameters (which all default to ``''``).
472.181 -
472.182 -
472.183 -Windows Platform
472.184 -----------------
472.185 -
472.186 -
472.187 -.. function:: win32_ver(release='', version='', csd='', ptype='')
472.188 -
472.189 - Get additional version information from the Windows Registry and return a tuple
472.190 - ``(version, csd, ptype)`` referring to version number, CSD level and OS type
472.191 - (multi/single processor).
472.192 -
472.193 - As a hint: *ptype* is ``'Uniprocessor Free'`` on single processor NT machines
472.194 - and ``'Multiprocessor Free'`` on multi processor machines. The *'Free'* refers
472.195 - to the OS version being free of debugging code. It could also state *'Checked'*
472.196 - which means the OS version uses debugging code, i.e. code that checks arguments,
472.197 - ranges, etc.
472.198 -
472.199 - .. note::
472.200 -
472.201 - Note: this function works best with Mark Hammond's
472.202 - :mod:`win32all` package installed, but also on Python 2.3 and
472.203 - later (support for this was added in Python 2.6). It obviously
472.204 - only runs on Win32 compatible platforms.
472.205 -
472.206 -
472.207 -Win95/98 specific
472.208 -^^^^^^^^^^^^^^^^^
472.209 -
472.210 -.. function:: popen(cmd, mode='r', bufsize=None)
472.211 -
472.212 - Portable :func:`popen` interface. Find a working popen implementation
472.213 - preferring :func:`win32pipe.popen`. On Windows NT, :func:`win32pipe.popen`
472.214 - should work; on Windows 9x it hangs due to bugs in the MS C library.
472.215 -
472.216 -
472.217 -Mac OS Platform
472.218 ----------------
472.219 -
472.220 -
472.221 -.. function:: mac_ver(release='', versioninfo=('','',''), machine='')
472.222 -
472.223 - Get Mac OS version information and return it as tuple ``(release, versioninfo,
472.224 - machine)`` with *versioninfo* being a tuple ``(version, dev_stage,
472.225 - non_release_version)``.
472.226 -
472.227 - Entries which cannot be determined are set to ``''``. All tuple entries are
472.228 - strings.
472.229 -
472.230 - Documentation for the underlying :cfunc:`gestalt` API is available online at
472.231 - http://www.rgaros.nl/gestalt/.
472.232 -
472.233 -
472.234 -Unix Platforms
472.235 ---------------
472.236 -
472.237 -
472.238 -.. function:: dist(distname='', version='', id='', supported_dists=('SuSE','debian','redhat','mandrake',...))
472.239 -
472.240 - This is another name for :func:`linux_distribution`.
472.241 -
472.242 -.. function:: linux_distribution(distname='', version='', id='', supported_dists=('SuSE','debian','redhat','mandrake',...), full_distribution_name=1)
472.243 -
472.244 - Tries to determine the name of the Linux OS distribution name.
472.245 -
472.246 - ``supported_dists`` may be given to define the set of Linux distributions to
472.247 - look for. It defaults to a list of currently supported Linux distributions
472.248 - identified by their release file name.
472.249 -
472.250 - If ``full_distribution_name`` is true (default), the full distribution read
472.251 - from the OS is returned. Otherwise the short name taken from
472.252 - ``supported_dists`` is used.
472.253 -
472.254 - Returns a tuple ``(distname,version,id)`` which defaults to the args given as
472.255 - parameters. ``id`` is the item in parentheses after the version number. It
472.256 - is usually the version codename.
472.257 -
472.258 -.. function:: libc_ver(executable=sys.executable, lib='', version='', chunksize=2048)
472.259 -
472.260 - Tries to determine the libc version against which the file executable (defaults
472.261 - to the Python interpreter) is linked. Returns a tuple of strings ``(lib,
472.262 - version)`` which default to the given parameters in case the lookup fails.
472.263 -
472.264 - Note that this function has intimate knowledge of how different libc versions
472.265 - add symbols to the executable is probably only usable for executables compiled
472.266 - using :program:`gcc`.
472.267 -
472.268 - The file is read and scanned in chunks of *chunksize* bytes.
472.269 -
473.1 --- a/python.editor/test/unit/data/testfiles/rst/platform.rst.html Sun Jan 04 13:11:53 2015 -0600
473.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
473.3 @@ -1,283 +0,0 @@
473.4 -<html><body>
473.5 -<h2><a href="mod:platform">platform</a> --- Access to underlying platform's identifying data.
473.6 -</h2>
473.7 -<a href="module:platform">platform</a><br>
473.8 - Retrieves as much platform identifying data as possible.
473.9 -<br>Module Author:</b> Marc-Andre Lemburg <mal@egenix.com>
473.10 -<br>Section Author:</b> Bjorn Pettersen <bpettersen@corp.fairisaac.com>
473.11 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
473.12 -</div>
473.13 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
473.14 - Specific platforms listed alphabetically, with Linux included in the Unix
473.15 - section.
473.16 -</div>
473.17 -<h3>Cross Platform
473.18 -</h3>
473.19 -<a href="func:architecture(executable=sys.executable, bits='', linkage='')">architecture(executable=sys.executable, bits='', linkage='')</a>
473.20 -
473.21 -<br><br>
473.22 - Queries the given executable (defaults to the Python interpreter binary) for
473.23 - various architecture information.
473.24 -
473.25 -<br><br>
473.26 - Returns a tuple <code>(bits, linkage)</code> which contain information about the bit
473.27 - architecture and the linkage format used for the executable. Both values are
473.28 - returned as strings.
473.29 -
473.30 -<br><br>
473.31 - Values that cannot be determined are returned as given by the parameter presets.
473.32 - If bits is given as <code>''</code>, the :cfunc:`sizeof(pointer)` (or
473.33 - :cfunc:`sizeof(long)` on Python version < 1.5.2) is used as indicator for the
473.34 - supported pointer size.
473.35 -
473.36 -<br><br>
473.37 - The function relies on the system's :file:<code>file</code> command to do the actual work.
473.38 - This is available on most if not all Unix platforms and some non-Unix platforms
473.39 - and then only if the executable points to the Python interpreter. Reasonable
473.40 - defaults are used when the above needs are not met.
473.41 -
473.42 -<br><br>
473.43 -<a href="func:machine()">machine()</a>
473.44 -
473.45 -<br><br>
473.46 - Returns the machine type, e.g. <code>'i386'</code>. An empty string is returned if the
473.47 - value cannot be determined.
473.48 -
473.49 -<br><br>
473.50 -<a href="func:node()">node()</a>
473.51 -
473.52 -<br><br>
473.53 - Returns the computer's network name (may not be fully qualified!). An empty
473.54 - string is returned if the value cannot be determined.
473.55 -
473.56 -<br><br>
473.57 -<a href="func:platform(aliased=0, terse=0)">platform(aliased=0, terse=0)</a>
473.58 -
473.59 -<br><br>
473.60 - Returns a single string identifying the underlying platform with as much useful
473.61 - information as possible.
473.62 -
473.63 -<br><br>
473.64 - The output is intended to be *human readable* rather than machine parseable. It
473.65 - may look different on different platforms and this is intended.
473.66 -
473.67 -<br><br>
473.68 - If <b>aliased</b> is true, the function will use aliases for various platforms that
473.69 - report system names which differ from their common names, for example SunOS will
473.70 - be reported as Solaris. The <a href="func:system_alias">system_alias</a> function is used to implement
473.71 - this.
473.72 -
473.73 -<br><br>
473.74 - Setting <b>terse</b> to true causes the function to return only the absolute minimum
473.75 - information needed to identify the platform.
473.76 -
473.77 -<br><br>
473.78 -<a href="func:processor()">processor()</a>
473.79 -
473.80 -<br><br>
473.81 - Returns the (real) processor name, e.g. <code>'amdk6'</code>.
473.82 -
473.83 -<br><br>
473.84 - An empty string is returned if the value cannot be determined. Note that many
473.85 - platforms do not provide this information or simply return the same value as for
473.86 - <a href="func:machine">machine</a>. NetBSD does this.
473.87 -
473.88 -<br><br>
473.89 -<a href="func:python_build()">python_build()</a>
473.90 -
473.91 -<br><br>
473.92 - Returns a tuple <code>(buildno, builddate)</code> stating the Python build number and
473.93 - date as strings.
473.94 -
473.95 -<br><br>
473.96 -<a href="func:python_compiler()">python_compiler()</a>
473.97 -
473.98 -<br><br>
473.99 - Returns a string identifying the compiler used for compiling Python.
473.100 -
473.101 -<br><br>
473.102 -<a href="func:python_branch()">python_branch()</a>
473.103 -
473.104 -<br><br>
473.105 - Returns a string identifying the Python implementation SCM branch.
473.106 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
473.107 -</div>
473.108 -<a href="func:python_implementation()">python_implementation()</a>
473.109 - Returns a string identifying the Python implementation. Possible return values
473.110 - are: 'CPython', 'IronPython', 'Jython'
473.111 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
473.112 -</div>
473.113 -<a href="func:python_revision()">python_revision()</a>
473.114 - Returns a string identifying the Python implementation SCM revision.
473.115 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
473.116 -</div>
473.117 -<a href="func:python_version()">python_version()</a>
473.118 - Returns the Python version as string <code>'major.minor.patchlevel'</code>
473.119 -
473.120 -<br><br>
473.121 - Note that unlike the Python <code>sys.version</code>, the returned value will always
473.122 - include the patchlevel (it defaults to 0).
473.123 -
473.124 -<br><br>
473.125 -<a href="func:python_version_tuple()">python_version_tuple()</a>
473.126 -
473.127 -<br><br>
473.128 - Returns the Python version as tuple <code>(major, minor, patchlevel)</code> of strings.
473.129 -
473.130 -<br><br>
473.131 - Note that unlike the Python <code>sys.version</code>, the returned value will always
473.132 - include the patchlevel (it defaults to <code>'0'</code>).
473.133 -
473.134 -<br><br>
473.135 -<a href="func:release()">release()</a>
473.136 -
473.137 -<br><br>
473.138 - Returns the system's release, e.g. <code>'2.2.0'</code> or <code>'NT'</code> An empty string is
473.139 - returned if the value cannot be determined.
473.140 -
473.141 -<br><br>
473.142 -<a href="func:system()">system()</a>
473.143 -
473.144 -<br><br>
473.145 - Returns the system/OS name, e.g. <code>'Linux'</code>, <code>'Windows'</code>, or <code>'Java'</code>. An
473.146 - empty string is returned if the value cannot be determined.
473.147 -
473.148 -<br><br>
473.149 -<a href="func:system_alias(system, release, version)">system_alias(system, release, version)</a>
473.150 -
473.151 -<br><br>
473.152 - Returns <code>(system, release, version)</code> aliased to common marketing names used
473.153 - for some systems. It also does some reordering of the information in some cases
473.154 - where it would otherwise cause confusion.
473.155 -
473.156 -<br><br>
473.157 -<a href="func:version()">version()</a>
473.158 -
473.159 -<br><br>
473.160 - Returns the system's release version, e.g. <code>'#3 on degas'</code>. An empty string is
473.161 - returned if the value cannot be determined.
473.162 -
473.163 -<br><br>
473.164 -<a href="func:uname()">uname()</a>
473.165 -
473.166 -<br><br>
473.167 - Fairly portable uname interface. Returns a tuple of strings ``(system, node,
473.168 - release, version, machine, processor)`` identifying the underlying platform.
473.169 -
473.170 -<br><br>
473.171 - Note that unlike the <a href="func:os.uname">os.uname</a> function this also returns possible
473.172 - processor information as additional tuple entry.
473.173 -
473.174 -<br><br>
473.175 - Entries which cannot be determined are set to <code>''</code>.
473.176 -
473.177 -<br><br>
473.178 -<h3>Java Platform
473.179 -</h3>
473.180 -<a href="func:java_ver(release='', vendor='', vminfo=('','',''), osinfo=('','',''))">java_ver(release='', vendor='', vminfo=('','',''), osinfo=('','',''))</a>
473.181 -
473.182 -<br><br>
473.183 - Version interface for JPython.
473.184 -
473.185 -<br><br>
473.186 - Returns a tuple <code>(release, vendor, vminfo, osinfo)</code> with <b>vminfo</b> being a
473.187 - tuple <code>(vm_name, vm_release, vm_vendor)</code> and <b>osinfo</b> being a tuple
473.188 - <code>(os_name, os_version, os_arch)</code>. Values which cannot be determined are set to
473.189 - the defaults given as parameters (which all default to <code>''</code>).
473.190 -
473.191 -<br><br>
473.192 -<h3>Windows Platform
473.193 -</h3>
473.194 -<a href="func:win32_ver(release='', version='', csd='', ptype='')">win32_ver(release='', version='', csd='', ptype='')</a>
473.195 -
473.196 -<br><br>
473.197 - Get additional version information from the Windows Registry and return a tuple
473.198 - <code>(version, csd, ptype)</code> referring to version number, CSD level and OS type
473.199 - (multi/single processor).
473.200 -
473.201 -<br><br>
473.202 - As a hint: <b>ptype</b> is <code>'Uniprocessor Free'</code> on single processor NT machines
473.203 - and <code>'Multiprocessor Free'</code> on multi processor machines. The *'Free'* refers
473.204 - to the OS version being free of debugging code. It could also state *'Checked'*
473.205 - which means the OS version uses debugging code, i.e. code that checks arguments,
473.206 - ranges, etc.
473.207 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
473.208 -
473.209 -<br><br>
473.210 - Note: this function works best with Mark Hammond's
473.211 - <a href="mod:win32all">win32all</a> package installed, but also on Python 2.3 and
473.212 - later (support for this was added in Python 2.6). It obviously
473.213 - only runs on Win32 compatible platforms.
473.214 -</div>
473.215 -<h3>Win95/98 specific
473.216 -</h3>
473.217 -<a href="func:popen(cmd, mode='r', bufsize=None)">popen(cmd, mode='r', bufsize=None)</a>
473.218 -
473.219 -<br><br>
473.220 - Portable <a href="func:popen">popen</a> interface. Find a working popen implementation
473.221 - preferring <a href="func:win32pipe.popen">win32pipe.popen</a>. On Windows NT, <a href="func:win32pipe.popen">win32pipe.popen</a>
473.222 - should work; on Windows 9x it hangs due to bugs in the MS C library.
473.223 -
473.224 -<br><br>
473.225 -<h3>Mac OS Platform
473.226 -</h3>
473.227 -<a href="func:mac_ver(release='', versioninfo=('','',''), machine='')">mac_ver(release='', versioninfo=('','',''), machine='')</a>
473.228 -
473.229 -<br><br>
473.230 - Get Mac OS version information and return it as tuple ``(release, versioninfo,
473.231 - machine)<code> with *versioninfo* being a tuple </code>(version, dev_stage,
473.232 - non_release_version)``.
473.233 -
473.234 -<br><br>
473.235 - Entries which cannot be determined are set to <code>''</code>. All tuple entries are
473.236 - strings.
473.237 -
473.238 -<br><br>
473.239 - Documentation for the underlying :cfunc:<code>gestalt</code> API is available online at
473.240 - http://www.rgaros.nl/gestalt/.
473.241 -
473.242 -<br><br>
473.243 -<h3>Unix Platforms
473.244 -</h3>
473.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>
473.246 -
473.247 -<br><br>
473.248 - This is another name for <a href="func:linux_distribution">linux_distribution</a>.
473.249 -
473.250 -<br><br>
473.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>
473.252 -
473.253 -<br><br>
473.254 - Tries to determine the name of the Linux OS distribution name.
473.255 -
473.256 -<br><br>
473.257 - <code>supported_dists</code> may be given to define the set of Linux distributions to
473.258 - look for. It defaults to a list of currently supported Linux distributions
473.259 - identified by their release file name.
473.260 -
473.261 -<br><br>
473.262 - If <code>full_distribution_name</code> is true (default), the full distribution read
473.263 - from the OS is returned. Otherwise the short name taken from
473.264 - <code>supported_dists</code> is used.
473.265 -
473.266 -<br><br>
473.267 - Returns a tuple <code>(distname,version,id)</code> which defaults to the args given as
473.268 - parameters. <code>id</code> is the item in parentheses after the version number. It
473.269 - is usually the version codename.
473.270 -
473.271 -<br><br>
473.272 -<a href="func:libc_ver(executable=sys.executable, lib='', version='', chunksize=2048)">libc_ver(executable=sys.executable, lib='', version='', chunksize=2048)</a>
473.273 -
473.274 -<br><br>
473.275 - Tries to determine the libc version against which the file executable (defaults
473.276 - to the Python interpreter) is linked. Returns a tuple of strings ``(lib,
473.277 - version)`` which default to the given parameters in case the lookup fails.
473.278 -
473.279 -<br><br>
473.280 - Note that this function has intimate knowledge of how different libc versions
473.281 - add symbols to the executable is probably only usable for executables compiled
473.282 - using :program:<code>gcc</code>.
473.283 -
473.284 -<br><br>
473.285 - The file is read and scanned in chunks of <b>chunksize</b> bytes.
473.286 -</body></html>
474.1 --- a/python.editor/test/unit/data/testfiles/rst/platform.rst.indexed Sun Jan 04 13:11:53 2015 -0600
474.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
474.3 @@ -1,32 +0,0 @@
474.4 -
474.5 -
474.6 -Document 0
474.7 -Searchable Keys:
474.8 - item : architecture;F;|DOCUMENTED|DOC_ONLY|;executable,bits,linkage;
474.9 - item : dist;F;|DOCUMENTED|DOC_ONLY|;distname,version,id,supported_dists;
474.10 - item : java_ver;F;|DOCUMENTED|DOC_ONLY|;release,vendor,vminfo,osinfo;
474.11 - item : libc_ver;F;|DOCUMENTED|DOC_ONLY|;executable,lib,version,chunksize;
474.12 - item : linux_distribution;F;|DOCUMENTED|DOC_ONLY|;distname,version,id,supported_dists,full_distribution_name;
474.13 - item : mac_ver;F;|DOCUMENTED|DOC_ONLY|;release,versioninfo,machine;
474.14 - item : machine;F;|DOCUMENTED|DOC_ONLY|;;
474.15 - item : node;F;|DOCUMENTED|DOC_ONLY|;;
474.16 - item : platform;F;|DOCUMENTED|DOC_ONLY|;aliased,terse;
474.17 - item : popen;F;|DOCUMENTED|DOC_ONLY|;cmd,mode,bufsize;
474.18 - item : processor;F;|DOCUMENTED|DOC_ONLY|;;
474.19 - item : python_branch;F;|DOCUMENTED|DOC_ONLY|;;
474.20 - item : python_build;F;|DOCUMENTED|DOC_ONLY|;;
474.21 - item : python_compiler;F;|DOCUMENTED|DOC_ONLY|;;
474.22 - item : python_implementation;F;|DOCUMENTED|DOC_ONLY|;;
474.23 - item : python_revision;F;|DOCUMENTED|DOC_ONLY|;;
474.24 - item : python_version;F;|DOCUMENTED|DOC_ONLY|;;
474.25 - item : python_version_tuple;F;|DOCUMENTED|DOC_ONLY|;;
474.26 - item : release;F;|DOCUMENTED|DOC_ONLY|;;
474.27 - item : system;F;|DOCUMENTED|DOC_ONLY|;;
474.28 - item : system_alias;F;|DOCUMENTED|DOC_ONLY|;system,release,version;
474.29 - item : uname;F;|DOCUMENTED|DOC_ONLY|;;
474.30 - item : version;F;|DOCUMENTED|DOC_ONLY|;;
474.31 - item : win32_ver;F;|DOCUMENTED|DOC_ONLY|;release,version,csd,ptype;
474.32 - module : platform
474.33 -
474.34 -Not Searchable Keys:
474.35 - modattrs : S
475.1 --- a/python.editor/test/unit/data/testfiles/rst/smtpd.rst Sun Jan 04 13:11:53 2015 -0600
475.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
475.3 @@ -1,73 +0,0 @@
475.4 -:mod:`smtpd` --- SMTP Server
475.5 -============================
475.6 -
475.7 -.. module:: smtpd
475.8 - :synopsis: A SMTP server implementation in Python.
475.9 -
475.10 -.. moduleauthor:: Barry Warsaw <barry@zope.com>
475.11 -.. sectionauthor:: Moshe Zadka <moshez@moshez.org>
475.12 -
475.13 -
475.14 -
475.15 -
475.16 -This module offers several classes to implement SMTP servers. One is a generic
475.17 -do-nothing implementation, which can be overridden, while the other two offer
475.18 -specific mail-sending strategies.
475.19 -
475.20 -
475.21 -SMTPServer Objects
475.22 -------------------
475.23 -
475.24 -
475.25 -.. class:: SMTPServer(localaddr, remoteaddr)
475.26 -
475.27 - Create a new :class:`SMTPServer` object, which binds to local address
475.28 - *localaddr*. It will treat *remoteaddr* as an upstream SMTP relayer. It
475.29 - inherits from :class:`asyncore.dispatcher`, and so will insert itself into
475.30 - :mod:`asyncore`'s event loop on instantiation.
475.31 -
475.32 -
475.33 - .. method:: process_message(peer, mailfrom, rcpttos, data)
475.34 -
475.35 - Raise :exc:`NotImplementedError` exception. Override this in subclasses to
475.36 - do something useful with this message. Whatever was passed in the
475.37 - constructor as *remoteaddr* will be available as the :attr:`_remoteaddr`
475.38 - attribute. *peer* is the remote host's address, *mailfrom* is the envelope
475.39 - originator, *rcpttos* are the envelope recipients and *data* is a string
475.40 - containing the contents of the e-mail (which should be in :rfc:`2822`
475.41 - format).
475.42 -
475.43 -
475.44 -DebuggingServer Objects
475.45 ------------------------
475.46 -
475.47 -
475.48 -.. class:: DebuggingServer(localaddr, remoteaddr)
475.49 -
475.50 - Create a new debugging server. Arguments are as per :class:`SMTPServer`.
475.51 - Messages will be discarded, and printed on stdout.
475.52 -
475.53 -
475.54 -PureProxy Objects
475.55 ------------------
475.56 -
475.57 -
475.58 -.. class:: PureProxy(localaddr, remoteaddr)
475.59 -
475.60 - Create a new pure proxy server. Arguments are as per :class:`SMTPServer`.
475.61 - Everything will be relayed to *remoteaddr*. Note that running this has a good
475.62 - chance to make you into an open relay, so please be careful.
475.63 -
475.64 -
475.65 -MailmanProxy Objects
475.66 ---------------------
475.67 -
475.68 -
475.69 -.. class:: MailmanProxy(localaddr, remoteaddr)
475.70 -
475.71 - Create a new pure proxy server. Arguments are as per :class:`SMTPServer`.
475.72 - Everything will be relayed to *remoteaddr*, unless local mailman configurations
475.73 - knows about an address, in which case it will be handled via mailman. Note that
475.74 - running this has a good chance to make you into an open relay, so please be
475.75 - careful.
475.76 -
476.1 --- a/python.editor/test/unit/data/testfiles/rst/smtpd.rst.html Sun Jan 04 13:11:53 2015 -0600
476.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
476.3 @@ -1,69 +0,0 @@
476.4 -<html><body>
476.5 -<h2><a href="mod:smtpd">smtpd</a> --- SMTP Server
476.6 -</h2>
476.7 -<a href="module:smtpd">smtpd</a><br>
476.8 - A SMTP server implementation in Python.
476.9 -
476.10 -<br><br>
476.11 -<br>Module Author:</b> Barry Warsaw <barry@zope.com>
476.12 -<br>Section Author:</b> Moshe Zadka <moshez@moshez.org>
476.13 -
476.14 -<br><br>
476.15 -This module offers several classes to implement SMTP servers. One is a generic
476.16 -do-nothing implementation, which can be overridden, while the other two offer
476.17 -specific mail-sending strategies.
476.18 -
476.19 -<br><br>
476.20 -<h3>SMTPServer Objects
476.21 -</h3>
476.22 -<a href="class:SMTPServer(localaddr, remoteaddr)">SMTPServer(localaddr, remoteaddr)</a>
476.23 -
476.24 -<br><br>
476.25 - Create a new <a href="class:SMTPServer">SMTPServer</a> object, which binds to local address
476.26 - <b>localaddr</b>. It will treat <b>remoteaddr</b> as an upstream SMTP relayer. It
476.27 - inherits from <a href="class:asyncore.dispatcher">asyncore.dispatcher</a>, and so will insert itself into
476.28 - <a href="mod:asyncore">asyncore</a>'s event loop on instantiation.
476.29 -
476.30 -<br><br>
476.31 -<a href="meth:process_message(peer, mailfrom, rcpttos, data)">process_message(peer, mailfrom, rcpttos, data)</a>
476.32 -
476.33 -<br><br>
476.34 - Raise <a href="exc:NotImplementedError">NotImplementedError</a> exception. Override this in subclasses to
476.35 - do something useful with this message. Whatever was passed in the
476.36 - constructor as <b>remoteaddr</b> will be available as the <code>_remoteaddr</code>
476.37 - attribute. <b>peer</b> is the remote host's address, <b>mailfrom</b> is the envelope
476.38 - originator, <b>rcpttos</b> are the envelope recipients and <b>data</b> is a string
476.39 - containing the contents of the e-mail (which should be in :rfc:<code>2822</code>
476.40 - format).
476.41 -
476.42 -<br><br>
476.43 -<h3>DebuggingServer Objects
476.44 -</h3>
476.45 -<a href="class:DebuggingServer(localaddr, remoteaddr)">DebuggingServer(localaddr, remoteaddr)</a>
476.46 -
476.47 -<br><br>
476.48 - Create a new debugging server. Arguments are as per <a href="class:SMTPServer">SMTPServer</a>.
476.49 - Messages will be discarded, and printed on stdout.
476.50 -
476.51 -<br><br>
476.52 -<h3>PureProxy Objects
476.53 -</h3>
476.54 -<a href="class:PureProxy(localaddr, remoteaddr)">PureProxy(localaddr, remoteaddr)</a>
476.55 -
476.56 -<br><br>
476.57 - Create a new pure proxy server. Arguments are as per <a href="class:SMTPServer">SMTPServer</a>.
476.58 - Everything will be relayed to <b>remoteaddr</b>. Note that running this has a good
476.59 - chance to make you into an open relay, so please be careful.
476.60 -
476.61 -<br><br>
476.62 -<h3>MailmanProxy Objects
476.63 -</h3>
476.64 -<a href="class:MailmanProxy(localaddr, remoteaddr)">MailmanProxy(localaddr, remoteaddr)</a>
476.65 -
476.66 -<br><br>
476.67 - Create a new pure proxy server. Arguments are as per <a href="class:SMTPServer">SMTPServer</a>.
476.68 - Everything will be relayed to <b>remoteaddr</b>, unless local mailman configurations
476.69 - knows about an address, in which case it will be handled via mailman. Note that
476.70 - running this has a good chance to make you into an open relay, so please be
476.71 - careful.
476.72 -</body></html>
477.1 --- a/python.editor/test/unit/data/testfiles/rst/smtpd.rst.indexed Sun Jan 04 13:11:53 2015 -0600
477.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
477.3 @@ -1,57 +0,0 @@
477.4 -
477.5 -
477.6 -Document 0
477.7 -Searchable Keys:
477.8 - class : DebuggingServer
477.9 - class-ig : debuggingserver
477.10 - in : smtpd
477.11 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;localaddr,remoteaddr;
477.12 -
477.13 -Not Searchable Keys:
477.14 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
477.15 -
477.16 -
477.17 -Document 1
477.18 -Searchable Keys:
477.19 - class : MailmanProxy
477.20 - class-ig : mailmanproxy
477.21 - in : smtpd
477.22 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;localaddr,remoteaddr;
477.23 -
477.24 -Not Searchable Keys:
477.25 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
477.26 -
477.27 -
477.28 -Document 2
477.29 -Searchable Keys:
477.30 - class : PureProxy
477.31 - class-ig : pureproxy
477.32 - in : smtpd
477.33 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;localaddr,remoteaddr;
477.34 -
477.35 -Not Searchable Keys:
477.36 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
477.37 -
477.38 -
477.39 -Document 3
477.40 -Searchable Keys:
477.41 - class : SMTPServer
477.42 - class-ig : smtpserver
477.43 - in : smtpd
477.44 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;localaddr,remoteaddr;
477.45 - member : process_message;F;|DOCUMENTED|DOC_ONLY|;peer,mailfrom,rcpttos,data;
477.46 -
477.47 -Not Searchable Keys:
477.48 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
477.49 -
477.50 -
477.51 -Document 4
477.52 -Searchable Keys:
477.53 - item : DebuggingServer;C;|DOCUMENTED|DOC_ONLY|;
477.54 - item : MailmanProxy;C;|DOCUMENTED|DOC_ONLY|;
477.55 - item : PureProxy;C;|DOCUMENTED|DOC_ONLY|;
477.56 - item : SMTPServer;C;|DOCUMENTED|DOC_ONLY|;
477.57 - module : smtpd
477.58 -
477.59 -Not Searchable Keys:
477.60 - modattrs : S
478.1 --- a/python.editor/test/unit/data/testfiles/rst/stdtypes.rst Sun Jan 04 13:11:53 2015 -0600
478.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
478.3 @@ -1,2662 +0,0 @@
478.4 -.. XXX: reference/datamodel and this have quite a few overlaps!
478.5 -
478.6 -
478.7 -.. _bltin-types:
478.8 -
478.9 -**************
478.10 -Built-in Types
478.11 -**************
478.12 -
478.13 -The following sections describe the standard types that are built into the
478.14 -interpreter.
478.15 -
478.16 -.. note::
478.17 -
478.18 - Historically (until release 2.2), Python's built-in types have differed from
478.19 - user-defined types because it was not possible to use the built-in types as the
478.20 - basis for object-oriented inheritance. This limitation no longer
478.21 - exists.
478.22 -
478.23 -.. index:: pair: built-in; types
478.24 -
478.25 -The principal built-in types are numerics, sequences, mappings, files, classes,
478.26 -instances and exceptions.
478.27 -
478.28 -.. index:: statement: print
478.29 -
478.30 -Some operations are supported by several object types; in particular,
478.31 -practically all objects can be compared, tested for truth value, and converted
478.32 -to a string (with the :func:`repr` function or the slightly different
478.33 -:func:`str` function). The latter function is implicitly used when an object is
478.34 -written by the :func:`print` function.
478.35 -
478.36 -
478.37 -.. _truth:
478.38 -
478.39 -Truth Value Testing
478.40 -===================
478.41 -
478.42 -.. index::
478.43 - statement: if
478.44 - statement: while
478.45 - pair: truth; value
478.46 - pair: Boolean; operations
478.47 - single: false
478.48 -
478.49 -Any object can be tested for truth value, for use in an :keyword:`if` or
478.50 -:keyword:`while` condition or as operand of the Boolean operations below. The
478.51 -following values are considered false:
478.52 -
478.53 - .. index:: single: None (Built-in object)
478.54 -
478.55 -* ``None``
478.56 -
478.57 - .. index:: single: False (Built-in object)
478.58 -
478.59 -* ``False``
478.60 -
478.61 -* zero of any numeric type, for example, ``0``, ``0L``, ``0.0``, ``0j``.
478.62 -
478.63 -* any empty sequence, for example, ``''``, ``()``, ``[]``.
478.64 -
478.65 -* any empty mapping, for example, ``{}``.
478.66 -
478.67 -* instances of user-defined classes, if the class defines a :meth:`__nonzero__`
478.68 - or :meth:`__len__` method, when that method returns the integer zero or
478.69 - :class:`bool` value ``False``. [#]_
478.70 -
478.71 -.. index:: single: true
478.72 -
478.73 -All other values are considered true --- so objects of many types are always
478.74 -true.
478.75 -
478.76 -.. index::
478.77 - operator: or
478.78 - operator: and
478.79 - single: False
478.80 - single: True
478.81 -
478.82 -Operations and built-in functions that have a Boolean result always return ``0``
478.83 -or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
478.84 -(Important exception: the Boolean operations ``or`` and ``and`` always return
478.85 -one of their operands.)
478.86 -
478.87 -
478.88 -.. _boolean:
478.89 -
478.90 -Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
478.91 -====================================================================
478.92 -
478.93 -.. index:: pair: Boolean; operations
478.94 -
478.95 -These are the Boolean operations, ordered by ascending priority:
478.96 -
478.97 -+-------------+---------------------------------+-------+
478.98 -| Operation | Result | Notes |
478.99 -+=============+=================================+=======+
478.100 -| ``x or y`` | if *x* is false, then *y*, else | \(1) |
478.101 -| | *x* | |
478.102 -+-------------+---------------------------------+-------+
478.103 -| ``x and y`` | if *x* is false, then *x*, else | \(2) |
478.104 -| | *y* | |
478.105 -+-------------+---------------------------------+-------+
478.106 -| ``not x`` | if *x* is false, then ``True``, | \(3) |
478.107 -| | else ``False`` | |
478.108 -+-------------+---------------------------------+-------+
478.109 -
478.110 -.. index::
478.111 - operator: and
478.112 - operator: or
478.113 - operator: not
478.114 -
478.115 -Notes:
478.116 -
478.117 -(1)
478.118 - This is a short-circuit operator, so it only evaluates the second
478.119 - argument if the first one is :const:`False`.
478.120 -
478.121 -(2)
478.122 - This is a short-circuit operator, so it only evaluates the second
478.123 - argument if the first one is :const:`True`.
478.124 -
478.125 -(3)
478.126 - ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
478.127 - interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
478.128 -
478.129 -
478.130 -.. _stdcomparisons:
478.131 -
478.132 -Comparisons
478.133 -===========
478.134 -
478.135 -.. index:: pair: chaining; comparisons
478.136 -
478.137 -Comparison operations are supported by all objects. They all have the same
478.138 -priority (which is higher than that of the Boolean operations). Comparisons can
478.139 -be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
478.140 -y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
478.141 -evaluated at all when ``x < y`` is found to be false).
478.142 -
478.143 -This table summarizes the comparison operations:
478.144 -
478.145 -+------------+-------------------------+-------+
478.146 -| Operation | Meaning | Notes |
478.147 -+============+=========================+=======+
478.148 -| ``<`` | strictly less than | |
478.149 -+------------+-------------------------+-------+
478.150 -| ``<=`` | less than or equal | |
478.151 -+------------+-------------------------+-------+
478.152 -| ``>`` | strictly greater than | |
478.153 -+------------+-------------------------+-------+
478.154 -| ``>=`` | greater than or equal | |
478.155 -+------------+-------------------------+-------+
478.156 -| ``==`` | equal | |
478.157 -+------------+-------------------------+-------+
478.158 -| ``!=`` | not equal | \(1) |
478.159 -+------------+-------------------------+-------+
478.160 -| ``is`` | object identity | |
478.161 -+------------+-------------------------+-------+
478.162 -| ``is not`` | negated object identity | |
478.163 -+------------+-------------------------+-------+
478.164 -
478.165 -.. index::
478.166 - pair: operator; comparison
478.167 - operator: ==
478.168 - operator: <
478.169 - operator: <=
478.170 - operator: >
478.171 - operator: >=
478.172 - operator: !=
478.173 - operator: is
478.174 - operator: is not
478.175 -
478.176 -Notes:
478.177 -
478.178 -(1)
478.179 - ``!=`` can also be written ``<>``, but this is an obsolete usage
478.180 - kept for backwards compatibility only. New code should always use
478.181 - ``!=``.
478.182 -
478.183 -.. index::
478.184 - pair: object; numeric
478.185 - pair: objects; comparing
478.186 -
478.187 -Objects of different types, except different numeric types and different string
478.188 -types, never compare equal; such objects are ordered consistently but
478.189 -arbitrarily (so that sorting a heterogeneous array yields a consistent result).
478.190 -Furthermore, some types (for example, file objects) support only a degenerate
478.191 -notion of comparison where any two objects of that type are unequal. Again,
478.192 -such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>``
478.193 -and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is
478.194 -a complex number.
478.195 -
478.196 -.. index:: single: __cmp__() (instance method)
478.197 -
478.198 -Instances of a class normally compare as non-equal unless the class defines the
478.199 -:meth:`__cmp__` method. Refer to :ref:`customization`) for information on the
478.200 -use of this method to effect object comparisons.
478.201 -
478.202 -**Implementation note:** Objects of different types except numbers are ordered
478.203 -by their type names; objects of the same types that don't support proper
478.204 -comparison are ordered by their address.
478.205 -
478.206 -.. index::
478.207 - operator: in
478.208 - operator: not in
478.209 -
478.210 -Two more operations with the same syntactic priority, ``in`` and ``not in``, are
478.211 -supported only by sequence types (below).
478.212 -
478.213 -
478.214 -.. _typesnumeric:
478.215 -
478.216 -Numeric Types --- :class:`int`, :class:`float`, :class:`long`, :class:`complex`
478.217 -===============================================================================
478.218 -
478.219 -.. index::
478.220 - object: numeric
478.221 - object: Boolean
478.222 - object: integer
478.223 - object: long integer
478.224 - object: floating point
478.225 - object: complex number
478.226 - pair: C; language
478.227 -
478.228 -There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long
478.229 -integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In
478.230 -addition, Booleans are a subtype of plain integers. Plain integers (also just
478.231 -called :dfn:`integers`) are implemented using :ctype:`long` in C, which gives
478.232 -them at least 32 bits of precision (``sys.maxint`` is always set to the maximum
478.233 -plain integer value for the current platform, the minimum value is
478.234 -``-sys.maxint - 1``). Long integers have unlimited precision. Floating point
478.235 -numbers are implemented using :ctype:`double` in C. All bets on their precision
478.236 -are off unless you happen to know the machine you are working with.
478.237 -
478.238 -Complex numbers have a real and imaginary part, which are each implemented using
478.239 -:ctype:`double` in C. To extract these parts from a complex number *z*, use
478.240 -``z.real`` and ``z.imag``.
478.241 -
478.242 -.. index::
478.243 - pair: numeric; literals
478.244 - pair: integer; literals
478.245 - triple: long; integer; literals
478.246 - pair: floating point; literals
478.247 - pair: complex number; literals
478.248 - pair: hexadecimal; literals
478.249 - pair: octal; literals
478.250 -
478.251 -Numbers are created by numeric literals or as the result of built-in functions
478.252 -and operators. Unadorned integer literals (including hex and octal numbers)
478.253 -yield plain integers unless the value they denote is too large to be represented
478.254 -as a plain integer, in which case they yield a long integer. Integer literals
478.255 -with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'`` is preferred
478.256 -because ``1l`` looks too much like eleven!). Numeric literals containing a
478.257 -decimal point or an exponent sign yield floating point numbers. Appending
478.258 -``'j'`` or ``'J'`` to a numeric literal yields a complex number with a zero real
478.259 -part. A complex numeric literal is the sum of a real and an imaginary part.
478.260 -
478.261 -.. index::
478.262 - single: arithmetic
478.263 - builtin: int
478.264 - builtin: long
478.265 - builtin: float
478.266 - builtin: complex
478.267 -
478.268 -Python fully supports mixed arithmetic: when a binary arithmetic operator has
478.269 -operands of different numeric types, the operand with the "narrower" type is
478.270 -widened to that of the other, where plain integer is narrower than long integer
478.271 -is narrower than floating point is narrower than complex. Comparisons between
478.272 -numbers of mixed type use the same rule. [#]_ The constructors :func:`int`,
478.273 -:func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers
478.274 -of a specific type.
478.275 -
478.276 -All builtin numeric types support the following operations. See
478.277 -:ref:`power` and later sections for the operators' priorities.
478.278 -
478.279 -+--------------------+---------------------------------+--------+
478.280 -| Operation | Result | Notes |
478.281 -+====================+=================================+========+
478.282 -| ``x + y`` | sum of *x* and *y* | |
478.283 -+--------------------+---------------------------------+--------+
478.284 -| ``x - y`` | difference of *x* and *y* | |
478.285 -+--------------------+---------------------------------+--------+
478.286 -| ``x * y`` | product of *x* and *y* | |
478.287 -+--------------------+---------------------------------+--------+
478.288 -| ``x / y`` | quotient of *x* and *y* | \(1) |
478.289 -+--------------------+---------------------------------+--------+
478.290 -| ``x // y`` | (floored) quotient of *x* and | (4)(5) |
478.291 -| | *y* | |
478.292 -+--------------------+---------------------------------+--------+
478.293 -| ``x % y`` | remainder of ``x / y`` | \(4) |
478.294 -+--------------------+---------------------------------+--------+
478.295 -| ``-x`` | *x* negated | |
478.296 -+--------------------+---------------------------------+--------+
478.297 -| ``+x`` | *x* unchanged | |
478.298 -+--------------------+---------------------------------+--------+
478.299 -| ``abs(x)`` | absolute value or magnitude of | \(3) |
478.300 -| | *x* | |
478.301 -+--------------------+---------------------------------+--------+
478.302 -| ``int(x)`` | *x* converted to integer | \(2) |
478.303 -+--------------------+---------------------------------+--------+
478.304 -| ``long(x)`` | *x* converted to long integer | \(2) |
478.305 -+--------------------+---------------------------------+--------+
478.306 -| ``float(x)`` | *x* converted to floating point | \(6) |
478.307 -+--------------------+---------------------------------+--------+
478.308 -| ``complex(re,im)`` | a complex number with real part | |
478.309 -| | *re*, imaginary part *im*. | |
478.310 -| | *im* defaults to zero. | |
478.311 -+--------------------+---------------------------------+--------+
478.312 -| ``c.conjugate()`` | conjugate of the complex number | |
478.313 -| | *c*. (Identity on real numbers) | |
478.314 -+--------------------+---------------------------------+--------+
478.315 -| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) |
478.316 -+--------------------+---------------------------------+--------+
478.317 -| ``pow(x, y)`` | *x* to the power *y* | (3)(7) |
478.318 -+--------------------+---------------------------------+--------+
478.319 -| ``x ** y`` | *x* to the power *y* | \(7) |
478.320 -+--------------------+---------------------------------+--------+
478.321 -
478.322 -.. index::
478.323 - triple: operations on; numeric; types
478.324 - single: conjugate() (complex number method)
478.325 -
478.326 -Notes:
478.327 -
478.328 -(1)
478.329 - .. index::
478.330 - pair: integer; division
478.331 - triple: long; integer; division
478.332 -
478.333 - For (plain or long) integer division, the result is an integer. The result is
478.334 - always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
478.335 - (-1)/(-2) is 0. Note that the result is a long integer if either operand is a
478.336 - long integer, regardless of the numeric value.
478.337 -
478.338 -(2)
478.339 - .. index::
478.340 - module: math
478.341 - single: floor() (in module math)
478.342 - single: ceil() (in module math)
478.343 - pair: numeric; conversions
478.344 - pair: C; language
478.345 -
478.346 - Conversion from floating point to (long or plain) integer may round or
478.347 - truncate as in C; see functions :func:`math.floor` and :func:`math.ceil` for
478.348 - well-defined conversions.
478.349 -
478.350 - .. deprecated:: 2.6
478.351 - Instead, convert floats to long explicitly with :func:`trunc`.
478.352 -
478.353 -(3)
478.354 - See :ref:`built-in-funcs` for a full description.
478.355 -
478.356 -(4)
478.357 - Complex floor division operator, modulo operator, and :func:`divmod`.
478.358 -
478.359 - .. deprecated:: 2.3
478.360 - Instead convert to float using :func:`abs` if appropriate.
478.361 -
478.362 -(5)
478.363 - Also referred to as integer division. The resultant value is a whole integer,
478.364 - though the result's type is not necessarily int.
478.365 -
478.366 -(6)
478.367 - float also accepts the strings "nan" and "inf" with an optional prefix "+"
478.368 - or "-" for Not a Number (NaN) and positive or negative infinity.
478.369 -
478.370 - .. versionadded:: 2.6
478.371 -
478.372 -(7)
478.373 - Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
478.374 - programming languages.
478.375 -
478.376 -All :class:`numbers.Real` types (:class:`int`, :class:`long`, and
478.377 -:class:`float`) also include the following operations:
478.378 -
478.379 -+--------------------+------------------------------------+--------+
478.380 -| Operation | Result | Notes |
478.381 -+====================+====================================+========+
478.382 -| ``trunc(x)`` | *x* truncated to Integral | |
478.383 -+--------------------+------------------------------------+--------+
478.384 -| ``round(x[, n])`` | *x* rounded to n digits, | |
478.385 -| | rounding half to even. If n is | |
478.386 -| | omitted, it defaults to 0. | |
478.387 -+--------------------+------------------------------------+--------+
478.388 -| ``math.floor(x)`` | the greatest integral float <= *x* | |
478.389 -+--------------------+------------------------------------+--------+
478.390 -| ``math.ceil(x)`` | the least integral float >= *x* | |
478.391 -+--------------------+------------------------------------+--------+
478.392 -
478.393 -.. XXXJH exceptions: overflow (when? what operations?) zerodivision
478.394 -
478.395 -
478.396 -.. _bitstring-ops:
478.397 -
478.398 -Bit-string Operations on Integer Types
478.399 ---------------------------------------
478.400 -
478.401 -.. _bit-string-operations:
478.402 -
478.403 -Plain and long integer types support additional operations that make sense only
478.404 -for bit-strings. Negative numbers are treated as their 2's complement value
478.405 -(for long integers, this assumes a sufficiently large number of bits that no
478.406 -overflow occurs during the operation).
478.407 -
478.408 -The priorities of the binary bitwise operations are all lower than the numeric
478.409 -operations and higher than the comparisons; the unary operation ``~`` has the
478.410 -same priority as the other unary numeric operations (``+`` and ``-``).
478.411 -
478.412 -This table lists the bit-string operations sorted in ascending priority:
478.413 -
478.414 -+------------+--------------------------------+----------+
478.415 -| Operation | Result | Notes |
478.416 -+============+================================+==========+
478.417 -| ``x | y`` | bitwise :dfn:`or` of *x* and | |
478.418 -| | *y* | |
478.419 -+------------+--------------------------------+----------+
478.420 -| ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
478.421 -| | *x* and *y* | |
478.422 -+------------+--------------------------------+----------+
478.423 -| ``x & y`` | bitwise :dfn:`and` of *x* and | |
478.424 -| | *y* | |
478.425 -+------------+--------------------------------+----------+
478.426 -| ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
478.427 -+------------+--------------------------------+----------+
478.428 -| ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
478.429 -+------------+--------------------------------+----------+
478.430 -| ``~x`` | the bits of *x* inverted | |
478.431 -+------------+--------------------------------+----------+
478.432 -
478.433 -.. index::
478.434 - triple: operations on; integer; types
478.435 - pair: bit-string; operations
478.436 - pair: shifting; operations
478.437 - pair: masking; operations
478.438 -
478.439 -Notes:
478.440 -
478.441 -(1)
478.442 - Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
478.443 -
478.444 -(2)
478.445 - A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``. A
478.446 - long integer is returned if the result exceeds the range of plain integers.
478.447 -
478.448 -(3)
478.449 - A right shift by *n* bits is equivalent to division by ``pow(2, n)``.
478.450 -
478.451 -
478.452 -Additional Methods on Float
478.453 ----------------------------
478.454 -
478.455 -The float type has some additional methods.
478.456 -
478.457 -.. method:: float.as_integer_ratio()
478.458 -
478.459 - Return a pair of integers whose ratio is exactly equal to the
478.460 - original float and with a positive denominator. Raises
478.461 - :exc:`OverflowError` on infinities and a :exc:`ValueError` on
478.462 - NaNs.
478.463 -
478.464 - .. versionadded:: 2.6
478.465 -
478.466 -Two methods support conversion to
478.467 -and from hexadecimal strings. Since Python's floats are stored
478.468 -internally as binary numbers, converting a float to or from a
478.469 -*decimal* string usually involves a small rounding error. In
478.470 -contrast, hexadecimal strings allow exact representation and
478.471 -specification of floating-point numbers. This can be useful when
478.472 -debugging, and in numerical work.
478.473 -
478.474 -
478.475 -.. method:: float.hex()
478.476 -
478.477 - Return a representation of a floating-point number as a hexadecimal
478.478 - string. For finite floating-point numbers, this representation
478.479 - will always include a leading ``0x`` and a trailing ``p`` and
478.480 - exponent.
478.481 -
478.482 - .. versionadded:: 2.6
478.483 -
478.484 -
478.485 -.. method:: float.fromhex(s)
478.486 -
478.487 - Class method to return the float represented by a hexadecimal
478.488 - string *s*. The string *s* may have leading and trailing
478.489 - whitespace.
478.490 -
478.491 - .. versionadded:: 2.6
478.492 -
478.493 -
478.494 -Note that :meth:`float.hex` is an instance method, while
478.495 -:meth:`float.fromhex` is a class method.
478.496 -
478.497 -A hexadecimal string takes the form::
478.498 -
478.499 - [sign] ['0x'] integer ['.' fraction] ['p' exponent]
478.500 -
478.501 -where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
478.502 -and ``fraction`` are strings of hexadecimal digits, and ``exponent``
478.503 -is a decimal integer with an optional leading sign. Case is not
478.504 -significant, and there must be at least one hexadecimal digit in
478.505 -either the integer or the fraction. This syntax is similar to the
478.506 -syntax specified in section 6.4.4.2 of the C99 standard, and also to
478.507 -the syntax used in Java 1.5 onwards. In particular, the output of
478.508 -:meth:`float.hex` is usable as a hexadecimal floating-point literal in
478.509 -C or Java code, and hexadecimal strings produced by C's ``%a`` format
478.510 -character or Java's ``Double.toHexString`` are accepted by
478.511 -:meth:`float.fromhex`.
478.512 -
478.513 -
478.514 -Note that the exponent is written in decimal rather than hexadecimal,
478.515 -and that it gives the power of 2 by which to multiply the coefficient.
478.516 -For example, the hexadecimal string ``0x3.a7p10`` represents the
478.517 -floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
478.518 -``3740.0``::
478.519 -
478.520 - >>> float.fromhex('0x3.a7p10')
478.521 - 3740.0
478.522 -
478.523 -
478.524 -Applying the reverse conversion to ``3740.0`` gives a different
478.525 -hexadecimal string representing the same number::
478.526 -
478.527 - >>> float.hex(3740.0)
478.528 - '0x1.d380000000000p+11'
478.529 -
478.530 -
478.531 -.. _typeiter:
478.532 -
478.533 -Iterator Types
478.534 -==============
478.535 -
478.536 -.. versionadded:: 2.2
478.537 -
478.538 -.. index::
478.539 - single: iterator protocol
478.540 - single: protocol; iterator
478.541 - single: sequence; iteration
478.542 - single: container; iteration over
478.543 -
478.544 -Python supports a concept of iteration over containers. This is implemented
478.545 -using two distinct methods; these are used to allow user-defined classes to
478.546 -support iteration. Sequences, described below in more detail, always support
478.547 -the iteration methods.
478.548 -
478.549 -One method needs to be defined for container objects to provide iteration
478.550 -support:
478.551 -
478.552 -.. XXX duplicated in reference/datamodel!
478.553 -
478.554 -.. method:: container.__iter__()
478.555 -
478.556 - Return an iterator object. The object is required to support the iterator
478.557 - protocol described below. If a container supports different types of
478.558 - iteration, additional methods can be provided to specifically request
478.559 - iterators for those iteration types. (An example of an object supporting
478.560 - multiple forms of iteration would be a tree structure which supports both
478.561 - breadth-first and depth-first traversal.) This method corresponds to the
478.562 - :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
478.563 - API.
478.564 -
478.565 -The iterator objects themselves are required to support the following two
478.566 -methods, which together form the :dfn:`iterator protocol`:
478.567 -
478.568 -
478.569 -.. method:: iterator.__iter__()
478.570 -
478.571 - Return the iterator object itself. This is required to allow both containers
478.572 - and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
478.573 - This method corresponds to the :attr:`tp_iter` slot of the type structure for
478.574 - Python objects in the Python/C API.
478.575 -
478.576 -
478.577 -.. method:: iterator.next()
478.578 -
478.579 - Return the next item from the container. If there are no further items, raise
478.580 - the :exc:`StopIteration` exception. This method corresponds to the
478.581 - :attr:`tp_iternext` slot of the type structure for Python objects in the
478.582 - Python/C API.
478.583 -
478.584 -Python defines several iterator objects to support iteration over general and
478.585 -specific sequence types, dictionaries, and other more specialized forms. The
478.586 -specific types are not important beyond their implementation of the iterator
478.587 -protocol.
478.588 -
478.589 -The intention of the protocol is that once an iterator's :meth:`next` method
478.590 -raises :exc:`StopIteration`, it will continue to do so on subsequent calls.
478.591 -Implementations that do not obey this property are deemed broken. (This
478.592 -constraint was added in Python 2.3; in Python 2.2, various iterators are broken
478.593 -according to this rule.)
478.594 -
478.595 -Python's :term:`generator`\s provide a convenient way to implement the iterator
478.596 -protocol. If a container object's :meth:`__iter__` method is implemented as a
478.597 -generator, it will automatically return an iterator object (technically, a
478.598 -generator object) supplying the :meth:`__iter__` and :meth:`next` methods.
478.599 -
478.600 -
478.601 -.. _typesseq:
478.602 -
478.603 -Sequence Types --- :class:`str`, :class:`unicode`, :class:`list`, :class:`tuple`, :class:`buffer`, :class:`xrange`
478.604 -==================================================================================================================
478.605 -
478.606 -There are six sequence types: strings, Unicode strings, lists, tuples, buffers,
478.607 -and xrange objects.
478.608 -(For other containers see the built in :class:`dict`, :class:`list`,
478.609 -:class:`set`, and :class:`tuple` classes, and the :mod:`collections`
478.610 -module.)
478.611 -
478.612 -
478.613 -.. index::
478.614 - object: sequence
478.615 - object: string
478.616 - object: Unicode
478.617 - object: tuple
478.618 - object: list
478.619 - object: buffer
478.620 - object: xrange
478.621 -
478.622 -String literals are written in single or double quotes: ``'xyzzy'``,
478.623 -``"frobozz"``. See :ref:`strings` for more about string literals.
478.624 -Unicode strings are much like strings, but are specified in the syntax
478.625 -using a preceding ``'u'`` character: ``u'abc'``, ``u"def"``. In addition
478.626 -to the functionality described here, there are also string-specific
478.627 -methods described in the :ref:`string-methods` section. Lists are
478.628 -constructed with square brackets, separating items with commas: ``[a, b, c]``.
478.629 -Tuples are constructed by the comma operator (not within square
478.630 -brackets), with or without enclosing parentheses, but an empty tuple
478.631 -must have the enclosing parentheses, such as ``a, b, c`` or ``()``. A
478.632 -single item tuple must have a trailing comma, such as ``(d,)``.
478.633 -
478.634 -Buffer objects are not directly supported by Python syntax, but can be created
478.635 -by calling the builtin function :func:`buffer`. They don't support
478.636 -concatenation or repetition.
478.637 -
478.638 -Objects of type xrange are similar to buffers in that there is no specific syntax to
478.639 -create them, but they are created using the :func:`xrange` function. They don't
478.640 -support slicing, concatenation or repetition, and using ``in``, ``not in``,
478.641 -:func:`min` or :func:`max` on them is inefficient.
478.642 -
478.643 -Most sequence types support the following operations. The ``in`` and ``not in``
478.644 -operations have the same priorities as the comparison operations. The ``+`` and
478.645 -``*`` operations have the same priority as the corresponding numeric operations.
478.646 -[#]_ Additional methods are provided for :ref:`typesseq-mutable`.
478.647 -
478.648 -This table lists the sequence operations sorted in ascending priority
478.649 -(operations in the same box have the same priority). In the table, *s* and *t*
478.650 -are sequences of the same type; *n*, *i* and *j* are integers:
478.651 -
478.652 -+------------------+--------------------------------+----------+
478.653 -| Operation | Result | Notes |
478.654 -+==================+================================+==========+
478.655 -| ``x in s`` | ``True`` if an item of *s* is | \(1) |
478.656 -| | equal to *x*, else ``False`` | |
478.657 -+------------------+--------------------------------+----------+
478.658 -| ``x not in s`` | ``False`` if an item of *s* is | \(1) |
478.659 -| | equal to *x*, else ``True`` | |
478.660 -+------------------+--------------------------------+----------+
478.661 -| ``s + t`` | the concatenation of *s* and | \(6) |
478.662 -| | *t* | |
478.663 -+------------------+--------------------------------+----------+
478.664 -| ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
478.665 -| | concatenated | |
478.666 -+------------------+--------------------------------+----------+
478.667 -| ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
478.668 -+------------------+--------------------------------+----------+
478.669 -| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
478.670 -+------------------+--------------------------------+----------+
478.671 -| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
478.672 -| | with step *k* | |
478.673 -+------------------+--------------------------------+----------+
478.674 -| ``len(s)`` | length of *s* | |
478.675 -+------------------+--------------------------------+----------+
478.676 -| ``min(s)`` | smallest item of *s* | |
478.677 -+------------------+--------------------------------+----------+
478.678 -| ``max(s)`` | largest item of *s* | |
478.679 -+------------------+--------------------------------+----------+
478.680 -
478.681 -Sequence types also support comparisons. In particular, tuples and lists
478.682 -are compared lexicographically by comparing corresponding
478.683 -elements. This means that to compare equal, every element must compare
478.684 -equal and the two sequences must be of the same type and have the same
478.685 -length. (For full details see :ref:`comparisons` in the language
478.686 -reference.)
478.687 -
478.688 -.. index::
478.689 - triple: operations on; sequence; types
478.690 - builtin: len
478.691 - builtin: min
478.692 - builtin: max
478.693 - pair: concatenation; operation
478.694 - pair: repetition; operation
478.695 - pair: subscript; operation
478.696 - pair: slice; operation
478.697 - pair: extended slice; operation
478.698 - operator: in
478.699 - operator: not in
478.700 -
478.701 -Notes:
478.702 -
478.703 -(1)
478.704 - When *s* is a string or Unicode string object the ``in`` and ``not in``
478.705 - operations act like a substring test. In Python versions before 2.3, *x* had to
478.706 - be a string of length 1. In Python 2.3 and beyond, *x* may be a string of any
478.707 - length.
478.708 -
478.709 -(2)
478.710 - Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
478.711 - sequence of the same type as *s*). Note also that the copies are shallow;
478.712 - nested structures are not copied. This often haunts new Python programmers;
478.713 - consider:
478.714 -
478.715 - >>> lists = [[]] * 3
478.716 - >>> lists
478.717 - [[], [], []]
478.718 - >>> lists[0].append(3)
478.719 - >>> lists
478.720 - [[3], [3], [3]]
478.721 -
478.722 - What has happened is that ``[[]]`` is a one-element list containing an empty
478.723 - list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
478.724 - list. Modifying any of the elements of ``lists`` modifies this single list.
478.725 - You can create a list of different lists this way:
478.726 -
478.727 - >>> lists = [[] for i in range(3)]
478.728 - >>> lists[0].append(3)
478.729 - >>> lists[1].append(5)
478.730 - >>> lists[2].append(7)
478.731 - >>> lists
478.732 - [[3], [5], [7]]
478.733 -
478.734 -(3)
478.735 - If *i* or *j* is negative, the index is relative to the end of the string:
478.736 - ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is still
478.737 - ``0``.
478.738 -
478.739 -(4)
478.740 - The slice of *s* from *i* to *j* is defined as the sequence of items with index
478.741 - *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
478.742 - ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
478.743 - ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
478.744 - empty.
478.745 -
478.746 -(5)
478.747 - The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
478.748 - items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
478.749 - the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
478.750 - *j* is reached (but never including *j*). If *i* or *j* is greater than
478.751 - ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become
478.752 - "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
478.753 - If *k* is ``None``, it is treated like ``1``.
478.754 -
478.755 -(6)
478.756 - If *s* and *t* are both strings, some Python implementations such as CPython can
478.757 - usually perform an in-place optimization for assignments of the form ``s=s+t``
478.758 - or ``s+=t``. When applicable, this optimization makes quadratic run-time much
478.759 - less likely. This optimization is both version and implementation dependent.
478.760 - For performance sensitive code, it is preferable to use the :meth:`str.join`
478.761 - method which assures consistent linear concatenation performance across versions
478.762 - and implementations.
478.763 -
478.764 - .. versionchanged:: 2.4
478.765 - Formerly, string concatenation never occurred in-place.
478.766 -
478.767 -
478.768 -.. _string-methods:
478.769 -
478.770 -String Methods
478.771 ---------------
478.772 -
478.773 -.. index:: pair: string; methods
478.774 -
478.775 -Below are listed the string methods which both 8-bit strings and Unicode objects
478.776 -support. Note that none of these methods take keyword arguments.
478.777 -
478.778 -In addition, Python's strings support the sequence type methods
478.779 -described in the :ref:`typesseq` section. To output formatted strings
478.780 -use template strings or the ``%`` operator described in the
478.781 -:ref:`string-formatting` section. Also, see the :mod:`re` module for
478.782 -string functions based on regular expressions.
478.783 -
478.784 -.. method:: str.capitalize()
478.785 -
478.786 - Return a copy of the string with only its first character capitalized.
478.787 -
478.788 - For 8-bit strings, this method is locale-dependent.
478.789 -
478.790 -
478.791 -.. method:: str.center(width[, fillchar])
478.792 -
478.793 - Return centered in a string of length *width*. Padding is done using the
478.794 - specified *fillchar* (default is a space).
478.795 -
478.796 - .. versionchanged:: 2.4
478.797 - Support for the *fillchar* argument.
478.798 -
478.799 -
478.800 -.. method:: str.count(sub[, start[, end]])
478.801 -
478.802 - Return the number of occurrences of substring *sub* in the range [*start*,
478.803 - *end*]. Optional arguments *start* and *end* are interpreted as in slice
478.804 - notation.
478.805 -
478.806 -
478.807 -.. method:: str.decode([encoding[, errors]])
478.808 -
478.809 - Decodes the string using the codec registered for *encoding*. *encoding*
478.810 - defaults to the default string encoding. *errors* may be given to set a
478.811 - different error handling scheme. The default is ``'strict'``, meaning that
478.812 - encoding errors raise :exc:`UnicodeError`. Other possible values are
478.813 - ``'ignore'``, ``'replace'`` and any other name registered via
478.814 - :func:`codecs.register_error`, see section :ref:`codec-base-classes`.
478.815 -
478.816 - .. versionadded:: 2.2
478.817 -
478.818 - .. versionchanged:: 2.3
478.819 - Support for other error handling schemes added.
478.820 -
478.821 -
478.822 -.. method:: str.encode([encoding[,errors]])
478.823 -
478.824 - Return an encoded version of the string. Default encoding is the current
478.825 - default string encoding. *errors* may be given to set a different error
478.826 - handling scheme. The default for *errors* is ``'strict'``, meaning that
478.827 - encoding errors raise a :exc:`UnicodeError`. Other possible values are
478.828 - ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and
478.829 - any other name registered via :func:`codecs.register_error`, see section
478.830 - :ref:`codec-base-classes`. For a list of possible encodings, see section
478.831 - :ref:`standard-encodings`.
478.832 -
478.833 - .. versionadded:: 2.0
478.834 -
478.835 - .. versionchanged:: 2.3
478.836 - Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other error
478.837 - handling schemes added.
478.838 -
478.839 -
478.840 -.. method:: str.endswith(suffix[, start[, end]])
478.841 -
478.842 - Return ``True`` if the string ends with the specified *suffix*, otherwise return
478.843 - ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
478.844 - *start*, test beginning at that position. With optional *end*, stop comparing
478.845 - at that position.
478.846 -
478.847 - .. versionchanged:: 2.5
478.848 - Accept tuples as *suffix*.
478.849 -
478.850 -
478.851 -.. method:: str.expandtabs([tabsize])
478.852 -
478.853 - Return a copy of the string where all tab characters are replaced by one or
478.854 - more spaces, depending on the current column and the given tab size. The
478.855 - column number is reset to zero after each newline occurring in the string.
478.856 - If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
478.857 - doesn't understand other non-printing characters or escape sequences.
478.858 -
478.859 -
478.860 -.. method:: str.find(sub[, start[, end]])
478.861 -
478.862 - Return the lowest index in the string where substring *sub* is found, such that
478.863 - *sub* is contained in the range [*start*, *end*]. Optional arguments *start*
478.864 - and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not
478.865 - found.
478.866 -
478.867 -
478.868 -.. method:: str.format(format_string, *args, **kwargs)
478.869 -
478.870 - Perform a string formatting operation. The *format_string* argument can
478.871 - contain literal text or replacement fields delimited by braces ``{}``. Each
478.872 - replacement field contains either the numeric index of a positional argument,
478.873 - or the name of a keyword argument. Returns a copy of *format_string* where
478.874 - each replacement field is replaced with the string value of the corresponding
478.875 - argument.
478.876 -
478.877 - >>> "The sum of 1 + 2 is {0}".format(1+2)
478.878 - 'The sum of 1 + 2 is 3'
478.879 -
478.880 - See :ref:`formatstrings` for a description of the various formatting options
478.881 - that can be specified in format strings.
478.882 -
478.883 - This method of string formatting is the new standard in Python 3.0, and
478.884 - should be preferred to the ``%`` formatting described in
478.885 - :ref:`string-formatting` in new code.
478.886 -
478.887 - .. versionadded:: 2.6
478.888 -
478.889 -
478.890 -.. method:: str.index(sub[, start[, end]])
478.891 -
478.892 - Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
478.893 -
478.894 -
478.895 -.. method:: str.isalnum()
478.896 -
478.897 - Return true if all characters in the string are alphanumeric and there is at
478.898 - least one character, false otherwise.
478.899 -
478.900 - For 8-bit strings, this method is locale-dependent.
478.901 -
478.902 -
478.903 -.. method:: str.isalpha()
478.904 -
478.905 - Return true if all characters in the string are alphabetic and there is at least
478.906 - one character, false otherwise.
478.907 -
478.908 - For 8-bit strings, this method is locale-dependent.
478.909 -
478.910 -
478.911 -.. method:: str.isdigit()
478.912 -
478.913 - Return true if all characters in the string are digits and there is at least one
478.914 - character, false otherwise.
478.915 -
478.916 - For 8-bit strings, this method is locale-dependent.
478.917 -
478.918 -
478.919 -.. method:: str.islower()
478.920 -
478.921 - Return true if all cased characters in the string are lowercase and there is at
478.922 - least one cased character, false otherwise.
478.923 -
478.924 - For 8-bit strings, this method is locale-dependent.
478.925 -
478.926 -
478.927 -.. method:: str.isspace()
478.928 -
478.929 - Return true if there are only whitespace characters in the string and there is
478.930 - at least one character, false otherwise.
478.931 -
478.932 - For 8-bit strings, this method is locale-dependent.
478.933 -
478.934 -
478.935 -.. method:: str.istitle()
478.936 -
478.937 - Return true if the string is a titlecased string and there is at least one
478.938 - character, for example uppercase characters may only follow uncased characters
478.939 - and lowercase characters only cased ones. Return false otherwise.
478.940 -
478.941 - For 8-bit strings, this method is locale-dependent.
478.942 -
478.943 -
478.944 -.. method:: str.isupper()
478.945 -
478.946 - Return true if all cased characters in the string are uppercase and there is at
478.947 - least one cased character, false otherwise.
478.948 -
478.949 - For 8-bit strings, this method is locale-dependent.
478.950 -
478.951 -
478.952 -.. method:: str.join(seq)
478.953 -
478.954 - Return a string which is the concatenation of the strings in the sequence *seq*.
478.955 - The separator between elements is the string providing this method.
478.956 -
478.957 -
478.958 -.. method:: str.ljust(width[, fillchar])
478.959 -
478.960 - Return the string left justified in a string of length *width*. Padding is done
478.961 - using the specified *fillchar* (default is a space). The original string is
478.962 - returned if *width* is less than ``len(s)``.
478.963 -
478.964 - .. versionchanged:: 2.4
478.965 - Support for the *fillchar* argument.
478.966 -
478.967 -
478.968 -.. method:: str.lower()
478.969 -
478.970 - Return a copy of the string converted to lowercase.
478.971 -
478.972 - For 8-bit strings, this method is locale-dependent.
478.973 -
478.974 -
478.975 -.. method:: str.lstrip([chars])
478.976 -
478.977 - Return a copy of the string with leading characters removed. The *chars*
478.978 - argument is a string specifying the set of characters to be removed. If omitted
478.979 - or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
478.980 - argument is not a prefix; rather, all combinations of its values are stripped:
478.981 -
478.982 - >>> ' spacious '.lstrip()
478.983 - 'spacious '
478.984 - >>> 'www.example.com'.lstrip('cmowz.')
478.985 - 'example.com'
478.986 -
478.987 - .. versionchanged:: 2.2.2
478.988 - Support for the *chars* argument.
478.989 -
478.990 -
478.991 -.. method:: str.partition(sep)
478.992 -
478.993 - Split the string at the first occurrence of *sep*, and return a 3-tuple
478.994 - containing the part before the separator, the separator itself, and the part
478.995 - after the separator. If the separator is not found, return a 3-tuple containing
478.996 - the string itself, followed by two empty strings.
478.997 -
478.998 - .. versionadded:: 2.5
478.999 -
478.1000 -
478.1001 -.. method:: str.replace(old, new[, count])
478.1002 -
478.1003 - Return a copy of the string with all occurrences of substring *old* replaced by
478.1004 - *new*. If the optional argument *count* is given, only the first *count*
478.1005 - occurrences are replaced.
478.1006 -
478.1007 -
478.1008 -.. method:: str.rfind(sub [,start [,end]])
478.1009 -
478.1010 - Return the highest index in the string where substring *sub* is found, such that
478.1011 - *sub* is contained within s[start,end]. Optional arguments *start* and *end*
478.1012 - are interpreted as in slice notation. Return ``-1`` on failure.
478.1013 -
478.1014 -
478.1015 -.. method:: str.rindex(sub[, start[, end]])
478.1016 -
478.1017 - Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
478.1018 - found.
478.1019 -
478.1020 -
478.1021 -.. method:: str.rjust(width[, fillchar])
478.1022 -
478.1023 - Return the string right justified in a string of length *width*. Padding is done
478.1024 - using the specified *fillchar* (default is a space). The original string is
478.1025 - returned if *width* is less than ``len(s)``.
478.1026 -
478.1027 - .. versionchanged:: 2.4
478.1028 - Support for the *fillchar* argument.
478.1029 -
478.1030 -
478.1031 -.. method:: str.rpartition(sep)
478.1032 -
478.1033 - Split the string at the last occurrence of *sep*, and return a 3-tuple
478.1034 - containing the part before the separator, the separator itself, and the part
478.1035 - after the separator. If the separator is not found, return a 3-tuple containing
478.1036 - two empty strings, followed by the string itself.
478.1037 -
478.1038 - .. versionadded:: 2.5
478.1039 -
478.1040 -
478.1041 -.. method:: str.rsplit([sep [,maxsplit]])
478.1042 -
478.1043 - Return a list of the words in the string, using *sep* as the delimiter string.
478.1044 - If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
478.1045 - ones. If *sep* is not specified or ``None``, any whitespace string is a
478.1046 - separator. Except for splitting from the right, :meth:`rsplit` behaves like
478.1047 - :meth:`split` which is described in detail below.
478.1048 -
478.1049 - .. versionadded:: 2.4
478.1050 -
478.1051 -
478.1052 -.. method:: str.rstrip([chars])
478.1053 -
478.1054 - Return a copy of the string with trailing characters removed. The *chars*
478.1055 - argument is a string specifying the set of characters to be removed. If omitted
478.1056 - or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
478.1057 - argument is not a suffix; rather, all combinations of its values are stripped:
478.1058 -
478.1059 - >>> ' spacious '.rstrip()
478.1060 - ' spacious'
478.1061 - >>> 'mississippi'.rstrip('ipz')
478.1062 - 'mississ'
478.1063 -
478.1064 - .. versionchanged:: 2.2.2
478.1065 - Support for the *chars* argument.
478.1066 -
478.1067 -
478.1068 -.. method:: str.split([sep[, maxsplit]])
478.1069 -
478.1070 - Return a list of the words in the string, using *sep* as the delimiter
478.1071 - string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
478.1072 - the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
478.1073 - specified, then there is no limit on the number of splits (all possible
478.1074 - splits are made).
478.1075 -
478.1076 - If *sep* is given, consecutive delimiters are not grouped together and are
478.1077 - deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
478.1078 - ``['1', '', '2']``). The *sep* argument may consist of multiple characters
478.1079 - (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
478.1080 - Splitting an empty string with a specified separator returns ``['']``.
478.1081 -
478.1082 - If *sep* is not specified or is ``None``, a different splitting algorithm is
478.1083 - applied: runs of consecutive whitespace are regarded as a single separator,
478.1084 - and the result will contain no empty strings at the start or end if the
478.1085 - string has leading or trailing whitespace. Consequently, splitting an empty
478.1086 - string or a string consisting of just whitespace with a ``None`` separator
478.1087 - returns ``[]``.
478.1088 -
478.1089 - For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
478.1090 - ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
478.1091 -
478.1092 -
478.1093 -.. method:: str.splitlines([keepends])
478.1094 -
478.1095 - Return a list of the lines in the string, breaking at line boundaries. Line
478.1096 - breaks are not included in the resulting list unless *keepends* is given and
478.1097 - true.
478.1098 -
478.1099 -
478.1100 -.. method:: str.startswith(prefix[, start[, end]])
478.1101 -
478.1102 - Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
478.1103 - *prefix* can also be a tuple of prefixes to look for. With optional *start*,
478.1104 - test string beginning at that position. With optional *end*, stop comparing
478.1105 - string at that position.
478.1106 -
478.1107 - .. versionchanged:: 2.5
478.1108 - Accept tuples as *prefix*.
478.1109 -
478.1110 -
478.1111 -.. method:: str.strip([chars])
478.1112 -
478.1113 - Return a copy of the string with the leading and trailing characters removed.
478.1114 - The *chars* argument is a string specifying the set of characters to be removed.
478.1115 - If omitted or ``None``, the *chars* argument defaults to removing whitespace.
478.1116 - The *chars* argument is not a prefix or suffix; rather, all combinations of its
478.1117 - values are stripped:
478.1118 -
478.1119 - >>> ' spacious '.strip()
478.1120 - 'spacious'
478.1121 - >>> 'www.example.com'.strip('cmowz.')
478.1122 - 'example'
478.1123 -
478.1124 - .. versionchanged:: 2.2.2
478.1125 - Support for the *chars* argument.
478.1126 -
478.1127 -
478.1128 -.. method:: str.swapcase()
478.1129 -
478.1130 - Return a copy of the string with uppercase characters converted to lowercase and
478.1131 - vice versa.
478.1132 -
478.1133 - For 8-bit strings, this method is locale-dependent.
478.1134 -
478.1135 -
478.1136 -.. method:: str.title()
478.1137 -
478.1138 - Return a titlecased version of the string: words start with uppercase
478.1139 - characters, all remaining cased characters are lowercase.
478.1140 -
478.1141 - For 8-bit strings, this method is locale-dependent.
478.1142 -
478.1143 -
478.1144 -.. method:: str.translate(table[, deletechars])
478.1145 -
478.1146 - Return a copy of the string where all characters occurring in the optional
478.1147 - argument *deletechars* are removed, and the remaining characters have been
478.1148 - mapped through the given translation table, which must be a string of length
478.1149 - 256.
478.1150 -
478.1151 - You can use the :func:`maketrans` helper function in the :mod:`string` module to
478.1152 - create a translation table. For string objects, set the *table* argument to
478.1153 - ``None`` for translations that only delete characters:
478.1154 -
478.1155 - >>> 'read this short text'.translate(None, 'aeiou')
478.1156 - 'rd ths shrt txt'
478.1157 -
478.1158 - .. versionadded:: 2.6
478.1159 - Support for a ``None`` *table* argument.
478.1160 -
478.1161 - For Unicode objects, the :meth:`translate` method does not accept the optional
478.1162 - *deletechars* argument. Instead, it returns a copy of the *s* where all
478.1163 - characters have been mapped through the given translation table which must be a
478.1164 - mapping of Unicode ordinals to Unicode ordinals, Unicode strings or ``None``.
478.1165 - Unmapped characters are left untouched. Characters mapped to ``None`` are
478.1166 - deleted. Note, a more flexible approach is to create a custom character mapping
478.1167 - codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
478.1168 - example).
478.1169 -
478.1170 -
478.1171 -.. method:: str.upper()
478.1172 -
478.1173 - Return a copy of the string converted to uppercase.
478.1174 -
478.1175 - For 8-bit strings, this method is locale-dependent.
478.1176 -
478.1177 -
478.1178 -.. method:: str.zfill(width)
478.1179 -
478.1180 - Return the numeric string left filled with zeros in a string of length
478.1181 - *width*. A sign prefix is handled correctly. The original string is
478.1182 - returned if *width* is less than ``len(s)``.
478.1183 -
478.1184 -
478.1185 - .. versionadded:: 2.2.2
478.1186 -
478.1187 -The following methods are present only on unicode objects:
478.1188 -
478.1189 -.. method:: unicode.isnumeric()
478.1190 -
478.1191 - Return ``True`` if there are only numeric characters in S, ``False``
478.1192 - otherwise. Numeric characters include digit characters, and all characters
478.1193 - that have the Unicode numeric value property, e.g. U+2155,
478.1194 - VULGAR FRACTION ONE FIFTH.
478.1195 -
478.1196 -.. method:: unicode.isdecimal()
478.1197 -
478.1198 - Return ``True`` if there are only decimal characters in S, ``False``
478.1199 - otherwise. Decimal characters include digit characters, and all characters
478.1200 - that that can be used to form decimal-radix numbers, e.g. U+0660,
478.1201 - ARABIC-INDIC DIGIT ZERO.
478.1202 -
478.1203 -
478.1204 -.. _string-formatting:
478.1205 -
478.1206 -String Formatting Operations
478.1207 -----------------------------
478.1208 -
478.1209 -.. index::
478.1210 - single: formatting, string (%)
478.1211 - single: interpolation, string (%)
478.1212 - single: string; formatting
478.1213 - single: string; interpolation
478.1214 - single: printf-style formatting
478.1215 - single: sprintf-style formatting
478.1216 - single: % formatting
478.1217 - single: % interpolation
478.1218 -
478.1219 -String and Unicode objects have one unique built-in operation: the ``%``
478.1220 -operator (modulo). This is also known as the string *formatting* or
478.1221 -*interpolation* operator. Given ``format % values`` (where *format* is a string
478.1222 -or Unicode object), ``%`` conversion specifications in *format* are replaced
478.1223 -with zero or more elements of *values*. The effect is similar to the using
478.1224 -:cfunc:`sprintf` in the C language. If *format* is a Unicode object, or if any
478.1225 -of the objects being converted using the ``%s`` conversion are Unicode objects,
478.1226 -the result will also be a Unicode object.
478.1227 -
478.1228 -If *format* requires a single argument, *values* may be a single non-tuple
478.1229 -object. [#]_ Otherwise, *values* must be a tuple with exactly the number of
478.1230 -items specified by the format string, or a single mapping object (for example, a
478.1231 -dictionary).
478.1232 -
478.1233 -A conversion specifier contains two or more characters and has the following
478.1234 -components, which must occur in this order:
478.1235 -
478.1236 -#. The ``'%'`` character, which marks the start of the specifier.
478.1237 -
478.1238 -#. Mapping key (optional), consisting of a parenthesised sequence of characters
478.1239 - (for example, ``(somename)``).
478.1240 -
478.1241 -#. Conversion flags (optional), which affect the result of some conversion
478.1242 - types.
478.1243 -
478.1244 -#. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
478.1245 - actual width is read from the next element of the tuple in *values*, and the
478.1246 - object to convert comes after the minimum field width and optional precision.
478.1247 -
478.1248 -#. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
478.1249 - specified as ``'*'`` (an asterisk), the actual width is read from the next
478.1250 - element of the tuple in *values*, and the value to convert comes after the
478.1251 - precision.
478.1252 -
478.1253 -#. Length modifier (optional).
478.1254 -
478.1255 -#. Conversion type.
478.1256 -
478.1257 -When the right argument is a dictionary (or other mapping type), then the
478.1258 -formats in the string *must* include a parenthesised mapping key into that
478.1259 -dictionary inserted immediately after the ``'%'`` character. The mapping key
478.1260 -selects the value to be formatted from the mapping. For example:
478.1261 -
478.1262 - >>> print '%(language)s has %(#)03d quote types.' % \
478.1263 - ... {'language': "Python", "#": 2}
478.1264 - Python has 002 quote types.
478.1265 -
478.1266 -In this case no ``*`` specifiers may occur in a format (since they require a
478.1267 -sequential parameter list).
478.1268 -
478.1269 -The conversion flag characters are:
478.1270 -
478.1271 -+---------+---------------------------------------------------------------------+
478.1272 -| Flag | Meaning |
478.1273 -+=========+=====================================================================+
478.1274 -| ``'#'`` | The value conversion will use the "alternate form" (where defined |
478.1275 -| | below). |
478.1276 -+---------+---------------------------------------------------------------------+
478.1277 -| ``'0'`` | The conversion will be zero padded for numeric values. |
478.1278 -+---------+---------------------------------------------------------------------+
478.1279 -| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
478.1280 -| | conversion if both are given). |
478.1281 -+---------+---------------------------------------------------------------------+
478.1282 -| ``' '`` | (a space) A blank should be left before a positive number (or empty |
478.1283 -| | string) produced by a signed conversion. |
478.1284 -+---------+---------------------------------------------------------------------+
478.1285 -| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
478.1286 -| | (overrides a "space" flag). |
478.1287 -+---------+---------------------------------------------------------------------+
478.1288 -
478.1289 -A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
478.1290 -is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
478.1291 -
478.1292 -The conversion types are:
478.1293 -
478.1294 -+------------+-----------------------------------------------------+-------+
478.1295 -| Conversion | Meaning | Notes |
478.1296 -+============+=====================================================+=======+
478.1297 -| ``'d'`` | Signed integer decimal. | |
478.1298 -+------------+-----------------------------------------------------+-------+
478.1299 -| ``'i'`` | Signed integer decimal. | |
478.1300 -+------------+-----------------------------------------------------+-------+
478.1301 -| ``'o'`` | Signed octal value. | \(1) |
478.1302 -+------------+-----------------------------------------------------+-------+
478.1303 -| ``'u'`` | Obselete type -- it is identical to ``'d'``. | \(7) |
478.1304 -+------------+-----------------------------------------------------+-------+
478.1305 -| ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
478.1306 -+------------+-----------------------------------------------------+-------+
478.1307 -| ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
478.1308 -+------------+-----------------------------------------------------+-------+
478.1309 -| ``'e'`` | Floating point exponential format (lowercase). | \(3) |
478.1310 -+------------+-----------------------------------------------------+-------+
478.1311 -| ``'E'`` | Floating point exponential format (uppercase). | \(3) |
478.1312 -+------------+-----------------------------------------------------+-------+
478.1313 -| ``'f'`` | Floating point decimal format. | \(3) |
478.1314 -+------------+-----------------------------------------------------+-------+
478.1315 -| ``'F'`` | Floating point decimal format. | \(3) |
478.1316 -+------------+-----------------------------------------------------+-------+
478.1317 -| ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
478.1318 -| | format if exponent is less than -4 or not less than | |
478.1319 -| | precision, decimal format otherwise. | |
478.1320 -+------------+-----------------------------------------------------+-------+
478.1321 -| ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
478.1322 -| | format if exponent is less than -4 or not less than | |
478.1323 -| | precision, decimal format otherwise. | |
478.1324 -+------------+-----------------------------------------------------+-------+
478.1325 -| ``'c'`` | Single character (accepts integer or single | |
478.1326 -| | character string). | |
478.1327 -+------------+-----------------------------------------------------+-------+
478.1328 -| ``'r'`` | String (converts any python object using | \(5) |
478.1329 -| | :func:`repr`). | |
478.1330 -+------------+-----------------------------------------------------+-------+
478.1331 -| ``'s'`` | String (converts any python object using | \(6) |
478.1332 -| | :func:`str`). | |
478.1333 -+------------+-----------------------------------------------------+-------+
478.1334 -| ``'%'`` | No argument is converted, results in a ``'%'`` | |
478.1335 -| | character in the result. | |
478.1336 -+------------+-----------------------------------------------------+-------+
478.1337 -
478.1338 -Notes:
478.1339 -
478.1340 -(1)
478.1341 - The alternate form causes a leading zero (``'0'``) to be inserted between
478.1342 - left-hand padding and the formatting of the number if the leading character
478.1343 - of the result is not already a zero.
478.1344 -
478.1345 -(2)
478.1346 - The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
478.1347 - the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
478.1348 - and the formatting of the number if the leading character of the result is not
478.1349 - already a zero.
478.1350 -
478.1351 -(3)
478.1352 - The alternate form causes the result to always contain a decimal point, even if
478.1353 - no digits follow it.
478.1354 -
478.1355 - The precision determines the number of digits after the decimal point and
478.1356 - defaults to 6.
478.1357 -
478.1358 -(4)
478.1359 - The alternate form causes the result to always contain a decimal point, and
478.1360 - trailing zeroes are not removed as they would otherwise be.
478.1361 -
478.1362 - The precision determines the number of significant digits before and after the
478.1363 - decimal point and defaults to 6.
478.1364 -
478.1365 -(5)
478.1366 - The ``%r`` conversion was added in Python 2.0.
478.1367 -
478.1368 - The precision determines the maximal number of characters used.
478.1369 -
478.1370 -(6)
478.1371 - If the object or format provided is a :class:`unicode` string, the resulting
478.1372 - string will also be :class:`unicode`.
478.1373 -
478.1374 - The precision determines the maximal number of characters used.
478.1375 -
478.1376 -(7)
478.1377 - See :pep:`237`.
478.1378 -
478.1379 -Since Python strings have an explicit length, ``%s`` conversions do not assume
478.1380 -that ``'\0'`` is the end of the string.
478.1381 -
478.1382 -.. XXX Examples?
478.1383 -
478.1384 -For safety reasons, floating point precisions are clipped to 50; ``%f``
478.1385 -conversions for numbers whose absolute value is over 1e25 are replaced by ``%g``
478.1386 -conversions. [#]_ All other errors raise exceptions.
478.1387 -
478.1388 -.. index::
478.1389 - module: string
478.1390 - module: re
478.1391 -
478.1392 -Additional string operations are defined in standard modules :mod:`string` and
478.1393 -:mod:`re`.
478.1394 -
478.1395 -
478.1396 -.. _typesseq-xrange:
478.1397 -
478.1398 -XRange Type
478.1399 ------------
478.1400 -
478.1401 -.. index:: object: xrange
478.1402 -
478.1403 -The :class:`xrange` type is an immutable sequence which is commonly used for
478.1404 -looping. The advantage of the :class:`xrange` type is that an :class:`xrange`
478.1405 -object will always take the same amount of memory, no matter the size of the
478.1406 -range it represents. There are no consistent performance advantages.
478.1407 -
478.1408 -XRange objects have very little behavior: they only support indexing, iteration,
478.1409 -and the :func:`len` function.
478.1410 -
478.1411 -
478.1412 -.. _typesseq-mutable:
478.1413 -
478.1414 -Mutable Sequence Types
478.1415 -----------------------
478.1416 -
478.1417 -.. index::
478.1418 - triple: mutable; sequence; types
478.1419 - object: list
478.1420 -
478.1421 -List objects support additional operations that allow in-place modification of
478.1422 -the object. Other mutable sequence types (when added to the language) should
478.1423 -also support these operations. Strings and tuples are immutable sequence types:
478.1424 -such objects cannot be modified once created. The following operations are
478.1425 -defined on mutable sequence types (where *x* is an arbitrary object):
478.1426 -
478.1427 -+------------------------------+--------------------------------+---------------------+
478.1428 -| Operation | Result | Notes |
478.1429 -+==============================+================================+=====================+
478.1430 -| ``s[i] = x`` | item *i* of *s* is replaced by | |
478.1431 -| | *x* | |
478.1432 -+------------------------------+--------------------------------+---------------------+
478.1433 -| ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
478.1434 -| | is replaced by the contents of | |
478.1435 -| | the iterable *t* | |
478.1436 -+------------------------------+--------------------------------+---------------------+
478.1437 -| ``del s[i:j]`` | same as ``s[i:j] = []`` | |
478.1438 -+------------------------------+--------------------------------+---------------------+
478.1439 -| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
478.1440 -| | are replaced by those of *t* | |
478.1441 -+------------------------------+--------------------------------+---------------------+
478.1442 -| ``del s[i:j:k]`` | removes the elements of | |
478.1443 -| | ``s[i:j:k]`` from the list | |
478.1444 -+------------------------------+--------------------------------+---------------------+
478.1445 -| ``s.append(x)`` | same as ``s[len(s):len(s)] = | \(2) |
478.1446 -| | [x]`` | |
478.1447 -+------------------------------+--------------------------------+---------------------+
478.1448 -| ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(3) |
478.1449 -| | x`` | |
478.1450 -+------------------------------+--------------------------------+---------------------+
478.1451 -| ``s.count(x)`` | return number of *i*'s for | |
478.1452 -| | which ``s[i] == x`` | |
478.1453 -+------------------------------+--------------------------------+---------------------+
478.1454 -| ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(4) |
478.1455 -| | ``s[k] == x`` and ``i <= k < | |
478.1456 -| | j`` | |
478.1457 -+------------------------------+--------------------------------+---------------------+
478.1458 -| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(5) |
478.1459 -+------------------------------+--------------------------------+---------------------+
478.1460 -| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(6) |
478.1461 -| | return x`` | |
478.1462 -+------------------------------+--------------------------------+---------------------+
478.1463 -| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(4) |
478.1464 -+------------------------------+--------------------------------+---------------------+
478.1465 -| ``s.reverse()`` | reverses the items of *s* in | \(7) |
478.1466 -| | place | |
478.1467 -+------------------------------+--------------------------------+---------------------+
478.1468 -| ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |
478.1469 -| reverse]]])`` | | |
478.1470 -+------------------------------+--------------------------------+---------------------+
478.1471 -
478.1472 -.. index::
478.1473 - triple: operations on; sequence; types
478.1474 - triple: operations on; list; type
478.1475 - pair: subscript; assignment
478.1476 - pair: slice; assignment
478.1477 - pair: extended slice; assignment
478.1478 - statement: del
478.1479 - single: append() (list method)
478.1480 - single: extend() (list method)
478.1481 - single: count() (list method)
478.1482 - single: index() (list method)
478.1483 - single: insert() (list method)
478.1484 - single: pop() (list method)
478.1485 - single: remove() (list method)
478.1486 - single: reverse() (list method)
478.1487 - single: sort() (list method)
478.1488 -
478.1489 -Notes:
478.1490 -
478.1491 -(1)
478.1492 - *t* must have the same length as the slice it is replacing.
478.1493 -
478.1494 -(2)
478.1495 - The C implementation of Python has historically accepted multiple parameters and
478.1496 - implicitly joined them into a tuple; this no longer works in Python 2.0. Use of
478.1497 - this misfeature has been deprecated since Python 1.4.
478.1498 -
478.1499 -(3)
478.1500 - *x* can be any iterable object.
478.1501 -
478.1502 -(4)
478.1503 - Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
478.1504 - passed as the second or third parameter to the :meth:`index` method, the list
478.1505 - length is added, as for slice indices. If it is still negative, it is truncated
478.1506 - to zero, as for slice indices.
478.1507 -
478.1508 - .. versionchanged:: 2.3
478.1509 - Previously, :meth:`index` didn't have arguments for specifying start and stop
478.1510 - positions.
478.1511 -
478.1512 -(5)
478.1513 - When a negative index is passed as the first parameter to the :meth:`insert`
478.1514 - method, the list length is added, as for slice indices. If it is still
478.1515 - negative, it is truncated to zero, as for slice indices.
478.1516 -
478.1517 - .. versionchanged:: 2.3
478.1518 - Previously, all negative indices were truncated to zero.
478.1519 -
478.1520 -(6)
478.1521 - The :meth:`pop` method is only supported by the list and array types. The
478.1522 - optional argument *i* defaults to ``-1``, so that by default the last item is
478.1523 - removed and returned.
478.1524 -
478.1525 -(7)
478.1526 - The :meth:`sort` and :meth:`reverse` methods modify the list in place for
478.1527 - economy of space when sorting or reversing a large list. To remind you that
478.1528 - they operate by side effect, they don't return the sorted or reversed list.
478.1529 -
478.1530 -(8)
478.1531 - The :meth:`sort` method takes optional arguments for controlling the
478.1532 - comparisons.
478.1533 -
478.1534 - *cmp* specifies a custom comparison function of two arguments (list items) which
478.1535 - should return a negative, zero or positive number depending on whether the first
478.1536 - argument is considered smaller than, equal to, or larger than the second
478.1537 - argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``. The default value
478.1538 - is ``None``.
478.1539 -
478.1540 - *key* specifies a function of one argument that is used to extract a comparison
478.1541 - key from each list element: ``key=str.lower``. The default value is ``None``.
478.1542 -
478.1543 - *reverse* is a boolean value. If set to ``True``, then the list elements are
478.1544 - sorted as if each comparison were reversed.
478.1545 -
478.1546 - In general, the *key* and *reverse* conversion processes are much faster than
478.1547 - specifying an equivalent *cmp* function. This is because *cmp* is called
478.1548 - multiple times for each list element while *key* and *reverse* touch each
478.1549 - element only once.
478.1550 -
478.1551 - .. versionchanged:: 2.3
478.1552 - Support for ``None`` as an equivalent to omitting *cmp* was added.
478.1553 -
478.1554 - .. versionchanged:: 2.4
478.1555 - Support for *key* and *reverse* was added.
478.1556 -
478.1557 -(9)
478.1558 - Starting with Python 2.3, the :meth:`sort` method is guaranteed to be stable. A
478.1559 - sort is stable if it guarantees not to change the relative order of elements
478.1560 - that compare equal --- this is helpful for sorting in multiple passes (for
478.1561 - example, sort by department, then by salary grade).
478.1562 -
478.1563 -(10)
478.1564 - While a list is being sorted, the effect of attempting to mutate, or even
478.1565 - inspect, the list is undefined. The C implementation of Python 2.3 and newer
478.1566 - makes the list appear empty for the duration, and raises :exc:`ValueError` if it
478.1567 - can detect that the list has been mutated during a sort.
478.1568 -
478.1569 -
478.1570 -.. _types-set:
478.1571 -
478.1572 -Set Types --- :class:`set`, :class:`frozenset`
478.1573 -==============================================
478.1574 -
478.1575 -.. index:: object: set
478.1576 -
478.1577 -A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
478.1578 -Common uses include membership testing, removing duplicates from a sequence, and
478.1579 -computing mathematical operations such as intersection, union, difference, and
478.1580 -symmetric difference.
478.1581 -(For other containers see the built in :class:`dict`, :class:`list`,
478.1582 -and :class:`tuple` classes, and the :mod:`collections` module.)
478.1583 -
478.1584 -
478.1585 -.. versionadded:: 2.4
478.1586 -
478.1587 -Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
478.1588 -set``. Being an unordered collection, sets do not record element position or
478.1589 -order of insertion. Accordingly, sets do not support indexing, slicing, or
478.1590 -other sequence-like behavior.
478.1591 -
478.1592 -There are currently two builtin set types, :class:`set` and :class:`frozenset`.
478.1593 -The :class:`set` type is mutable --- the contents can be changed using methods
478.1594 -like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
478.1595 -and cannot be used as either a dictionary key or as an element of another set.
478.1596 -The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be
478.1597 -altered after it is created; it can therefore be used as a dictionary key or as
478.1598 -an element of another set.
478.1599 -
478.1600 -The constructors for both classes work the same:
478.1601 -
478.1602 -.. class:: set([iterable])
478.1603 - frozenset([iterable])
478.1604 -
478.1605 - Return a new set or frozenset object whose elements are taken from
478.1606 - *iterable*. The elements of a set must be hashable. To represent sets of
478.1607 - sets, the inner sets must be :class:`frozenset` objects. If *iterable* is
478.1608 - not specified, a new empty set is returned.
478.1609 -
478.1610 - Instances of :class:`set` and :class:`frozenset` provide the following
478.1611 - operations:
478.1612 -
478.1613 - .. describe:: len(s)
478.1614 -
478.1615 - Return the cardinality of set *s*.
478.1616 -
478.1617 - .. describe:: x in s
478.1618 -
478.1619 - Test *x* for membership in *s*.
478.1620 -
478.1621 - .. describe:: x not in s
478.1622 -
478.1623 - Test *x* for non-membership in *s*.
478.1624 -
478.1625 - .. method:: isdisjoint(other)
478.1626 -
478.1627 - Return True if the set has no elements in common with *other*. Sets are
478.1628 - disjoint if and only if their intersection is the empty set.
478.1629 -
478.1630 - .. versionadded:: 2.6
478.1631 -
478.1632 - .. method:: issubset(other)
478.1633 - set <= other
478.1634 -
478.1635 - Test whether every element in the set is in *other*.
478.1636 -
478.1637 - .. method:: set < other
478.1638 -
478.1639 - Test whether the set is a true subset of *other*, that is,
478.1640 - ``set <= other and set != other``.
478.1641 -
478.1642 - .. method:: issuperset(other)
478.1643 - set >= other
478.1644 -
478.1645 - Test whether every element in *other* is in the set.
478.1646 -
478.1647 - .. method:: set > other
478.1648 -
478.1649 - Test whether the set is a true superset of *other*, that is, ``set >=
478.1650 - other and set != other``.
478.1651 -
478.1652 - .. method:: union(other, ...)
478.1653 - set | other | ...
478.1654 -
478.1655 - Return a new set with elements from both sets.
478.1656 -
478.1657 - .. versionchanged:: 2.6
478.1658 - Accepts multiple input iterables.
478.1659 -
478.1660 - .. method:: intersection(other, ...)
478.1661 - set & other & ...
478.1662 -
478.1663 - Return a new set with elements common to both sets.
478.1664 -
478.1665 - .. versionchanged:: 2.6
478.1666 - Accepts multiple input iterables.
478.1667 -
478.1668 - .. method:: difference(other, ...)
478.1669 - set - other - ...
478.1670 -
478.1671 - Return a new set with elements in the set that are not in the others.
478.1672 -
478.1673 - .. versionchanged:: 2.6
478.1674 - Accepts multiple input iterables.
478.1675 -
478.1676 - .. method:: symmetric_difference(other)
478.1677 - set ^ other
478.1678 -
478.1679 - Return a new set with elements in either the set or *other* but not both.
478.1680 -
478.1681 - .. method:: copy()
478.1682 -
478.1683 - Return a new set with a shallow copy of *s*.
478.1684 -
478.1685 -
478.1686 - Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
478.1687 - :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
478.1688 - :meth:`issuperset` methods will accept any iterable as an argument. In
478.1689 - contrast, their operator based counterparts require their arguments to be
478.1690 - sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
478.1691 - in favor of the more readable ``set('abc').intersection('cbs')``.
478.1692 -
478.1693 - Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
478.1694 - sets are equal if and only if every element of each set is contained in the
478.1695 - other (each is a subset of the other). A set is less than another set if and
478.1696 - only if the first set is a proper subset of the second set (is a subset, but
478.1697 - is not equal). A set is greater than another set if and only if the first set
478.1698 - is a proper superset of the second set (is a superset, but is not equal).
478.1699 -
478.1700 - Instances of :class:`set` are compared to instances of :class:`frozenset`
478.1701 - based on their members. For example, ``set('abc') == frozenset('abc')``
478.1702 - returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
478.1703 -
478.1704 - The subset and equality comparisons do not generalize to a complete ordering
478.1705 - function. For example, any two disjoint sets are not equal and are not
478.1706 - subsets of each other, so *all* of the following return ``False``: ``a<b``,
478.1707 - ``a==b``, or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__`
478.1708 - method.
478.1709 -
478.1710 - Since sets only define partial ordering (subset relationships), the output of
478.1711 - the :meth:`list.sort` method is undefined for lists of sets.
478.1712 -
478.1713 - Set elements, like dictionary keys, must be :term:`hashable`.
478.1714 -
478.1715 - Binary operations that mix :class:`set` instances with :class:`frozenset`
478.1716 - return the type of the first operand. For example: ``frozenset('ab') |
478.1717 - set('bc')`` returns an instance of :class:`frozenset`.
478.1718 -
478.1719 - The following table lists operations available for :class:`set` that do not
478.1720 - apply to immutable instances of :class:`frozenset`:
478.1721 -
478.1722 - .. method:: update(other, ...)
478.1723 - set |= other | ...
478.1724 -
478.1725 - Update the set, adding elements from *other*.
478.1726 -
478.1727 - .. versionchanged:: 2.6
478.1728 - Accepts multiple input iterables.
478.1729 -
478.1730 - .. method:: intersection_update(other, ...)
478.1731 - set &= other & ...
478.1732 -
478.1733 - Update the set, keeping only elements found in it and *other*.
478.1734 -
478.1735 - .. versionchanged:: 2.6
478.1736 - Accepts multiple input iterables.
478.1737 -
478.1738 - .. method:: difference_update(other, ...)
478.1739 - set -= other | ...
478.1740 -
478.1741 - Update the set, removing elements found in others.
478.1742 -
478.1743 - .. versionchanged:: 2.6
478.1744 - Accepts multiple input iterables.
478.1745 -
478.1746 - .. method:: symmetric_difference_update(other)
478.1747 - set ^= other
478.1748 -
478.1749 - Update the set, keeping only elements found in either set, but not in both.
478.1750 -
478.1751 - .. method:: add(elem)
478.1752 -
478.1753 - Add element *elem* to the set.
478.1754 -
478.1755 - .. method:: remove(elem)
478.1756 -
478.1757 - Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
478.1758 - not contained in the set.
478.1759 -
478.1760 - .. method:: discard(elem)
478.1761 -
478.1762 - Remove element *elem* from the set if it is present.
478.1763 -
478.1764 - .. method:: pop()
478.1765 -
478.1766 - Remove and return an arbitrary element from the set. Raises
478.1767 - :exc:`KeyError` if the set is empty.
478.1768 -
478.1769 - .. method:: clear()
478.1770 -
478.1771 - Remove all elements from the set.
478.1772 -
478.1773 -
478.1774 - Note, the non-operator versions of the :meth:`update`,
478.1775 - :meth:`intersection_update`, :meth:`difference_update`, and
478.1776 - :meth:`symmetric_difference_update` methods will accept any iterable as an
478.1777 - argument.
478.1778 -
478.1779 - Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
478.1780 - :meth:`discard` methods may be a set. To support searching for an equivalent
478.1781 - frozenset, the *elem* set is temporarily mutated during the search and then
478.1782 - restored. During the search, the *elem* set should not be read or mutated
478.1783 - since it does not have a meaningful value.
478.1784 -
478.1785 -
478.1786 -.. seealso::
478.1787 -
478.1788 - :ref:`comparison-to-builtin-set`
478.1789 - Differences between the :mod:`sets` module and the built-in set types.
478.1790 -
478.1791 -
478.1792 -.. _typesmapping:
478.1793 -
478.1794 -Mapping Types --- :class:`dict`
478.1795 -===============================
478.1796 -
478.1797 -.. index::
478.1798 - object: mapping
478.1799 - object: dictionary
478.1800 - triple: operations on; mapping; types
478.1801 - triple: operations on; dictionary; type
478.1802 - statement: del
478.1803 - builtin: len
478.1804 -
478.1805 -A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects.
478.1806 -Mappings are mutable objects. There is currently only one standard mapping
478.1807 -type, the :dfn:`dictionary`. (For other containers see the built in
478.1808 -:class:`list`, :class:`set`, and :class:`tuple` classes, and the
478.1809 -:mod:`collections` module.)
478.1810 -
478.1811 -A dictionary's keys are *almost* arbitrary values. Values that are not
478.1812 -:term:`hashable`, that is, values containing lists, dictionaries or other
478.1813 -mutable types (that are compared by value rather than by object identity) may
478.1814 -not be used as keys. Numeric types used for keys obey the normal rules for
478.1815 -numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
478.1816 -then they can be used interchangeably to index the same dictionary entry. (Note
478.1817 -however, that since computers store floating-point numbers as approximations it
478.1818 -is usually unwise to use them as dictionary keys.)
478.1819 -
478.1820 -Dictionaries can be created by placing a comma-separated list of ``key: value``
478.1821 -pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
478.1822 -'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
478.1823 -
478.1824 -.. class:: dict([arg])
478.1825 -
478.1826 - Return a new dictionary initialized from an optional positional argument or from
478.1827 - a set of keyword arguments. If no arguments are given, return a new empty
478.1828 - dictionary. If the positional argument *arg* is a mapping object, return a
478.1829 - dictionary mapping the same keys to the same values as does the mapping object.
478.1830 - Otherwise the positional argument must be a sequence, a container that supports
478.1831 - iteration, or an iterator object. The elements of the argument must each also
478.1832 - be of one of those kinds, and each must in turn contain exactly two objects.
478.1833 - The first is used as a key in the new dictionary, and the second as the key's
478.1834 - value. If a given key is seen more than once, the last value associated with it
478.1835 - is retained in the new dictionary.
478.1836 -
478.1837 - If keyword arguments are given, the keywords themselves with their associated
478.1838 - values are added as items to the dictionary. If a key is specified both in the
478.1839 - positional argument and as a keyword argument, the value associated with the
478.1840 - keyword is retained in the dictionary. For example, these all return a
478.1841 - dictionary equal to ``{"one": 2, "two": 3}``:
478.1842 -
478.1843 - * ``dict(one=2, two=3)``
478.1844 -
478.1845 - * ``dict({'one': 2, 'two': 3})``
478.1846 -
478.1847 - * ``dict(zip(('one', 'two'), (2, 3)))``
478.1848 -
478.1849 - * ``dict([['two', 3], ['one', 2]])``
478.1850 -
478.1851 - The first example only works for keys that are valid Python
478.1852 - identifiers; the others work with any valid keys.
478.1853 -
478.1854 - .. versionadded:: 2.2
478.1855 -
478.1856 - .. versionchanged:: 2.3
478.1857 - Support for building a dictionary from keyword arguments added.
478.1858 -
478.1859 -
478.1860 - These are the operations that dictionaries support (and therefore, custom
478.1861 - mapping types should support too):
478.1862 -
478.1863 - .. describe:: len(d)
478.1864 -
478.1865 - Return the number of items in the dictionary *d*.
478.1866 -
478.1867 - .. describe:: d[key]
478.1868 -
478.1869 - Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key*
478.1870 - is not in the map.
478.1871 -
478.1872 - .. versionadded:: 2.5
478.1873 - If a subclass of dict defines a method :meth:`__missing__`, if the key
478.1874 - *key* is not present, the ``d[key]`` operation calls that method with
478.1875 - the key *key* as argument. The ``d[key]`` operation then returns or
478.1876 - raises whatever is returned or raised by the ``__missing__(key)`` call
478.1877 - if the key is not present. No other operations or methods invoke
478.1878 - :meth:`__missing__`. If :meth:`__missing__` is not defined,
478.1879 - :exc:`KeyError` is raised. :meth:`__missing__` must be a method; it
478.1880 - cannot be an instance variable. For an example, see
478.1881 - :class:`collections.defaultdict`.
478.1882 -
478.1883 - .. describe:: d[key] = value
478.1884 -
478.1885 - Set ``d[key]`` to *value*.
478.1886 -
478.1887 - .. describe:: del d[key]
478.1888 -
478.1889 - Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
478.1890 - map.
478.1891 -
478.1892 - .. describe:: key in d
478.1893 -
478.1894 - Return ``True`` if *d* has a key *key*, else ``False``.
478.1895 -
478.1896 - .. versionadded:: 2.2
478.1897 -
478.1898 - .. describe:: key not in d
478.1899 -
478.1900 - Equivalent to ``not key in d``.
478.1901 -
478.1902 - .. versionadded:: 2.2
478.1903 -
478.1904 - .. method:: clear()
478.1905 -
478.1906 - Remove all items from the dictionary.
478.1907 -
478.1908 - .. method:: copy()
478.1909 -
478.1910 - Return a shallow copy of the dictionary.
478.1911 -
478.1912 - .. method:: fromkeys(seq[, value])
478.1913 -
478.1914 - Create a new dictionary with keys from *seq* and values set to *value*.
478.1915 -
478.1916 - :func:`fromkeys` is a class method that returns a new dictionary. *value*
478.1917 - defaults to ``None``.
478.1918 -
478.1919 - .. versionadded:: 2.3
478.1920 -
478.1921 - .. method:: get(key[, default])
478.1922 -
478.1923 - Return the value for *key* if *key* is in the dictionary, else *default*.
478.1924 - If *default* is not given, it defaults to ``None``, so that this method
478.1925 - never raises a :exc:`KeyError`.
478.1926 -
478.1927 - .. method:: has_key(key)
478.1928 -
478.1929 - ``dict.has_key(key)`` is equivalent to ``key in d``, but deprecated.
478.1930 -
478.1931 - .. method:: items()
478.1932 -
478.1933 - Return a copy of the dictionary's list of ``(key, value)`` pairs.
478.1934 -
478.1935 - .. note::
478.1936 -
478.1937 - Keys and values are listed in an arbitrary order which is non-random,
478.1938 - varies across Python implementations, and depends on the dictionary's
478.1939 - history of insertions and deletions. If :meth:`items`, :meth:`keys`,
478.1940 - :meth:`values`, :meth:`iteritems`, :meth:`iterkeys`, and
478.1941 - :meth:`itervalues` are called with no intervening modifications to the
478.1942 - dictionary, the lists will directly correspond. This allows the
478.1943 - creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
478.1944 - zip(d.values(), d.keys())``. The same relationship holds for the
478.1945 - :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs =
478.1946 - zip(d.itervalues(), d.iterkeys())`` provides the same value for
478.1947 - ``pairs``. Another way to create the same list is ``pairs = [(v, k) for
478.1948 - (k, v) in d.iteritems()]``.
478.1949 -
478.1950 - .. method:: iteritems()
478.1951 -
478.1952 - Return an iterator over the dictionary's ``(key, value)`` pairs. See the
478.1953 - note for :meth:`dict.items`.
478.1954 -
478.1955 - .. versionadded:: 2.2
478.1956 -
478.1957 - .. method:: iterkeys()
478.1958 -
478.1959 - Return an iterator over the dictionary's keys. See the note for
478.1960 - :meth:`dict.items`.
478.1961 -
478.1962 - .. versionadded:: 2.2
478.1963 -
478.1964 - .. method:: itervalues()
478.1965 -
478.1966 - Return an iterator over the dictionary's values. See the note for
478.1967 - :meth:`dict.items`.
478.1968 -
478.1969 - .. versionadded:: 2.2
478.1970 -
478.1971 - .. method:: keys()
478.1972 -
478.1973 - Return a copy of the dictionary's list of keys. See the note for
478.1974 - :meth:`dict.items`.
478.1975 -
478.1976 - .. method:: pop(key[, default])
478.1977 -
478.1978 - If *key* is in the dictionary, remove it and return its value, else return
478.1979 - *default*. If *default* is not given and *key* is not in the dictionary,
478.1980 - a :exc:`KeyError` is raised.
478.1981 -
478.1982 - .. versionadded:: 2.3
478.1983 -
478.1984 - .. method:: popitem()
478.1985 -
478.1986 - Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
478.1987 -
478.1988 - :func:`popitem` is useful to destructively iterate over a dictionary, as
478.1989 - often used in set algorithms. If the dictionary is empty, calling
478.1990 - :func:`popitem` raises a :exc:`KeyError`.
478.1991 -
478.1992 - .. method:: setdefault(key[, default])
478.1993 -
478.1994 - If *key* is in the dictionary, return its value. If not, insert *key*
478.1995 - with a value of *default* and return *default*. *default* defaults to
478.1996 - ``None``.
478.1997 -
478.1998 - .. method:: update([other])
478.1999 -
478.2000 - Update the dictionary with the key/value pairs from *other*, overwriting
478.2001 - existing keys. Return ``None``.
478.2002 -
478.2003 - :func:`update` accepts either another dictionary object or an iterable of
478.2004 - key/value pairs (as a tuple or other iterable of length two). If keyword
478.2005 - arguments are specified, the dictionary is then is updated with those
478.2006 - key/value pairs: ``d.update(red=1, blue=2)``.
478.2007 -
478.2008 - .. versionchanged:: 2.4
478.2009 - Allowed the argument to be an iterable of key/value pairs and allowed
478.2010 - keyword arguments.
478.2011 -
478.2012 - .. method:: values()
478.2013 -
478.2014 - Return a copy of the dictionary's list of values. See the note for
478.2015 - :meth:`dict.items`.
478.2016 -
478.2017 -
478.2018 -.. _bltin-file-objects:
478.2019 -
478.2020 -File Objects
478.2021 -============
478.2022 -
478.2023 -.. index::
478.2024 - object: file
478.2025 - builtin: file
478.2026 - module: os
478.2027 - module: socket
478.2028 -
478.2029 -File objects are implemented using C's ``stdio`` package and can be
478.2030 -created with the built-in :func:`open` function. File
478.2031 -objects are also returned by some other built-in functions and methods,
478.2032 -such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile`
478.2033 -method of socket objects. Temporary files can be created using the
478.2034 -:mod:`tempfile` module, and high-level file operations such as copying,
478.2035 -moving, and deleting files and directories can be achieved with the
478.2036 -:mod:`shutil` module.
478.2037 -
478.2038 -When a file operation fails for an I/O-related reason, the exception
478.2039 -:exc:`IOError` is raised. This includes situations where the operation is not
478.2040 -defined for some reason, like :meth:`seek` on a tty device or writing a file
478.2041 -opened for reading.
478.2042 -
478.2043 -Files have the following methods:
478.2044 -
478.2045 -
478.2046 -.. method:: file.close()
478.2047 -
478.2048 - Close the file. A closed file cannot be read or written any more. Any operation
478.2049 - which requires that the file be open will raise a :exc:`ValueError` after the
478.2050 - file has been closed. Calling :meth:`close` more than once is allowed.
478.2051 -
478.2052 - As of Python 2.5, you can avoid having to call this method explicitly if you use
478.2053 - the :keyword:`with` statement. For example, the following code will
478.2054 - automatically close *f* when the :keyword:`with` block is exited::
478.2055 -
478.2056 - from __future__ import with_statement # This isn't required in Python 2.6
478.2057 -
478.2058 - with open("hello.txt") as f:
478.2059 - for line in f:
478.2060 - print line
478.2061 -
478.2062 - In older versions of Python, you would have needed to do this to get the same
478.2063 - effect::
478.2064 -
478.2065 - f = open("hello.txt")
478.2066 - try:
478.2067 - for line in f:
478.2068 - print line
478.2069 - finally:
478.2070 - f.close()
478.2071 -
478.2072 - .. note::
478.2073 -
478.2074 - Not all "file-like" types in Python support use as a context manager for the
478.2075 - :keyword:`with` statement. If your code is intended to work with any file-like
478.2076 - object, you can use the function :func:`contextlib.closing` instead of using
478.2077 - the object directly.
478.2078 -
478.2079 -
478.2080 -.. method:: file.flush()
478.2081 -
478.2082 - Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`. This may be a
478.2083 - no-op on some file-like objects.
478.2084 -
478.2085 -
478.2086 -.. method:: file.fileno()
478.2087 -
478.2088 - .. index::
478.2089 - pair: file; descriptor
478.2090 - module: fcntl
478.2091 -
478.2092 - Return the integer "file descriptor" that is used by the underlying
478.2093 - implementation to request I/O operations from the operating system. This can be
478.2094 - useful for other, lower level interfaces that use file descriptors, such as the
478.2095 - :mod:`fcntl` module or :func:`os.read` and friends.
478.2096 -
478.2097 - .. note::
478.2098 -
478.2099 - File-like objects which do not have a real file descriptor should *not* provide
478.2100 - this method!
478.2101 -
478.2102 -
478.2103 -.. method:: file.isatty()
478.2104 -
478.2105 - Return ``True`` if the file is connected to a tty(-like) device, else ``False``.
478.2106 -
478.2107 - .. note::
478.2108 -
478.2109 - If a file-like object is not associated with a real file, this method should
478.2110 - *not* be implemented.
478.2111 -
478.2112 -
478.2113 -.. method:: file.next()
478.2114 -
478.2115 - A file object is its own iterator, for example ``iter(f)`` returns *f* (unless
478.2116 - *f* is closed). When a file is used as an iterator, typically in a
478.2117 - :keyword:`for` loop (for example, ``for line in f: print line``), the
478.2118 - :meth:`next` method is called repeatedly. This method returns the next input
478.2119 - line, or raises :exc:`StopIteration` when EOF is hit when the file is open for
478.2120 - reading (behavior is undefined when the file is open for writing). In order to
478.2121 - make a :keyword:`for` loop the most efficient way of looping over the lines of a
478.2122 - file (a very common operation), the :meth:`next` method uses a hidden read-ahead
478.2123 - buffer. As a consequence of using a read-ahead buffer, combining :meth:`next`
478.2124 - with other file methods (like :meth:`readline`) does not work right. However,
478.2125 - using :meth:`seek` to reposition the file to an absolute position will flush the
478.2126 - read-ahead buffer.
478.2127 -
478.2128 - .. versionadded:: 2.3
478.2129 -
478.2130 -
478.2131 -.. method:: file.read([size])
478.2132 -
478.2133 - Read at most *size* bytes from the file (less if the read hits EOF before
478.2134 - obtaining *size* bytes). If the *size* argument is negative or omitted, read
478.2135 - all data until EOF is reached. The bytes are returned as a string object. An
478.2136 - empty string is returned when EOF is encountered immediately. (For certain
478.2137 - files, like ttys, it makes sense to continue reading after an EOF is hit.) Note
478.2138 - that this method may call the underlying C function :cfunc:`fread` more than
478.2139 - once in an effort to acquire as close to *size* bytes as possible. Also note
478.2140 - that when in non-blocking mode, less data than was requested may be
478.2141 - returned, even if no *size* parameter was given.
478.2142 -
478.2143 - .. note::
478.2144 - This function is simply a wrapper for the underlying
478.2145 - :cfunc:`fread` C function, and will behave the same in corner cases,
478.2146 - such as whether the EOF value is cached.
478.2147 -
478.2148 -
478.2149 -.. method:: file.readline([size])
478.2150 -
478.2151 - Read one entire line from the file. A trailing newline character is kept in the
478.2152 - string (but may be absent when a file ends with an incomplete line). [#]_ If
478.2153 - the *size* argument is present and non-negative, it is a maximum byte count
478.2154 - (including the trailing newline) and an incomplete line may be returned. An
478.2155 - empty string is returned *only* when EOF is encountered immediately.
478.2156 -
478.2157 - .. note::
478.2158 -
478.2159 - Unlike ``stdio``'s :cfunc:`fgets`, the returned string contains null characters
478.2160 - (``'\0'``) if they occurred in the input.
478.2161 -
478.2162 -
478.2163 -.. method:: file.readlines([sizehint])
478.2164 -
478.2165 - Read until EOF using :meth:`readline` and return a list containing the lines
478.2166 - thus read. If the optional *sizehint* argument is present, instead of
478.2167 - reading up to EOF, whole lines totalling approximately *sizehint* bytes
478.2168 - (possibly after rounding up to an internal buffer size) are read. Objects
478.2169 - implementing a file-like interface may choose to ignore *sizehint* if it
478.2170 - cannot be implemented, or cannot be implemented efficiently.
478.2171 -
478.2172 -
478.2173 -.. method:: file.xreadlines()
478.2174 -
478.2175 - This method returns the same thing as ``iter(f)``.
478.2176 -
478.2177 - .. versionadded:: 2.1
478.2178 -
478.2179 - .. deprecated:: 2.3
478.2180 - Use ``for line in file`` instead.
478.2181 -
478.2182 -
478.2183 -.. method:: file.seek(offset[, whence])
478.2184 -
478.2185 - Set the file's current position, like ``stdio``'s :cfunc:`fseek`. The *whence*
478.2186 - argument is optional and defaults to ``os.SEEK_SET`` or ``0`` (absolute file
478.2187 - positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
478.2188 - current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's
478.2189 - end). There is no return value.
478.2190 -
478.2191 - For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
478.2192 - ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
478.2193 -
478.2194 - Note that if the file is opened for appending
478.2195 - (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
478.2196 - next write. If the file is only opened for writing in append mode (mode
478.2197 - ``'a'``), this method is essentially a no-op, but it remains useful for files
478.2198 - opened in append mode with reading enabled (mode ``'a+'``). If the file is
478.2199 - opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are
478.2200 - legal. Use of other offsets causes undefined behavior.
478.2201 -
478.2202 - Note that not all file objects are seekable.
478.2203 -
478.2204 - .. versionchanged:: 2.6
478.2205 - Passing float values as offset has been deprecated.
478.2206 -
478.2207 -
478.2208 -.. method:: file.tell()
478.2209 -
478.2210 - Return the file's current position, like ``stdio``'s :cfunc:`ftell`.
478.2211 -
478.2212 - .. note::
478.2213 -
478.2214 - On Windows, :meth:`tell` can return illegal values (after an :cfunc:`fgets`)
478.2215 - when reading files with Unix-style line-endings. Use binary mode (``'rb'``) to
478.2216 - circumvent this problem.
478.2217 -
478.2218 -
478.2219 -.. method:: file.truncate([size])
478.2220 -
478.2221 - Truncate the file's size. If the optional *size* argument is present, the file
478.2222 - is truncated to (at most) that size. The size defaults to the current position.
478.2223 - The current file position is not changed. Note that if a specified size exceeds
478.2224 - the file's current size, the result is platform-dependent: possibilities
478.2225 - include that the file may remain unchanged, increase to the specified size as if
478.2226 - zero-filled, or increase to the specified size with undefined new content.
478.2227 - Availability: Windows, many Unix variants.
478.2228 -
478.2229 -
478.2230 -.. method:: file.write(str)
478.2231 -
478.2232 - Write a string to the file. There is no return value. Due to buffering, the
478.2233 - string may not actually show up in the file until the :meth:`flush` or
478.2234 - :meth:`close` method is called.
478.2235 -
478.2236 -
478.2237 -.. method:: file.writelines(sequence)
478.2238 -
478.2239 - Write a sequence of strings to the file. The sequence can be any iterable
478.2240 - object producing strings, typically a list of strings. There is no return value.
478.2241 - (The name is intended to match :meth:`readlines`; :meth:`writelines` does not
478.2242 - add line separators.)
478.2243 -
478.2244 -Files support the iterator protocol. Each iteration returns the same result as
478.2245 -``file.readline()``, and iteration ends when the :meth:`readline` method returns
478.2246 -an empty string.
478.2247 -
478.2248 -File objects also offer a number of other interesting attributes. These are not
478.2249 -required for file-like objects, but should be implemented if they make sense for
478.2250 -the particular object.
478.2251 -
478.2252 -
478.2253 -.. attribute:: file.closed
478.2254 -
478.2255 - bool indicating the current state of the file object. This is a read-only
478.2256 - attribute; the :meth:`close` method changes the value. It may not be available
478.2257 - on all file-like objects.
478.2258 -
478.2259 -
478.2260 -.. attribute:: file.encoding
478.2261 -
478.2262 - The encoding that this file uses. When Unicode strings are written to a file,
478.2263 - they will be converted to byte strings using this encoding. In addition, when
478.2264 - the file is connected to a terminal, the attribute gives the encoding that the
478.2265 - terminal is likely to use (that information might be incorrect if the user has
478.2266 - misconfigured the terminal). The attribute is read-only and may not be present
478.2267 - on all file-like objects. It may also be ``None``, in which case the file uses
478.2268 - the system default encoding for converting Unicode strings.
478.2269 -
478.2270 - .. versionadded:: 2.3
478.2271 -
478.2272 -
478.2273 -.. attribute:: file.errors
478.2274 -
478.2275 - The Unicode error handler used along with the encoding.
478.2276 -
478.2277 - .. versionadded:: 2.6
478.2278 -
478.2279 -
478.2280 -.. attribute:: file.mode
478.2281 -
478.2282 - The I/O mode for the file. If the file was created using the :func:`open`
478.2283 - built-in function, this will be the value of the *mode* parameter. This is a
478.2284 - read-only attribute and may not be present on all file-like objects.
478.2285 -
478.2286 -
478.2287 -.. attribute:: file.name
478.2288 -
478.2289 - If the file object was created using :func:`open`, the name of the file.
478.2290 - Otherwise, some string that indicates the source of the file object, of the
478.2291 - form ``<...>``. This is a read-only attribute and may not be present on all
478.2292 - file-like objects.
478.2293 -
478.2294 -
478.2295 -.. attribute:: file.newlines
478.2296 -
478.2297 - If Python was built with the :option:`--with-universal-newlines` option to
478.2298 - :program:`configure` (the default) this read-only attribute exists, and for
478.2299 - files opened in universal newline read mode it keeps track of the types of
478.2300 - newlines encountered while reading the file. The values it can take are
478.2301 - ``'\r'``, ``'\n'``, ``'\r\n'``, ``None`` (unknown, no newlines read yet) or a
478.2302 - tuple containing all the newline types seen, to indicate that multiple newline
478.2303 - conventions were encountered. For files not opened in universal newline read
478.2304 - mode the value of this attribute will be ``None``.
478.2305 -
478.2306 -
478.2307 -.. attribute:: file.softspace
478.2308 -
478.2309 - Boolean that indicates whether a space character needs to be printed before
478.2310 - another value when using the :keyword:`print` statement. Classes that are trying
478.2311 - to simulate a file object should also have a writable :attr:`softspace`
478.2312 - attribute, which should be initialized to zero. This will be automatic for most
478.2313 - classes implemented in Python (care may be needed for objects that override
478.2314 - attribute access); types implemented in C will have to provide a writable
478.2315 - :attr:`softspace` attribute.
478.2316 -
478.2317 - .. note::
478.2318 -
478.2319 - This attribute is not used to control the :keyword:`print` statement, but to
478.2320 - allow the implementation of :keyword:`print` to keep track of its internal
478.2321 - state.
478.2322 -
478.2323 -
478.2324 -.. _typecontextmanager:
478.2325 -
478.2326 -Context Manager Types
478.2327 -=====================
478.2328 -
478.2329 -.. versionadded:: 2.5
478.2330 -
478.2331 -.. index::
478.2332 - single: context manager
478.2333 - single: context management protocol
478.2334 - single: protocol; context management
478.2335 -
478.2336 -Python's :keyword:`with` statement supports the concept of a runtime context
478.2337 -defined by a context manager. This is implemented using two separate methods
478.2338 -that allow user-defined classes to define a runtime context that is entered
478.2339 -before the statement body is executed and exited when the statement ends.
478.2340 -
478.2341 -The :dfn:`context management protocol` consists of a pair of methods that need
478.2342 -to be provided for a context manager object to define a runtime context:
478.2343 -
478.2344 -
478.2345 -.. method:: contextmanager.__enter__()
478.2346 -
478.2347 - Enter the runtime context and return either this object or another object
478.2348 - related to the runtime context. The value returned by this method is bound to
478.2349 - the identifier in the :keyword:`as` clause of :keyword:`with` statements using
478.2350 - this context manager.
478.2351 -
478.2352 - An example of a context manager that returns itself is a file object. File
478.2353 - objects return themselves from __enter__() to allow :func:`open` to be used as
478.2354 - the context expression in a :keyword:`with` statement.
478.2355 -
478.2356 - An example of a context manager that returns a related object is the one
478.2357 - returned by :func:`decimal.localcontext`. These managers set the active
478.2358 - decimal context to a copy of the original decimal context and then return the
478.2359 - copy. This allows changes to be made to the current decimal context in the body
478.2360 - of the :keyword:`with` statement without affecting code outside the
478.2361 - :keyword:`with` statement.
478.2362 -
478.2363 -
478.2364 -.. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
478.2365 -
478.2366 - Exit the runtime context and return a Boolean flag indicating if any exception
478.2367 - that occurred should be suppressed. If an exception occurred while executing the
478.2368 - body of the :keyword:`with` statement, the arguments contain the exception type,
478.2369 - value and traceback information. Otherwise, all three arguments are ``None``.
478.2370 -
478.2371 - Returning a true value from this method will cause the :keyword:`with` statement
478.2372 - to suppress the exception and continue execution with the statement immediately
478.2373 - following the :keyword:`with` statement. Otherwise the exception continues
478.2374 - propagating after this method has finished executing. Exceptions that occur
478.2375 - during execution of this method will replace any exception that occurred in the
478.2376 - body of the :keyword:`with` statement.
478.2377 -
478.2378 - The exception passed in should never be reraised explicitly - instead, this
478.2379 - method should return a false value to indicate that the method completed
478.2380 - successfully and does not want to suppress the raised exception. This allows
478.2381 - context management code (such as ``contextlib.nested``) to easily detect whether
478.2382 - or not an :meth:`__exit__` method has actually failed.
478.2383 -
478.2384 -Python defines several context managers to support easy thread synchronisation,
478.2385 -prompt closure of files or other objects, and simpler manipulation of the active
478.2386 -decimal arithmetic context. The specific types are not treated specially beyond
478.2387 -their implementation of the context management protocol. See the
478.2388 -:mod:`contextlib` module for some examples.
478.2389 -
478.2390 -Python's :term:`generator`\s and the ``contextlib.contextfactory`` :term:`decorator`
478.2391 -provide a convenient way to implement these protocols. If a generator function is
478.2392 -decorated with the ``contextlib.contextfactory`` decorator, it will return a
478.2393 -context manager implementing the necessary :meth:`__enter__` and
478.2394 -:meth:`__exit__` methods, rather than the iterator produced by an undecorated
478.2395 -generator function.
478.2396 -
478.2397 -Note that there is no specific slot for any of these methods in the type
478.2398 -structure for Python objects in the Python/C API. Extension types wanting to
478.2399 -define these methods must provide them as a normal Python accessible method.
478.2400 -Compared to the overhead of setting up the runtime context, the overhead of a
478.2401 -single class dictionary lookup is negligible.
478.2402 -
478.2403 -
478.2404 -.. _typesother:
478.2405 -
478.2406 -Other Built-in Types
478.2407 -====================
478.2408 -
478.2409 -The interpreter supports several other kinds of objects. Most of these support
478.2410 -only one or two operations.
478.2411 -
478.2412 -
478.2413 -.. _typesmodules:
478.2414 -
478.2415 -Modules
478.2416 --------
478.2417 -
478.2418 -The only special operation on a module is attribute access: ``m.name``, where
478.2419 -*m* is a module and *name* accesses a name defined in *m*'s symbol table.
478.2420 -Module attributes can be assigned to. (Note that the :keyword:`import`
478.2421 -statement is not, strictly speaking, an operation on a module object; ``import
478.2422 -foo`` does not require a module object named *foo* to exist, rather it requires
478.2423 -an (external) *definition* for a module named *foo* somewhere.)
478.2424 -
478.2425 -A special member of every module is :attr:`__dict__`. This is the dictionary
478.2426 -containing the module's symbol table. Modifying this dictionary will actually
478.2427 -change the module's symbol table, but direct assignment to the :attr:`__dict__`
478.2428 -attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
478.2429 -``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying
478.2430 -:attr:`__dict__` directly is not recommended.
478.2431 -
478.2432 -Modules built into the interpreter are written like this: ``<module 'sys'
478.2433 -(built-in)>``. If loaded from a file, they are written as ``<module 'os' from
478.2434 -'/usr/local/lib/pythonX.Y/os.pyc'>``.
478.2435 -
478.2436 -
478.2437 -.. _typesobjects:
478.2438 -
478.2439 -Classes and Class Instances
478.2440 ----------------------------
478.2441 -
478.2442 -See :ref:`objects` and :ref:`class` for these.
478.2443 -
478.2444 -
478.2445 -.. _typesfunctions:
478.2446 -
478.2447 -Functions
478.2448 ----------
478.2449 -
478.2450 -Function objects are created by function definitions. The only operation on a
478.2451 -function object is to call it: ``func(argument-list)``.
478.2452 -
478.2453 -There are really two flavors of function objects: built-in functions and
478.2454 -user-defined functions. Both support the same operation (to call the function),
478.2455 -but the implementation is different, hence the different object types.
478.2456 -
478.2457 -See :ref:`function` for more information.
478.2458 -
478.2459 -
478.2460 -.. _typesmethods:
478.2461 -
478.2462 -Methods
478.2463 --------
478.2464 -
478.2465 -.. index:: object: method
478.2466 -
478.2467 -Methods are functions that are called using the attribute notation. There are
478.2468 -two flavors: built-in methods (such as :meth:`append` on lists) and class
478.2469 -instance methods. Built-in methods are described with the types that support
478.2470 -them.
478.2471 -
478.2472 -The implementation adds two special read-only attributes to class instance
478.2473 -methods: ``m.im_self`` is the object on which the method operates, and
478.2474 -``m.im_func`` is the function implementing the method. Calling ``m(arg-1,
478.2475 -arg-2, ..., arg-n)`` is completely equivalent to calling ``m.im_func(m.im_self,
478.2476 -arg-1, arg-2, ..., arg-n)``.
478.2477 -
478.2478 -Class instance methods are either *bound* or *unbound*, referring to whether the
478.2479 -method was accessed through an instance or a class, respectively. When a method
478.2480 -is unbound, its ``im_self`` attribute will be ``None`` and if called, an
478.2481 -explicit ``self`` object must be passed as the first argument. In this case,
478.2482 -``self`` must be an instance of the unbound method's class (or a subclass of
478.2483 -that class), otherwise a :exc:`TypeError` is raised.
478.2484 -
478.2485 -Like function objects, methods objects support getting arbitrary attributes.
478.2486 -However, since method attributes are actually stored on the underlying function
478.2487 -object (``meth.im_func``), setting method attributes on either bound or unbound
478.2488 -methods is disallowed. Attempting to set a method attribute results in a
478.2489 -:exc:`TypeError` being raised. In order to set a method attribute, you need to
478.2490 -explicitly set it on the underlying function object::
478.2491 -
478.2492 - class C:
478.2493 - def method(self):
478.2494 - pass
478.2495 -
478.2496 - c = C()
478.2497 - c.method.im_func.whoami = 'my name is c'
478.2498 -
478.2499 -See :ref:`types` for more information.
478.2500 -
478.2501 -
478.2502 -.. _bltin-code-objects:
478.2503 -
478.2504 -Code Objects
478.2505 -------------
478.2506 -
478.2507 -.. index:: object: code
478.2508 -
478.2509 -.. index::
478.2510 - builtin: compile
478.2511 - single: func_code (function object attribute)
478.2512 -
478.2513 -Code objects are used by the implementation to represent "pseudo-compiled"
478.2514 -executable Python code such as a function body. They differ from function
478.2515 -objects because they don't contain a reference to their global execution
478.2516 -environment. Code objects are returned by the built-in :func:`compile` function
478.2517 -and can be extracted from function objects through their :attr:`func_code`
478.2518 -attribute. See also the :mod:`code` module.
478.2519 -
478.2520 -.. index::
478.2521 - statement: exec
478.2522 - builtin: eval
478.2523 -
478.2524 -A code object can be executed or evaluated by passing it (instead of a source
478.2525 -string) to the :keyword:`exec` statement or the built-in :func:`eval` function.
478.2526 -
478.2527 -See :ref:`types` for more information.
478.2528 -
478.2529 -
478.2530 -.. _bltin-type-objects:
478.2531 -
478.2532 -Type Objects
478.2533 -------------
478.2534 -
478.2535 -.. index::
478.2536 - builtin: type
478.2537 - module: types
478.2538 -
478.2539 -Type objects represent the various object types. An object's type is accessed
478.2540 -by the built-in function :func:`type`. There are no special operations on
478.2541 -types. The standard module :mod:`types` defines names for all standard built-in
478.2542 -types.
478.2543 -
478.2544 -Types are written like this: ``<type 'int'>``.
478.2545 -
478.2546 -
478.2547 -.. _bltin-null-object:
478.2548 -
478.2549 -The Null Object
478.2550 ----------------
478.2551 -
478.2552 -This object is returned by functions that don't explicitly return a value. It
478.2553 -supports no special operations. There is exactly one null object, named
478.2554 -``None`` (a built-in name).
478.2555 -
478.2556 -It is written as ``None``.
478.2557 -
478.2558 -
478.2559 -.. _bltin-ellipsis-object:
478.2560 -
478.2561 -The Ellipsis Object
478.2562 --------------------
478.2563 -
478.2564 -This object is used by extended slice notation (see :ref:`slicings`). It
478.2565 -supports no special operations. There is exactly one ellipsis object, named
478.2566 -:const:`Ellipsis` (a built-in name).
478.2567 -
478.2568 -It is written as ``Ellipsis``.
478.2569 -
478.2570 -
478.2571 -Boolean Values
478.2572 ---------------
478.2573 -
478.2574 -Boolean values are the two constant objects ``False`` and ``True``. They are
478.2575 -used to represent truth values (although other values can also be considered
478.2576 -false or true). In numeric contexts (for example when used as the argument to
478.2577 -an arithmetic operator), they behave like the integers 0 and 1, respectively.
478.2578 -The built-in function :func:`bool` can be used to cast any value to a Boolean,
478.2579 -if the value can be interpreted as a truth value (see section Truth Value
478.2580 -Testing above).
478.2581 -
478.2582 -.. index::
478.2583 - single: False
478.2584 - single: True
478.2585 - pair: Boolean; values
478.2586 -
478.2587 -They are written as ``False`` and ``True``, respectively.
478.2588 -
478.2589 -
478.2590 -.. _typesinternal:
478.2591 -
478.2592 -Internal Objects
478.2593 -----------------
478.2594 -
478.2595 -See :ref:`types` for this information. It describes stack frame objects,
478.2596 -traceback objects, and slice objects.
478.2597 -
478.2598 -
478.2599 -.. _specialattrs:
478.2600 -
478.2601 -Special Attributes
478.2602 -==================
478.2603 -
478.2604 -The implementation adds a few special read-only attributes to several object
478.2605 -types, where they are relevant. Some of these are not reported by the
478.2606 -:func:`dir` built-in function.
478.2607 -
478.2608 -
478.2609 -.. attribute:: object.__dict__
478.2610 -
478.2611 - A dictionary or other mapping object used to store an object's (writable)
478.2612 - attributes.
478.2613 -
478.2614 -
478.2615 -.. attribute:: object.__methods__
478.2616 -
478.2617 - .. deprecated:: 2.2
478.2618 - Use the built-in function :func:`dir` to get a list of an object's attributes.
478.2619 - This attribute is no longer available.
478.2620 -
478.2621 -
478.2622 -.. attribute:: object.__members__
478.2623 -
478.2624 - .. deprecated:: 2.2
478.2625 - Use the built-in function :func:`dir` to get a list of an object's attributes.
478.2626 - This attribute is no longer available.
478.2627 -
478.2628 -
478.2629 -.. attribute:: instance.__class__
478.2630 -
478.2631 - The class to which a class instance belongs.
478.2632 -
478.2633 -
478.2634 -.. attribute:: class.__bases__
478.2635 -
478.2636 - The tuple of base classes of a class object. If there are no base classes, this
478.2637 - will be an empty tuple.
478.2638 -
478.2639 -
478.2640 -.. attribute:: class.__name__
478.2641 -
478.2642 - The name of the class or type.
478.2643 -
478.2644 -.. rubric:: Footnotes
478.2645 -
478.2646 -.. [#] Additional information on these special methods may be found in the Python
478.2647 - Reference Manual (:ref:`customization`).
478.2648 -
478.2649 -.. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
478.2650 - similarly for tuples.
478.2651 -
478.2652 -.. [#] They must have since the parser can't tell the type of the operands.
478.2653 -
478.2654 -.. [#] To format only a tuple you should therefore provide a singleton tuple whose only
478.2655 - element is the tuple to be formatted.
478.2656 -
478.2657 -.. [#] These numbers are fairly arbitrary. They are intended to avoid printing endless
478.2658 - strings of meaningless digits without hampering correct use and without having
478.2659 - to know the exact precision of floating point values on a particular machine.
478.2660 -
478.2661 -.. [#] The advantage of leaving the newline on is that returning an empty string is
478.2662 - then an unambiguous EOF indication. It is also possible (in cases where it
478.2663 - might matter, for example, if you want to make an exact copy of a file while
478.2664 - scanning its lines) to tell whether the last line of a file ended in a newline
478.2665 - or not (yes this happens!).
479.1 --- a/python.editor/test/unit/data/testfiles/rst/stdtypes.rst.html Sun Jan 04 13:11:53 2015 -0600
479.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
479.3 @@ -1,2519 +0,0 @@
479.4 -<html><body>
479.5 -.. XXX: reference/datamodel and this have quite a few overlaps!
479.6 -
479.7 -<br><br>
479.8 -
479.9 -<h2><br><br>
479.10 -</h2>
479.11 -<h2>Built-in Types
479.12 -</h2>
479.13 -The following sections describe the standard types that are built into the
479.14 -interpreter.
479.15 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
479.16 -
479.17 -<br><br>
479.18 - Historically (until release 2.2), Python's built-in types have differed from
479.19 - user-defined types because it was not possible to use the built-in types as the
479.20 - basis for object-oriented inheritance. This limitation no longer
479.21 - exists.
479.22 -</div>
479.23 -The principal built-in types are numerics, sequences, mappings, files, classes,
479.24 -instances and exceptions.
479.25 -
479.26 -<br><br>
479.27 -Some operations are supported by several object types; in particular,
479.28 -practically all objects can be compared, tested for truth value, and converted
479.29 -to a string (with the <a href="func:repr">repr</a> function or the slightly different
479.30 -<a href="func:str">str</a> function). The latter function is implicitly used when an object is
479.31 -written by the <a href="func:print">print</a> function.
479.32 -
479.33 -<br><br>
479.34 -
479.35 -<br><br>
479.36 -<h2>Truth Value Testing
479.37 -</h2>
479.38 -Any object can be tested for truth value, for use in an <code style="color:#0000e6;">if</code> or
479.39 -<code style="color:#0000e6;">while</code> condition or as operand of the Boolean operations below. The
479.40 -following values are considered false:
479.41 -
479.42 -<br><br>
479.43 -* <code>None</code>
479.44 -* <code>False</code>
479.45 -* zero of any numeric type, for example, <code>0</code>, <code>0L</code>, <code>0.0</code>, <code>0j</code>.
479.46 -
479.47 -<br><br>
479.48 -* any empty sequence, for example, <code>''</code>, <code>()</code>, <code>[]</code>.
479.49 -
479.50 -<br><br>
479.51 -* any empty mapping, for example, <code>{}</code>.
479.52 -
479.53 -<br><br>
479.54 -* instances of user-defined classes, if the class defines a <a href="meth:__nonzero__">__nonzero__</a>
479.55 - or <a href="meth:__len__">__len__</a> method, when that method returns the integer zero or
479.56 - <a href="class:bool">bool</a> value <code>False</code>. [#]_
479.57 -
479.58 -<br><br>
479.59 -All other values are considered true --- so objects of many types are always
479.60 -true.
479.61 -
479.62 -<br><br>
479.63 -Operations and built-in functions that have a Boolean result always return <code>0</code>
479.64 -or <code>False</code> for false and <code>1</code> or <code>True</code> for true, unless otherwise stated.
479.65 -(Important exception: the Boolean operations <code>or</code> and <code>and</code> always return
479.66 -one of their operands.)
479.67 -
479.68 -<br><br>
479.69 -
479.70 -<br><br>
479.71 -<h2>Boolean Operations --- <code style="color:#0000e6;">and</code>, <code style="color:#0000e6;">or</code>, <code style="color:#0000e6;">not</code>
479.72 -</h2>
479.73 -These are the Boolean operations, ordered by ascending priority:
479.74 -<pre>+-------------+---------------------------------+-------+
479.75 -| Operation | Result | Notes |
479.76 -+=============+=================================+=======+
479.77 -| ``x or y`` | if *x* is false, then *y*, else | \(1) |
479.78 -| | *x* | |
479.79 -+-------------+---------------------------------+-------+
479.80 -| ``x and y`` | if *x* is false, then *x*, else | \(2) |
479.81 -| | *y* | |
479.82 -+-------------+---------------------------------+-------+
479.83 -| ``not x`` | if *x* is false, then ``True``, | \(3) |
479.84 -| | else ``False`` | |
479.85 -+-------------+---------------------------------+-------+
479.86 -</pre>
479.87 -Notes:
479.88 -(1)
479.89 - This is a short-circuit operator, so it only evaluates the second
479.90 - argument if the first one is :const:<code>False</code>.
479.91 -
479.92 -<br><br>
479.93 -(2)
479.94 - This is a short-circuit operator, so it only evaluates the second
479.95 - argument if the first one is :const:<code>True</code>.
479.96 -
479.97 -<br><br>
479.98 -(3)
479.99 - <code>not</code> has a lower priority than non-Boolean operators, so <code>not a == b</code> is
479.100 - interpreted as <code>not (a == b)</code>, and <code>a == not b</code> is a syntax error.
479.101 -
479.102 -<br><br>
479.103 -
479.104 -<br><br>
479.105 -<h2>Comparisons
479.106 -</h2>
479.107 -Comparison operations are supported by all objects. They all have the same
479.108 -priority (which is higher than that of the Boolean operations). Comparisons can
479.109 -be chained arbitrarily; for example, <code>x < y <= z</code> is equivalent to ``x < y and
479.110 -y <= z``, except that <b>y</b> is evaluated only once (but in both cases <b>z</b> is not
479.111 -evaluated at all when <code>x < y</code> is found to be false).
479.112 -
479.113 -<br><br>
479.114 -This table summarizes the comparison operations:
479.115 -
479.116 -<br><br>
479.117 -<pre>+------------+-------------------------+-------+
479.118 -| Operation | Meaning | Notes |
479.119 -+============+=========================+=======+
479.120 -| ``<`` | strictly less than | |
479.121 -+------------+-------------------------+-------+
479.122 -| ``<=`` | less than or equal | |
479.123 -+------------+-------------------------+-------+
479.124 -| ``>`` | strictly greater than | |
479.125 -+------------+-------------------------+-------+
479.126 -| ``>=`` | greater than or equal | |
479.127 -+------------+-------------------------+-------+
479.128 -| ``==`` | equal | |
479.129 -+------------+-------------------------+-------+
479.130 -| ``!=`` | not equal | \(1) |
479.131 -+------------+-------------------------+-------+
479.132 -| ``is`` | object identity | |
479.133 -+------------+-------------------------+-------+
479.134 -| ``is not`` | negated object identity | |
479.135 -+------------+-------------------------+-------+
479.136 -</pre>
479.137 -Notes:
479.138 -(1)
479.139 - <code>!=</code> can also be written <code><></code>, but this is an obsolete usage
479.140 - kept for backwards compatibility only. New code should always use
479.141 - <code>!=</code>.
479.142 -
479.143 -<br><br>
479.144 -Objects of different types, except different numeric types and different string
479.145 -types, never compare equal; such objects are ordered consistently but
479.146 -arbitrarily (so that sorting a heterogeneous array yields a consistent result).
479.147 -Furthermore, some types (for example, file objects) support only a degenerate
479.148 -notion of comparison where any two objects of that type are unequal. Again,
479.149 -such objects are ordered arbitrarily but consistently. The <code><</code>, <code><=</code>, <code>></code>
479.150 -and <code>>=</code> operators will raise a <a href="exc:TypeError">TypeError</a> exception when any operand is
479.151 -a complex number.
479.152 -
479.153 -<br><br>
479.154 -Instances of a class normally compare as non-equal unless the class defines the
479.155 -<a href="meth:__cmp__">__cmp__</a> method. Refer to <code>customization</code>) for information on the
479.156 -use of this method to effect object comparisons.
479.157 -
479.158 -<br><br>
479.159 -**Implementation note:** Objects of different types except numbers are ordered
479.160 -by their type names; objects of the same types that don't support proper
479.161 -comparison are ordered by their address.
479.162 -
479.163 -<br><br>
479.164 -Two more operations with the same syntactic priority, <code>in</code> and <code>not in</code>, are
479.165 -supported only by sequence types (below).
479.166 -
479.167 -<br><br>
479.168 -
479.169 -<br><br>
479.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>
479.171 -</h2>
479.172 -There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long
479.173 -integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In
479.174 -addition, Booleans are a subtype of plain integers. Plain integers (also just
479.175 -called :dfn:<code>integers</code>) are implemented using :ctype:<code>long</code> in C, which gives
479.176 -them at least 32 bits of precision (<code>sys.maxint</code> is always set to the maximum
479.177 -plain integer value for the current platform, the minimum value is
479.178 -<code>-sys.maxint - 1</code>). Long integers have unlimited precision. Floating point
479.179 -numbers are implemented using :ctype:<code>double</code> in C. All bets on their precision
479.180 -are off unless you happen to know the machine you are working with.
479.181 -
479.182 -<br><br>
479.183 -Complex numbers have a real and imaginary part, which are each implemented using
479.184 -:ctype:<code>double</code> in C. To extract these parts from a complex number <b>z</b>, use
479.185 -<code>z.real</code> and <code>z.imag</code>.
479.186 -
479.187 -<br><br>
479.188 -Numbers are created by numeric literals or as the result of built-in functions
479.189 -and operators. Unadorned integer literals (including hex and octal numbers)
479.190 -yield plain integers unless the value they denote is too large to be represented
479.191 -as a plain integer, in which case they yield a long integer. Integer literals
479.192 -with an <code>'L'</code> or <code>'l'</code> suffix yield long integers (<code>'L'</code> is preferred
479.193 -because <code>1l</code> looks too much like eleven!). Numeric literals containing a
479.194 -decimal point or an exponent sign yield floating point numbers. Appending
479.195 -<code>'j'</code> or <code>'J'</code> to a numeric literal yields a complex number with a zero real
479.196 -part. A complex numeric literal is the sum of a real and an imaginary part.
479.197 -
479.198 -<br><br>
479.199 -Python fully supports mixed arithmetic: when a binary arithmetic operator has
479.200 -operands of different numeric types, the operand with the "narrower" type is
479.201 -widened to that of the other, where plain integer is narrower than long integer
479.202 -is narrower than floating point is narrower than complex. Comparisons between
479.203 -numbers of mixed type use the same rule. [#]_ The constructors <a href="func:int">int</a>,
479.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
479.205 -of a specific type.
479.206 -
479.207 -<br><br>
479.208 -All builtin numeric types support the following operations. See
479.209 -<code>power</code> and later sections for the operators' priorities.
479.210 -
479.211 -<br><br>
479.212 -<pre>+--------------------+---------------------------------+--------+
479.213 -| Operation | Result | Notes |
479.214 -+====================+=================================+========+
479.215 -| ``x + y`` | sum of *x* and *y* | |
479.216 -+--------------------+---------------------------------+--------+
479.217 -| ``x - y`` | difference of *x* and *y* | |
479.218 -+--------------------+---------------------------------+--------+
479.219 -| ``x * y`` | product of *x* and *y* | |
479.220 -+--------------------+---------------------------------+--------+
479.221 -| ``x / y`` | quotient of *x* and *y* | \(1) |
479.222 -+--------------------+---------------------------------+--------+
479.223 -| ``x // y`` | (floored) quotient of *x* and | (4)(5) |
479.224 -| | *y* | |
479.225 -+--------------------+---------------------------------+--------+
479.226 -| ``x % y`` | remainder of ``x / y`` | \(4) |
479.227 -+--------------------+---------------------------------+--------+
479.228 -| ``-x`` | *x* negated | |
479.229 -+--------------------+---------------------------------+--------+
479.230 -| ``+x`` | *x* unchanged | |
479.231 -+--------------------+---------------------------------+--------+
479.232 -| ``abs(x)`` | absolute value or magnitude of | \(3) |
479.233 -| | *x* | |
479.234 -+--------------------+---------------------------------+--------+
479.235 -| ``int(x)`` | *x* converted to integer | \(2) |
479.236 -+--------------------+---------------------------------+--------+
479.237 -| ``long(x)`` | *x* converted to long integer | \(2) |
479.238 -+--------------------+---------------------------------+--------+
479.239 -| ``float(x)`` | *x* converted to floating point | \(6) |
479.240 -+--------------------+---------------------------------+--------+
479.241 -| ``complex(re,im)`` | a complex number with real part | |
479.242 -| | *re*, imaginary part *im*. | |
479.243 -| | *im* defaults to zero. | |
479.244 -+--------------------+---------------------------------+--------+
479.245 -| ``c.conjugate()`` | conjugate of the complex number | |
479.246 -| | *c*. (Identity on real numbers) | |
479.247 -+--------------------+---------------------------------+--------+
479.248 -| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) |
479.249 -+--------------------+---------------------------------+--------+
479.250 -| ``pow(x, y)`` | *x* to the power *y* | (3)(7) |
479.251 -+--------------------+---------------------------------+--------+
479.252 -| ``x ** y`` | *x* to the power *y* | \(7) |
479.253 -+--------------------+---------------------------------+--------+
479.254 -</pre>
479.255 -Notes:
479.256 -(1)
479.257 - For (plain or long) integer division, the result is an integer. The result is
479.258 - always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
479.259 - (-1)/(-2) is 0. Note that the result is a long integer if either operand is a
479.260 - long integer, regardless of the numeric value.
479.261 -
479.262 -<br><br>
479.263 -(2)
479.264 - Conversion from floating point to (long or plain) integer may round or
479.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
479.266 - well-defined conversions.
479.267 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.6
479.268 - Instead, convert floats to long explicitly with <a href="func:trunc">trunc</a>.
479.269 -</div>
479.270 -(3)
479.271 - See <code>built-in-funcs</code> for a full description.
479.272 -
479.273 -<br><br>
479.274 -(4)
479.275 - Complex floor division operator, modulo operator, and <a href="func:divmod">divmod</a>.
479.276 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.3
479.277 - Instead convert to float using <a href="func:abs">abs</a> if appropriate.
479.278 -</div>
479.279 -(5)
479.280 - Also referred to as integer division. The resultant value is a whole integer,
479.281 - though the result's type is not necessarily int.
479.282 -
479.283 -<br><br>
479.284 -(6)
479.285 - float also accepts the strings "nan" and "inf" with an optional prefix "+"
479.286 - or "-" for Not a Number (NaN) and positive or negative infinity.
479.287 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
479.288 -</div>
479.289 -(7)
479.290 - Python defines <code>pow(0, 0)</code> and <code>0 ** 0</code> to be <code>1</code>, as is common for
479.291 - programming languages.
479.292 -
479.293 -<br><br>
479.294 -All <a href="class:numbers.Real">numbers.Real</a> types (<a href="class:int">int</a>, <a href="class:long">long</a>, and
479.295 -<a href="class:float">float</a>) also include the following operations:
479.296 -
479.297 -<br><br>
479.298 -<pre>+--------------------+------------------------------------+--------+
479.299 -| Operation | Result | Notes |
479.300 -+====================+====================================+========+
479.301 -| ``trunc(x)`` | *x* truncated to Integral | |
479.302 -+--------------------+------------------------------------+--------+
479.303 -| ``round(x[, n])`` | *x* rounded to n digits, | |
479.304 -| | rounding half to even. If n is | |
479.305 -| | omitted, it defaults to 0. | |
479.306 -+--------------------+------------------------------------+--------+
479.307 -| ``math.floor(x)`` | the greatest integral float <= *x* | |
479.308 -+--------------------+------------------------------------+--------+
479.309 -| ``math.ceil(x)`` | the least integral float >= *x* | |
479.310 -+--------------------+------------------------------------+--------+
479.311 -</pre>
479.312 -.. XXXJH exceptions: overflow (when? what operations?) zerodivision
479.313 -
479.314 -<br><br>
479.315 -
479.316 -<br><br>
479.317 -<h3>Bit-string Operations on Integer Types
479.318 -</h3>
479.319 -
479.320 -<br><br>
479.321 -Plain and long integer types support additional operations that make sense only
479.322 -for bit-strings. Negative numbers are treated as their 2's complement value
479.323 -(for long integers, this assumes a sufficiently large number of bits that no
479.324 -overflow occurs during the operation).
479.325 -
479.326 -<br><br>
479.327 -The priorities of the binary bitwise operations are all lower than the numeric
479.328 -operations and higher than the comparisons; the unary operation <code>~</code> has the
479.329 -same priority as the other unary numeric operations (<code>+</code> and <code>-</code>).
479.330 -
479.331 -<br><br>
479.332 -This table lists the bit-string operations sorted in ascending priority:
479.333 -
479.334 -<br><br>
479.335 -<pre>+------------+--------------------------------+----------+
479.336 -| Operation | Result | Notes |
479.337 -+============+================================+==========+
479.338 -| ``x | y`` | bitwise :dfn:`or` of *x* and | |
479.339 -| | *y* | |
479.340 -+------------+--------------------------------+----------+
479.341 -| ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
479.342 -| | *x* and *y* | |
479.343 -+------------+--------------------------------+----------+
479.344 -| ``x & y`` | bitwise :dfn:`and` of *x* and | |
479.345 -| | *y* | |
479.346 -+------------+--------------------------------+----------+
479.347 -| ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
479.348 -+------------+--------------------------------+----------+
479.349 -| ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
479.350 -+------------+--------------------------------+----------+
479.351 -| ``~x`` | the bits of *x* inverted | |
479.352 -+------------+--------------------------------+----------+
479.353 -</pre>
479.354 -Notes:
479.355 -(1)
479.356 - Negative shift counts are illegal and cause a <a href="exc:ValueError">ValueError</a> to be raised.
479.357 -
479.358 -<br><br>
479.359 -(2)
479.360 - A left shift by <b>n</b> bits is equivalent to multiplication by <code>pow(2, n)</code>. A
479.361 - long integer is returned if the result exceeds the range of plain integers.
479.362 -
479.363 -<br><br>
479.364 -(3)
479.365 - A right shift by <b>n</b> bits is equivalent to division by <code>pow(2, n)</code>.
479.366 -
479.367 -<br><br>
479.368 -<h3>Additional Methods on Float
479.369 -</h3>
479.370 -The float type has some additional methods.
479.371 -
479.372 -<br><br>
479.373 -<a href="meth:float.as_integer_ratio()">float.as_integer_ratio()</a>
479.374 -
479.375 -<br><br>
479.376 - Return a pair of integers whose ratio is exactly equal to the
479.377 - original float and with a positive denominator. Raises
479.378 - <a href="exc:OverflowError">OverflowError</a> on infinities and a <a href="exc:ValueError">ValueError</a> on
479.379 - NaNs.
479.380 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
479.381 -</div>
479.382 -Two methods support conversion to
479.383 -and from hexadecimal strings. Since Python's floats are stored
479.384 -internally as binary numbers, converting a float to or from a
479.385 -*decimal* string usually involves a small rounding error. In
479.386 -contrast, hexadecimal strings allow exact representation and
479.387 -specification of floating-point numbers. This can be useful when
479.388 -debugging, and in numerical work.
479.389 -
479.390 -<br><br>
479.391 -<a href="meth:float.hex()">float.hex()</a>
479.392 -
479.393 -<br><br>
479.394 - Return a representation of a floating-point number as a hexadecimal
479.395 - string. For finite floating-point numbers, this representation
479.396 - will always include a leading <code>0x</code> and a trailing <code>p</code> and
479.397 - exponent.
479.398 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
479.399 -</div>
479.400 -<a href="meth:float.fromhex(s)">float.fromhex(s)</a>
479.401 - Class method to return the float represented by a hexadecimal
479.402 - string <b>s</b>. The string <b>s</b> may have leading and trailing
479.403 - whitespace.
479.404 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
479.405 -</div>
479.406 -Note that <a href="meth:float.hex">float.hex</a> is an instance method, while
479.407 -<a href="meth:float.fromhex">float.fromhex</a> is a class method.
479.408 -
479.409 -<br><br>
479.410 -A hexadecimal string takes the form::
479.411 -
479.412 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
479.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>
479.414 -where the optional <code>sign</code> may by either <code>+</code> or <code>-</code>, <code>integer</code>
479.415 -and <code>fraction</code> are strings of hexadecimal digits, and <code>exponent</code>
479.416 -is a decimal integer with an optional leading sign. Case is not
479.417 -significant, and there must be at least one hexadecimal digit in
479.418 -either the integer or the fraction. This syntax is similar to the
479.419 -syntax specified in section 6.4.4.2 of the C99 standard, and also to
479.420 -the syntax used in Java 1.5 onwards. In particular, the output of
479.421 -<a href="meth:float.hex">float.hex</a> is usable as a hexadecimal floating-point literal in
479.422 -C or Java code, and hexadecimal strings produced by C's <code>%a</code> format
479.423 -character or Java's <code>Double.toHexString</code> are accepted by
479.424 -<a href="meth:float.fromhex">float.fromhex</a>.
479.425 -
479.426 -<br><br>
479.427 -Note that the exponent is written in decimal rather than hexadecimal,
479.428 -and that it gives the power of 2 by which to multiply the coefficient.
479.429 -For example, the hexadecimal string <code>0x3.a7p10</code> represents the
479.430 -floating-point number <code>(3 + 10./16 + 7./16**2) * 2.0**10</code>, or
479.431 -<code>3740.0</code>::
479.432 -
479.433 -
479.434 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
479.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>
479.436 -Applying the reverse conversion to <code>3740.0</code> gives a different
479.437 -hexadecimal string representing the same number::
479.438 -
479.439 -
479.440 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
479.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>
479.442 -<h2>Iterator Types
479.443 -</h2>
479.444 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
479.445 -</div>
479.446 -Python supports a concept of iteration over containers. This is implemented
479.447 -using two distinct methods; these are used to allow user-defined classes to
479.448 -support iteration. Sequences, described below in more detail, always support
479.449 -the iteration methods.
479.450 -
479.451 -<br><br>
479.452 -One method needs to be defined for container objects to provide iteration
479.453 -support:
479.454 -
479.455 -<br><br>
479.456 -.. XXX duplicated in reference/datamodel!
479.457 -
479.458 -<br><br>
479.459 -<a href="meth:container.__iter__()">container.__iter__()</a>
479.460 -
479.461 -<br><br>
479.462 - Return an iterator object. The object is required to support the iterator
479.463 - protocol described below. If a container supports different types of
479.464 - iteration, additional methods can be provided to specifically request
479.465 - iterators for those iteration types. (An example of an object supporting
479.466 - multiple forms of iteration would be a tree structure which supports both
479.467 - breadth-first and depth-first traversal.) This method corresponds to the
479.468 - <code>tp_iter</code> slot of the type structure for Python objects in the Python/C
479.469 - API.
479.470 -
479.471 -<br><br>
479.472 -The iterator objects themselves are required to support the following two
479.473 -methods, which together form the :dfn:`iterator protocol`:
479.474 -
479.475 -<br><br>
479.476 -<a href="meth:iterator.__iter__()">iterator.__iter__()</a>
479.477 -
479.478 -<br><br>
479.479 - Return the iterator object itself. This is required to allow both containers
479.480 - and iterators to be used with the <code style="color:#0000e6;">for</code> and <code style="color:#0000e6;">in</code> statements.
479.481 - This method corresponds to the <code>tp_iter</code> slot of the type structure for
479.482 - Python objects in the Python/C API.
479.483 -
479.484 -<br><br>
479.485 -<a href="meth:iterator.next()">iterator.next()</a>
479.486 -
479.487 -<br><br>
479.488 - Return the next item from the container. If there are no further items, raise
479.489 - the <a href="exc:StopIteration">StopIteration</a> exception. This method corresponds to the
479.490 - <code>tp_iternext</code> slot of the type structure for Python objects in the
479.491 - Python/C API.
479.492 -
479.493 -<br><br>
479.494 -Python defines several iterator objects to support iteration over general and
479.495 -specific sequence types, dictionaries, and other more specialized forms. The
479.496 -specific types are not important beyond their implementation of the iterator
479.497 -protocol.
479.498 -
479.499 -<br><br>
479.500 -The intention of the protocol is that once an iterator's <a href="meth:next">next</a> method
479.501 -raises <a href="exc:StopIteration">StopIteration</a>, it will continue to do so on subsequent calls.
479.502 -Implementations that do not obey this property are deemed broken. (This
479.503 -constraint was added in Python 2.3; in Python 2.2, various iterators are broken
479.504 -according to this rule.)
479.505 -
479.506 -<br><br>
479.507 -Python's :term:<code>generator</code>\s provide a convenient way to implement the iterator
479.508 -protocol. If a container object's <a href="meth:__iter__">__iter__</a> method is implemented as a
479.509 -generator, it will automatically return an iterator object (technically, a
479.510 -generator object) supplying the <a href="meth:__iter__">__iter__</a> and <a href="meth:next">next</a> methods.
479.511 -
479.512 -<br><br>
479.513 -
479.514 -<br><br>
479.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>
479.516 -</h2>
479.517 -There are six sequence types: strings, Unicode strings, lists, tuples, buffers,
479.518 -and xrange objects.
479.519 -(For other containers see the built in <a href="class:dict">dict</a>, <a href="class:list">list</a>,
479.520 -<a href="class:set">set</a>, and <a href="class:tuple">tuple</a> classes, and the <a href="mod:collections">collections</a>
479.521 -module.)
479.522 -
479.523 -<br><br>
479.524 -String literals are written in single or double quotes: <code>'xyzzy'</code>,
479.525 -<code>"frobozz"</code>. See <code>strings</code> for more about string literals.
479.526 -Unicode strings are much like strings, but are specified in the syntax
479.527 -using a preceding <code>'u'</code> character: <code>u'abc'</code>, <code>u"def"</code>. In addition
479.528 -to the functionality described here, there are also string-specific
479.529 -methods described in the <code>string-methods</code> section. Lists are
479.530 -constructed with square brackets, separating items with commas: <code>[a, b, c]</code>.
479.531 -Tuples are constructed by the comma operator (not within square
479.532 -brackets), with or without enclosing parentheses, but an empty tuple
479.533 -must have the enclosing parentheses, such as <code>a, b, c</code> or <code>()</code>. A
479.534 -single item tuple must have a trailing comma, such as <code>(d,)</code>.
479.535 -
479.536 -<br><br>
479.537 -Buffer objects are not directly supported by Python syntax, but can be created
479.538 -by calling the builtin function <a href="func:buffer">buffer</a>. They don't support
479.539 -concatenation or repetition.
479.540 -
479.541 -<br><br>
479.542 -Objects of type xrange are similar to buffers in that there is no specific syntax to
479.543 -create them, but they are created using the <a href="func:xrange">xrange</a> function. They don't
479.544 -support slicing, concatenation or repetition, and using <code>in</code>, <code>not in</code>,
479.545 -<a href="func:min">min</a> or <a href="func:max">max</a> on them is inefficient.
479.546 -
479.547 -<br><br>
479.548 -Most sequence types support the following operations. The <code>in</code> and <code>not in</code>
479.549 -operations have the same priorities as the comparison operations. The <code>+</code> and
479.550 -<code>*</code> operations have the same priority as the corresponding numeric operations.
479.551 -[#]_ Additional methods are provided for <code>typesseq-mutable</code>.
479.552 -
479.553 -<br><br>
479.554 -This table lists the sequence operations sorted in ascending priority
479.555 -(operations in the same box have the same priority). In the table, <b>s</b> and <b>t</b>
479.556 -are sequences of the same type; <b>n</b>, <b>i</b> and <b>j</b> are integers:
479.557 -
479.558 -<br><br>
479.559 -<pre>+------------------+--------------------------------+----------+
479.560 -| Operation | Result | Notes |
479.561 -+==================+================================+==========+
479.562 -| ``x in s`` | ``True`` if an item of *s* is | \(1) |
479.563 -| | equal to *x*, else ``False`` | |
479.564 -+------------------+--------------------------------+----------+
479.565 -| ``x not in s`` | ``False`` if an item of *s* is | \(1) |
479.566 -| | equal to *x*, else ``True`` | |
479.567 -+------------------+--------------------------------+----------+
479.568 -| ``s + t`` | the concatenation of *s* and | \(6) |
479.569 -| | *t* | |
479.570 -+------------------+--------------------------------+----------+
479.571 -| ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
479.572 -| | concatenated | |
479.573 -+------------------+--------------------------------+----------+
479.574 -| ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
479.575 -+------------------+--------------------------------+----------+
479.576 -| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
479.577 -+------------------+--------------------------------+----------+
479.578 -| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
479.579 -| | with step *k* | |
479.580 -+------------------+--------------------------------+----------+
479.581 -| ``len(s)`` | length of *s* | |
479.582 -+------------------+--------------------------------+----------+
479.583 -| ``min(s)`` | smallest item of *s* | |
479.584 -+------------------+--------------------------------+----------+
479.585 -| ``max(s)`` | largest item of *s* | |
479.586 -+------------------+--------------------------------+----------+
479.587 -</pre>
479.588 -Sequence types also support comparisons. In particular, tuples and lists
479.589 -are compared lexicographically by comparing corresponding
479.590 -elements. This means that to compare equal, every element must compare
479.591 -equal and the two sequences must be of the same type and have the same
479.592 -length. (For full details see <code>comparisons</code> in the language
479.593 -reference.)
479.594 -
479.595 -<br><br>
479.596 -Notes:
479.597 -(1)
479.598 - When <b>s</b> is a string or Unicode string object the <code>in</code> and <code>not in</code>
479.599 - operations act like a substring test. In Python versions before 2.3, <b>x</b> had to
479.600 - be a string of length 1. In Python 2.3 and beyond, <b>x</b> may be a string of any
479.601 - length.
479.602 -
479.603 -<br><br>
479.604 -(2)
479.605 - Values of <b>n</b> less than <code>0</code> are treated as <code>0</code> (which yields an empty
479.606 - sequence of the same type as <b>s</b>). Note also that the copies are shallow;
479.607 - nested structures are not copied. This often haunts new Python programmers;
479.608 - consider:
479.609 -
479.610 -<br><br>
479.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>
479.612 -<br><br>
479.613 - What has happened is that <code>[[]]</code> is a one-element list containing an empty
479.614 - list, so all three elements of <code>[[]] * 3</code> are (pointers to) this single empty
479.615 - list. Modifying any of the elements of <code>lists</code> modifies this single list.
479.616 - You can create a list of different lists this way:
479.617 -
479.618 -<br><br>
479.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>
479.620 -<br><br>
479.621 -(3)
479.622 - If <b>i</b> or <b>j</b> is negative, the index is relative to the end of the string:
479.623 - <code>len(s) + i</code> or <code>len(s) + j</code> is substituted. But note that <code>-0</code> is still
479.624 - <code>0</code>.
479.625 -
479.626 -<br><br>
479.627 -(4)
479.628 - The slice of <b>s</b> from <b>i</b> to <b>j</b> is defined as the sequence of items with index
479.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
479.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
479.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
479.632 - empty.
479.633 -
479.634 -<br><br>
479.635 -(5)
479.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
479.637 - items with index <code>x = i + n*k</code> such that <code>0 <= n < (j-i)/k</code>. In other words,
479.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
479.639 - <b>j</b> is reached (but never including <b>j</b>). If <b>i</b> or <b>j</b> is greater than
479.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
479.641 - "end" values (which end depends on the sign of <b>k</b>). Note, <b>k</b> cannot be zero.
479.642 - If <b>k</b> is <code>None</code>, it is treated like <code>1</code>.
479.643 -
479.644 -<br><br>
479.645 -(6)
479.646 - If <b>s</b> and <b>t</b> are both strings, some Python implementations such as CPython can
479.647 - usually perform an in-place optimization for assignments of the form <code>s=s+t</code>
479.648 - or <code>s+=t</code>. When applicable, this optimization makes quadratic run-time much
479.649 - less likely. This optimization is both version and implementation dependent.
479.650 - For performance sensitive code, it is preferable to use the <a href="meth:str.join">str.join</a>
479.651 - method which assures consistent linear concatenation performance across versions
479.652 - and implementations.
479.653 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
479.654 - Formerly, string concatenation never occurred in-place.
479.655 -</div>
479.656 -<h3>String Methods
479.657 -</h3>
479.658 -Below are listed the string methods which both 8-bit strings and Unicode objects
479.659 -support. Note that none of these methods take keyword arguments.
479.660 -
479.661 -<br><br>
479.662 -In addition, Python's strings support the sequence type methods
479.663 -described in the <code>typesseq</code> section. To output formatted strings
479.664 -use template strings or the <code>%</code> operator described in the
479.665 -<code>string-formatting</code> section. Also, see the <a href="mod:re">re</a> module for
479.666 -string functions based on regular expressions.
479.667 -
479.668 -<br><br>
479.669 -<a href="meth:str.capitalize()">str.capitalize()</a>
479.670 -
479.671 -<br><br>
479.672 - Return a copy of the string with only its first character capitalized.
479.673 -
479.674 -<br><br>
479.675 - For 8-bit strings, this method is locale-dependent.
479.676 -
479.677 -<br><br>
479.678 -<a href="meth:str.center(width[, fillchar])">str.center(width[, fillchar])</a>
479.679 -
479.680 -<br><br>
479.681 - Return centered in a string of length <b>width</b>. Padding is done using the
479.682 - specified <b>fillchar</b> (default is a space).
479.683 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
479.684 - Support for the <b>fillchar</b> argument.
479.685 -</div>
479.686 -<a href="meth:str.count(sub[, start[, end]])">str.count(sub[, start[, end]])</a>
479.687 - Return the number of occurrences of substring <b>sub</b> in the range [<b>start</b>,
479.688 - <b>end</b>]. Optional arguments <b>start</b> and <b>end</b> are interpreted as in slice
479.689 - notation.
479.690 -
479.691 -<br><br>
479.692 -<a href="meth:str.decode([encoding[, errors]])">str.decode([encoding[, errors]])</a>
479.693 -
479.694 -<br><br>
479.695 - Decodes the string using the codec registered for <b>encoding</b>. <b>encoding</b>
479.696 - defaults to the default string encoding. <b>errors</b> may be given to set a
479.697 - different error handling scheme. The default is <code>'strict'</code>, meaning that
479.698 - encoding errors raise <a href="exc:UnicodeError">UnicodeError</a>. Other possible values are
479.699 - <code>'ignore'</code>, <code>'replace'</code> and any other name registered via
479.700 - <a href="func:codecs.register_error">codecs.register_error</a>, see section <code>codec-base-classes</code>.
479.701 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
479.702 -</div>
479.703 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
479.704 - Support for other error handling schemes added.
479.705 -</div>
479.706 -<a href="meth:str.encode([encoding[,errors]])">str.encode([encoding[,errors]])</a>
479.707 - Return an encoded version of the string. Default encoding is the current
479.708 - default string encoding. <b>errors</b> may be given to set a different error
479.709 - handling scheme. The default for <b>errors</b> is <code>'strict'</code>, meaning that
479.710 - encoding errors raise a <a href="exc:UnicodeError">UnicodeError</a>. Other possible values are
479.711 - <code>'ignore'</code>, <code>'replace'</code>, <code>'xmlcharrefreplace'</code>, <code>'backslashreplace'</code> and
479.712 - any other name registered via <a href="func:codecs.register_error">codecs.register_error</a>, see section
479.713 - <code>codec-base-classes</code>. For a list of possible encodings, see section
479.714 - <code>standard-encodings</code>.
479.715 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.0
479.716 -</div>
479.717 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
479.718 - Support for <code>'xmlcharrefreplace'</code> and <code>'backslashreplace'</code> and other error
479.719 - handling schemes added.
479.720 -</div>
479.721 -<a href="meth:str.endswith(suffix[, start[, end]])">str.endswith(suffix[, start[, end]])</a>
479.722 - Return <code>True</code> if the string ends with the specified <b>suffix</b>, otherwise return
479.723 - <code>False</code>. <b>suffix</b> can also be a tuple of suffixes to look for. With optional
479.724 - <b>start</b>, test beginning at that position. With optional <b>end</b>, stop comparing
479.725 - at that position.
479.726 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.5
479.727 - Accept tuples as <b>suffix</b>.
479.728 -</div>
479.729 -<a href="meth:str.expandtabs([tabsize])">str.expandtabs([tabsize])</a>
479.730 - Return a copy of the string where all tab characters are replaced by one or
479.731 - more spaces, depending on the current column and the given tab size. The
479.732 - column number is reset to zero after each newline occurring in the string.
479.733 - If <b>tabsize</b> is not given, a tab size of <code>8</code> characters is assumed. This
479.734 - doesn't understand other non-printing characters or escape sequences.
479.735 -
479.736 -<br><br>
479.737 -<a href="meth:str.find(sub[, start[, end]])">str.find(sub[, start[, end]])</a>
479.738 -
479.739 -<br><br>
479.740 - Return the lowest index in the string where substring <b>sub</b> is found, such that
479.741 - <b>sub</b> is contained in the range [<b>start</b>, <b>end</b>]. Optional arguments <b>start</b>
479.742 - and <b>end</b> are interpreted as in slice notation. Return <code>-1</code> if <b>sub</b> is not
479.743 - found.
479.744 -
479.745 -<br><br>
479.746 -<a href="meth:str.format(format_string, *args, **kwargs)">str.format(format_string, *args, **kwargs)</a>
479.747 -
479.748 -<br><br>
479.749 - Perform a string formatting operation. The <b>format_string</b> argument can
479.750 - contain literal text or replacement fields delimited by braces <code>{}</code>. Each
479.751 - replacement field contains either the numeric index of a positional argument,
479.752 - or the name of a keyword argument. Returns a copy of <b>format_string</b> where
479.753 - each replacement field is replaced with the string value of the corresponding
479.754 - argument.
479.755 -
479.756 -<br><br>
479.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>
479.758 -<br><br>
479.759 - See <code>formatstrings</code> for a description of the various formatting options
479.760 - that can be specified in format strings.
479.761 -
479.762 -<br><br>
479.763 - This method of string formatting is the new standard in Python 3.0, and
479.764 - should be preferred to the <code>%</code> formatting described in
479.765 - <code>string-formatting</code> in new code.
479.766 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
479.767 -</div>
479.768 -<a href="meth:str.index(sub[, start[, end]])">str.index(sub[, start[, end]])</a>
479.769 - Like <a href="meth:find">find</a>, but raise <a href="exc:ValueError">ValueError</a> when the substring is not found.
479.770 -
479.771 -<br><br>
479.772 -<a href="meth:str.isalnum()">str.isalnum()</a>
479.773 -
479.774 -<br><br>
479.775 - Return true if all characters in the string are alphanumeric and there is at
479.776 - least one character, false otherwise.
479.777 -
479.778 -<br><br>
479.779 - For 8-bit strings, this method is locale-dependent.
479.780 -
479.781 -<br><br>
479.782 -<a href="meth:str.isalpha()">str.isalpha()</a>
479.783 -
479.784 -<br><br>
479.785 - Return true if all characters in the string are alphabetic and there is at least
479.786 - one character, false otherwise.
479.787 -
479.788 -<br><br>
479.789 - For 8-bit strings, this method is locale-dependent.
479.790 -
479.791 -<br><br>
479.792 -<a href="meth:str.isdigit()">str.isdigit()</a>
479.793 -
479.794 -<br><br>
479.795 - Return true if all characters in the string are digits and there is at least one
479.796 - character, false otherwise.
479.797 -
479.798 -<br><br>
479.799 - For 8-bit strings, this method is locale-dependent.
479.800 -
479.801 -<br><br>
479.802 -<a href="meth:str.islower()">str.islower()</a>
479.803 -
479.804 -<br><br>
479.805 - Return true if all cased characters in the string are lowercase and there is at
479.806 - least one cased character, false otherwise.
479.807 -
479.808 -<br><br>
479.809 - For 8-bit strings, this method is locale-dependent.
479.810 -
479.811 -<br><br>
479.812 -<a href="meth:str.isspace()">str.isspace()</a>
479.813 -
479.814 -<br><br>
479.815 - Return true if there are only whitespace characters in the string and there is
479.816 - at least one character, false otherwise.
479.817 -
479.818 -<br><br>
479.819 - For 8-bit strings, this method is locale-dependent.
479.820 -
479.821 -<br><br>
479.822 -<a href="meth:str.istitle()">str.istitle()</a>
479.823 -
479.824 -<br><br>
479.825 - Return true if the string is a titlecased string and there is at least one
479.826 - character, for example uppercase characters may only follow uncased characters
479.827 - and lowercase characters only cased ones. Return false otherwise.
479.828 -
479.829 -<br><br>
479.830 - For 8-bit strings, this method is locale-dependent.
479.831 -
479.832 -<br><br>
479.833 -<a href="meth:str.isupper()">str.isupper()</a>
479.834 -
479.835 -<br><br>
479.836 - Return true if all cased characters in the string are uppercase and there is at
479.837 - least one cased character, false otherwise.
479.838 -
479.839 -<br><br>
479.840 - For 8-bit strings, this method is locale-dependent.
479.841 -
479.842 -<br><br>
479.843 -<a href="meth:str.join(seq)">str.join(seq)</a>
479.844 -
479.845 -<br><br>
479.846 - Return a string which is the concatenation of the strings in the sequence <b>seq</b>.
479.847 - The separator between elements is the string providing this method.
479.848 -
479.849 -<br><br>
479.850 -<a href="meth:str.ljust(width[, fillchar])">str.ljust(width[, fillchar])</a>
479.851 -
479.852 -<br><br>
479.853 - Return the string left justified in a string of length <b>width</b>. Padding is done
479.854 - using the specified <b>fillchar</b> (default is a space). The original string is
479.855 - returned if <b>width</b> is less than <code>len(s)</code>.
479.856 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
479.857 - Support for the <b>fillchar</b> argument.
479.858 -</div>
479.859 -<a href="meth:str.lower()">str.lower()</a>
479.860 - Return a copy of the string converted to lowercase.
479.861 -
479.862 -<br><br>
479.863 - For 8-bit strings, this method is locale-dependent.
479.864 -
479.865 -<br><br>
479.866 -<a href="meth:str.lstrip([chars])">str.lstrip([chars])</a>
479.867 -
479.868 -<br><br>
479.869 - Return a copy of the string with leading characters removed. The <b>chars</b>
479.870 - argument is a string specifying the set of characters to be removed. If omitted
479.871 - or <code>None</code>, the <b>chars</b> argument defaults to removing whitespace. The <b>chars</b>
479.872 - argument is not a prefix; rather, all combinations of its values are stripped:
479.873 -
479.874 -<br><br>
479.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
479.876 - Support for the <b>chars</b> argument.
479.877 -</div>
479.878 -<a href="meth:str.partition(sep)">str.partition(sep)</a>
479.879 - Split the string at the first occurrence of <b>sep</b>, and return a 3-tuple
479.880 - containing the part before the separator, the separator itself, and the part
479.881 - after the separator. If the separator is not found, return a 3-tuple containing
479.882 - the string itself, followed by two empty strings.
479.883 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.5
479.884 -</div>
479.885 -<a href="meth:str.replace(old, new[, count])">str.replace(old, new[, count])</a>
479.886 - Return a copy of the string with all occurrences of substring <b>old</b> replaced by
479.887 - <b>new</b>. If the optional argument <b>count</b> is given, only the first <b>count</b>
479.888 - occurrences are replaced.
479.889 -
479.890 -<br><br>
479.891 -<a href="meth:str.rfind(sub [,start [,end]])">str.rfind(sub [,start [,end]])</a>
479.892 -
479.893 -<br><br>
479.894 - Return the highest index in the string where substring <b>sub</b> is found, such that
479.895 - <b>sub</b> is contained within s[start,end]. Optional arguments <b>start</b> and <b>end</b>
479.896 - are interpreted as in slice notation. Return <code>-1</code> on failure.
479.897 -
479.898 -<br><br>
479.899 -<a href="meth:str.rindex(sub[, start[, end]])">str.rindex(sub[, start[, end]])</a>
479.900 -
479.901 -<br><br>
479.902 - Like <a href="meth:rfind">rfind</a> but raises <a href="exc:ValueError">ValueError</a> when the substring <b>sub</b> is not
479.903 - found.
479.904 -
479.905 -<br><br>
479.906 -<a href="meth:str.rjust(width[, fillchar])">str.rjust(width[, fillchar])</a>
479.907 -
479.908 -<br><br>
479.909 - Return the string right justified in a string of length <b>width</b>. Padding is done
479.910 - using the specified <b>fillchar</b> (default is a space). The original string is
479.911 - returned if <b>width</b> is less than <code>len(s)</code>.
479.912 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
479.913 - Support for the <b>fillchar</b> argument.
479.914 -</div>
479.915 -<a href="meth:str.rpartition(sep)">str.rpartition(sep)</a>
479.916 - Split the string at the last occurrence of <b>sep</b>, and return a 3-tuple
479.917 - containing the part before the separator, the separator itself, and the part
479.918 - after the separator. If the separator is not found, return a 3-tuple containing
479.919 - two empty strings, followed by the string itself.
479.920 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.5
479.921 -</div>
479.922 -<a href="meth:str.rsplit([sep [,maxsplit]])">str.rsplit([sep [,maxsplit]])</a>
479.923 - Return a list of the words in the string, using <b>sep</b> as the delimiter string.
479.924 - If <b>maxsplit</b> is given, at most <b>maxsplit</b> splits are done, the <b>rightmost</b>
479.925 - ones. If <b>sep</b> is not specified or <code>None</code>, any whitespace string is a
479.926 - separator. Except for splitting from the right, <a href="meth:rsplit">rsplit</a> behaves like
479.927 - <a href="meth:split">split</a> which is described in detail below.
479.928 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.4
479.929 -</div>
479.930 -<a href="meth:str.rstrip([chars])">str.rstrip([chars])</a>
479.931 - Return a copy of the string with trailing characters removed. The <b>chars</b>
479.932 - argument is a string specifying the set of characters to be removed. If omitted
479.933 - or <code>None</code>, the <b>chars</b> argument defaults to removing whitespace. The <b>chars</b>
479.934 - argument is not a suffix; rather, all combinations of its values are stripped:
479.935 -
479.936 -<br><br>
479.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
479.938 - Support for the <b>chars</b> argument.
479.939 -</div>
479.940 -<a href="meth:str.split([sep[, maxsplit]])">str.split([sep[, maxsplit]])</a>
479.941 - Return a list of the words in the string, using <b>sep</b> as the delimiter
479.942 - string. If <b>maxsplit</b> is given, at most <b>maxsplit</b> splits are done (thus,
479.943 - the list will have at most <code>maxsplit+1</code> elements). If <b>maxsplit</b> is not
479.944 - specified, then there is no limit on the number of splits (all possible
479.945 - splits are made).
479.946 -
479.947 -<br><br>
479.948 - If <b>sep</b> is given, consecutive delimiters are not grouped together and are
479.949 - deemed to delimit empty strings (for example, <code>'1,,2'.split(',')</code> returns
479.950 - <code>['1', '', '2']</code>). The <b>sep</b> argument may consist of multiple characters
479.951 - (for example, <code>'1<>2<>3'.split('<>')</code> returns <code>['1', '2', '3']</code>).
479.952 - Splitting an empty string with a specified separator returns <code>['']</code>.
479.953 -
479.954 -<br><br>
479.955 - If <b>sep</b> is not specified or is <code>None</code>, a different splitting algorithm is
479.956 - applied: runs of consecutive whitespace are regarded as a single separator,
479.957 - and the result will contain no empty strings at the start or end if the
479.958 - string has leading or trailing whitespace. Consequently, splitting an empty
479.959 - string or a string consisting of just whitespace with a <code>None</code> separator
479.960 - returns <code>[]</code>.
479.961 -
479.962 -<br><br>
479.963 - For example, <code>' 1 2 3 '.split()</code> returns <code>['1', '2', '3']</code>, and
479.964 - <code>' 1 2 3 '.split(None, 1)</code> returns <code>['1', '2 3 ']</code>.
479.965 -
479.966 -<br><br>
479.967 -<a href="meth:str.splitlines([keepends])">str.splitlines([keepends])</a>
479.968 -
479.969 -<br><br>
479.970 - Return a list of the lines in the string, breaking at line boundaries. Line
479.971 - breaks are not included in the resulting list unless <b>keepends</b> is given and
479.972 - true.
479.973 -
479.974 -<br><br>
479.975 -<a href="meth:str.startswith(prefix[, start[, end]])">str.startswith(prefix[, start[, end]])</a>
479.976 -
479.977 -<br><br>
479.978 - Return <code>True</code> if string starts with the <b>prefix</b>, otherwise return <code>False</code>.
479.979 - <b>prefix</b> can also be a tuple of prefixes to look for. With optional <b>start</b>,
479.980 - test string beginning at that position. With optional <b>end</b>, stop comparing
479.981 - string at that position.
479.982 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.5
479.983 - Accept tuples as <b>prefix</b>.
479.984 -</div>
479.985 -<a href="meth:str.strip([chars])">str.strip([chars])</a>
479.986 - Return a copy of the string with the leading and trailing characters removed.
479.987 - The <b>chars</b> argument is a string specifying the set of characters to be removed.
479.988 - If omitted or <code>None</code>, the <b>chars</b> argument defaults to removing whitespace.
479.989 - The <b>chars</b> argument is not a prefix or suffix; rather, all combinations of its
479.990 - values are stripped:
479.991 -
479.992 -<br><br>
479.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
479.994 - Support for the <b>chars</b> argument.
479.995 -</div>
479.996 -<a href="meth:str.swapcase()">str.swapcase()</a>
479.997 - Return a copy of the string with uppercase characters converted to lowercase and
479.998 - vice versa.
479.999 -
479.1000 -<br><br>
479.1001 - For 8-bit strings, this method is locale-dependent.
479.1002 -
479.1003 -<br><br>
479.1004 -<a href="meth:str.title()">str.title()</a>
479.1005 -
479.1006 -<br><br>
479.1007 - Return a titlecased version of the string: words start with uppercase
479.1008 - characters, all remaining cased characters are lowercase.
479.1009 -
479.1010 -<br><br>
479.1011 - For 8-bit strings, this method is locale-dependent.
479.1012 -
479.1013 -<br><br>
479.1014 -<a href="meth:str.translate(table[, deletechars])">str.translate(table[, deletechars])</a>
479.1015 -
479.1016 -<br><br>
479.1017 - Return a copy of the string where all characters occurring in the optional
479.1018 - argument <b>deletechars</b> are removed, and the remaining characters have been
479.1019 - mapped through the given translation table, which must be a string of length
479.1020 - 256.
479.1021 -
479.1022 -<br><br>
479.1023 - You can use the <a href="func:maketrans">maketrans</a> helper function in the <a href="mod:string">string</a> module to
479.1024 - create a translation table. For string objects, set the <b>table</b> argument to
479.1025 - <code>None</code> for translations that only delete characters:
479.1026 -
479.1027 -<br><br>
479.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
479.1029 - Support for a <code>None</code> <b>table</b> argument.
479.1030 -</div>
479.1031 - For Unicode objects, the <a href="meth:translate">translate</a> method does not accept the optional
479.1032 - <b>deletechars</b> argument. Instead, it returns a copy of the <b>s</b> where all
479.1033 - characters have been mapped through the given translation table which must be a
479.1034 - mapping of Unicode ordinals to Unicode ordinals, Unicode strings or <code>None</code>.
479.1035 - Unmapped characters are left untouched. Characters mapped to <code>None</code> are
479.1036 - deleted. Note, a more flexible approach is to create a custom character mapping
479.1037 - codec using the <a href="mod:codecs">codecs</a> module (see <a href="mod:encodings.cp1251">encodings.cp1251</a> for an
479.1038 - example).
479.1039 -
479.1040 -<br><br>
479.1041 -<a href="meth:str.upper()">str.upper()</a>
479.1042 -
479.1043 -<br><br>
479.1044 - Return a copy of the string converted to uppercase.
479.1045 -
479.1046 -<br><br>
479.1047 - For 8-bit strings, this method is locale-dependent.
479.1048 -
479.1049 -<br><br>
479.1050 -<a href="meth:str.zfill(width)">str.zfill(width)</a>
479.1051 -
479.1052 -<br><br>
479.1053 - Return the numeric string left filled with zeros in a string of length
479.1054 - <b>width</b>. A sign prefix is handled correctly. The original string is
479.1055 - returned if <b>width</b> is less than <code>len(s)</code>.
479.1056 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2.2
479.1057 -</div>
479.1058 -The following methods are present only on unicode objects:
479.1059 -<a href="meth:unicode.isnumeric()">unicode.isnumeric()</a>
479.1060 -
479.1061 -<br><br>
479.1062 - Return <code>True</code> if there are only numeric characters in S, <code>False</code>
479.1063 - otherwise. Numeric characters include digit characters, and all characters
479.1064 - that have the Unicode numeric value property, e.g. U+2155,
479.1065 - VULGAR FRACTION ONE FIFTH.
479.1066 -
479.1067 -<br><br>
479.1068 -<a href="meth:unicode.isdecimal()">unicode.isdecimal()</a>
479.1069 -
479.1070 -<br><br>
479.1071 - Return <code>True</code> if there are only decimal characters in S, <code>False</code>
479.1072 - otherwise. Decimal characters include digit characters, and all characters
479.1073 - that that can be used to form decimal-radix numbers, e.g. U+0660,
479.1074 - ARABIC-INDIC DIGIT ZERO.
479.1075 -
479.1076 -<br><br>
479.1077 -
479.1078 -<br><br>
479.1079 -<h3>String Formatting Operations
479.1080 -</h3>
479.1081 -String and Unicode objects have one unique built-in operation: the <code>%</code>
479.1082 -operator (modulo). This is also known as the string <b>formatting</b> or
479.1083 -*interpolation* operator. Given <code>format % values</code> (where <b>format</b> is a string
479.1084 -or Unicode object), <code>%</code> conversion specifications in <b>format</b> are replaced
479.1085 -with zero or more elements of <b>values</b>. The effect is similar to the using
479.1086 -:cfunc:<code>sprintf</code> in the C language. If <b>format</b> is a Unicode object, or if any
479.1087 -of the objects being converted using the <code>%s</code> conversion are Unicode objects,
479.1088 -the result will also be a Unicode object.
479.1089 -
479.1090 -<br><br>
479.1091 -If <b>format</b> requires a single argument, <b>values</b> may be a single non-tuple
479.1092 -object. [#]_ Otherwise, <b>values</b> must be a tuple with exactly the number of
479.1093 -items specified by the format string, or a single mapping object (for example, a
479.1094 -dictionary).
479.1095 -
479.1096 -<br><br>
479.1097 -A conversion specifier contains two or more characters and has the following
479.1098 -components, which must occur in this order:
479.1099 -
479.1100 -<br><br>
479.1101 -#. The <code>'%'</code> character, which marks the start of the specifier.
479.1102 -
479.1103 -<br><br>
479.1104 -#. Mapping key (optional), consisting of a parenthesised sequence of characters
479.1105 - (for example, <code>(somename)</code>).
479.1106 -
479.1107 -<br><br>
479.1108 -#. Conversion flags (optional), which affect the result of some conversion
479.1109 - types.
479.1110 -
479.1111 -<br><br>
479.1112 -#. Minimum field width (optional). If specified as an <code>'*'</code> (asterisk), the
479.1113 - actual width is read from the next element of the tuple in <b>values</b>, and the
479.1114 - object to convert comes after the minimum field width and optional precision.
479.1115 -
479.1116 -<br><br>
479.1117 -#. Precision (optional), given as a <code>'.'</code> (dot) followed by the precision. If
479.1118 - specified as <code>'*'</code> (an asterisk), the actual width is read from the next
479.1119 - element of the tuple in <b>values</b>, and the value to convert comes after the
479.1120 - precision.
479.1121 -
479.1122 -<br><br>
479.1123 -#. Length modifier (optional).
479.1124 -
479.1125 -<br><br>
479.1126 -#. Conversion type.
479.1127 -
479.1128 -<br><br>
479.1129 -When the right argument is a dictionary (or other mapping type), then the
479.1130 -formats in the string <b>must</b> include a parenthesised mapping key into that
479.1131 -dictionary inserted immediately after the <code>'%'</code> character. The mapping key
479.1132 -selects the value to be formatted from the mapping. For example:
479.1133 -
479.1134 -<br><br>
479.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>
479.1136 -<br><br>
479.1137 -In this case no <code>*</code> specifiers may occur in a format (since they require a
479.1138 -sequential parameter list).
479.1139 -
479.1140 -<br><br>
479.1141 -The conversion flag characters are:
479.1142 -
479.1143 -<br><br>
479.1144 -<pre>+---------+---------------------------------------------------------------------+
479.1145 -| Flag | Meaning |
479.1146 -+=========+=====================================================================+
479.1147 -| ``'#'`` | The value conversion will use the "alternate form" (where defined |
479.1148 -| | below). |
479.1149 -+---------+---------------------------------------------------------------------+
479.1150 -| ``'0'`` | The conversion will be zero padded for numeric values. |
479.1151 -+---------+---------------------------------------------------------------------+
479.1152 -| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
479.1153 -| | conversion if both are given). |
479.1154 -+---------+---------------------------------------------------------------------+
479.1155 -| ``' '`` | (a space) A blank should be left before a positive number (or empty |
479.1156 -| | string) produced by a signed conversion. |
479.1157 -+---------+---------------------------------------------------------------------+
479.1158 -| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
479.1159 -| | (overrides a "space" flag). |
479.1160 -+---------+---------------------------------------------------------------------+
479.1161 -</pre>
479.1162 -A length modifier (<code>h</code>, <code>l</code>, or <code>L</code>) may be present, but is ignored as it
479.1163 -is not necessary for Python -- so e.g. <code>%ld</code> is identical to <code>%d</code>.
479.1164 -
479.1165 -<br><br>
479.1166 -The conversion types are:
479.1167 -
479.1168 -<br><br>
479.1169 -<pre>+------------+-----------------------------------------------------+-------+
479.1170 -| Conversion | Meaning | Notes |
479.1171 -+============+=====================================================+=======+
479.1172 -| ``'d'`` | Signed integer decimal. | |
479.1173 -+------------+-----------------------------------------------------+-------+
479.1174 -| ``'i'`` | Signed integer decimal. | |
479.1175 -+------------+-----------------------------------------------------+-------+
479.1176 -| ``'o'`` | Signed octal value. | \(1) |
479.1177 -+------------+-----------------------------------------------------+-------+
479.1178 -| ``'u'`` | Obselete type -- it is identical to ``'d'``. | \(7) |
479.1179 -+------------+-----------------------------------------------------+-------+
479.1180 -| ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
479.1181 -+------------+-----------------------------------------------------+-------+
479.1182 -| ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
479.1183 -+------------+-----------------------------------------------------+-------+
479.1184 -| ``'e'`` | Floating point exponential format (lowercase). | \(3) |
479.1185 -+------------+-----------------------------------------------------+-------+
479.1186 -| ``'E'`` | Floating point exponential format (uppercase). | \(3) |
479.1187 -+------------+-----------------------------------------------------+-------+
479.1188 -| ``'f'`` | Floating point decimal format. | \(3) |
479.1189 -+------------+-----------------------------------------------------+-------+
479.1190 -| ``'F'`` | Floating point decimal format. | \(3) |
479.1191 -+------------+-----------------------------------------------------+-------+
479.1192 -| ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
479.1193 -| | format if exponent is less than -4 or not less than | |
479.1194 -| | precision, decimal format otherwise. | |
479.1195 -+------------+-----------------------------------------------------+-------+
479.1196 -| ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
479.1197 -| | format if exponent is less than -4 or not less than | |
479.1198 -| | precision, decimal format otherwise. | |
479.1199 -+------------+-----------------------------------------------------+-------+
479.1200 -| ``'c'`` | Single character (accepts integer or single | |
479.1201 -| | character string). | |
479.1202 -+------------+-----------------------------------------------------+-------+
479.1203 -| ``'r'`` | String (converts any python object using | \(5) |
479.1204 -| | :func:`repr`). | |
479.1205 -+------------+-----------------------------------------------------+-------+
479.1206 -| ``'s'`` | String (converts any python object using | \(6) |
479.1207 -| | :func:`str`). | |
479.1208 -+------------+-----------------------------------------------------+-------+
479.1209 -| ``'%'`` | No argument is converted, results in a ``'%'`` | |
479.1210 -| | character in the result. | |
479.1211 -+------------+-----------------------------------------------------+-------+
479.1212 -</pre>
479.1213 -Notes:
479.1214 -
479.1215 -<br><br>
479.1216 -(1)
479.1217 - The alternate form causes a leading zero (<code>'0'</code>) to be inserted between
479.1218 - left-hand padding and the formatting of the number if the leading character
479.1219 - of the result is not already a zero.
479.1220 -
479.1221 -<br><br>
479.1222 -(2)
479.1223 - The alternate form causes a leading <code>'0x'</code> or <code>'0X'</code> (depending on whether
479.1224 - the <code>'x'</code> or <code>'X'</code> format was used) to be inserted between left-hand padding
479.1225 - and the formatting of the number if the leading character of the result is not
479.1226 - already a zero.
479.1227 -
479.1228 -<br><br>
479.1229 -(3)
479.1230 - The alternate form causes the result to always contain a decimal point, even if
479.1231 - no digits follow it.
479.1232 -
479.1233 -<br><br>
479.1234 - The precision determines the number of digits after the decimal point and
479.1235 - defaults to 6.
479.1236 -
479.1237 -<br><br>
479.1238 -(4)
479.1239 - The alternate form causes the result to always contain a decimal point, and
479.1240 - trailing zeroes are not removed as they would otherwise be.
479.1241 -
479.1242 -<br><br>
479.1243 - The precision determines the number of significant digits before and after the
479.1244 - decimal point and defaults to 6.
479.1245 -
479.1246 -<br><br>
479.1247 -(5)
479.1248 - The <code>%r</code> conversion was added in Python 2.0.
479.1249 -
479.1250 -<br><br>
479.1251 - The precision determines the maximal number of characters used.
479.1252 -
479.1253 -<br><br>
479.1254 -(6)
479.1255 - If the object or format provided is a <a href="class:unicode">unicode</a> string, the resulting
479.1256 - string will also be <a href="class:unicode">unicode</a>.
479.1257 -
479.1258 -<br><br>
479.1259 - The precision determines the maximal number of characters used.
479.1260 -
479.1261 -<br><br>
479.1262 -(7)
479.1263 - See <a href="http://www.python.org/dev/peps/pep-0237/">PEP 237</a>.
479.1264 -
479.1265 -<br><br>
479.1266 -Since Python strings have an explicit length, <code>%s</code> conversions do not assume
479.1267 -that <code>'\0'</code> is the end of the string.
479.1268 -
479.1269 -<br><br>
479.1270 -.. XXX Examples?
479.1271 -
479.1272 -<br><br>
479.1273 -For safety reasons, floating point precisions are clipped to 50; <code>%f</code>
479.1274 -conversions for numbers whose absolute value is over 1e25 are replaced by <code>%g</code>
479.1275 -conversions. [#]_ All other errors raise exceptions.
479.1276 -
479.1277 -<br><br>
479.1278 -Additional string operations are defined in standard modules <a href="mod:string">string</a> and
479.1279 -<a href="mod:re">re</a>.
479.1280 -
479.1281 -<br><br>
479.1282 -
479.1283 -<br><br>
479.1284 -<h3>XRange Type
479.1285 -</h3>
479.1286 -The <a href="class:xrange">xrange</a> type is an immutable sequence which is commonly used for
479.1287 -looping. The advantage of the <a href="class:xrange">xrange</a> type is that an <a href="class:xrange">xrange</a>
479.1288 -object will always take the same amount of memory, no matter the size of the
479.1289 -range it represents. There are no consistent performance advantages.
479.1290 -
479.1291 -<br><br>
479.1292 -XRange objects have very little behavior: they only support indexing, iteration,
479.1293 -and the <a href="func:len">len</a> function.
479.1294 -
479.1295 -<br><br>
479.1296 -
479.1297 -<br><br>
479.1298 -<h3>Mutable Sequence Types
479.1299 -</h3>
479.1300 -List objects support additional operations that allow in-place modification of
479.1301 -the object. Other mutable sequence types (when added to the language) should
479.1302 -also support these operations. Strings and tuples are immutable sequence types:
479.1303 -such objects cannot be modified once created. The following operations are
479.1304 -defined on mutable sequence types (where <b>x</b> is an arbitrary object):
479.1305 -
479.1306 -<br><br>
479.1307 -<pre>+------------------------------+--------------------------------+---------------------+
479.1308 -| Operation | Result | Notes |
479.1309 -+==============================+================================+=====================+
479.1310 -| ``s[i] = x`` | item *i* of *s* is replaced by | |
479.1311 -| | *x* | |
479.1312 -+------------------------------+--------------------------------+---------------------+
479.1313 -| ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
479.1314 -| | is replaced by the contents of | |
479.1315 -| | the iterable *t* | |
479.1316 -+------------------------------+--------------------------------+---------------------+
479.1317 -| ``del s[i:j]`` | same as ``s[i:j] = []`` | |
479.1318 -+------------------------------+--------------------------------+---------------------+
479.1319 -| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
479.1320 -| | are replaced by those of *t* | |
479.1321 -+------------------------------+--------------------------------+---------------------+
479.1322 -| ``del s[i:j:k]`` | removes the elements of | |
479.1323 -| | ``s[i:j:k]`` from the list | |
479.1324 -+------------------------------+--------------------------------+---------------------+
479.1325 -| ``s.append(x)`` | same as ``s[len(s):len(s)] = | \(2) |
479.1326 -| | [x]`` | |
479.1327 -+------------------------------+--------------------------------+---------------------+
479.1328 -| ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(3) |
479.1329 -| | x`` | |
479.1330 -+------------------------------+--------------------------------+---------------------+
479.1331 -| ``s.count(x)`` | return number of *i*'s for | |
479.1332 -| | which ``s[i] == x`` | |
479.1333 -+------------------------------+--------------------------------+---------------------+
479.1334 -| ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(4) |
479.1335 -| | ``s[k] == x`` and ``i <= k < | |
479.1336 -| | j`` | |
479.1337 -+------------------------------+--------------------------------+---------------------+
479.1338 -| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(5) |
479.1339 -+------------------------------+--------------------------------+---------------------+
479.1340 -| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(6) |
479.1341 -| | return x`` | |
479.1342 -+------------------------------+--------------------------------+---------------------+
479.1343 -| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(4) |
479.1344 -+------------------------------+--------------------------------+---------------------+
479.1345 -| ``s.reverse()`` | reverses the items of *s* in | \(7) |
479.1346 -| | place | |
479.1347 -+------------------------------+--------------------------------+---------------------+
479.1348 -| ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |
479.1349 -| reverse]]])`` | | |
479.1350 -+------------------------------+--------------------------------+---------------------+
479.1351 -</pre>
479.1352 -Notes:
479.1353 -(1)
479.1354 - <b>t</b> must have the same length as the slice it is replacing.
479.1355 -
479.1356 -<br><br>
479.1357 -(2)
479.1358 - The C implementation of Python has historically accepted multiple parameters and
479.1359 - implicitly joined them into a tuple; this no longer works in Python 2.0. Use of
479.1360 - this misfeature has been deprecated since Python 1.4.
479.1361 -
479.1362 -<br><br>
479.1363 -(3)
479.1364 - <b>x</b> can be any iterable object.
479.1365 -
479.1366 -<br><br>
479.1367 -(4)
479.1368 - Raises <a href="exc:ValueError">ValueError</a> when <b>x</b> is not found in <b>s</b>. When a negative index is
479.1369 - passed as the second or third parameter to the <a href="meth:index">index</a> method, the list
479.1370 - length is added, as for slice indices. If it is still negative, it is truncated
479.1371 - to zero, as for slice indices.
479.1372 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
479.1373 - Previously, <a href="meth:index">index</a> didn't have arguments for specifying start and stop
479.1374 - positions.
479.1375 -</div>
479.1376 -(5)
479.1377 - When a negative index is passed as the first parameter to the <a href="meth:insert">insert</a>
479.1378 - method, the list length is added, as for slice indices. If it is still
479.1379 - negative, it is truncated to zero, as for slice indices.
479.1380 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
479.1381 - Previously, all negative indices were truncated to zero.
479.1382 -</div>
479.1383 -(6)
479.1384 - The <a href="meth:pop">pop</a> method is only supported by the list and array types. The
479.1385 - optional argument <b>i</b> defaults to <code>-1</code>, so that by default the last item is
479.1386 - removed and returned.
479.1387 -
479.1388 -<br><br>
479.1389 -(7)
479.1390 - The <a href="meth:sort">sort</a> and <a href="meth:reverse">reverse</a> methods modify the list in place for
479.1391 - economy of space when sorting or reversing a large list. To remind you that
479.1392 - they operate by side effect, they don't return the sorted or reversed list.
479.1393 -
479.1394 -<br><br>
479.1395 -(8)
479.1396 - The <a href="meth:sort">sort</a> method takes optional arguments for controlling the
479.1397 - comparisons.
479.1398 -
479.1399 -<br><br>
479.1400 - <b>cmp</b> specifies a custom comparison function of two arguments (list items) which
479.1401 - should return a negative, zero or positive number depending on whether the first
479.1402 - argument is considered smaller than, equal to, or larger than the second
479.1403 - argument: <code>cmp=lambda x,y: cmp(x.lower(), y.lower())</code>. The default value
479.1404 - is <code>None</code>.
479.1405 -
479.1406 -<br><br>
479.1407 - <b>key</b> specifies a function of one argument that is used to extract a comparison
479.1408 - key from each list element: <code>key=str.lower</code>. The default value is <code>None</code>.
479.1409 -
479.1410 -<br><br>
479.1411 - <b>reverse</b> is a boolean value. If set to <code>True</code>, then the list elements are
479.1412 - sorted as if each comparison were reversed.
479.1413 -
479.1414 -<br><br>
479.1415 - In general, the <b>key</b> and <b>reverse</b> conversion processes are much faster than
479.1416 - specifying an equivalent <b>cmp</b> function. This is because <b>cmp</b> is called
479.1417 - multiple times for each list element while <b>key</b> and <b>reverse</b> touch each
479.1418 - element only once.
479.1419 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
479.1420 - Support for <code>None</code> as an equivalent to omitting <b>cmp</b> was added.
479.1421 -</div>
479.1422 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
479.1423 - Support for <b>key</b> and <b>reverse</b> was added.
479.1424 -</div>
479.1425 -(9)
479.1426 - Starting with Python 2.3, the <a href="meth:sort">sort</a> method is guaranteed to be stable. A
479.1427 - sort is stable if it guarantees not to change the relative order of elements
479.1428 - that compare equal --- this is helpful for sorting in multiple passes (for
479.1429 - example, sort by department, then by salary grade).
479.1430 -
479.1431 -<br><br>
479.1432 -(10)
479.1433 - While a list is being sorted, the effect of attempting to mutate, or even
479.1434 - inspect, the list is undefined. The C implementation of Python 2.3 and newer
479.1435 - makes the list appear empty for the duration, and raises <a href="exc:ValueError">ValueError</a> if it
479.1436 - can detect that the list has been mutated during a sort.
479.1437 -
479.1438 -<br><br>
479.1439 -
479.1440 -<br><br>
479.1441 -<h2>Set Types --- <a href="class:set">set</a>, <a href="class:frozenset">frozenset</a>
479.1442 -</h2>
479.1443 -A :dfn:<code>set</code> object is an unordered collection of distinct :term:<code>hashable</code> objects.
479.1444 -Common uses include membership testing, removing duplicates from a sequence, and
479.1445 -computing mathematical operations such as intersection, union, difference, and
479.1446 -symmetric difference.
479.1447 -(For other containers see the built in <a href="class:dict">dict</a>, <a href="class:list">list</a>,
479.1448 -and <a href="class:tuple">tuple</a> classes, and the <a href="mod:collections">collections</a> module.)
479.1449 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.4
479.1450 -</div>
479.1451 -Like other collections, sets support <code>x in set</code>, <code>len(set)</code>, and ``for x in
479.1452 -set``. Being an unordered collection, sets do not record element position or
479.1453 -order of insertion. Accordingly, sets do not support indexing, slicing, or
479.1454 -other sequence-like behavior.
479.1455 -
479.1456 -<br><br>
479.1457 -There are currently two builtin set types, <a href="class:set">set</a> and <a href="class:frozenset">frozenset</a>.
479.1458 -The <a href="class:set">set</a> type is mutable --- the contents can be changed using methods
479.1459 -like <a href="meth:add">add</a> and <a href="meth:remove">remove</a>. Since it is mutable, it has no hash value
479.1460 -and cannot be used as either a dictionary key or as an element of another set.
479.1461 -The <a href="class:frozenset">frozenset</a> type is immutable and :term:<code>hashable</code> --- its contents cannot be
479.1462 -altered after it is created; it can therefore be used as a dictionary key or as
479.1463 -an element of another set.
479.1464 -
479.1465 -<br><br>
479.1466 -The constructors for both classes work the same:
479.1467 -
479.1468 -<br><br>
479.1469 -<a href="class:set([iterable])">set([iterable])</a>
479.1470 - frozenset([iterable])
479.1471 -
479.1472 -<br><br>
479.1473 - Return a new set or frozenset object whose elements are taken from
479.1474 - <b>iterable</b>. The elements of a set must be hashable. To represent sets of
479.1475 - sets, the inner sets must be <a href="class:frozenset">frozenset</a> objects. If <b>iterable</b> is
479.1476 - not specified, a new empty set is returned.
479.1477 -
479.1478 -<br><br>
479.1479 - Instances of <a href="class:set">set</a> and <a href="class:frozenset">frozenset</a> provide the following
479.1480 - operations:
479.1481 -
479.1482 -<br><br>
479.1483 - .. describe:: len(s)
479.1484 -
479.1485 -<br><br>
479.1486 - Return the cardinality of set <b>s</b>.
479.1487 -
479.1488 -<br><br>
479.1489 - .. describe:: x in s
479.1490 -
479.1491 -<br><br>
479.1492 - Test <b>x</b> for membership in <b>s</b>.
479.1493 -
479.1494 -<br><br>
479.1495 - .. describe:: x not in s
479.1496 -
479.1497 -<br><br>
479.1498 - Test <b>x</b> for non-membership in <b>s</b>.
479.1499 -
479.1500 -<br><br>
479.1501 -<a href="meth:isdisjoint(other)">isdisjoint(other)</a>
479.1502 -
479.1503 -<br><br>
479.1504 - Return True if the set has no elements in common with <b>other</b>. Sets are
479.1505 - disjoint if and only if their intersection is the empty set.
479.1506 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
479.1507 -</div>
479.1508 -<a href="meth:issubset(other)">issubset(other)</a>
479.1509 - set <= other
479.1510 -
479.1511 -<br><br>
479.1512 - Test whether every element in the set is in <b>other</b>.
479.1513 -
479.1514 -<br><br>
479.1515 -<a href="meth:set < other">set < other</a>
479.1516 -
479.1517 -<br><br>
479.1518 - Test whether the set is a true subset of <b>other</b>, that is,
479.1519 - <code>set <= other and set != other</code>.
479.1520 -
479.1521 -<br><br>
479.1522 -<a href="meth:issuperset(other)">issuperset(other)</a>
479.1523 - set >= other
479.1524 -
479.1525 -<br><br>
479.1526 - Test whether every element in <b>other</b> is in the set.
479.1527 -
479.1528 -<br><br>
479.1529 -<a href="meth:set > other">set > other</a>
479.1530 -
479.1531 -<br><br>
479.1532 - Test whether the set is a true superset of <b>other</b>, that is, ``set >=
479.1533 - other and set != other``.
479.1534 -
479.1535 -<br><br>
479.1536 -<a href="meth:union(other, ...)">union(other, ...)</a>
479.1537 - set | other | ...
479.1538 -
479.1539 -<br><br>
479.1540 - Return a new set with elements from both sets.
479.1541 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
479.1542 - Accepts multiple input iterables.
479.1543 -</div>
479.1544 -<a href="meth:intersection(other, ...)">intersection(other, ...)</a>
479.1545 - set & other & ...
479.1546 -
479.1547 -<br><br>
479.1548 - Return a new set with elements common to both sets.
479.1549 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
479.1550 - Accepts multiple input iterables.
479.1551 -</div>
479.1552 -<a href="meth:difference(other, ...)">difference(other, ...)</a>
479.1553 - set - other - ...
479.1554 -
479.1555 -<br><br>
479.1556 - Return a new set with elements in the set that are not in the others.
479.1557 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
479.1558 - Accepts multiple input iterables.
479.1559 -</div>
479.1560 -<a href="meth:symmetric_difference(other)">symmetric_difference(other)</a>
479.1561 - set ^ other
479.1562 -
479.1563 -<br><br>
479.1564 - Return a new set with elements in either the set or <b>other</b> but not both.
479.1565 -
479.1566 -<br><br>
479.1567 -<a href="meth:copy()">copy()</a>
479.1568 -
479.1569 -<br><br>
479.1570 - Return a new set with a shallow copy of <b>s</b>.
479.1571 -
479.1572 -<br><br>
479.1573 - Note, the non-operator versions of <a href="meth:union">union</a>, <a href="meth:intersection">intersection</a>,
479.1574 - <a href="meth:difference">difference</a>, and <a href="meth:symmetric_difference">symmetric_difference</a>, <a href="meth:issubset">issubset</a>, and
479.1575 - <a href="meth:issuperset">issuperset</a> methods will accept any iterable as an argument. In
479.1576 - contrast, their operator based counterparts require their arguments to be
479.1577 - sets. This precludes error-prone constructions like <code>set('abc') & 'cbs'</code>
479.1578 - in favor of the more readable <code>set('abc').intersection('cbs')</code>.
479.1579 -
479.1580 -<br><br>
479.1581 - Both <a href="class:set">set</a> and <a href="class:frozenset">frozenset</a> support set to set comparisons. Two
479.1582 - sets are equal if and only if every element of each set is contained in the
479.1583 - other (each is a subset of the other). A set is less than another set if and
479.1584 - only if the first set is a proper subset of the second set (is a subset, but
479.1585 - is not equal). A set is greater than another set if and only if the first set
479.1586 - is a proper superset of the second set (is a superset, but is not equal).
479.1587 -
479.1588 -<br><br>
479.1589 - Instances of <a href="class:set">set</a> are compared to instances of <a href="class:frozenset">frozenset</a>
479.1590 - based on their members. For example, <code>set('abc') == frozenset('abc')</code>
479.1591 - returns <code>True</code> and so does <code>set('abc') in set([frozenset('abc')])</code>.
479.1592 -
479.1593 -<br><br>
479.1594 - The subset and equality comparisons do not generalize to a complete ordering
479.1595 - function. For example, any two disjoint sets are not equal and are not
479.1596 - subsets of each other, so <b>all</b> of the following return <code>False</code>: <code>a<b</code>,
479.1597 - <code>a==b</code>, or <code>a>b</code>. Accordingly, sets do not implement the <a href="meth:__cmp__">__cmp__</a>
479.1598 - method.
479.1599 -
479.1600 -<br><br>
479.1601 - Since sets only define partial ordering (subset relationships), the output of
479.1602 - the <a href="meth:list.sort">list.sort</a> method is undefined for lists of sets.
479.1603 -
479.1604 -<br><br>
479.1605 - Set elements, like dictionary keys, must be :term:<code>hashable</code>.
479.1606 -
479.1607 -<br><br>
479.1608 - Binary operations that mix <a href="class:set">set</a> instances with <a href="class:frozenset">frozenset</a>
479.1609 - return the type of the first operand. For example: ``frozenset('ab') |
479.1610 - set('bc')`` returns an instance of <a href="class:frozenset">frozenset</a>.
479.1611 -
479.1612 -<br><br>
479.1613 - The following table lists operations available for <a href="class:set">set</a> that do not
479.1614 - apply to immutable instances of <a href="class:frozenset">frozenset</a>:
479.1615 -
479.1616 -<br><br>
479.1617 -<a href="meth:update(other, ...)">update(other, ...)</a>
479.1618 - set |= other | ...
479.1619 -
479.1620 -<br><br>
479.1621 - Update the set, adding elements from <b>other</b>.
479.1622 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
479.1623 - Accepts multiple input iterables.
479.1624 -</div>
479.1625 -<a href="meth:intersection_update(other, ...)">intersection_update(other, ...)</a>
479.1626 - set &= other & ...
479.1627 -
479.1628 -<br><br>
479.1629 - Update the set, keeping only elements found in it and <b>other</b>.
479.1630 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
479.1631 - Accepts multiple input iterables.
479.1632 -</div>
479.1633 -<a href="meth:difference_update(other, ...)">difference_update(other, ...)</a>
479.1634 - set -= other | ...
479.1635 -
479.1636 -<br><br>
479.1637 - Update the set, removing elements found in others.
479.1638 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
479.1639 - Accepts multiple input iterables.
479.1640 -</div>
479.1641 -<a href="meth:symmetric_difference_update(other)">symmetric_difference_update(other)</a>
479.1642 - set ^= other
479.1643 -
479.1644 -<br><br>
479.1645 - Update the set, keeping only elements found in either set, but not in both.
479.1646 -
479.1647 -<br><br>
479.1648 -<a href="meth:add(elem)">add(elem)</a>
479.1649 -
479.1650 -<br><br>
479.1651 - Add element <b>elem</b> to the set.
479.1652 -
479.1653 -<br><br>
479.1654 -<a href="meth:remove(elem)">remove(elem)</a>
479.1655 -
479.1656 -<br><br>
479.1657 - Remove element <b>elem</b> from the set. Raises <a href="exc:KeyError">KeyError</a> if <b>elem</b> is
479.1658 - not contained in the set.
479.1659 -
479.1660 -<br><br>
479.1661 -<a href="meth:discard(elem)">discard(elem)</a>
479.1662 -
479.1663 -<br><br>
479.1664 - Remove element <b>elem</b> from the set if it is present.
479.1665 -
479.1666 -<br><br>
479.1667 -<a href="meth:pop()">pop()</a>
479.1668 -
479.1669 -<br><br>
479.1670 - Remove and return an arbitrary element from the set. Raises
479.1671 - <a href="exc:KeyError">KeyError</a> if the set is empty.
479.1672 -
479.1673 -<br><br>
479.1674 -<a href="meth:clear()">clear()</a>
479.1675 -
479.1676 -<br><br>
479.1677 - Remove all elements from the set.
479.1678 -
479.1679 -<br><br>
479.1680 - Note, the non-operator versions of the <a href="meth:update">update</a>,
479.1681 - <a href="meth:intersection_update">intersection_update</a>, <a href="meth:difference_update">difference_update</a>, and
479.1682 - <a href="meth:symmetric_difference_update">symmetric_difference_update</a> methods will accept any iterable as an
479.1683 - argument.
479.1684 -
479.1685 -<br><br>
479.1686 - Note, the <b>elem</b> argument to the <a href="meth:__contains__">__contains__</a>, <a href="meth:remove">remove</a>, and
479.1687 - <a href="meth:discard">discard</a> methods may be a set. To support searching for an equivalent
479.1688 - frozenset, the <b>elem</b> set is temporarily mutated during the search and then
479.1689 - restored. During the search, the <b>elem</b> set should not be read or mutated
479.1690 - since it does not have a meaningful value.
479.1691 -<div style="margin: 5px 5px; background: #ddffdd; border-size: 1px; padding: 5px"><b>See Also</b>:
479.1692 -
479.1693 -<br><br>
479.1694 - <code>comparison-to-builtin-set</code>
479.1695 - Differences between the <a href="mod:sets">sets</a> module and the built-in set types.
479.1696 -</div>
479.1697 -<h2>Mapping Types --- <a href="class:dict">dict</a>
479.1698 -</h2>
479.1699 -A :dfn:<code>mapping</code> object maps :term:<code>hashable</code> values to arbitrary objects.
479.1700 -Mappings are mutable objects. There is currently only one standard mapping
479.1701 -type, the :dfn:<code>dictionary</code>. (For other containers see the built in
479.1702 -<a href="class:list">list</a>, <a href="class:set">set</a>, and <a href="class:tuple">tuple</a> classes, and the
479.1703 -<a href="mod:collections">collections</a> module.)
479.1704 -
479.1705 -<br><br>
479.1706 -A dictionary's keys are <b>almost</b> arbitrary values. Values that are not
479.1707 -:term:<code>hashable</code>, that is, values containing lists, dictionaries or other
479.1708 -mutable types (that are compared by value rather than by object identity) may
479.1709 -not be used as keys. Numeric types used for keys obey the normal rules for
479.1710 -numeric comparison: if two numbers compare equal (such as <code>1</code> and <code>1.0</code>)
479.1711 -then they can be used interchangeably to index the same dictionary entry. (Note
479.1712 -however, that since computers store floating-point numbers as approximations it
479.1713 -is usually unwise to use them as dictionary keys.)
479.1714 -
479.1715 -<br><br>
479.1716 -Dictionaries can be created by placing a comma-separated list of <code>key: value</code>
479.1717 -pairs within braces, for example: <code>{'jack': 4098, 'sjoerd': 4127}</code> or ``{4098:
479.1718 -'jack', 4127: 'sjoerd'}``, or by the <a href="class:dict">dict</a> constructor.
479.1719 -
479.1720 -<br><br>
479.1721 -<a href="class:dict([arg])">dict([arg])</a>
479.1722 -
479.1723 -<br><br>
479.1724 - Return a new dictionary initialized from an optional positional argument or from
479.1725 - a set of keyword arguments. If no arguments are given, return a new empty
479.1726 - dictionary. If the positional argument <b>arg</b> is a mapping object, return a
479.1727 - dictionary mapping the same keys to the same values as does the mapping object.
479.1728 - Otherwise the positional argument must be a sequence, a container that supports
479.1729 - iteration, or an iterator object. The elements of the argument must each also
479.1730 - be of one of those kinds, and each must in turn contain exactly two objects.
479.1731 - The first is used as a key in the new dictionary, and the second as the key's
479.1732 - value. If a given key is seen more than once, the last value associated with it
479.1733 - is retained in the new dictionary.
479.1734 -
479.1735 -<br><br>
479.1736 - If keyword arguments are given, the keywords themselves with their associated
479.1737 - values are added as items to the dictionary. If a key is specified both in the
479.1738 - positional argument and as a keyword argument, the value associated with the
479.1739 - keyword is retained in the dictionary. For example, these all return a
479.1740 - dictionary equal to <code>{"one": 2, "two": 3}</code>:
479.1741 -
479.1742 -<br><br>
479.1743 - * <code>dict(one=2, two=3)</code>
479.1744 -
479.1745 -<br><br>
479.1746 - * <code>dict({'one': 2, 'two': 3})</code>
479.1747 -
479.1748 -<br><br>
479.1749 - * <code>dict(zip(('one', 'two'), (2, 3)))</code>
479.1750 -
479.1751 -<br><br>
479.1752 - * <code>dict([['two', 3], ['one', 2]])</code>
479.1753 -
479.1754 -<br><br>
479.1755 - The first example only works for keys that are valid Python
479.1756 - identifiers; the others work with any valid keys.
479.1757 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
479.1758 -</div>
479.1759 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
479.1760 - Support for building a dictionary from keyword arguments added.
479.1761 -</div>
479.1762 - These are the operations that dictionaries support (and therefore, custom
479.1763 - mapping types should support too):
479.1764 -
479.1765 -<br><br>
479.1766 - .. describe:: len(d)
479.1767 -
479.1768 -<br><br>
479.1769 - Return the number of items in the dictionary <b>d</b>.
479.1770 -
479.1771 -<br><br>
479.1772 - .. describe:: d[key]
479.1773 -
479.1774 -<br><br>
479.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>
479.1776 - is not in the map.
479.1777 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.5
479.1778 - If a subclass of dict defines a method <a href="meth:__missing__">__missing__</a>, if the key
479.1779 - <b>key</b> is not present, the <code>d[key]</code> operation calls that method with
479.1780 - the key <b>key</b> as argument. The <code>d[key]</code> operation then returns or
479.1781 - raises whatever is returned or raised by the <code>__missing__(key)</code> call
479.1782 - if the key is not present. No other operations or methods invoke
479.1783 - <a href="meth:__missing__">__missing__</a>. If <a href="meth:__missing__">__missing__</a> is not defined,
479.1784 - <a href="exc:KeyError">KeyError</a> is raised. <a href="meth:__missing__">__missing__</a> must be a method; it
479.1785 - cannot be an instance variable. For an example, see
479.1786 - <a href="class:collections.defaultdict">collections.defaultdict</a>.
479.1787 -</div>
479.1788 - .. describe:: d[key] = value
479.1789 - Set <code>d[key]</code> to <b>value</b>.
479.1790 -
479.1791 -<br><br>
479.1792 - .. describe:: del d[key]
479.1793 -
479.1794 -<br><br>
479.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
479.1796 - map.
479.1797 -
479.1798 -<br><br>
479.1799 - .. describe:: key in d
479.1800 -
479.1801 -<br><br>
479.1802 - Return <code>True</code> if <b>d</b> has a key <b>key</b>, else <code>False</code>.
479.1803 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
479.1804 -</div>
479.1805 - .. describe:: key not in d
479.1806 - Equivalent to <code>not key in d</code>.
479.1807 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
479.1808 -</div>
479.1809 -<a href="meth:clear()">clear()</a>
479.1810 - Remove all items from the dictionary.
479.1811 -
479.1812 -<br><br>
479.1813 -<a href="meth:copy()">copy()</a>
479.1814 -
479.1815 -<br><br>
479.1816 - Return a shallow copy of the dictionary.
479.1817 -
479.1818 -<br><br>
479.1819 -<a href="meth:fromkeys(seq[, value])">fromkeys(seq[, value])</a>
479.1820 -
479.1821 -<br><br>
479.1822 - Create a new dictionary with keys from <b>seq</b> and values set to <b>value</b>.
479.1823 -
479.1824 -<br><br>
479.1825 - <a href="func:fromkeys">fromkeys</a> is a class method that returns a new dictionary. <b>value</b>
479.1826 - defaults to <code>None</code>.
479.1827 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
479.1828 -</div>
479.1829 -<a href="meth:get(key[, default])">get(key[, default])</a>
479.1830 - Return the value for <b>key</b> if <b>key</b> is in the dictionary, else <b>default</b>.
479.1831 - If <b>default</b> is not given, it defaults to <code>None</code>, so that this method
479.1832 - never raises a <a href="exc:KeyError">KeyError</a>.
479.1833 -
479.1834 -<br><br>
479.1835 -<a href="meth:has_key(key)">has_key(key)</a>
479.1836 -
479.1837 -<br><br>
479.1838 - <code>dict.has_key(key)</code> is equivalent to <code>key in d</code>, but deprecated.
479.1839 -
479.1840 -<br><br>
479.1841 -<a href="meth:items()">items()</a>
479.1842 -
479.1843 -<br><br>
479.1844 - Return a copy of the dictionary's list of <code>(key, value)</code> pairs.
479.1845 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
479.1846 -
479.1847 -<br><br>
479.1848 - Keys and values are listed in an arbitrary order which is non-random,
479.1849 - varies across Python implementations, and depends on the dictionary's
479.1850 - history of insertions and deletions. If <a href="meth:items">items</a>, <a href="meth:keys">keys</a>,
479.1851 - <a href="meth:values">values</a>, <a href="meth:iteritems">iteritems</a>, <a href="meth:iterkeys">iterkeys</a>, and
479.1852 - <a href="meth:itervalues">itervalues</a> are called with no intervening modifications to the
479.1853 - dictionary, the lists will directly correspond. This allows the
479.1854 - creation of <code>(value, key)</code> pairs using <a href="func:zip">zip</a>: ``pairs =
479.1855 - zip(d.values(), d.keys())``. The same relationship holds for the
479.1856 - <a href="meth:iterkeys">iterkeys</a> and <a href="meth:itervalues">itervalues</a> methods: ``pairs =
479.1857 - zip(d.itervalues(), d.iterkeys())`` provides the same value for
479.1858 - <code>pairs</code>. Another way to create the same list is ``pairs = [(v, k) for
479.1859 - (k, v) in d.iteritems()]``.
479.1860 -</div>
479.1861 -<a href="meth:iteritems()">iteritems()</a>
479.1862 - Return an iterator over the dictionary's <code>(key, value)</code> pairs. See the
479.1863 - note for <a href="meth:dict.items">dict.items</a>.
479.1864 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
479.1865 -</div>
479.1866 -<a href="meth:iterkeys()">iterkeys()</a>
479.1867 - Return an iterator over the dictionary's keys. See the note for
479.1868 - <a href="meth:dict.items">dict.items</a>.
479.1869 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
479.1870 -</div>
479.1871 -<a href="meth:itervalues()">itervalues()</a>
479.1872 - Return an iterator over the dictionary's values. See the note for
479.1873 - <a href="meth:dict.items">dict.items</a>.
479.1874 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
479.1875 -</div>
479.1876 -<a href="meth:keys()">keys()</a>
479.1877 - Return a copy of the dictionary's list of keys. See the note for
479.1878 - <a href="meth:dict.items">dict.items</a>.
479.1879 -
479.1880 -<br><br>
479.1881 -<a href="meth:pop(key[, default])">pop(key[, default])</a>
479.1882 -
479.1883 -<br><br>
479.1884 - If <b>key</b> is in the dictionary, remove it and return its value, else return
479.1885 - <b>default</b>. If <b>default</b> is not given and <b>key</b> is not in the dictionary,
479.1886 - a <a href="exc:KeyError">KeyError</a> is raised.
479.1887 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
479.1888 -</div>
479.1889 -<a href="meth:popitem()">popitem()</a>
479.1890 - Remove and return an arbitrary <code>(key, value)</code> pair from the dictionary.
479.1891 -
479.1892 -<br><br>
479.1893 - <a href="func:popitem">popitem</a> is useful to destructively iterate over a dictionary, as
479.1894 - often used in set algorithms. If the dictionary is empty, calling
479.1895 - <a href="func:popitem">popitem</a> raises a <a href="exc:KeyError">KeyError</a>.
479.1896 -
479.1897 -<br><br>
479.1898 -<a href="meth:setdefault(key[, default])">setdefault(key[, default])</a>
479.1899 -
479.1900 -<br><br>
479.1901 - If <b>key</b> is in the dictionary, return its value. If not, insert <b>key</b>
479.1902 - with a value of <b>default</b> and return <b>default</b>. <b>default</b> defaults to
479.1903 - <code>None</code>.
479.1904 -
479.1905 -<br><br>
479.1906 -<a href="meth:update([other])">update([other])</a>
479.1907 -
479.1908 -<br><br>
479.1909 - Update the dictionary with the key/value pairs from <b>other</b>, overwriting
479.1910 - existing keys. Return <code>None</code>.
479.1911 -
479.1912 -<br><br>
479.1913 - <a href="func:update">update</a> accepts either another dictionary object or an iterable of
479.1914 - key/value pairs (as a tuple or other iterable of length two). If keyword
479.1915 - arguments are specified, the dictionary is then is updated with those
479.1916 - key/value pairs: <code>d.update(red=1, blue=2)</code>.
479.1917 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
479.1918 - Allowed the argument to be an iterable of key/value pairs and allowed
479.1919 - keyword arguments.
479.1920 -</div>
479.1921 -<a href="meth:values()">values()</a>
479.1922 - Return a copy of the dictionary's list of values. See the note for
479.1923 - <a href="meth:dict.items">dict.items</a>.
479.1924 -
479.1925 -<br><br>
479.1926 -
479.1927 -<br><br>
479.1928 -<h2>File Objects
479.1929 -</h2>
479.1930 -File objects are implemented using C's <code>stdio</code> package and can be
479.1931 -created with the built-in <a href="func:open">open</a> function. File
479.1932 -objects are also returned by some other built-in functions and methods,
479.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>
479.1934 -method of socket objects. Temporary files can be created using the
479.1935 -<a href="mod:tempfile">tempfile</a> module, and high-level file operations such as copying,
479.1936 -moving, and deleting files and directories can be achieved with the
479.1937 -<a href="mod:shutil">shutil</a> module.
479.1938 -
479.1939 -<br><br>
479.1940 -When a file operation fails for an I/O-related reason, the exception
479.1941 -<a href="exc:IOError">IOError</a> is raised. This includes situations where the operation is not
479.1942 -defined for some reason, like <a href="meth:seek">seek</a> on a tty device or writing a file
479.1943 -opened for reading.
479.1944 -
479.1945 -<br><br>
479.1946 -Files have the following methods:
479.1947 -
479.1948 -<br><br>
479.1949 -<a href="meth:file.close()">file.close()</a>
479.1950 -
479.1951 -<br><br>
479.1952 - Close the file. A closed file cannot be read or written any more. Any operation
479.1953 - which requires that the file be open will raise a <a href="exc:ValueError">ValueError</a> after the
479.1954 - file has been closed. Calling <a href="meth:close">close</a> more than once is allowed.
479.1955 -
479.1956 -<br><br>
479.1957 - As of Python 2.5, you can avoid having to call this method explicitly if you use
479.1958 - the <code style="color:#0000e6;">with</code> statement. For example, the following code will
479.1959 - automatically close <b>f</b> when the <code style="color:#0000e6;">with</code> block is exited::
479.1960 -
479.1961 -
479.1962 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
479.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>
479.1964 - In older versions of Python, you would have needed to do this to get the same
479.1965 - effect::
479.1966 -
479.1967 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
479.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>
479.1969 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
479.1970 - Not all "file-like" types in Python support use as a context manager for the
479.1971 - <code style="color:#0000e6;">with</code> statement. If your code is intended to work with any file-like
479.1972 - object, you can use the function <a href="func:contextlib.closing">contextlib.closing</a> instead of using
479.1973 - the object directly.
479.1974 -</div>
479.1975 -<a href="meth:file.flush()">file.flush()</a>
479.1976 - Flush the internal buffer, like <code>stdio</code>'s :cfunc:<code>fflush</code>. This may be a
479.1977 - no-op on some file-like objects.
479.1978 -
479.1979 -<br><br>
479.1980 -<a href="meth:file.fileno()">file.fileno()</a>
479.1981 -
479.1982 -<br><br>
479.1983 - Return the integer "file descriptor" that is used by the underlying
479.1984 - implementation to request I/O operations from the operating system. This can be
479.1985 - useful for other, lower level interfaces that use file descriptors, such as the
479.1986 - <a href="mod:fcntl">fcntl</a> module or <a href="func:os.read">os.read</a> and friends.
479.1987 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
479.1988 -
479.1989 -<br><br>
479.1990 - File-like objects which do not have a real file descriptor should <b>not</b> provide
479.1991 - this method!
479.1992 -</div>
479.1993 -<a href="meth:file.isatty()">file.isatty()</a>
479.1994 - Return <code>True</code> if the file is connected to a tty(-like) device, else <code>False</code>.
479.1995 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
479.1996 -
479.1997 -<br><br>
479.1998 - If a file-like object is not associated with a real file, this method should
479.1999 - <b>not</b> be implemented.
479.2000 -</div>
479.2001 -<a href="meth:file.next()">file.next()</a>
479.2002 - A file object is its own iterator, for example <code>iter(f)</code> returns <b>f</b> (unless
479.2003 - <b>f</b> is closed). When a file is used as an iterator, typically in a
479.2004 - <code style="color:#0000e6;">for</code> loop (for example, <code>for line in f: print line</code>), the
479.2005 - <a href="meth:next">next</a> method is called repeatedly. This method returns the next input
479.2006 - line, or raises <a href="exc:StopIteration">StopIteration</a> when EOF is hit when the file is open for
479.2007 - reading (behavior is undefined when the file is open for writing). In order to
479.2008 - make a <code style="color:#0000e6;">for</code> loop the most efficient way of looping over the lines of a
479.2009 - file (a very common operation), the <a href="meth:next">next</a> method uses a hidden read-ahead
479.2010 - buffer. As a consequence of using a read-ahead buffer, combining <a href="meth:next">next</a>
479.2011 - with other file methods (like <a href="meth:readline">readline</a>) does not work right. However,
479.2012 - using <a href="meth:seek">seek</a> to reposition the file to an absolute position will flush the
479.2013 - read-ahead buffer.
479.2014 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
479.2015 -</div>
479.2016 -<a href="meth:file.read([size])">file.read([size])</a>
479.2017 - Read at most <b>size</b> bytes from the file (less if the read hits EOF before
479.2018 - obtaining <b>size</b> bytes). If the <b>size</b> argument is negative or omitted, read
479.2019 - all data until EOF is reached. The bytes are returned as a string object. An
479.2020 - empty string is returned when EOF is encountered immediately. (For certain
479.2021 - files, like ttys, it makes sense to continue reading after an EOF is hit.) Note
479.2022 - that this method may call the underlying C function :cfunc:<code>fread</code> more than
479.2023 - once in an effort to acquire as close to <b>size</b> bytes as possible. Also note
479.2024 - that when in non-blocking mode, less data than was requested may be
479.2025 - returned, even if no <b>size</b> parameter was given.
479.2026 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
479.2027 - This function is simply a wrapper for the underlying
479.2028 - :cfunc:<code>fread</code> C function, and will behave the same in corner cases,
479.2029 - such as whether the EOF value is cached.
479.2030 -</div>
479.2031 -<a href="meth:file.readline([size])">file.readline([size])</a>
479.2032 - Read one entire line from the file. A trailing newline character is kept in the
479.2033 - string (but may be absent when a file ends with an incomplete line). [#]_ If
479.2034 - the <b>size</b> argument is present and non-negative, it is a maximum byte count
479.2035 - (including the trailing newline) and an incomplete line may be returned. An
479.2036 - empty string is returned <b>only</b> when EOF is encountered immediately.
479.2037 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
479.2038 -
479.2039 -<br><br>
479.2040 - Unlike <code>stdio</code>'s :cfunc:<code>fgets</code>, the returned string contains null characters
479.2041 - (<code>'\0'</code>) if they occurred in the input.
479.2042 -</div>
479.2043 -<a href="meth:file.readlines([sizehint])">file.readlines([sizehint])</a>
479.2044 - Read until EOF using <a href="meth:readline">readline</a> and return a list containing the lines
479.2045 - thus read. If the optional <b>sizehint</b> argument is present, instead of
479.2046 - reading up to EOF, whole lines totalling approximately <b>sizehint</b> bytes
479.2047 - (possibly after rounding up to an internal buffer size) are read. Objects
479.2048 - implementing a file-like interface may choose to ignore <b>sizehint</b> if it
479.2049 - cannot be implemented, or cannot be implemented efficiently.
479.2050 -
479.2051 -<br><br>
479.2052 -<a href="meth:file.xreadlines()">file.xreadlines()</a>
479.2053 -
479.2054 -<br><br>
479.2055 - This method returns the same thing as <code>iter(f)</code>.
479.2056 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.1
479.2057 -</div>
479.2058 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.3
479.2059 - Use <code>for line in file</code> instead.
479.2060 -</div>
479.2061 -<a href="meth:file.seek(offset[, whence])">file.seek(offset[, whence])</a>
479.2062 - Set the file's current position, like <code>stdio</code>'s :cfunc:<code>fseek</code>. The <b>whence</b>
479.2063 - argument is optional and defaults to <code>os.SEEK_SET</code> or <code>0</code> (absolute file
479.2064 - positioning); other values are <code>os.SEEK_CUR</code> or <code>1</code> (seek relative to the
479.2065 - current position) and <code>os.SEEK_END</code> or <code>2</code> (seek relative to the file's
479.2066 - end). There is no return value.
479.2067 -
479.2068 -<br><br>
479.2069 - For example, <code>f.seek(2, os.SEEK_CUR)</code> advances the position by two and
479.2070 - <code>f.seek(-3, os.SEEK_END)</code> sets the position to the third to last.
479.2071 -
479.2072 -<br><br>
479.2073 - Note that if the file is opened for appending
479.2074 - (mode <code>'a'</code> or <code>'a+'</code>), any <a href="meth:seek">seek</a> operations will be undone at the
479.2075 - next write. If the file is only opened for writing in append mode (mode
479.2076 - <code>'a'</code>), this method is essentially a no-op, but it remains useful for files
479.2077 - opened in append mode with reading enabled (mode <code>'a+'</code>). If the file is
479.2078 - opened in text mode (without <code>'b'</code>), only offsets returned by <a href="meth:tell">tell</a> are
479.2079 - legal. Use of other offsets causes undefined behavior.
479.2080 -
479.2081 -<br><br>
479.2082 - Note that not all file objects are seekable.
479.2083 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
479.2084 - Passing float values as offset has been deprecated.
479.2085 -</div>
479.2086 -<a href="meth:file.tell()">file.tell()</a>
479.2087 - Return the file's current position, like <code>stdio</code>'s :cfunc:<code>ftell</code>.
479.2088 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
479.2089 -
479.2090 -<br><br>
479.2091 - On Windows, <a href="meth:tell">tell</a> can return illegal values (after an :cfunc:<code>fgets</code>)
479.2092 - when reading files with Unix-style line-endings. Use binary mode (<code>'rb'</code>) to
479.2093 - circumvent this problem.
479.2094 -</div>
479.2095 -<a href="meth:file.truncate([size])">file.truncate([size])</a>
479.2096 - Truncate the file's size. If the optional <b>size</b> argument is present, the file
479.2097 - is truncated to (at most) that size. The size defaults to the current position.
479.2098 - The current file position is not changed. Note that if a specified size exceeds
479.2099 - the file's current size, the result is platform-dependent: possibilities
479.2100 - include that the file may remain unchanged, increase to the specified size as if
479.2101 - zero-filled, or increase to the specified size with undefined new content.
479.2102 - Availability: Windows, many Unix variants.
479.2103 -
479.2104 -<br><br>
479.2105 -<a href="meth:file.write(str)">file.write(str)</a>
479.2106 -
479.2107 -<br><br>
479.2108 - Write a string to the file. There is no return value. Due to buffering, the
479.2109 - string may not actually show up in the file until the <a href="meth:flush">flush</a> or
479.2110 - <a href="meth:close">close</a> method is called.
479.2111 -
479.2112 -<br><br>
479.2113 -<a href="meth:file.writelines(sequence)">file.writelines(sequence)</a>
479.2114 -
479.2115 -<br><br>
479.2116 - Write a sequence of strings to the file. The sequence can be any iterable
479.2117 - object producing strings, typically a list of strings. There is no return value.
479.2118 - (The name is intended to match <a href="meth:readlines">readlines</a>; <a href="meth:writelines">writelines</a> does not
479.2119 - add line separators.)
479.2120 -
479.2121 -<br><br>
479.2122 -Files support the iterator protocol. Each iteration returns the same result as
479.2123 -<code>file.readline()</code>, and iteration ends when the <a href="meth:readline">readline</a> method returns
479.2124 -an empty string.
479.2125 -
479.2126 -<br><br>
479.2127 -File objects also offer a number of other interesting attributes. These are not
479.2128 -required for file-like objects, but should be implemented if they make sense for
479.2129 -the particular object.
479.2130 -
479.2131 -<br><br>
479.2132 -<a href="attr:file.closed">file.closed</a>
479.2133 -
479.2134 -<br><br>
479.2135 - bool indicating the current state of the file object. This is a read-only
479.2136 - attribute; the <a href="meth:close">close</a> method changes the value. It may not be available
479.2137 - on all file-like objects.
479.2138 -
479.2139 -<br><br>
479.2140 -<a href="attr:file.encoding">file.encoding</a>
479.2141 -
479.2142 -<br><br>
479.2143 - The encoding that this file uses. When Unicode strings are written to a file,
479.2144 - they will be converted to byte strings using this encoding. In addition, when
479.2145 - the file is connected to a terminal, the attribute gives the encoding that the
479.2146 - terminal is likely to use (that information might be incorrect if the user has
479.2147 - misconfigured the terminal). The attribute is read-only and may not be present
479.2148 - on all file-like objects. It may also be <code>None</code>, in which case the file uses
479.2149 - the system default encoding for converting Unicode strings.
479.2150 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
479.2151 -</div>
479.2152 -<a href="attr:file.errors">file.errors</a>
479.2153 - The Unicode error handler used along with the encoding.
479.2154 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
479.2155 -</div>
479.2156 -<a href="attr:file.mode">file.mode</a>
479.2157 - The I/O mode for the file. If the file was created using the <a href="func:open">open</a>
479.2158 - built-in function, this will be the value of the <b>mode</b> parameter. This is a
479.2159 - read-only attribute and may not be present on all file-like objects.
479.2160 -
479.2161 -<br><br>
479.2162 -<a href="attr:file.name">file.name</a>
479.2163 -
479.2164 -<br><br>
479.2165 - If the file object was created using <a href="func:open">open</a>, the name of the file.
479.2166 - Otherwise, some string that indicates the source of the file object, of the
479.2167 - form <code><...></code>. This is a read-only attribute and may not be present on all
479.2168 - file-like objects.
479.2169 -
479.2170 -<br><br>
479.2171 -<a href="attr:file.newlines">file.newlines</a>
479.2172 -
479.2173 -<br><br>
479.2174 - If Python was built with the :option:`--with-universal-newlines` option to
479.2175 - :program:<code>configure</code> (the default) this read-only attribute exists, and for
479.2176 - files opened in universal newline read mode it keeps track of the types of
479.2177 - newlines encountered while reading the file. The values it can take are
479.2178 - <code>'\r'</code>, <code>'\n'</code>, <code>'\r\n'</code>, <code>None</code> (unknown, no newlines read yet) or a
479.2179 - tuple containing all the newline types seen, to indicate that multiple newline
479.2180 - conventions were encountered. For files not opened in universal newline read
479.2181 - mode the value of this attribute will be <code>None</code>.
479.2182 -
479.2183 -<br><br>
479.2184 -<a href="attr:file.softspace">file.softspace</a>
479.2185 -
479.2186 -<br><br>
479.2187 - Boolean that indicates whether a space character needs to be printed before
479.2188 - another value when using the <code style="color:#0000e6;">print</code> statement. Classes that are trying
479.2189 - to simulate a file object should also have a writable <code>softspace</code>
479.2190 - attribute, which should be initialized to zero. This will be automatic for most
479.2191 - classes implemented in Python (care may be needed for objects that override
479.2192 - attribute access); types implemented in C will have to provide a writable
479.2193 - <code>softspace</code> attribute.
479.2194 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
479.2195 -
479.2196 -<br><br>
479.2197 - This attribute is not used to control the <code style="color:#0000e6;">print</code> statement, but to
479.2198 - allow the implementation of <code style="color:#0000e6;">print</code> to keep track of its internal
479.2199 - state.
479.2200 -</div>
479.2201 -<h2>Context Manager Types
479.2202 -</h2>
479.2203 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.5
479.2204 -</div>
479.2205 -Python's <code style="color:#0000e6;">with</code> statement supports the concept of a runtime context
479.2206 -defined by a context manager. This is implemented using two separate methods
479.2207 -that allow user-defined classes to define a runtime context that is entered
479.2208 -before the statement body is executed and exited when the statement ends.
479.2209 -
479.2210 -<br><br>
479.2211 -The :dfn:`context management protocol` consists of a pair of methods that need
479.2212 -to be provided for a context manager object to define a runtime context:
479.2213 -
479.2214 -<br><br>
479.2215 -<a href="meth:contextmanager.__enter__()">contextmanager.__enter__()</a>
479.2216 -
479.2217 -<br><br>
479.2218 - Enter the runtime context and return either this object or another object
479.2219 - related to the runtime context. The value returned by this method is bound to
479.2220 - the identifier in the <code style="color:#0000e6;">as</code> clause of <code style="color:#0000e6;">with</code> statements using
479.2221 - this context manager.
479.2222 -
479.2223 -<br><br>
479.2224 - An example of a context manager that returns itself is a file object. File
479.2225 - objects return themselves from __enter__() to allow <a href="func:open">open</a> to be used as
479.2226 - the context expression in a <code style="color:#0000e6;">with</code> statement.
479.2227 -
479.2228 -<br><br>
479.2229 - An example of a context manager that returns a related object is the one
479.2230 - returned by <a href="func:decimal.localcontext">decimal.localcontext</a>. These managers set the active
479.2231 - decimal context to a copy of the original decimal context and then return the
479.2232 - copy. This allows changes to be made to the current decimal context in the body
479.2233 - of the <code style="color:#0000e6;">with</code> statement without affecting code outside the
479.2234 - <code style="color:#0000e6;">with</code> statement.
479.2235 -
479.2236 -<br><br>
479.2237 -<a href="meth:contextmanager.__exit__(exc_type, exc_val, exc_tb)">contextmanager.__exit__(exc_type, exc_val, exc_tb)</a>
479.2238 -
479.2239 -<br><br>
479.2240 - Exit the runtime context and return a Boolean flag indicating if any exception
479.2241 - that occurred should be suppressed. If an exception occurred while executing the
479.2242 - body of the <code style="color:#0000e6;">with</code> statement, the arguments contain the exception type,
479.2243 - value and traceback information. Otherwise, all three arguments are <code>None</code>.
479.2244 -
479.2245 -<br><br>
479.2246 - Returning a true value from this method will cause the <code style="color:#0000e6;">with</code> statement
479.2247 - to suppress the exception and continue execution with the statement immediately
479.2248 - following the <code style="color:#0000e6;">with</code> statement. Otherwise the exception continues
479.2249 - propagating after this method has finished executing. Exceptions that occur
479.2250 - during execution of this method will replace any exception that occurred in the
479.2251 - body of the <code style="color:#0000e6;">with</code> statement.
479.2252 -
479.2253 -<br><br>
479.2254 - The exception passed in should never be reraised explicitly - instead, this
479.2255 - method should return a false value to indicate that the method completed
479.2256 - successfully and does not want to suppress the raised exception. This allows
479.2257 - context management code (such as <code>contextlib.nested</code>) to easily detect whether
479.2258 - or not an <a href="meth:__exit__">__exit__</a> method has actually failed.
479.2259 -
479.2260 -<br><br>
479.2261 -Python defines several context managers to support easy thread synchronisation,
479.2262 -prompt closure of files or other objects, and simpler manipulation of the active
479.2263 -decimal arithmetic context. The specific types are not treated specially beyond
479.2264 -their implementation of the context management protocol. See the
479.2265 -<a href="mod:contextlib">contextlib</a> module for some examples.
479.2266 -
479.2267 -<br><br>
479.2268 -Python's :term:<code>generator</code>\s and the <code>contextlib.contextfactory</code> :term:<code>decorator</code>
479.2269 -provide a convenient way to implement these protocols. If a generator function is
479.2270 -decorated with the <code>contextlib.contextfactory</code> decorator, it will return a
479.2271 -context manager implementing the necessary <a href="meth:__enter__">__enter__</a> and
479.2272 -<a href="meth:__exit__">__exit__</a> methods, rather than the iterator produced by an undecorated
479.2273 -generator function.
479.2274 -
479.2275 -<br><br>
479.2276 -Note that there is no specific slot for any of these methods in the type
479.2277 -structure for Python objects in the Python/C API. Extension types wanting to
479.2278 -define these methods must provide them as a normal Python accessible method.
479.2279 -Compared to the overhead of setting up the runtime context, the overhead of a
479.2280 -single class dictionary lookup is negligible.
479.2281 -
479.2282 -<br><br>
479.2283 -
479.2284 -<br><br>
479.2285 -<h2>Other Built-in Types
479.2286 -</h2>
479.2287 -The interpreter supports several other kinds of objects. Most of these support
479.2288 -only one or two operations.
479.2289 -
479.2290 -<br><br>
479.2291 -
479.2292 -<br><br>
479.2293 -<h3>Modules
479.2294 -</h3>
479.2295 -The only special operation on a module is attribute access: <code>m.name</code>, where
479.2296 -*m* is a module and <b>name</b> accesses a name defined in <b>m</b>'s symbol table.
479.2297 -Module attributes can be assigned to. (Note that the <code style="color:#0000e6;">import</code>
479.2298 -statement is not, strictly speaking, an operation on a module object; ``import
479.2299 -foo`` does not require a module object named <b>foo</b> to exist, rather it requires
479.2300 -an (external) <b>definition</b> for a module named <b>foo</b> somewhere.)
479.2301 -
479.2302 -<br><br>
479.2303 -A special member of every module is <code>__dict__</code>. This is the dictionary
479.2304 -containing the module's symbol table. Modifying this dictionary will actually
479.2305 -change the module's symbol table, but direct assignment to the <code>__dict__</code>
479.2306 -attribute is not possible (you can write <code>m.__dict__['a'] = 1</code>, which defines
479.2307 -<code>m.a</code> to be <code>1</code>, but you can't write <code>m.__dict__ = {}</code>). Modifying
479.2308 -<code>__dict__</code> directly is not recommended.
479.2309 -
479.2310 -<br><br>
479.2311 -Modules built into the interpreter are written like this: ``<module 'sys'
479.2312 -(built-in)><code>. If loaded from a file, they are written as </code><module 'os' from
479.2313 -'/usr/local/lib/pythonX.Y/os.pyc'>``.
479.2314 -
479.2315 -<br><br>
479.2316 -
479.2317 -<br><br>
479.2318 -<h3>Classes and Class Instances
479.2319 -</h3>
479.2320 -See <code>objects</code> and <code>class</code> for these.
479.2321 -
479.2322 -<br><br>
479.2323 -
479.2324 -<br><br>
479.2325 -<h3>Functions
479.2326 -</h3>
479.2327 -Function objects are created by function definitions. The only operation on a
479.2328 -function object is to call it: <code>func(argument-list)</code>.
479.2329 -
479.2330 -<br><br>
479.2331 -There are really two flavors of function objects: built-in functions and
479.2332 -user-defined functions. Both support the same operation (to call the function),
479.2333 -but the implementation is different, hence the different object types.
479.2334 -
479.2335 -<br><br>
479.2336 -See <code>function</code> for more information.
479.2337 -
479.2338 -<br><br>
479.2339 -
479.2340 -<br><br>
479.2341 -<h3>Methods
479.2342 -</h3>
479.2343 -Methods are functions that are called using the attribute notation. There are
479.2344 -two flavors: built-in methods (such as <a href="meth:append">append</a> on lists) and class
479.2345 -instance methods. Built-in methods are described with the types that support
479.2346 -them.
479.2347 -
479.2348 -<br><br>
479.2349 -The implementation adds two special read-only attributes to class instance
479.2350 -methods: <code>m.im_self</code> is the object on which the method operates, and
479.2351 -<code>m.im_func</code> is the function implementing the method. Calling ``m(arg-1,
479.2352 -arg-2, ..., arg-n)<code> is completely equivalent to calling </code>m.im_func(m.im_self,
479.2353 -arg-1, arg-2, ..., arg-n)``.
479.2354 -
479.2355 -<br><br>
479.2356 -Class instance methods are either <b>bound</b> or <b>unbound</b>, referring to whether the
479.2357 -method was accessed through an instance or a class, respectively. When a method
479.2358 -is unbound, its <code>im_self</code> attribute will be <code>None</code> and if called, an
479.2359 -explicit <code>self</code> object must be passed as the first argument. In this case,
479.2360 -<code>self</code> must be an instance of the unbound method's class (or a subclass of
479.2361 -that class), otherwise a <a href="exc:TypeError">TypeError</a> is raised.
479.2362 -
479.2363 -<br><br>
479.2364 -Like function objects, methods objects support getting arbitrary attributes.
479.2365 -However, since method attributes are actually stored on the underlying function
479.2366 -object (<code>meth.im_func</code>), setting method attributes on either bound or unbound
479.2367 -methods is disallowed. Attempting to set a method attribute results in a
479.2368 -<a href="exc:TypeError">TypeError</a> being raised. In order to set a method attribute, you need to
479.2369 -explicitly set it on the underlying function object::
479.2370 -
479.2371 -
479.2372 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
479.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>
479.2374 -See <code>types</code> for more information.
479.2375 -
479.2376 -<br><br>
479.2377 -<h3>Code Objects
479.2378 -</h3>
479.2379 -Code objects are used by the implementation to represent "pseudo-compiled"
479.2380 -executable Python code such as a function body. They differ from function
479.2381 -objects because they don't contain a reference to their global execution
479.2382 -environment. Code objects are returned by the built-in <a href="func:compile">compile</a> function
479.2383 -and can be extracted from function objects through their <code>func_code</code>
479.2384 -attribute. See also the <a href="mod:code">code</a> module.
479.2385 -
479.2386 -<br><br>
479.2387 -A code object can be executed or evaluated by passing it (instead of a source
479.2388 -string) to the <code style="color:#0000e6;">exec</code> statement or the built-in <a href="func:eval">eval</a> function.
479.2389 -
479.2390 -<br><br>
479.2391 -See <code>types</code> for more information.
479.2392 -
479.2393 -<br><br>
479.2394 -
479.2395 -<br><br>
479.2396 -<h3>Type Objects
479.2397 -</h3>
479.2398 -Type objects represent the various object types. An object's type is accessed
479.2399 -by the built-in function <a href="func:type">type</a>. There are no special operations on
479.2400 -types. The standard module <a href="mod:types">types</a> defines names for all standard built-in
479.2401 -types.
479.2402 -
479.2403 -<br><br>
479.2404 -Types are written like this: <code><type 'int'></code>.
479.2405 -
479.2406 -<br><br>
479.2407 -
479.2408 -<br><br>
479.2409 -<h3>The Null Object
479.2410 -</h3>
479.2411 -This object is returned by functions that don't explicitly return a value. It
479.2412 -supports no special operations. There is exactly one null object, named
479.2413 -<code>None</code> (a built-in name).
479.2414 -
479.2415 -<br><br>
479.2416 -It is written as <code>None</code>.
479.2417 -
479.2418 -<br><br>
479.2419 -
479.2420 -<br><br>
479.2421 -<h3>The Ellipsis Object
479.2422 -</h3>
479.2423 -This object is used by extended slice notation (see <code>slicings</code>). It
479.2424 -supports no special operations. There is exactly one ellipsis object, named
479.2425 -:const:<code>Ellipsis</code> (a built-in name).
479.2426 -
479.2427 -<br><br>
479.2428 -It is written as <code>Ellipsis</code>.
479.2429 -
479.2430 -<br><br>
479.2431 -<h3>Boolean Values
479.2432 -</h3>
479.2433 -Boolean values are the two constant objects <code>False</code> and <code>True</code>. They are
479.2434 -used to represent truth values (although other values can also be considered
479.2435 -false or true). In numeric contexts (for example when used as the argument to
479.2436 -an arithmetic operator), they behave like the integers 0 and 1, respectively.
479.2437 -The built-in function <a href="func:bool">bool</a> can be used to cast any value to a Boolean,
479.2438 -if the value can be interpreted as a truth value (see section Truth Value
479.2439 -Testing above).
479.2440 -
479.2441 -<br><br>
479.2442 -They are written as <code>False</code> and <code>True</code>, respectively.
479.2443 -
479.2444 -<br><br>
479.2445 -<h3>Internal Objects
479.2446 -</h3>
479.2447 -See <code>types</code> for this information. It describes stack frame objects,
479.2448 -traceback objects, and slice objects.
479.2449 -
479.2450 -<br><br>
479.2451 -
479.2452 -<br><br>
479.2453 -<h2>Special Attributes
479.2454 -</h2>
479.2455 -The implementation adds a few special read-only attributes to several object
479.2456 -types, where they are relevant. Some of these are not reported by the
479.2457 -<a href="func:dir">dir</a> built-in function.
479.2458 -
479.2459 -<br><br>
479.2460 -<a href="attr:object.__dict__">object.__dict__</a>
479.2461 -
479.2462 -<br><br>
479.2463 - A dictionary or other mapping object used to store an object's (writable)
479.2464 - attributes.
479.2465 -
479.2466 -<br><br>
479.2467 -<a href="attr:object.__methods__">object.__methods__</a>
479.2468 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.2
479.2469 - Use the built-in function <a href="func:dir">dir</a> to get a list of an object's attributes.
479.2470 - This attribute is no longer available.
479.2471 -</div>
479.2472 -<a href="attr:object.__members__">object.__members__</a>
479.2473 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.2
479.2474 - Use the built-in function <a href="func:dir">dir</a> to get a list of an object's attributes.
479.2475 - This attribute is no longer available.
479.2476 -</div>
479.2477 -<a href="attr:instance.__class__">instance.__class__</a>
479.2478 - The class to which a class instance belongs.
479.2479 -
479.2480 -<br><br>
479.2481 -<a href="attr:class.__bases__">class.__bases__</a>
479.2482 -
479.2483 -<br><br>
479.2484 - The tuple of base classes of a class object. If there are no base classes, this
479.2485 - will be an empty tuple.
479.2486 -
479.2487 -<br><br>
479.2488 -<a href="attr:class.__name__">class.__name__</a>
479.2489 -
479.2490 -<br><br>
479.2491 - The name of the class or type.
479.2492 -
479.2493 -<br><br>
479.2494 -.. rubric:: Footnotes
479.2495 -
479.2496 -<br><br>
479.2497 -.. [#] Additional information on these special methods may be found in the Python
479.2498 - Reference Manual (<code>customization</code>).
479.2499 -
479.2500 -<br><br>
479.2501 -.. [#] As a consequence, the list <code>[1, 2]</code> is considered equal to <code>[1.0, 2.0]</code>, and
479.2502 - similarly for tuples.
479.2503 -
479.2504 -<br><br>
479.2505 -.. [#] They must have since the parser can't tell the type of the operands.
479.2506 -
479.2507 -<br><br>
479.2508 -.. [#] To format only a tuple you should therefore provide a singleton tuple whose only
479.2509 - element is the tuple to be formatted.
479.2510 -
479.2511 -<br><br>
479.2512 -.. [#] These numbers are fairly arbitrary. They are intended to avoid printing endless
479.2513 - strings of meaningless digits without hampering correct use and without having
479.2514 - to know the exact precision of floating point values on a particular machine.
479.2515 -
479.2516 -<br><br>
479.2517 -.. [#] The advantage of leaving the newline on is that returning an empty string is
479.2518 - then an unambiguous EOF indication. It is also possible (in cases where it
479.2519 - might matter, for example, if you want to make an exact copy of a file while
479.2520 - scanning its lines) to tell whether the last line of a file ended in a newline
479.2521 - or not (yes this happens!).
479.2522 -</body></html>
480.1 --- a/python.editor/test/unit/data/testfiles/rst/stdtypes.rst.indexed Sun Jan 04 13:11:53 2015 -0600
480.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
480.3 @@ -1,241 +0,0 @@
480.4 -
480.5 -
480.6 -Document 0
480.7 -Searchable Keys:
480.8 - class : class
480.9 - class-ig : class
480.10 - in : stdtypes
480.11 - member : __bases__;A;|DOCUMENTED|DOC_ONLY|;
480.12 - member : __name__;A;|DOCUMENTED|DOC_ONLY|;
480.13 -
480.14 -Not Searchable Keys:
480.15 -
480.16 -
480.17 -Document 1
480.18 -Searchable Keys:
480.19 - class : container
480.20 - class-ig : container
480.21 - in : stdtypes
480.22 - member : __iter__;F;|DOCUMENTED|DOC_ONLY|;;
480.23 -
480.24 -Not Searchable Keys:
480.25 -
480.26 -
480.27 -Document 2
480.28 -Searchable Keys:
480.29 - class : contextmanager
480.30 - class-ig : contextmanager
480.31 - in : stdtypes
480.32 - member : __enter__;F;|DOCUMENTED|DOC_ONLY|;;
480.33 - member : __exit__;F;|DOCUMENTED|DOC_ONLY|;exc_type,exc_val,exc_tb;
480.34 -
480.35 -Not Searchable Keys:
480.36 -
480.37 -
480.38 -Document 3
480.39 -Searchable Keys:
480.40 - class : dict
480.41 - class-ig : dict
480.42 - in : stdtypes
480.43 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;arg;
480.44 - member : clear;F;|DOCUMENTED|DOC_ONLY|;;
480.45 - member : copy;F;|DOCUMENTED|DOC_ONLY|;;
480.46 - member : fromkeys;F;|DOCUMENTED|DOC_ONLY|;seq,value;
480.47 - member : get;F;|DOCUMENTED|DOC_ONLY|;key,default;
480.48 - member : has_key;F;|DOCUMENTED|DOC_ONLY|;key;
480.49 - member : items;F;|DOCUMENTED|DOC_ONLY|;;
480.50 - member : iteritems;F;|DOCUMENTED|DOC_ONLY|;;
480.51 - member : iterkeys;F;|DOCUMENTED|DOC_ONLY|;;
480.52 - member : itervalues;F;|DOCUMENTED|DOC_ONLY|;;
480.53 - member : keys;F;|DOCUMENTED|DOC_ONLY|;;
480.54 - member : pop;F;|DOCUMENTED|DOC_ONLY|;key,default;
480.55 - member : popitem;F;|DOCUMENTED|DOC_ONLY|;;
480.56 - member : setdefault;F;|DOCUMENTED|DOC_ONLY|;key,default;
480.57 - member : update;F;|DOCUMENTED|DOC_ONLY|;other;
480.58 - member : values;F;|DOCUMENTED|DOC_ONLY|;;
480.59 -
480.60 -Not Searchable Keys:
480.61 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
480.62 -
480.63 -
480.64 -Document 4
480.65 -Searchable Keys:
480.66 - class : file
480.67 - class-ig : file
480.68 - in : stdtypes
480.69 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
480.70 - member : closed;A;|DOCUMENTED|DOC_ONLY|;
480.71 - member : encoding;A;|DOCUMENTED|DOC_ONLY|;
480.72 - member : errors;A;|DOCUMENTED|DOC_ONLY|;
480.73 - member : fileno;F;|DOCUMENTED|DOC_ONLY|;;
480.74 - member : flush;F;|DOCUMENTED|DOC_ONLY|;;
480.75 - member : isatty;F;|DOCUMENTED|DOC_ONLY|;;
480.76 - member : mode;A;|DOCUMENTED|DOC_ONLY|;
480.77 - member : name;A;|DOCUMENTED|DOC_ONLY|;
480.78 - member : newlines;A;|DOCUMENTED|DOC_ONLY|;
480.79 - member : next;F;|DOCUMENTED|DOC_ONLY|;;
480.80 - member : read;F;|DOCUMENTED|DOC_ONLY|;size;
480.81 - member : readline;F;|DOCUMENTED|DOC_ONLY|;size;
480.82 - member : readlines;F;|DOCUMENTED|DOC_ONLY|;sizehint;
480.83 - member : seek;F;|DOCUMENTED|DOC_ONLY|;offset,whence;
480.84 - member : softspace;A;|DOCUMENTED|DOC_ONLY|;
480.85 - member : tell;F;|DOCUMENTED|DOC_ONLY|;;
480.86 - member : truncate;F;|DOCUMENTED|DOC_ONLY|;size;
480.87 - member : write;F;|DOCUMENTED|DOC_ONLY|;str;
480.88 - member : writelines;F;|DOCUMENTED|DOC_ONLY|;sequence;
480.89 - member : xreadlines;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;;
480.90 -
480.91 -Not Searchable Keys:
480.92 -
480.93 -
480.94 -Document 5
480.95 -Searchable Keys:
480.96 - class : float
480.97 - class-ig : float
480.98 - in : stdtypes
480.99 - member : as_integer_ratio;F;|DOCUMENTED|DOC_ONLY|;;
480.100 - member : fromhex;F;|DOCUMENTED|DOC_ONLY|;s;
480.101 - member : hex;F;|DOCUMENTED|DOC_ONLY|;;
480.102 -
480.103 -Not Searchable Keys:
480.104 -
480.105 -
480.106 -Document 6
480.107 -Searchable Keys:
480.108 - class : instance
480.109 - class-ig : instance
480.110 - in : stdtypes
480.111 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
480.112 -
480.113 -Not Searchable Keys:
480.114 -
480.115 -
480.116 -Document 7
480.117 -Searchable Keys:
480.118 - class : iterator
480.119 - class-ig : iterator
480.120 - in : stdtypes
480.121 - member : __iter__;F;|DOCUMENTED|DOC_ONLY|;;
480.122 - member : next;F;|DOCUMENTED|DOC_ONLY|;;
480.123 -
480.124 -Not Searchable Keys:
480.125 -
480.126 -
480.127 -Document 8
480.128 -Searchable Keys:
480.129 - class : object
480.130 - class-ig : object
480.131 - in : stdtypes
480.132 - member : __dict__;A;|DOCUMENTED|DOC_ONLY|;
480.133 - member : __members__;A;|DOCUMENTED|DEPRECATED|DOC_ONLY|;
480.134 - member : __methods__;A;|DOCUMENTED|DEPRECATED|DOC_ONLY|;
480.135 -
480.136 -Not Searchable Keys:
480.137 -
480.138 -
480.139 -Document 9
480.140 -Searchable Keys:
480.141 - class : set
480.142 - class-ig : set
480.143 - in : stdtypes
480.144 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;iterable;
480.145 - member : add;F;|DOCUMENTED|DOC_ONLY|;elem;
480.146 - member : clear;F;|DOCUMENTED|DOC_ONLY|;;
480.147 - member : copy;F;|DOCUMENTED|DOC_ONLY|;;
480.148 - member : difference;F;|DOCUMENTED|DOC_ONLY|;other;
480.149 - member : difference_update;F;|DOCUMENTED|DOC_ONLY|;other;
480.150 - member : discard;F;|DOCUMENTED|DOC_ONLY|;elem;
480.151 - member : intersection;F;|DOCUMENTED|DOC_ONLY|;other;
480.152 - member : intersection_update;F;|DOCUMENTED|DOC_ONLY|;other;
480.153 - member : isdisjoint;F;|DOCUMENTED|DOC_ONLY|;other;
480.154 - member : issubset;F;|DOCUMENTED|DOC_ONLY|;other;
480.155 - member : issuperset;F;|DOCUMENTED|DOC_ONLY|;other;
480.156 - member : pop;F;|DOCUMENTED|DOC_ONLY|;;
480.157 - member : remove;F;|DOCUMENTED|DOC_ONLY|;elem;
480.158 - member : set<other;F;|DOCUMENTED|DOC_ONLY|;;
480.159 - member : set>other;F;|DOCUMENTED|DOC_ONLY|;;
480.160 - member : symmetric_difference;F;|DOCUMENTED|DOC_ONLY|;other;
480.161 - member : symmetric_difference_update;F;|DOCUMENTED|DOC_ONLY|;other;
480.162 - member : union;F;|DOCUMENTED|DOC_ONLY|;other;
480.163 - member : update;F;|DOCUMENTED|DOC_ONLY|;other;
480.164 -
480.165 -Not Searchable Keys:
480.166 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
480.167 -
480.168 -
480.169 -Document 10
480.170 -Searchable Keys:
480.171 - class : str
480.172 - class-ig : str
480.173 - in : stdtypes
480.174 - member : capitalize;F;|DOCUMENTED|DOC_ONLY|;;
480.175 - member : center;F;|DOCUMENTED|DOC_ONLY|;width,fillchar;
480.176 - member : count;F;|DOCUMENTED|DOC_ONLY|;sub,start,end;
480.177 - member : decode;F;|DOCUMENTED|DOC_ONLY|;encoding,errors;
480.178 - member : encode;F;|DOCUMENTED|DOC_ONLY|;encoding,errors;
480.179 - member : endswith;F;|DOCUMENTED|DOC_ONLY|;suffix,start,end;
480.180 - member : expandtabs;F;|DOCUMENTED|DOC_ONLY|;tabsize;
480.181 - member : find;F;|DOCUMENTED|DOC_ONLY|;sub,start,end;
480.182 - member : format;F;|DOCUMENTED|DOC_ONLY|;format_string,*args,**kwargs;
480.183 - member : index;F;|DOCUMENTED|DOC_ONLY|;sub,start,end;
480.184 - member : isalnum;F;|DOCUMENTED|DOC_ONLY|;;
480.185 - member : isalpha;F;|DOCUMENTED|DOC_ONLY|;;
480.186 - member : isdigit;F;|DOCUMENTED|DOC_ONLY|;;
480.187 - member : islower;F;|DOCUMENTED|DOC_ONLY|;;
480.188 - member : isspace;F;|DOCUMENTED|DOC_ONLY|;;
480.189 - member : istitle;F;|DOCUMENTED|DOC_ONLY|;;
480.190 - member : isupper;F;|DOCUMENTED|DOC_ONLY|;;
480.191 - member : join;F;|DOCUMENTED|DOC_ONLY|;seq;
480.192 - member : ljust;F;|DOCUMENTED|DOC_ONLY|;width,fillchar;
480.193 - member : lower;F;|DOCUMENTED|DOC_ONLY|;;
480.194 - member : lstrip;F;|DOCUMENTED|DOC_ONLY|;chars;
480.195 - member : partition;F;|DOCUMENTED|DOC_ONLY|;sep;
480.196 - member : replace;F;|DOCUMENTED|DOC_ONLY|;old,new,count;
480.197 - member : rfind;F;|DOCUMENTED|DOC_ONLY|;sub,start,end;
480.198 - member : rindex;F;|DOCUMENTED|DOC_ONLY|;sub,start,end;
480.199 - member : rjust;F;|DOCUMENTED|DOC_ONLY|;width,fillchar;
480.200 - member : rpartition;F;|DOCUMENTED|DOC_ONLY|;sep;
480.201 - member : rsplit;F;|DOCUMENTED|DOC_ONLY|;sep,maxsplit;
480.202 - member : rstrip;F;|DOCUMENTED|DOC_ONLY|;chars;
480.203 - member : split;F;|DOCUMENTED|DOC_ONLY|;sep,maxsplit;
480.204 - member : splitlines;F;|DOCUMENTED|DOC_ONLY|;keepends;
480.205 - member : startswith;F;|DOCUMENTED|DOC_ONLY|;prefix,start,end;
480.206 - member : strip;F;|DOCUMENTED|DOC_ONLY|;chars;
480.207 - member : swapcase;F;|DOCUMENTED|DOC_ONLY|;;
480.208 - member : title;F;|DOCUMENTED|DOC_ONLY|;;
480.209 - member : translate;F;|DOCUMENTED|DOC_ONLY|;table,deletechars;
480.210 - member : upper;F;|DOCUMENTED|DOC_ONLY|;;
480.211 - member : zfill;F;|DOCUMENTED|DOC_ONLY|;width;
480.212 -
480.213 -Not Searchable Keys:
480.214 -
480.215 -
480.216 -Document 11
480.217 -Searchable Keys:
480.218 - class : unicode
480.219 - class-ig : unicode
480.220 - in : stdtypes
480.221 - member : isdecimal;F;|DOCUMENTED|DOC_ONLY|;;
480.222 - member : isnumeric;F;|DOCUMENTED|DOC_ONLY|;;
480.223 -
480.224 -Not Searchable Keys:
480.225 -
480.226 -
480.227 -Document 12
480.228 -Searchable Keys:
480.229 - item : class;C;|DOCUMENTED|DOC_ONLY|;
480.230 - item : container;C;|DOCUMENTED|DOC_ONLY|;
480.231 - item : contextmanager;C;|DOCUMENTED|DOC_ONLY|;
480.232 - item : dict;C;|DOCUMENTED|DOC_ONLY|;
480.233 - item : file;C;|DOCUMENTED|DOC_ONLY|;
480.234 - item : float;C;|DOCUMENTED|DOC_ONLY|;
480.235 - item : instance;C;|DOCUMENTED|DOC_ONLY|;
480.236 - item : iterator;C;|DOCUMENTED|DOC_ONLY|;
480.237 - item : object;C;|DOCUMENTED|DOC_ONLY|;
480.238 - item : set;C;|DOCUMENTED|DOC_ONLY|;
480.239 - item : str;C;|DOCUMENTED|DOC_ONLY|;
480.240 - item : unicode;C;|DOCUMENTED|DOC_ONLY|;
480.241 - module : stdtypes
480.242 -
480.243 -Not Searchable Keys:
480.244 - modattrs : S
481.1 --- a/python.editor/test/unit/data/testfiles/rst/stdtypes.rst.testGetDoc2.html Sun Jan 04 13:11:53 2015 -0600
481.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
481.3 @@ -1,204 +0,0 @@
481.4 -<html><body><pre><b>dict</b></pre>
481.5 -
481.6 -<hr>
481.7 - Return a new dictionary initialized from an optional positional argument or from
481.8 - a set of keyword arguments. If no arguments are given, return a new empty
481.9 - dictionary. If the positional argument <b>arg</b> is a mapping object, return a
481.10 - dictionary mapping the same keys to the same values as does the mapping object.
481.11 - Otherwise the positional argument must be a sequence, a container that supports
481.12 - iteration, or an iterator object. The elements of the argument must each also
481.13 - be of one of those kinds, and each must in turn contain exactly two objects.
481.14 - The first is used as a key in the new dictionary, and the second as the key's
481.15 - value. If a given key is seen more than once, the last value associated with it
481.16 - is retained in the new dictionary.
481.17 -
481.18 -<br><br>
481.19 - If keyword arguments are given, the keywords themselves with their associated
481.20 - values are added as items to the dictionary. If a key is specified both in the
481.21 - positional argument and as a keyword argument, the value associated with the
481.22 - keyword is retained in the dictionary. For example, these all return a
481.23 - dictionary equal to <code>{"one": 2, "two": 3}</code>:
481.24 -
481.25 -<br><br>
481.26 - * <code>dict(one=2, two=3)</code>
481.27 -
481.28 -<br><br>
481.29 - * <code>dict({'one': 2, 'two': 3})</code>
481.30 -
481.31 -<br><br>
481.32 - * <code>dict(zip(('one', 'two'), (2, 3)))</code>
481.33 -
481.34 -<br><br>
481.35 - * <code>dict([['two', 3], ['one', 2]])</code>
481.36 -
481.37 -<br><br>
481.38 - The first example only works for keys that are valid Python
481.39 - identifiers; the others work with any valid keys.
481.40 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
481.41 -</div>
481.42 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
481.43 - Support for building a dictionary from keyword arguments added.
481.44 -</div>
481.45 - These are the operations that dictionaries support (and therefore, custom
481.46 - mapping types should support too):
481.47 -
481.48 -<br><br>
481.49 - .. describe:: len(d)
481.50 -
481.51 -<br><br>
481.52 - Return the number of items in the dictionary <b>d</b>.
481.53 -
481.54 -<br><br>
481.55 - .. describe:: d[key]
481.56 -
481.57 -<br><br>
481.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>
481.59 - is not in the map.
481.60 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.5
481.61 - If a subclass of dict defines a method <a href="meth:__missing__">__missing__</a>, if the key
481.62 - <b>key</b> is not present, the <code>d[key]</code> operation calls that method with
481.63 - the key <b>key</b> as argument. The <code>d[key]</code> operation then returns or
481.64 - raises whatever is returned or raised by the <code>__missing__(key)</code> call
481.65 - if the key is not present. No other operations or methods invoke
481.66 - <a href="meth:__missing__">__missing__</a>. If <a href="meth:__missing__">__missing__</a> is not defined,
481.67 - <a href="exc:KeyError">KeyError</a> is raised. <a href="meth:__missing__">__missing__</a> must be a method; it
481.68 - cannot be an instance variable. For an example, see
481.69 - <a href="class:collections.defaultdict">collections.defaultdict</a>.
481.70 -</div>
481.71 - .. describe:: d[key] = value
481.72 - Set <code>d[key]</code> to <b>value</b>.
481.73 -
481.74 -<br><br>
481.75 - .. describe:: del d[key]
481.76 -
481.77 -<br><br>
481.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
481.79 - map.
481.80 -
481.81 -<br><br>
481.82 - .. describe:: key in d
481.83 -
481.84 -<br><br>
481.85 - Return <code>True</code> if <b>d</b> has a key <b>key</b>, else <code>False</code>.
481.86 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
481.87 -</div>
481.88 - .. describe:: key not in d
481.89 - Equivalent to <code>not key in d</code>.
481.90 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
481.91 -</div>
481.92 -<a href="meth:clear()">clear()</a>
481.93 - Remove all items from the dictionary.
481.94 -
481.95 -<br><br>
481.96 -<a href="meth:copy()">copy()</a>
481.97 -
481.98 -<br><br>
481.99 - Return a shallow copy of the dictionary.
481.100 -
481.101 -<br><br>
481.102 -<a href="meth:fromkeys(seq[, value])">fromkeys(seq[, value])</a>
481.103 -
481.104 -<br><br>
481.105 - Create a new dictionary with keys from <b>seq</b> and values set to <b>value</b>.
481.106 -
481.107 -<br><br>
481.108 - <a href="func:fromkeys">fromkeys</a> is a class method that returns a new dictionary. <b>value</b>
481.109 - defaults to <code>None</code>.
481.110 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
481.111 -</div>
481.112 -<a href="meth:get(key[, default])">get(key[, default])</a>
481.113 - Return the value for <b>key</b> if <b>key</b> is in the dictionary, else <b>default</b>.
481.114 - If <b>default</b> is not given, it defaults to <code>None</code>, so that this method
481.115 - never raises a <a href="exc:KeyError">KeyError</a>.
481.116 -
481.117 -<br><br>
481.118 -<a href="meth:has_key(key)">has_key(key)</a>
481.119 -
481.120 -<br><br>
481.121 - <code>dict.has_key(key)</code> is equivalent to <code>key in d</code>, but deprecated.
481.122 -
481.123 -<br><br>
481.124 -<a href="meth:items()">items()</a>
481.125 -
481.126 -<br><br>
481.127 - Return a copy of the dictionary's list of <code>(key, value)</code> pairs.
481.128 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
481.129 -
481.130 -<br><br>
481.131 - Keys and values are listed in an arbitrary order which is non-random,
481.132 - varies across Python implementations, and depends on the dictionary's
481.133 - history of insertions and deletions. If <a href="meth:items">items</a>, <a href="meth:keys">keys</a>,
481.134 - <a href="meth:values">values</a>, <a href="meth:iteritems">iteritems</a>, <a href="meth:iterkeys">iterkeys</a>, and
481.135 - <a href="meth:itervalues">itervalues</a> are called with no intervening modifications to the
481.136 - dictionary, the lists will directly correspond. This allows the
481.137 - creation of <code>(value, key)</code> pairs using <a href="func:zip">zip</a>: ``pairs =
481.138 - zip(d.values(), d.keys())``. The same relationship holds for the
481.139 - <a href="meth:iterkeys">iterkeys</a> and <a href="meth:itervalues">itervalues</a> methods: ``pairs =
481.140 - zip(d.itervalues(), d.iterkeys())`` provides the same value for
481.141 - <code>pairs</code>. Another way to create the same list is ``pairs = [(v, k) for
481.142 - (k, v) in d.iteritems()]``.
481.143 -</div>
481.144 -<a href="meth:iteritems()">iteritems()</a>
481.145 - Return an iterator over the dictionary's <code>(key, value)</code> pairs. See the
481.146 - note for <a href="meth:dict.items">dict.items</a>.
481.147 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
481.148 -</div>
481.149 -<a href="meth:iterkeys()">iterkeys()</a>
481.150 - Return an iterator over the dictionary's keys. See the note for
481.151 - <a href="meth:dict.items">dict.items</a>.
481.152 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
481.153 -</div>
481.154 -<a href="meth:itervalues()">itervalues()</a>
481.155 - Return an iterator over the dictionary's values. See the note for
481.156 - <a href="meth:dict.items">dict.items</a>.
481.157 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
481.158 -</div>
481.159 -<a href="meth:keys()">keys()</a>
481.160 - Return a copy of the dictionary's list of keys. See the note for
481.161 - <a href="meth:dict.items">dict.items</a>.
481.162 -
481.163 -<br><br>
481.164 -<a href="meth:pop(key[, default])">pop(key[, default])</a>
481.165 -
481.166 -<br><br>
481.167 - If <b>key</b> is in the dictionary, remove it and return its value, else return
481.168 - <b>default</b>. If <b>default</b> is not given and <b>key</b> is not in the dictionary,
481.169 - a <a href="exc:KeyError">KeyError</a> is raised.
481.170 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
481.171 -</div>
481.172 -<a href="meth:popitem()">popitem()</a>
481.173 - Remove and return an arbitrary <code>(key, value)</code> pair from the dictionary.
481.174 -
481.175 -<br><br>
481.176 - <a href="func:popitem">popitem</a> is useful to destructively iterate over a dictionary, as
481.177 - often used in set algorithms. If the dictionary is empty, calling
481.178 - <a href="func:popitem">popitem</a> raises a <a href="exc:KeyError">KeyError</a>.
481.179 -
481.180 -<br><br>
481.181 -<a href="meth:setdefault(key[, default])">setdefault(key[, default])</a>
481.182 -
481.183 -<br><br>
481.184 - If <b>key</b> is in the dictionary, return its value. If not, insert <b>key</b>
481.185 - with a value of <b>default</b> and return <b>default</b>. <b>default</b> defaults to
481.186 - <code>None</code>.
481.187 -
481.188 -<br><br>
481.189 -<a href="meth:update([other])">update([other])</a>
481.190 -
481.191 -<br><br>
481.192 - Update the dictionary with the key/value pairs from <b>other</b>, overwriting
481.193 - existing keys. Return <code>None</code>.
481.194 -
481.195 -<br><br>
481.196 - <a href="func:update">update</a> accepts either another dictionary object or an iterable of
481.197 - key/value pairs (as a tuple or other iterable of length two). If keyword
481.198 - arguments are specified, the dictionary is then is updated with those
481.199 - key/value pairs: <code>d.update(red=1, blue=2)</code>.
481.200 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
481.201 - Allowed the argument to be an iterable of key/value pairs and allowed
481.202 - keyword arguments.
481.203 -</div>
481.204 -<a href="meth:values()">values()</a>
481.205 - Return a copy of the dictionary's list of values. See the note for
481.206 - <a href="meth:dict.items">dict.items</a>.
481.207 -</body></html>
482.1 --- a/python.editor/test/unit/data/testfiles/rst/stdtypes.rst.testGetDoc4.html Sun Jan 04 13:11:53 2015 -0600
482.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
482.3 @@ -1,26 +0,0 @@
482.4 -<html><body><pre><b>file.close</b><font color="#808080">()</font></pre>
482.5 -<hr>
482.6 - Close the file. A closed file cannot be read or written any more. Any operation
482.7 - which requires that the file be open will raise a <a href="exc:ValueError">ValueError</a> after the
482.8 - file has been closed. Calling <a href="meth:close">close</a> more than once is allowed.
482.9 -
482.10 -<br><br>
482.11 - As of Python 2.5, you can avoid having to call this method explicitly if you use
482.12 - the <code style="color:#0000e6;">with</code> statement. For example, the following code will
482.13 - automatically close <b>f</b> when the <code style="color:#0000e6;">with</code> block is exited::
482.14 -
482.15 -
482.16 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
482.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>
482.18 - In older versions of Python, you would have needed to do this to get the same
482.19 - effect::
482.20 -
482.21 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
482.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>
482.23 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
482.24 - Not all "file-like" types in Python support use as a context manager for the
482.25 - <code style="color:#0000e6;">with</code> statement. If your code is intended to work with any file-like
482.26 - object, you can use the function <a href="func:contextlib.closing">contextlib.closing</a> instead of using
482.27 - the object directly.
482.28 -</div>
482.29 -</body></html>
483.1 --- a/python.editor/test/unit/data/testfiles/rst/string.rst Sun Jan 04 13:11:53 2015 -0600
483.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
483.3 @@ -1,849 +0,0 @@
483.4 -:mod:`string` --- Common string operations
483.5 -==========================================
483.6 -
483.7 -.. module:: string
483.8 - :synopsis: Common string operations.
483.9 -
483.10 -
483.11 -.. index:: module: re
483.12 -
483.13 -The :mod:`string` module contains a number of useful constants and
483.14 -classes, as well as some deprecated legacy functions that are also
483.15 -available as methods on strings. In addition, Python's built-in string
483.16 -classes support the sequence type methods described in the
483.17 -:ref:`typesseq` section, and also the string-specific methods described
483.18 -in the :ref:`string-methods` section. To output formatted strings use
483.19 -template strings or the ``%`` operator described in the
483.20 -:ref:`string-formatting` section. Also, see the :mod:`re` module for
483.21 -string functions based on regular expressions.
483.22 -
483.23 -
483.24 -String constants
483.25 -----------------
483.26 -
483.27 -The constants defined in this module are:
483.28 -
483.29 -
483.30 -.. data:: ascii_letters
483.31 -
483.32 - The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
483.33 - constants described below. This value is not locale-dependent.
483.34 -
483.35 -
483.36 -.. data:: ascii_lowercase
483.37 -
483.38 - The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``. This value is not
483.39 - locale-dependent and will not change.
483.40 -
483.41 -
483.42 -.. data:: ascii_uppercase
483.43 -
483.44 - The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. This value is not
483.45 - locale-dependent and will not change.
483.46 -
483.47 -
483.48 -.. data:: digits
483.49 -
483.50 - The string ``'0123456789'``.
483.51 -
483.52 -
483.53 -.. data:: hexdigits
483.54 -
483.55 - The string ``'0123456789abcdefABCDEF'``.
483.56 -
483.57 -
483.58 -.. data:: letters
483.59 -
483.60 - The concatenation of the strings :const:`lowercase` and :const:`uppercase`
483.61 - described below. The specific value is locale-dependent, and will be updated
483.62 - when :func:`locale.setlocale` is called.
483.63 -
483.64 -
483.65 -.. data:: lowercase
483.66 -
483.67 - A string containing all the characters that are considered lowercase letters.
483.68 - On most systems this is the string ``'abcdefghijklmnopqrstuvwxyz'``. Do not
483.69 - change its definition --- the effect on the routines :func:`upper` and
483.70 - :func:`swapcase` is undefined. The specific value is locale-dependent, and will
483.71 - be updated when :func:`locale.setlocale` is called.
483.72 -
483.73 -
483.74 -.. data:: octdigits
483.75 -
483.76 - The string ``'01234567'``.
483.77 -
483.78 -
483.79 -.. data:: punctuation
483.80 -
483.81 - String of ASCII characters which are considered punctuation characters in the
483.82 - ``C`` locale.
483.83 -
483.84 -
483.85 -.. data:: printable
483.86 -
483.87 - String of characters which are considered printable. This is a combination of
483.88 - :const:`digits`, :const:`letters`, :const:`punctuation`, and
483.89 - :const:`whitespace`.
483.90 -
483.91 -
483.92 -.. data:: uppercase
483.93 -
483.94 - A string containing all the characters that are considered uppercase letters.
483.95 - On most systems this is the string ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. Do not
483.96 - change its definition --- the effect on the routines :func:`lower` and
483.97 - :func:`swapcase` is undefined. The specific value is locale-dependent, and will
483.98 - be updated when :func:`locale.setlocale` is called.
483.99 -
483.100 -
483.101 -.. data:: whitespace
483.102 -
483.103 - A string containing all characters that are considered whitespace. On most
483.104 - systems this includes the characters space, tab, linefeed, return, formfeed, and
483.105 - vertical tab. Do not change its definition --- the effect on the routines
483.106 - :func:`strip` and :func:`split` is undefined.
483.107 -
483.108 -
483.109 -.. _new-string-formatting:
483.110 -
483.111 -String Formatting
483.112 ------------------
483.113 -
483.114 -Starting in Python 2.6, the built-in str and unicode classes provide the ability
483.115 -to do complex variable substitutions and value formatting via the
483.116 -:meth:`str.format` method described in :pep:`3101`. The :class:`Formatter`
483.117 -class in the :mod:`string` module allows you to create and customize your own
483.118 -string formatting behaviors using the same implementation as the built-in
483.119 -:meth:`format` method.
483.120 -
483.121 -.. class:: Formatter
483.122 -
483.123 - The :class:`Formatter` class has the following public methods:
483.124 -
483.125 - .. method:: format(format_string, *args, *kwargs)
483.126 -
483.127 - :meth:`format` is the primary API method. It takes a format template
483.128 - string, and an arbitrary set of positional and keyword argument.
483.129 - :meth:`format` is just a wrapper that calls :meth:`vformat`.
483.130 -
483.131 - .. method:: vformat(format_string, args, kwargs)
483.132 -
483.133 - This function does the actual work of formatting. It is exposed as a
483.134 - separate function for cases where you want to pass in a predefined
483.135 - dictionary of arguments, rather than unpacking and repacking the
483.136 - dictionary as individual arguments using the ``*args`` and ``**kwds``
483.137 - syntax. :meth:`vformat` does the work of breaking up the format template
483.138 - string into character data and replacement fields. It calls the various
483.139 - methods described below.
483.140 -
483.141 - In addition, the :class:`Formatter` defines a number of methods that are
483.142 - intended to be replaced by subclasses:
483.143 -
483.144 - .. method:: parse(format_string)
483.145 -
483.146 - Loop over the format_string and return an iterable of tuples
483.147 - (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
483.148 - by :meth:`vformat` to break the string in to either literal text, or
483.149 - replacement fields.
483.150 -
483.151 - The values in the tuple conceptually represent a span of literal text
483.152 - followed by a single replacement field. If there is no literal text
483.153 - (which can happen if two replacement fields occur consecutively), then
483.154 - *literal_text* will be a zero-length string. If there is no replacement
483.155 - field, then the values of *field_name*, *format_spec* and *conversion*
483.156 - will be ``None``.
483.157 -
483.158 - .. method:: get_field(field_name, args, kwargs)
483.159 -
483.160 - Given *field_name* as returned by :meth:`parse` (see above), convert it to
483.161 - an object to be formatted. Returns a tuple (obj, used_key). The default
483.162 - version takes strings of the form defined in :pep:`3101`, such as
483.163 - "0[name]" or "label.title". *args* and *kwargs* are as passed in to
483.164 - :meth:`vformat`. The return value *used_key* has the same meaning as the
483.165 - *key* parameter to :meth:`get_value`.
483.166 -
483.167 - .. method:: get_value(key, args, kwargs)
483.168 -
483.169 - Retrieve a given field value. The *key* argument will be either an
483.170 - integer or a string. If it is an integer, it represents the index of the
483.171 - positional argument in *args*; if it is a string, then it represents a
483.172 - named argument in *kwargs*.
483.173 -
483.174 - The *args* parameter is set to the list of positional arguments to
483.175 - :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
483.176 - keyword arguments.
483.177 -
483.178 - For compound field names, these functions are only called for the first
483.179 - component of the field name; Subsequent components are handled through
483.180 - normal attribute and indexing operations.
483.181 -
483.182 - So for example, the field expression '0.name' would cause
483.183 - :meth:`get_value` to be called with a *key* argument of 0. The ``name``
483.184 - attribute will be looked up after :meth:`get_value` returns by calling the
483.185 - built-in :func:`getattr` function.
483.186 -
483.187 - If the index or keyword refers to an item that does not exist, then an
483.188 - :exc:`IndexError` or :exc:`KeyError` should be raised.
483.189 -
483.190 - .. method:: check_unused_args(used_args, args, kwargs)
483.191 -
483.192 - Implement checking for unused arguments if desired. The arguments to this
483.193 - function is the set of all argument keys that were actually referred to in
483.194 - the format string (integers for positional arguments, and strings for
483.195 - named arguments), and a reference to the *args* and *kwargs* that was
483.196 - passed to vformat. The set of unused args can be calculated from these
483.197 - parameters. :meth:`check_unused_args` is assumed to throw an exception if
483.198 - the check fails.
483.199 -
483.200 - .. method:: format_field(value, format_spec)
483.201 -
483.202 - :meth:`format_field` simply calls the global :func:`format` built-in. The
483.203 - method is provided so that subclasses can override it.
483.204 -
483.205 - .. method:: convert_field(value, conversion)
483.206 -
483.207 - Converts the value (returned by :meth:`get_field`) given a conversion type
483.208 - (as in the tuple returned by the :meth:`parse` method.) The default
483.209 - version understands 'r' (repr) and 's' (str) conversion types.
483.210 -
483.211 -
483.212 -.. _formatstrings:
483.213 -
483.214 -Format String Syntax
483.215 ---------------------
483.216 -
483.217 -The :meth:`str.format` method and the :class:`Formatter` class share the same
483.218 -syntax for format strings (although in the case of :class:`Formatter`,
483.219 -subclasses can define their own format string syntax.)
483.220 -
483.221 -Format strings contain "replacement fields" surrounded by curly braces ``{}``.
483.222 -Anything that is not contained in braces is considered literal text, which is
483.223 -copied unchanged to the output. If you need to include a brace character in the
483.224 -literal text, it can be escaped by doubling: ``{{`` and ``}}``.
483.225 -
483.226 -The grammar for a replacement field is as follows:
483.227 -
483.228 - .. productionlist:: sf
483.229 - replacement_field: "{" `field_name` ["!" `conversion`] [":" `format_spec`] "}"
483.230 - field_name: (`identifier` | `integer`) ("." `attribute_name` | "[" element_index "]")*
483.231 - attribute_name: `identifier`
483.232 - element_index: `integer`
483.233 - conversion: "r" | "s"
483.234 - format_spec: <described in the next section>
483.235 -
483.236 -In less formal terms, the replacement field starts with a *field_name*, which
483.237 -can either be a number (for a positional argument), or an identifier (for
483.238 -keyword arguments). Following this is an optional *conversion* field, which is
483.239 -preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
483.240 -by a colon ``':'``.
483.241 -
483.242 -The *field_name* itself begins with either a number or a keyword. If it's a
483.243 -number, it refers to a positional argument, and if it's a keyword it refers to a
483.244 -named keyword argument. This can be followed by any number of index or
483.245 -attribute expressions. An expression of the form ``'.name'`` selects the named
483.246 -attribute using :func:`getattr`, while an expression of the form ``'[index]'``
483.247 -does an index lookup using :func:`__getitem__`.
483.248 -
483.249 -Some simple format string examples::
483.250 -
483.251 - "First, thou shalt count to {0}" # References first positional argument
483.252 - "My quest is {name}" # References keyword argument 'name'
483.253 - "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
483.254 - "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
483.255 -
483.256 -The *conversion* field causes a type coercion before formatting. Normally, the
483.257 -job of formatting a value is done by the :meth:`__format__` method of the value
483.258 -itself. However, in some cases it is desirable to force a type to be formatted
483.259 -as a string, overriding its own definition of formatting. By converting the
483.260 -value to a string before calling :meth:`__format__`, the normal formatting logic
483.261 -is bypassed.
483.262 -
483.263 -Two conversion flags are currently supported: ``'!s'`` which calls :func:`str`
483.264 -on the value, and ``'!r'`` which calls :func:`repr`.
483.265 -
483.266 -Some examples::
483.267 -
483.268 - "Harold's a clever {0!s}" # Calls str() on the argument first
483.269 - "Bring out the holy {name!r}" # Calls repr() on the argument first
483.270 -
483.271 -The *format_spec* field contains a specification of how the value should be
483.272 -presented, including such details as field width, alignment, padding, decimal
483.273 -precision and so on. Each value type can define it's own "formatting
483.274 -mini-language" or interpretation of the *format_spec*.
483.275 -
483.276 -Most built-in types support a common formatting mini-language, which is
483.277 -described in the next section.
483.278 -
483.279 -A *format_spec* field can also include nested replacement fields within it.
483.280 -These nested replacement fields can contain only a field name; conversion flags
483.281 -and format specifications are not allowed. The replacement fields within the
483.282 -format_spec are substituted before the *format_spec* string is interpreted.
483.283 -This allows the formatting of a value to be dynamically specified.
483.284 -
483.285 -For example, suppose you wanted to have a replacement field whose field width is
483.286 -determined by another variable::
483.287 -
483.288 - "A man with two {0:{1}}".format("noses", 10)
483.289 -
483.290 -This would first evaluate the inner replacement field, making the format string
483.291 -effectively::
483.292 -
483.293 - "A man with two {0:10}"
483.294 -
483.295 -Then the outer replacement field would be evaluated, producing::
483.296 -
483.297 - "noses "
483.298 -
483.299 -Which is substituted into the string, yielding::
483.300 -
483.301 - "A man with two noses "
483.302 -
483.303 -(The extra space is because we specified a field width of 10, and because left
483.304 -alignment is the default for strings.)
483.305 -
483.306 -
483.307 -.. _formatspec:
483.308 -
483.309 -Format Specification Mini-Language
483.310 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
483.311 -
483.312 -"Format specifications" are used within replacement fields contained within a
483.313 -format string to define how individual values are presented (see
483.314 -:ref:`formatstrings`.) They can also be passed directly to the builtin
483.315 -:func:`format` function. Each formattable type may define how the format
483.316 -specification is to be interpreted.
483.317 -
483.318 -Most built-in types implement the following options for format specifications,
483.319 -although some of the formatting options are only supported by the numeric types.
483.320 -
483.321 -A general convention is that an empty format string (``""``) produces the same
483.322 -result as if you had called :func:`str` on the value.
483.323 -
483.324 -The general form of a *standard format specifier* is:
483.325 -
483.326 -.. productionlist:: sf
483.327 - format_spec: [[`fill`]`align`][`sign`][#][0][`width`][.`precision`][`type`]
483.328 - fill: <a character other than '}'>
483.329 - align: "<" | ">" | "=" | "^"
483.330 - sign: "+" | "-" | " "
483.331 - width: `integer`
483.332 - precision: `integer`
483.333 - type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%"
483.334 -
483.335 -The *fill* character can be any character other than '}' (which signifies the
483.336 -end of the field). The presence of a fill character is signaled by the *next*
483.337 -character, which must be one of the alignment options. If the second character
483.338 -of *format_spec* is not a valid alignment option, then it is assumed that both
483.339 -the fill character and the alignment option are absent.
483.340 -
483.341 -The meaning of the various alignment options is as follows:
483.342 -
483.343 - +---------+----------------------------------------------------------+
483.344 - | Option | Meaning |
483.345 - +=========+==========================================================+
483.346 - | ``'<'`` | Forces the field to be left-aligned within the available |
483.347 - | | space (This is the default.) |
483.348 - +---------+----------------------------------------------------------+
483.349 - | ``'>'`` | Forces the field to be right-aligned within the |
483.350 - | | available space. |
483.351 - +---------+----------------------------------------------------------+
483.352 - | ``'='`` | Forces the padding to be placed after the sign (if any) |
483.353 - | | but before the digits. This is used for printing fields |
483.354 - | | in the form '+000000120'. This alignment option is only |
483.355 - | | valid for numeric types. |
483.356 - +---------+----------------------------------------------------------+
483.357 - | ``'^'`` | Forces the field to be centered within the available |
483.358 - | | space. |
483.359 - +---------+----------------------------------------------------------+
483.360 -
483.361 -Note that unless a minimum field width is defined, the field width will always
483.362 -be the same size as the data to fill it, so that the alignment option has no
483.363 -meaning in this case.
483.364 -
483.365 -The *sign* option is only valid for number types, and can be one of the
483.366 -following:
483.367 -
483.368 - +---------+----------------------------------------------------------+
483.369 - | Option | Meaning |
483.370 - +=========+==========================================================+
483.371 - | ``'+'`` | indicates that a sign should be used for both |
483.372 - | | positive as well as negative numbers. |
483.373 - +---------+----------------------------------------------------------+
483.374 - | ``'-'`` | indicates that a sign should be used only for negative |
483.375 - | | numbers (this is the default behavior). |
483.376 - +---------+----------------------------------------------------------+
483.377 - | space | indicates that a leading space should be used on |
483.378 - | | positive numbers, and a minus sign on negative numbers. |
483.379 - +---------+----------------------------------------------------------+
483.380 -
483.381 -The ``'#'`` option is only valid for integers, and only for binary, octal, or
483.382 -hexadecimal output. If present, it specifies that the output will be prefixed
483.383 -by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
483.384 -
483.385 -*width* is a decimal integer defining the minimum field width. If not
483.386 -specified, then the field width will be determined by the content.
483.387 -
483.388 -If the *width* field is preceded by a zero (``'0'``) character, this enables
483.389 -zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
483.390 -character of ``'0'``.
483.391 -
483.392 -The *precision* is a decimal number indicating how many digits should be
483.393 -displayed after the decimal point for a floating point value formatted with
483.394 -``'f'`` and ``'F'``, or before and after the decimal point for a floating point
483.395 -value formatted with ``'g'`` or ``'G'``. For non-number types the field
483.396 -indicates the maximum field size - in other words, how many characters will be
483.397 -used from the field content. The *precision* is ignored for integer values.
483.398 -
483.399 -Finally, the *type* determines how the data should be presented.
483.400 -
483.401 -The available integer presentation types are:
483.402 -
483.403 - +---------+----------------------------------------------------------+
483.404 - | Type | Meaning |
483.405 - +=========+==========================================================+
483.406 - | ``'b'`` | Binary format. Outputs the number in base 2. |
483.407 - +---------+----------------------------------------------------------+
483.408 - | ``'c'`` | Character. Converts the integer to the corresponding |
483.409 - | | unicode character before printing. |
483.410 - +---------+----------------------------------------------------------+
483.411 - | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
483.412 - +---------+----------------------------------------------------------+
483.413 - | ``'o'`` | Octal format. Outputs the number in base 8. |
483.414 - +---------+----------------------------------------------------------+
483.415 - | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
483.416 - | | case letters for the digits above 9. |
483.417 - +---------+----------------------------------------------------------+
483.418 - | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
483.419 - | | case letters for the digits above 9. |
483.420 - +---------+----------------------------------------------------------+
483.421 - | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
483.422 - | | the current locale setting to insert the appropriate |
483.423 - | | number separator characters. |
483.424 - +---------+----------------------------------------------------------+
483.425 - | None | The same as ``'d'``. |
483.426 - +---------+----------------------------------------------------------+
483.427 -
483.428 -The available presentation types for floating point and decimal values are:
483.429 -
483.430 - +---------+----------------------------------------------------------+
483.431 - | Type | Meaning |
483.432 - +=========+==========================================================+
483.433 - | ``'e'`` | Exponent notation. Prints the number in scientific |
483.434 - | | notation using the letter 'e' to indicate the exponent. |
483.435 - +---------+----------------------------------------------------------+
483.436 - | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
483.437 - | | upper case 'E' as the separator character. |
483.438 - +---------+----------------------------------------------------------+
483.439 - | ``'f'`` | Fixed point. Displays the number as a fixed-point |
483.440 - | | number. |
483.441 - +---------+----------------------------------------------------------+
483.442 - | ``'F'`` | Fixed point. Same as ``'f'``. |
483.443 - +---------+----------------------------------------------------------+
483.444 - | ``'g'`` | General format. This prints the number as a fixed-point |
483.445 - | | number, unless the number is too large, in which case |
483.446 - | | it switches to ``'e'`` exponent notation. Infinity and |
483.447 - | | NaN values are formatted as ``inf``, ``-inf`` and |
483.448 - | | ``nan``, respectively. |
483.449 - +---------+----------------------------------------------------------+
483.450 - | ``'G'`` | General format. Same as ``'g'`` except switches to |
483.451 - | | ``'E'`` if the number gets to large. The representations |
483.452 - | | of infinity and NaN are uppercased, too. |
483.453 - +---------+----------------------------------------------------------+
483.454 - | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
483.455 - | | the current locale setting to insert the appropriate |
483.456 - | | number separator characters. |
483.457 - +---------+----------------------------------------------------------+
483.458 - | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
483.459 - | | in fixed (``'f'``) format, followed by a percent sign. |
483.460 - +---------+----------------------------------------------------------+
483.461 - | None | The same as ``'g'``. |
483.462 - +---------+----------------------------------------------------------+
483.463 -
483.464 -
483.465 -Template strings
483.466 -----------------
483.467 -
483.468 -Templates provide simpler string substitutions as described in :pep:`292`.
483.469 -Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
483.470 --based substitutions, using the following rules:
483.471 -
483.472 -* ``$$`` is an escape; it is replaced with a single ``$``.
483.473 -
483.474 -* ``$identifier`` names a substitution placeholder matching a mapping key of
483.475 - ``"identifier"``. By default, ``"identifier"`` must spell a Python
483.476 - identifier. The first non-identifier character after the ``$`` character
483.477 - terminates this placeholder specification.
483.478 -
483.479 -* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
483.480 - identifier characters follow the placeholder but are not part of the
483.481 - placeholder, such as ``"${noun}ification"``.
483.482 -
483.483 -Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
483.484 -being raised.
483.485 -
483.486 -.. versionadded:: 2.4
483.487 -
483.488 -The :mod:`string` module provides a :class:`Template` class that implements
483.489 -these rules. The methods of :class:`Template` are:
483.490 -
483.491 -
483.492 -.. class:: Template(template)
483.493 -
483.494 - The constructor takes a single argument which is the template string.
483.495 -
483.496 -
483.497 - .. method:: substitute(mapping[, **kws])
483.498 -
483.499 - Performs the template substitution, returning a new string. *mapping* is
483.500 - any dictionary-like object with keys that match the placeholders in the
483.501 - template. Alternatively, you can provide keyword arguments, where the
483.502 - keywords are the placeholders. When both *mapping* and *kws* are given
483.503 - and there are duplicates, the placeholders from *kws* take precedence.
483.504 -
483.505 -
483.506 - .. method:: safe_substitute(mapping[, **kws])
483.507 -
483.508 - Like :meth:`substitute`, except that if placeholders are missing from
483.509 - *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the
483.510 - original placeholder will appear in the resulting string intact. Also,
483.511 - unlike with :meth:`substitute`, any other appearances of the ``$`` will
483.512 - simply return ``$`` instead of raising :exc:`ValueError`.
483.513 -
483.514 - While other exceptions may still occur, this method is called "safe"
483.515 - because substitutions always tries to return a usable string instead of
483.516 - raising an exception. In another sense, :meth:`safe_substitute` may be
483.517 - anything other than safe, since it will silently ignore malformed
483.518 - templates containing dangling delimiters, unmatched braces, or
483.519 - placeholders that are not valid Python identifiers.
483.520 -
483.521 -:class:`Template` instances also provide one public data attribute:
483.522 -
483.523 -
483.524 -.. attribute:: string.template
483.525 -
483.526 - This is the object passed to the constructor's *template* argument. In general,
483.527 - you shouldn't change it, but read-only access is not enforced.
483.528 -
483.529 -Here is an example of how to use a Template:
483.530 -
483.531 - >>> from string import Template
483.532 - >>> s = Template('$who likes $what')
483.533 - >>> s.substitute(who='tim', what='kung pao')
483.534 - 'tim likes kung pao'
483.535 - >>> d = dict(who='tim')
483.536 - >>> Template('Give $who $100').substitute(d)
483.537 - Traceback (most recent call last):
483.538 - [...]
483.539 - ValueError: Invalid placeholder in string: line 1, col 10
483.540 - >>> Template('$who likes $what').substitute(d)
483.541 - Traceback (most recent call last):
483.542 - [...]
483.543 - KeyError: 'what'
483.544 - >>> Template('$who likes $what').safe_substitute(d)
483.545 - 'tim likes $what'
483.546 -
483.547 -Advanced usage: you can derive subclasses of :class:`Template` to customize the
483.548 -placeholder syntax, delimiter character, or the entire regular expression used
483.549 -to parse template strings. To do this, you can override these class attributes:
483.550 -
483.551 -* *delimiter* -- This is the literal string describing a placeholder introducing
483.552 - delimiter. The default value ``$``. Note that this should *not* be a regular
483.553 - expression, as the implementation will call :meth:`re.escape` on this string as
483.554 - needed.
483.555 -
483.556 -* *idpattern* -- This is the regular expression describing the pattern for
483.557 - non-braced placeholders (the braces will be added automatically as
483.558 - appropriate). The default value is the regular expression
483.559 - ``[_a-z][_a-z0-9]*``.
483.560 -
483.561 -Alternatively, you can provide the entire regular expression pattern by
483.562 -overriding the class attribute *pattern*. If you do this, the value must be a
483.563 -regular expression object with four named capturing groups. The capturing
483.564 -groups correspond to the rules given above, along with the invalid placeholder
483.565 -rule:
483.566 -
483.567 -* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
483.568 - default pattern.
483.569 -
483.570 -* *named* -- This group matches the unbraced placeholder name; it should not
483.571 - include the delimiter in capturing group.
483.572 -
483.573 -* *braced* -- This group matches the brace enclosed placeholder name; it should
483.574 - not include either the delimiter or braces in the capturing group.
483.575 -
483.576 -* *invalid* -- This group matches any other delimiter pattern (usually a single
483.577 - delimiter), and it should appear last in the regular expression.
483.578 -
483.579 -
483.580 -String functions
483.581 -----------------
483.582 -
483.583 -The following functions are available to operate on string and Unicode objects.
483.584 -They are not available as string methods.
483.585 -
483.586 -
483.587 -.. function:: capwords(s)
483.588 -
483.589 - Split the argument into words using :func:`split`, capitalize each word using
483.590 - :func:`capitalize`, and join the capitalized words using :func:`join`. Note
483.591 - that this replaces runs of whitespace characters by a single space, and removes
483.592 - leading and trailing whitespace.
483.593 -
483.594 -
483.595 -.. function:: maketrans(from, to)
483.596 -
483.597 - Return a translation table suitable for passing to :func:`translate`, that will
483.598 - map each character in *from* into the character at the same position in *to*;
483.599 - *from* and *to* must have the same length.
483.600 -
483.601 - .. warning::
483.602 -
483.603 - Don't use strings derived from :const:`lowercase` and :const:`uppercase` as
483.604 - arguments; in some locales, these don't have the same length. For case
483.605 - conversions, always use :func:`lower` and :func:`upper`.
483.606 -
483.607 -
483.608 -Deprecated string functions
483.609 ----------------------------
483.610 -
483.611 -The following list of functions are also defined as methods of string and
483.612 -Unicode objects; see section :ref:`string-methods` for more information on
483.613 -those. You should consider these functions as deprecated, although they will
483.614 -not be removed until Python 3.0. The functions defined in this module are:
483.615 -
483.616 -
483.617 -.. function:: atof(s)
483.618 -
483.619 - .. deprecated:: 2.0
483.620 - Use the :func:`float` built-in function.
483.621 -
483.622 - .. index:: builtin: float
483.623 -
483.624 - Convert a string to a floating point number. The string must have the standard
483.625 - syntax for a floating point literal in Python, optionally preceded by a sign
483.626 - (``+`` or ``-``). Note that this behaves identical to the built-in function
483.627 - :func:`float` when passed a string.
483.628 -
483.629 - .. note::
483.630 -
483.631 - .. index::
483.632 - single: NaN
483.633 - single: Infinity
483.634 -
483.635 - When passing in a string, values for NaN and Infinity may be returned, depending
483.636 - on the underlying C library. The specific set of strings accepted which cause
483.637 - these values to be returned depends entirely on the C library and is known to
483.638 - vary.
483.639 -
483.640 -
483.641 -.. function:: atoi(s[, base])
483.642 -
483.643 - .. deprecated:: 2.0
483.644 - Use the :func:`int` built-in function.
483.645 -
483.646 - .. index:: builtin: eval
483.647 -
483.648 - Convert string *s* to an integer in the given *base*. The string must consist
483.649 - of one or more digits, optionally preceded by a sign (``+`` or ``-``). The
483.650 - *base* defaults to 10. If it is 0, a default base is chosen depending on the
483.651 - leading characters of the string (after stripping the sign): ``0x`` or ``0X``
483.652 - means 16, ``0`` means 8, anything else means 10. If *base* is 16, a leading
483.653 - ``0x`` or ``0X`` is always accepted, though not required. This behaves
483.654 - identically to the built-in function :func:`int` when passed a string. (Also
483.655 - note: for a more flexible interpretation of numeric literals, use the built-in
483.656 - function :func:`eval`.)
483.657 -
483.658 -
483.659 -.. function:: atol(s[, base])
483.660 -
483.661 - .. deprecated:: 2.0
483.662 - Use the :func:`long` built-in function.
483.663 -
483.664 - .. index:: builtin: long
483.665 -
483.666 - Convert string *s* to a long integer in the given *base*. The string must
483.667 - consist of one or more digits, optionally preceded by a sign (``+`` or ``-``).
483.668 - The *base* argument has the same meaning as for :func:`atoi`. A trailing ``l``
483.669 - or ``L`` is not allowed, except if the base is 0. Note that when invoked
483.670 - without *base* or with *base* set to 10, this behaves identical to the built-in
483.671 - function :func:`long` when passed a string.
483.672 -
483.673 -
483.674 -.. function:: capitalize(word)
483.675 -
483.676 - Return a copy of *word* with only its first character capitalized.
483.677 -
483.678 -
483.679 -.. function:: expandtabs(s[, tabsize])
483.680 -
483.681 - Expand tabs in a string replacing them by one or more spaces, depending on the
483.682 - current column and the given tab size. The column number is reset to zero after
483.683 - each newline occurring in the string. This doesn't understand other non-printing
483.684 - characters or escape sequences. The tab size defaults to 8.
483.685 -
483.686 -
483.687 -.. function:: find(s, sub[, start[,end]])
483.688 -
483.689 - Return the lowest index in *s* where the substring *sub* is found such that
483.690 - *sub* is wholly contained in ``s[start:end]``. Return ``-1`` on failure.
483.691 - Defaults for *start* and *end* and interpretation of negative values is the same
483.692 - as for slices.
483.693 -
483.694 -
483.695 -.. function:: rfind(s, sub[, start[, end]])
483.696 -
483.697 - Like :func:`find` but find the highest index.
483.698 -
483.699 -
483.700 -.. function:: index(s, sub[, start[, end]])
483.701 -
483.702 - Like :func:`find` but raise :exc:`ValueError` when the substring is not found.
483.703 -
483.704 -
483.705 -.. function:: rindex(s, sub[, start[, end]])
483.706 -
483.707 - Like :func:`rfind` but raise :exc:`ValueError` when the substring is not found.
483.708 -
483.709 -
483.710 -.. function:: count(s, sub[, start[, end]])
483.711 -
483.712 - Return the number of (non-overlapping) occurrences of substring *sub* in string
483.713 - ``s[start:end]``. Defaults for *start* and *end* and interpretation of negative
483.714 - values are the same as for slices.
483.715 -
483.716 -
483.717 -.. function:: lower(s)
483.718 -
483.719 - Return a copy of *s*, but with upper case letters converted to lower case.
483.720 -
483.721 -
483.722 -.. function:: split(s[, sep[, maxsplit]])
483.723 -
483.724 - Return a list of the words of the string *s*. If the optional second argument
483.725 - *sep* is absent or ``None``, the words are separated by arbitrary strings of
483.726 - whitespace characters (space, tab, newline, return, formfeed). If the second
483.727 - argument *sep* is present and not ``None``, it specifies a string to be used as
483.728 - the word separator. The returned list will then have one more item than the
483.729 - number of non-overlapping occurrences of the separator in the string. The
483.730 - optional third argument *maxsplit* defaults to 0. If it is nonzero, at most
483.731 - *maxsplit* number of splits occur, and the remainder of the string is returned
483.732 - as the final element of the list (thus, the list will have at most
483.733 - ``maxsplit+1`` elements).
483.734 -
483.735 - The behavior of split on an empty string depends on the value of *sep*. If *sep*
483.736 - is not specified, or specified as ``None``, the result will be an empty list.
483.737 - If *sep* is specified as any string, the result will be a list containing one
483.738 - element which is an empty string.
483.739 -
483.740 -
483.741 -.. function:: rsplit(s[, sep[, maxsplit]])
483.742 -
483.743 - Return a list of the words of the string *s*, scanning *s* from the end. To all
483.744 - intents and purposes, the resulting list of words is the same as returned by
483.745 - :func:`split`, except when the optional third argument *maxsplit* is explicitly
483.746 - specified and nonzero. When *maxsplit* is nonzero, at most *maxsplit* number of
483.747 - splits -- the *rightmost* ones -- occur, and the remainder of the string is
483.748 - returned as the first element of the list (thus, the list will have at most
483.749 - ``maxsplit+1`` elements).
483.750 -
483.751 - .. versionadded:: 2.4
483.752 -
483.753 -
483.754 -.. function:: splitfields(s[, sep[, maxsplit]])
483.755 -
483.756 - This function behaves identically to :func:`split`. (In the past, :func:`split`
483.757 - was only used with one argument, while :func:`splitfields` was only used with
483.758 - two arguments.)
483.759 -
483.760 -
483.761 -.. function:: join(words[, sep])
483.762 -
483.763 - Concatenate a list or tuple of words with intervening occurrences of *sep*.
483.764 - The default value for *sep* is a single space character. It is always true that
483.765 - ``string.join(string.split(s, sep), sep)`` equals *s*.
483.766 -
483.767 -
483.768 -.. function:: joinfields(words[, sep])
483.769 -
483.770 - This function behaves identically to :func:`join`. (In the past, :func:`join`
483.771 - was only used with one argument, while :func:`joinfields` was only used with two
483.772 - arguments.) Note that there is no :meth:`joinfields` method on string objects;
483.773 - use the :meth:`join` method instead.
483.774 -
483.775 -
483.776 -.. function:: lstrip(s[, chars])
483.777 -
483.778 - Return a copy of the string with leading characters removed. If *chars* is
483.779 - omitted or ``None``, whitespace characters are removed. If given and not
483.780 - ``None``, *chars* must be a string; the characters in the string will be
483.781 - stripped from the beginning of the string this method is called on.
483.782 -
483.783 - .. versionchanged:: 2.2.3
483.784 - The *chars* parameter was added. The *chars* parameter cannot be passed in
483.785 - earlier 2.2 versions.
483.786 -
483.787 -
483.788 -.. function:: rstrip(s[, chars])
483.789 -
483.790 - Return a copy of the string with trailing characters removed. If *chars* is
483.791 - omitted or ``None``, whitespace characters are removed. If given and not
483.792 - ``None``, *chars* must be a string; the characters in the string will be
483.793 - stripped from the end of the string this method is called on.
483.794 -
483.795 - .. versionchanged:: 2.2.3
483.796 - The *chars* parameter was added. The *chars* parameter cannot be passed in
483.797 - earlier 2.2 versions.
483.798 -
483.799 -
483.800 -.. function:: strip(s[, chars])
483.801 -
483.802 - Return a copy of the string with leading and trailing characters removed. If
483.803 - *chars* is omitted or ``None``, whitespace characters are removed. If given and
483.804 - not ``None``, *chars* must be a string; the characters in the string will be
483.805 - stripped from the both ends of the string this method is called on.
483.806 -
483.807 - .. versionchanged:: 2.2.3
483.808 - The *chars* parameter was added. The *chars* parameter cannot be passed in
483.809 - earlier 2.2 versions.
483.810 -
483.811 -
483.812 -.. function:: swapcase(s)
483.813 -
483.814 - Return a copy of *s*, but with lower case letters converted to upper case and
483.815 - vice versa.
483.816 -
483.817 -
483.818 -.. function:: translate(s, table[, deletechars])
483.819 -
483.820 - Delete all characters from *s* that are in *deletechars* (if present), and then
483.821 - translate the characters using *table*, which must be a 256-character string
483.822 - giving the translation for each character value, indexed by its ordinal. If
483.823 - *table* is ``None``, then only the character deletion step is performed.
483.824 -
483.825 -
483.826 -.. function:: upper(s)
483.827 -
483.828 - Return a copy of *s*, but with lower case letters converted to upper case.
483.829 -
483.830 -
483.831 -.. function:: ljust(s, width)
483.832 - rjust(s, width)
483.833 - center(s, width)
483.834 -
483.835 - These functions respectively left-justify, right-justify and center a string in
483.836 - a field of given width. They return a string that is at least *width*
483.837 - characters wide, created by padding the string *s* with spaces until the given
483.838 - width on the right, left or both sides. The string is never truncated.
483.839 -
483.840 -
483.841 -.. function:: zfill(s, width)
483.842 -
483.843 - Pad a numeric string on the left with zero digits until the given width is
483.844 - reached. Strings starting with a sign are handled correctly.
483.845 -
483.846 -
483.847 -.. function:: replace(str, old, new[, maxreplace])
483.848 -
483.849 - Return a copy of string *str* with all occurrences of substring *old* replaced
483.850 - by *new*. If the optional argument *maxreplace* is given, the first
483.851 - *maxreplace* occurrences are replaced.
483.852 -
484.1 --- a/python.editor/test/unit/data/testfiles/rst/string.rst.html Sun Jan 04 13:11:53 2015 -0600
484.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
484.3 @@ -1,888 +0,0 @@
484.4 -<html><body>
484.5 -<h2><a href="mod:string">string</a> --- Common string operations
484.6 -</h2>
484.7 -<a href="module:string">string</a><br>
484.8 - Common string operations.
484.9 -
484.10 -<br><br>
484.11 -The <a href="mod:string">string</a> module contains a number of useful constants and
484.12 -classes, as well as some deprecated legacy functions that are also
484.13 -available as methods on strings. In addition, Python's built-in string
484.14 -classes support the sequence type methods described in the
484.15 -<code>typesseq</code> section, and also the string-specific methods described
484.16 -in the <code>string-methods</code> section. To output formatted strings use
484.17 -template strings or the <code>%</code> operator described in the
484.18 -<code>string-formatting</code> section. Also, see the <a href="mod:re">re</a> module for
484.19 -string functions based on regular expressions.
484.20 -
484.21 -<br><br>
484.22 -<h3>String constants
484.23 -</h3>
484.24 -The constants defined in this module are:
484.25 -
484.26 -<br><br>
484.27 -<a href="data:ascii_letters">ascii_letters</a>
484.28 -
484.29 -<br><br>
484.30 - The concatenation of the :const:<code>ascii_lowercase</code> and :const:<code>ascii_uppercase</code>
484.31 - constants described below. This value is not locale-dependent.
484.32 -
484.33 -<br><br>
484.34 -<a href="data:ascii_lowercase">ascii_lowercase</a>
484.35 -
484.36 -<br><br>
484.37 - The lowercase letters <code>'abcdefghijklmnopqrstuvwxyz'</code>. This value is not
484.38 - locale-dependent and will not change.
484.39 -
484.40 -<br><br>
484.41 -<a href="data:ascii_uppercase">ascii_uppercase</a>
484.42 -
484.43 -<br><br>
484.44 - The uppercase letters <code>'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</code>. This value is not
484.45 - locale-dependent and will not change.
484.46 -
484.47 -<br><br>
484.48 -<a href="data:digits">digits</a>
484.49 -
484.50 -<br><br>
484.51 - The string <code>'0123456789'</code>.
484.52 -
484.53 -<br><br>
484.54 -<a href="data:hexdigits">hexdigits</a>
484.55 -
484.56 -<br><br>
484.57 - The string <code>'0123456789abcdefABCDEF'</code>.
484.58 -
484.59 -<br><br>
484.60 -<a href="data:letters">letters</a>
484.61 -
484.62 -<br><br>
484.63 - The concatenation of the strings :const:<code>lowercase</code> and :const:<code>uppercase</code>
484.64 - described below. The specific value is locale-dependent, and will be updated
484.65 - when <a href="func:locale.setlocale">locale.setlocale</a> is called.
484.66 -
484.67 -<br><br>
484.68 -<a href="data:lowercase">lowercase</a>
484.69 -
484.70 -<br><br>
484.71 - A string containing all the characters that are considered lowercase letters.
484.72 - On most systems this is the string <code>'abcdefghijklmnopqrstuvwxyz'</code>. Do not
484.73 - change its definition --- the effect on the routines <a href="func:upper">upper</a> and
484.74 - <a href="func:swapcase">swapcase</a> is undefined. The specific value is locale-dependent, and will
484.75 - be updated when <a href="func:locale.setlocale">locale.setlocale</a> is called.
484.76 -
484.77 -<br><br>
484.78 -<a href="data:octdigits">octdigits</a>
484.79 -
484.80 -<br><br>
484.81 - The string <code>'01234567'</code>.
484.82 -
484.83 -<br><br>
484.84 -<a href="data:punctuation">punctuation</a>
484.85 -
484.86 -<br><br>
484.87 - String of ASCII characters which are considered punctuation characters in the
484.88 - <code>C</code> locale.
484.89 -
484.90 -<br><br>
484.91 -<a href="data:printable">printable</a>
484.92 -
484.93 -<br><br>
484.94 - String of characters which are considered printable. This is a combination of
484.95 - :const:<code>digits</code>, :const:<code>letters</code>, :const:<code>punctuation</code>, and
484.96 - :const:<code>whitespace</code>.
484.97 -
484.98 -<br><br>
484.99 -<a href="data:uppercase">uppercase</a>
484.100 -
484.101 -<br><br>
484.102 - A string containing all the characters that are considered uppercase letters.
484.103 - On most systems this is the string <code>'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</code>. Do not
484.104 - change its definition --- the effect on the routines <a href="func:lower">lower</a> and
484.105 - <a href="func:swapcase">swapcase</a> is undefined. The specific value is locale-dependent, and will
484.106 - be updated when <a href="func:locale.setlocale">locale.setlocale</a> is called.
484.107 -
484.108 -<br><br>
484.109 -<a href="data:whitespace">whitespace</a>
484.110 -
484.111 -<br><br>
484.112 - A string containing all characters that are considered whitespace. On most
484.113 - systems this includes the characters space, tab, linefeed, return, formfeed, and
484.114 - vertical tab. Do not change its definition --- the effect on the routines
484.115 - <a href="func:strip">strip</a> and <a href="func:split">split</a> is undefined.
484.116 -
484.117 -<br><br>
484.118 -
484.119 -<br><br>
484.120 -<h3>String Formatting
484.121 -</h3>
484.122 -Starting in Python 2.6, the built-in str and unicode classes provide the ability
484.123 -to do complex variable substitutions and value formatting via the
484.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>
484.125 -class in the <a href="mod:string">string</a> module allows you to create and customize your own
484.126 -string formatting behaviors using the same implementation as the built-in
484.127 -<a href="meth:format">format</a> method.
484.128 -
484.129 -<br><br>
484.130 -<a href="class:Formatter">Formatter</a>
484.131 -
484.132 -<br><br>
484.133 - The <a href="class:Formatter">Formatter</a> class has the following public methods:
484.134 -
484.135 -<br><br>
484.136 -<a href="meth:format(format_string, *args, *kwargs)">format(format_string, *args, *kwargs)</a>
484.137 -
484.138 -<br><br>
484.139 - <a href="meth:format">format</a> is the primary API method. It takes a format template
484.140 - string, and an arbitrary set of positional and keyword argument.
484.141 - <a href="meth:format">format</a> is just a wrapper that calls <a href="meth:vformat">vformat</a>.
484.142 -
484.143 -<br><br>
484.144 -<a href="meth:vformat(format_string, args, kwargs)">vformat(format_string, args, kwargs)</a>
484.145 -
484.146 -<br><br>
484.147 - This function does the actual work of formatting. It is exposed as a
484.148 - separate function for cases where you want to pass in a predefined
484.149 - dictionary of arguments, rather than unpacking and repacking the
484.150 - dictionary as individual arguments using the <code>*args</code> and <code>**kwds</code>
484.151 - syntax. <a href="meth:vformat">vformat</a> does the work of breaking up the format template
484.152 - string into character data and replacement fields. It calls the various
484.153 - methods described below.
484.154 -
484.155 -<br><br>
484.156 - In addition, the <a href="class:Formatter">Formatter</a> defines a number of methods that are
484.157 - intended to be replaced by subclasses:
484.158 -
484.159 -<br><br>
484.160 -<a href="meth:parse(format_string)">parse(format_string)</a>
484.161 -
484.162 -<br><br>
484.163 - Loop over the format_string and return an iterable of tuples
484.164 - (<b>literal_text</b>, <b>field_name</b>, <b>format_spec</b>, <b>conversion</b>). This is used
484.165 - by <a href="meth:vformat">vformat</a> to break the string in to either literal text, or
484.166 - replacement fields.
484.167 -
484.168 -<br><br>
484.169 - The values in the tuple conceptually represent a span of literal text
484.170 - followed by a single replacement field. If there is no literal text
484.171 - (which can happen if two replacement fields occur consecutively), then
484.172 - <b>literal_text</b> will be a zero-length string. If there is no replacement
484.173 - field, then the values of <b>field_name</b>, <b>format_spec</b> and <b>conversion</b>
484.174 - will be <code>None</code>.
484.175 -
484.176 -<br><br>
484.177 -<a href="meth:get_field(field_name, args, kwargs)">get_field(field_name, args, kwargs)</a>
484.178 -
484.179 -<br><br>
484.180 - Given <b>field_name</b> as returned by <a href="meth:parse">parse</a> (see above), convert it to
484.181 - an object to be formatted. Returns a tuple (obj, used_key). The default
484.182 - version takes strings of the form defined in <a href="http://www.python.org/dev/peps/pep-3101/">PEP 3101</a>, such as
484.183 - "0[name]" or "label.title". <b>args</b> and <b>kwargs</b> are as passed in to
484.184 - <a href="meth:vformat">vformat</a>. The return value <b>used_key</b> has the same meaning as the
484.185 - <b>key</b> parameter to <a href="meth:get_value">get_value</a>.
484.186 -
484.187 -<br><br>
484.188 -<a href="meth:get_value(key, args, kwargs)">get_value(key, args, kwargs)</a>
484.189 -
484.190 -<br><br>
484.191 - Retrieve a given field value. The <b>key</b> argument will be either an
484.192 - integer or a string. If it is an integer, it represents the index of the
484.193 - positional argument in <b>args</b>; if it is a string, then it represents a
484.194 - named argument in <b>kwargs</b>.
484.195 -
484.196 -<br><br>
484.197 - The <b>args</b> parameter is set to the list of positional arguments to
484.198 - <a href="meth:vformat">vformat</a>, and the <b>kwargs</b> parameter is set to the dictionary of
484.199 - keyword arguments.
484.200 -
484.201 -<br><br>
484.202 - For compound field names, these functions are only called for the first
484.203 - component of the field name; Subsequent components are handled through
484.204 - normal attribute and indexing operations.
484.205 -
484.206 -<br><br>
484.207 - So for example, the field expression '0.name' would cause
484.208 - <a href="meth:get_value">get_value</a> to be called with a <b>key</b> argument of 0. The <code>name</code>
484.209 - attribute will be looked up after <a href="meth:get_value">get_value</a> returns by calling the
484.210 - built-in <a href="func:getattr">getattr</a> function.
484.211 -
484.212 -<br><br>
484.213 - If the index or keyword refers to an item that does not exist, then an
484.214 - <a href="exc:IndexError">IndexError</a> or <a href="exc:KeyError">KeyError</a> should be raised.
484.215 -
484.216 -<br><br>
484.217 -<a href="meth:check_unused_args(used_args, args, kwargs)">check_unused_args(used_args, args, kwargs)</a>
484.218 -
484.219 -<br><br>
484.220 - Implement checking for unused arguments if desired. The arguments to this
484.221 - function is the set of all argument keys that were actually referred to in
484.222 - the format string (integers for positional arguments, and strings for
484.223 - named arguments), and a reference to the <b>args</b> and <b>kwargs</b> that was
484.224 - passed to vformat. The set of unused args can be calculated from these
484.225 - parameters. <a href="meth:check_unused_args">check_unused_args</a> is assumed to throw an exception if
484.226 - the check fails.
484.227 -
484.228 -<br><br>
484.229 -<a href="meth:format_field(value, format_spec)">format_field(value, format_spec)</a>
484.230 -
484.231 -<br><br>
484.232 - <a href="meth:format_field">format_field</a> simply calls the global <a href="func:format">format</a> built-in. The
484.233 - method is provided so that subclasses can override it.
484.234 -
484.235 -<br><br>
484.236 -<a href="meth:convert_field(value, conversion)">convert_field(value, conversion)</a>
484.237 -
484.238 -<br><br>
484.239 - Converts the value (returned by <a href="meth:get_field">get_field</a>) given a conversion type
484.240 - (as in the tuple returned by the <a href="meth:parse">parse</a> method.) The default
484.241 - version understands 'r' (repr) and 's' (str) conversion types.
484.242 -
484.243 -<br><br>
484.244 -
484.245 -<br><br>
484.246 -<h3>Format String Syntax
484.247 -</h3>
484.248 -The <a href="meth:str.format">str.format</a> method and the <a href="class:Formatter">Formatter</a> class share the same
484.249 -syntax for format strings (although in the case of <a href="class:Formatter">Formatter</a>,
484.250 -subclasses can define their own format string syntax.)
484.251 -
484.252 -<br><br>
484.253 -Format strings contain "replacement fields" surrounded by curly braces <code>{}</code>.
484.254 -Anything that is not contained in braces is considered literal text, which is
484.255 -copied unchanged to the output. If you need to include a brace character in the
484.256 -literal text, it can be escaped by doubling: <code>{{</code> and <code>}}</code>.
484.257 -
484.258 -<br><br>
484.259 -The grammar for a replacement field is as follows:
484.260 -
484.261 -<br><br>
484.262 -
484.263 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
484.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>
484.265 -In less formal terms, the replacement field starts with a <b>field_name</b>, which
484.266 -can either be a number (for a positional argument), or an identifier (for
484.267 -keyword arguments). Following this is an optional <b>conversion</b> field, which is
484.268 -preceded by an exclamation point <code>'!'</code>, and a <b>format_spec</b>, which is preceded
484.269 -by a colon <code>':'</code>.
484.270 -
484.271 -<br><br>
484.272 -The <b>field_name</b> itself begins with either a number or a keyword. If it's a
484.273 -number, it refers to a positional argument, and if it's a keyword it refers to a
484.274 -named keyword argument. This can be followed by any number of index or
484.275 -attribute expressions. An expression of the form <code>'.name'</code> selects the named
484.276 -attribute using <a href="func:getattr">getattr</a>, while an expression of the form <code>'[index]'</code>
484.277 -does an index lookup using <a href="func:__getitem__">__getitem__</a>.
484.278 -
484.279 -<br><br>
484.280 -Some simple format string examples::
484.281 -
484.282 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
484.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>
484.284 -The <b>conversion</b> field causes a type coercion before formatting. Normally, the
484.285 -job of formatting a value is done by the <a href="meth:__format__">__format__</a> method of the value
484.286 -itself. However, in some cases it is desirable to force a type to be formatted
484.287 -as a string, overriding its own definition of formatting. By converting the
484.288 -value to a string before calling <a href="meth:__format__">__format__</a>, the normal formatting logic
484.289 -is bypassed.
484.290 -
484.291 -<br><br>
484.292 -Two conversion flags are currently supported: <code>'!s'</code> which calls <a href="func:str">str</a>
484.293 -on the value, and <code>'!r'</code> which calls <a href="func:repr">repr</a>.
484.294 -
484.295 -<br><br>
484.296 -Some examples::
484.297 -
484.298 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
484.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>
484.300 -The <b>format_spec</b> field contains a specification of how the value should be
484.301 -presented, including such details as field width, alignment, padding, decimal
484.302 -precision and so on. Each value type can define it's own "formatting
484.303 -mini-language" or interpretation of the <b>format_spec</b>.
484.304 -
484.305 -<br><br>
484.306 -Most built-in types support a common formatting mini-language, which is
484.307 -described in the next section.
484.308 -
484.309 -<br><br>
484.310 -A <b>format_spec</b> field can also include nested replacement fields within it.
484.311 -These nested replacement fields can contain only a field name; conversion flags
484.312 -and format specifications are not allowed. The replacement fields within the
484.313 -format_spec are substituted before the <b>format_spec</b> string is interpreted.
484.314 -This allows the formatting of a value to be dynamically specified.
484.315 -
484.316 -<br><br>
484.317 -For example, suppose you wanted to have a replacement field whose field width is
484.318 -determined by another variable::
484.319 -
484.320 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
484.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>
484.322 -This would first evaluate the inner replacement field, making the format string
484.323 -effectively::
484.324 -
484.325 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
484.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>
484.327 -Then the outer replacement field would be evaluated, producing::
484.328 -
484.329 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
484.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>
484.331 -Which is substituted into the string, yielding::
484.332 -
484.333 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
484.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>
484.335 -(The extra space is because we specified a field width of 10, and because left
484.336 -alignment is the default for strings.)
484.337 -
484.338 -<br><br>
484.339 -
484.340 -<br><br>
484.341 -<h3>Format Specification Mini-Language
484.342 -</h3>
484.343 -"Format specifications" are used within replacement fields contained within a
484.344 -format string to define how individual values are presented (see
484.345 -<code>formatstrings</code>.) They can also be passed directly to the builtin
484.346 -<a href="func:format">format</a> function. Each formattable type may define how the format
484.347 -specification is to be interpreted.
484.348 -
484.349 -<br><br>
484.350 -Most built-in types implement the following options for format specifications,
484.351 -although some of the formatting options are only supported by the numeric types.
484.352 -
484.353 -<br><br>
484.354 -A general convention is that an empty format string (<code>""</code>) produces the same
484.355 -result as if you had called <a href="func:str">str</a> on the value.
484.356 -
484.357 -<br><br>
484.358 -The general form of a *standard format specifier* is:
484.359 -
484.360 -<br><br>
484.361 -
484.362 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
484.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>
484.364 -The <b>fill</b> character can be any character other than '}' (which signifies the
484.365 -end of the field). The presence of a fill character is signaled by the <b>next</b>
484.366 -character, which must be one of the alignment options. If the second character
484.367 -of <b>format_spec</b> is not a valid alignment option, then it is assumed that both
484.368 -the fill character and the alignment option are absent.
484.369 -
484.370 -<br><br>
484.371 -The meaning of the various alignment options is as follows:
484.372 -
484.373 -<br><br>
484.374 -<pre> +---------+----------------------------------------------------------+
484.375 - | Option | Meaning |
484.376 - +=========+==========================================================+
484.377 - | ``'<'`` | Forces the field to be left-aligned within the available |
484.378 - | | space (This is the default.) |
484.379 - +---------+----------------------------------------------------------+
484.380 - | ``'>'`` | Forces the field to be right-aligned within the |
484.381 - | | available space. |
484.382 - +---------+----------------------------------------------------------+
484.383 - | ``'='`` | Forces the padding to be placed after the sign (if any) |
484.384 - | | but before the digits. This is used for printing fields |
484.385 - | | in the form '+000000120'. This alignment option is only |
484.386 - | | valid for numeric types. |
484.387 - +---------+----------------------------------------------------------+
484.388 - | ``'^'`` | Forces the field to be centered within the available |
484.389 - | | space. |
484.390 - +---------+----------------------------------------------------------+
484.391 -</pre>
484.392 -Note that unless a minimum field width is defined, the field width will always
484.393 -be the same size as the data to fill it, so that the alignment option has no
484.394 -meaning in this case.
484.395 -
484.396 -<br><br>
484.397 -The <b>sign</b> option is only valid for number types, and can be one of the
484.398 -following:
484.399 -
484.400 -<br><br>
484.401 -<pre> +---------+----------------------------------------------------------+
484.402 - | Option | Meaning |
484.403 - +=========+==========================================================+
484.404 - | ``'+'`` | indicates that a sign should be used for both |
484.405 - | | positive as well as negative numbers. |
484.406 - +---------+----------------------------------------------------------+
484.407 - | ``'-'`` | indicates that a sign should be used only for negative |
484.408 - | | numbers (this is the default behavior). |
484.409 - +---------+----------------------------------------------------------+
484.410 - | space | indicates that a leading space should be used on |
484.411 - | | positive numbers, and a minus sign on negative numbers. |
484.412 - +---------+----------------------------------------------------------+
484.413 -</pre>
484.414 -The <code>'#'</code> option is only valid for integers, and only for binary, octal, or
484.415 -hexadecimal output. If present, it specifies that the output will be prefixed
484.416 -by <code>'0b'</code>, <code>'0o'</code>, or <code>'0x'</code>, respectively.
484.417 -
484.418 -<br><br>
484.419 -*width* is a decimal integer defining the minimum field width. If not
484.420 -specified, then the field width will be determined by the content.
484.421 -
484.422 -<br><br>
484.423 -If the <b>width</b> field is preceded by a zero (<code>'0'</code>) character, this enables
484.424 -zero-padding. This is equivalent to an <b>alignment</b> type of <code>'='</code> and a <b>fill</b>
484.425 -character of <code>'0'</code>.
484.426 -
484.427 -<br><br>
484.428 -The <b>precision</b> is a decimal number indicating how many digits should be
484.429 -displayed after the decimal point for a floating point value formatted with
484.430 -<code>'f'</code> and <code>'F'</code>, or before and after the decimal point for a floating point
484.431 -value formatted with <code>'g'</code> or <code>'G'</code>. For non-number types the field
484.432 -indicates the maximum field size - in other words, how many characters will be
484.433 -used from the field content. The <b>precision</b> is ignored for integer values.
484.434 -
484.435 -<br><br>
484.436 -Finally, the <b>type</b> determines how the data should be presented.
484.437 -
484.438 -<br><br>
484.439 -The available integer presentation types are:
484.440 -
484.441 -<br><br>
484.442 -<pre> +---------+----------------------------------------------------------+
484.443 - | Type | Meaning |
484.444 - +=========+==========================================================+
484.445 - | ``'b'`` | Binary format. Outputs the number in base 2. |
484.446 - +---------+----------------------------------------------------------+
484.447 - | ``'c'`` | Character. Converts the integer to the corresponding |
484.448 - | | unicode character before printing. |
484.449 - +---------+----------------------------------------------------------+
484.450 - | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
484.451 - +---------+----------------------------------------------------------+
484.452 - | ``'o'`` | Octal format. Outputs the number in base 8. |
484.453 - +---------+----------------------------------------------------------+
484.454 - | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
484.455 - | | case letters for the digits above 9. |
484.456 - +---------+----------------------------------------------------------+
484.457 - | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
484.458 - | | case letters for the digits above 9. |
484.459 - +---------+----------------------------------------------------------+
484.460 - | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
484.461 - | | the current locale setting to insert the appropriate |
484.462 - | | number separator characters. |
484.463 - +---------+----------------------------------------------------------+
484.464 - | None | The same as ``'d'``. |
484.465 - +---------+----------------------------------------------------------+
484.466 -</pre>
484.467 -The available presentation types for floating point and decimal values are:
484.468 -
484.469 -<br><br>
484.470 -<pre> +---------+----------------------------------------------------------+
484.471 - | Type | Meaning |
484.472 - +=========+==========================================================+
484.473 - | ``'e'`` | Exponent notation. Prints the number in scientific |
484.474 - | | notation using the letter 'e' to indicate the exponent. |
484.475 - +---------+----------------------------------------------------------+
484.476 - | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
484.477 - | | upper case 'E' as the separator character. |
484.478 - +---------+----------------------------------------------------------+
484.479 - | ``'f'`` | Fixed point. Displays the number as a fixed-point |
484.480 - | | number. |
484.481 - +---------+----------------------------------------------------------+
484.482 - | ``'F'`` | Fixed point. Same as ``'f'``. |
484.483 - +---------+----------------------------------------------------------+
484.484 - | ``'g'`` | General format. This prints the number as a fixed-point |
484.485 - | | number, unless the number is too large, in which case |
484.486 - | | it switches to ``'e'`` exponent notation. Infinity and |
484.487 - | | NaN values are formatted as ``inf``, ``-inf`` and |
484.488 - | | ``nan``, respectively. |
484.489 - +---------+----------------------------------------------------------+
484.490 - | ``'G'`` | General format. Same as ``'g'`` except switches to |
484.491 - | | ``'E'`` if the number gets to large. The representations |
484.492 - | | of infinity and NaN are uppercased, too. |
484.493 - +---------+----------------------------------------------------------+
484.494 - | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
484.495 - | | the current locale setting to insert the appropriate |
484.496 - | | number separator characters. |
484.497 - +---------+----------------------------------------------------------+
484.498 - | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
484.499 - | | in fixed (``'f'``) format, followed by a percent sign. |
484.500 - +---------+----------------------------------------------------------+
484.501 - | None | The same as ``'g'``. |
484.502 - +---------+----------------------------------------------------------+
484.503 -</pre>
484.504 -<h3>Template strings
484.505 -</h3>
484.506 -Templates provide simpler string substitutions as described in <a href="http://www.python.org/dev/peps/pep-0292/">PEP 292</a>.
484.507 -Instead of the normal <code>%</code>\ -based substitutions, Templates support <code>$</code>\
484.508 --based substitutions, using the following rules:
484.509 -
484.510 -<br><br>
484.511 -* <code>$$</code> is an escape; it is replaced with a single <code>$</code>.
484.512 -
484.513 -<br><br>
484.514 -* <code>$identifier</code> names a substitution placeholder matching a mapping key of
484.515 - <code>"identifier"</code>. By default, <code>"identifier"</code> must spell a Python
484.516 - identifier. The first non-identifier character after the <code>$</code> character
484.517 - terminates this placeholder specification.
484.518 -
484.519 -<br><br>
484.520 -* <code>${identifier}</code> is equivalent to <code>$identifier</code>. It is required when valid
484.521 - identifier characters follow the placeholder but are not part of the
484.522 - placeholder, such as <code>"${noun}ification"</code>.
484.523 -
484.524 -<br><br>
484.525 -Any other appearance of <code>$</code> in the string will result in a <a href="exc:ValueError">ValueError</a>
484.526 -being raised.
484.527 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.4
484.528 -</div>
484.529 -The <a href="mod:string">string</a> module provides a <a href="class:Template">Template</a> class that implements
484.530 -these rules. The methods of <a href="class:Template">Template</a> are:
484.531 -
484.532 -<br><br>
484.533 -<a href="class:Template(template)">Template(template)</a>
484.534 -
484.535 -<br><br>
484.536 - The constructor takes a single argument which is the template string.
484.537 -
484.538 -<br><br>
484.539 -<a href="meth:substitute(mapping[, **kws])">substitute(mapping[, **kws])</a>
484.540 -
484.541 -<br><br>
484.542 - Performs the template substitution, returning a new string. <b>mapping</b> is
484.543 - any dictionary-like object with keys that match the placeholders in the
484.544 - template. Alternatively, you can provide keyword arguments, where the
484.545 - keywords are the placeholders. When both <b>mapping</b> and <b>kws</b> are given
484.546 - and there are duplicates, the placeholders from <b>kws</b> take precedence.
484.547 -
484.548 -<br><br>
484.549 -<a href="meth:safe_substitute(mapping[, **kws])">safe_substitute(mapping[, **kws])</a>
484.550 -
484.551 -<br><br>
484.552 - Like <a href="meth:substitute">substitute</a>, except that if placeholders are missing from
484.553 - <b>mapping</b> and <b>kws</b>, instead of raising a <a href="exc:KeyError">KeyError</a> exception, the
484.554 - original placeholder will appear in the resulting string intact. Also,
484.555 - unlike with <a href="meth:substitute">substitute</a>, any other appearances of the <code>$</code> will
484.556 - simply return <code>$</code> instead of raising <a href="exc:ValueError">ValueError</a>.
484.557 -
484.558 -<br><br>
484.559 - While other exceptions may still occur, this method is called "safe"
484.560 - because substitutions always tries to return a usable string instead of
484.561 - raising an exception. In another sense, <a href="meth:safe_substitute">safe_substitute</a> may be
484.562 - anything other than safe, since it will silently ignore malformed
484.563 - templates containing dangling delimiters, unmatched braces, or
484.564 - placeholders that are not valid Python identifiers.
484.565 -
484.566 -<br><br>
484.567 -<a href="class:Template">Template</a> instances also provide one public data attribute:
484.568 -
484.569 -<br><br>
484.570 -<a href="attr:string.template">string.template</a>
484.571 -
484.572 -<br><br>
484.573 - This is the object passed to the constructor's <b>template</b> argument. In general,
484.574 - you shouldn't change it, but read-only access is not enforced.
484.575 -
484.576 -<br><br>
484.577 -Here is an example of how to use a Template:
484.578 -
484.579 -<br><br>
484.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>
484.581 -<br><br>
484.582 -Advanced usage: you can derive subclasses of <a href="class:Template">Template</a> to customize the
484.583 -placeholder syntax, delimiter character, or the entire regular expression used
484.584 -to parse template strings. To do this, you can override these class attributes:
484.585 -
484.586 -<br><br>
484.587 -* <b>delimiter</b> -- This is the literal string describing a placeholder introducing
484.588 - delimiter. The default value <code>$</code>. Note that this should <b>not</b> be a regular
484.589 - expression, as the implementation will call <a href="meth:re.escape">re.escape</a> on this string as
484.590 - needed.
484.591 -
484.592 -<br><br>
484.593 -* <b>idpattern</b> -- This is the regular expression describing the pattern for
484.594 - non-braced placeholders (the braces will be added automatically as
484.595 - appropriate). The default value is the regular expression
484.596 - <code>[_a-z][_a-z0-9]*</code>.
484.597 -
484.598 -<br><br>
484.599 -Alternatively, you can provide the entire regular expression pattern by
484.600 -overriding the class attribute <b>pattern</b>. If you do this, the value must be a
484.601 -regular expression object with four named capturing groups. The capturing
484.602 -groups correspond to the rules given above, along with the invalid placeholder
484.603 -rule:
484.604 -
484.605 -<br><br>
484.606 -* <b>escaped</b> -- This group matches the escape sequence, e.g. <code>$$</code>, in the
484.607 - default pattern.
484.608 -
484.609 -<br><br>
484.610 -* <b>named</b> -- This group matches the unbraced placeholder name; it should not
484.611 - include the delimiter in capturing group.
484.612 -
484.613 -<br><br>
484.614 -* <b>braced</b> -- This group matches the brace enclosed placeholder name; it should
484.615 - not include either the delimiter or braces in the capturing group.
484.616 -
484.617 -<br><br>
484.618 -* <b>invalid</b> -- This group matches any other delimiter pattern (usually a single
484.619 - delimiter), and it should appear last in the regular expression.
484.620 -
484.621 -<br><br>
484.622 -<h3>String functions
484.623 -</h3>
484.624 -The following functions are available to operate on string and Unicode objects.
484.625 -They are not available as string methods.
484.626 -
484.627 -<br><br>
484.628 -<a href="func:capwords(s)">capwords(s)</a>
484.629 -
484.630 -<br><br>
484.631 - Split the argument into words using <a href="func:split">split</a>, capitalize each word using
484.632 - <a href="func:capitalize">capitalize</a>, and join the capitalized words using <a href="func:join">join</a>. Note
484.633 - that this replaces runs of whitespace characters by a single space, and removes
484.634 - leading and trailing whitespace.
484.635 -
484.636 -<br><br>
484.637 -<a href="func:maketrans(from, to)">maketrans(from, to)</a>
484.638 -
484.639 -<br><br>
484.640 - Return a translation table suitable for passing to <a href="func:translate">translate</a>, that will
484.641 - map each character in <b>from</b> into the character at the same position in <b>to</b>;
484.642 - <b>from</b> and <b>to</b> must have the same length.
484.643 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>WARNING</b>:
484.644 -
484.645 -<br><br>
484.646 - Don't use strings derived from :const:<code>lowercase</code> and :const:<code>uppercase</code> as
484.647 - arguments; in some locales, these don't have the same length. For case
484.648 - conversions, always use <a href="func:lower">lower</a> and <a href="func:upper">upper</a>.
484.649 -</div>
484.650 -<h3>Deprecated string functions
484.651 -</h3>
484.652 -The following list of functions are also defined as methods of string and
484.653 -Unicode objects; see section <code>string-methods</code> for more information on
484.654 -those. You should consider these functions as deprecated, although they will
484.655 -not be removed until Python 3.0. The functions defined in this module are:
484.656 -
484.657 -<br><br>
484.658 -<a href="func:atof(s)">atof(s)</a>
484.659 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.0
484.660 - Use the <a href="func:float">float</a> built-in function.
484.661 -</div>
484.662 - Convert a string to a floating point number. The string must have the standard
484.663 - syntax for a floating point literal in Python, optionally preceded by a sign
484.664 - (<code>+</code> or <code>-</code>). Note that this behaves identical to the built-in function
484.665 - <a href="func:float">float</a> when passed a string.
484.666 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
484.667 -
484.668 -<br><br>
484.669 - .. index::
484.670 - single: NaN
484.671 - single: Infinity
484.672 -
484.673 -<br><br>
484.674 - When passing in a string, values for NaN and Infinity may be returned, depending
484.675 - on the underlying C library. The specific set of strings accepted which cause
484.676 - these values to be returned depends entirely on the C library and is known to
484.677 - vary.
484.678 -</div>
484.679 -<a href="func:atoi(s[, base])">atoi(s[, base])</a>
484.680 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.0
484.681 - Use the <a href="func:int">int</a> built-in function.
484.682 -</div>
484.683 - Convert string <b>s</b> to an integer in the given <b>base</b>. The string must consist
484.684 - of one or more digits, optionally preceded by a sign (<code>+</code> or <code>-</code>). The
484.685 - <b>base</b> defaults to 10. If it is 0, a default base is chosen depending on the
484.686 - leading characters of the string (after stripping the sign): <code>0x</code> or <code>0X</code>
484.687 - means 16, <code>0</code> means 8, anything else means 10. If <b>base</b> is 16, a leading
484.688 - <code>0x</code> or <code>0X</code> is always accepted, though not required. This behaves
484.689 - identically to the built-in function <a href="func:int">int</a> when passed a string. (Also
484.690 - note: for a more flexible interpretation of numeric literals, use the built-in
484.691 - function <a href="func:eval">eval</a>.)
484.692 -
484.693 -<br><br>
484.694 -<a href="func:atol(s[, base])">atol(s[, base])</a>
484.695 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.0
484.696 - Use the <a href="func:long">long</a> built-in function.
484.697 -</div>
484.698 - Convert string <b>s</b> to a long integer in the given <b>base</b>. The string must
484.699 - consist of one or more digits, optionally preceded by a sign (<code>+</code> or <code>-</code>).
484.700 - The <b>base</b> argument has the same meaning as for <a href="func:atoi">atoi</a>. A trailing <code>l</code>
484.701 - or <code>L</code> is not allowed, except if the base is 0. Note that when invoked
484.702 - without <b>base</b> or with <b>base</b> set to 10, this behaves identical to the built-in
484.703 - function <a href="func:long">long</a> when passed a string.
484.704 -
484.705 -<br><br>
484.706 -<a href="func:capitalize(word)">capitalize(word)</a>
484.707 -
484.708 -<br><br>
484.709 - Return a copy of <b>word</b> with only its first character capitalized.
484.710 -
484.711 -<br><br>
484.712 -<a href="func:expandtabs(s[, tabsize])">expandtabs(s[, tabsize])</a>
484.713 -
484.714 -<br><br>
484.715 - Expand tabs in a string replacing them by one or more spaces, depending on the
484.716 - current column and the given tab size. The column number is reset to zero after
484.717 - each newline occurring in the string. This doesn't understand other non-printing
484.718 - characters or escape sequences. The tab size defaults to 8.
484.719 -
484.720 -<br><br>
484.721 -<a href="func:find(s, sub[, start[,end]])">find(s, sub[, start[,end]])</a>
484.722 -
484.723 -<br><br>
484.724 - Return the lowest index in <b>s</b> where the substring <b>sub</b> is found such that
484.725 - <b>sub</b> is wholly contained in <code>s[start:end]</code>. Return <code>-1</code> on failure.
484.726 - Defaults for <b>start</b> and <b>end</b> and interpretation of negative values is the same
484.727 - as for slices.
484.728 -
484.729 -<br><br>
484.730 -<a href="func:rfind(s, sub[, start[, end]])">rfind(s, sub[, start[, end]])</a>
484.731 -
484.732 -<br><br>
484.733 - Like <a href="func:find">find</a> but find the highest index.
484.734 -
484.735 -<br><br>
484.736 -<a href="func:index(s, sub[, start[, end]])">index(s, sub[, start[, end]])</a>
484.737 -
484.738 -<br><br>
484.739 - Like <a href="func:find">find</a> but raise <a href="exc:ValueError">ValueError</a> when the substring is not found.
484.740 -
484.741 -<br><br>
484.742 -<a href="func:rindex(s, sub[, start[, end]])">rindex(s, sub[, start[, end]])</a>
484.743 -
484.744 -<br><br>
484.745 - Like <a href="func:rfind">rfind</a> but raise <a href="exc:ValueError">ValueError</a> when the substring is not found.
484.746 -
484.747 -<br><br>
484.748 -<a href="func:count(s, sub[, start[, end]])">count(s, sub[, start[, end]])</a>
484.749 -
484.750 -<br><br>
484.751 - Return the number of (non-overlapping) occurrences of substring <b>sub</b> in string
484.752 - <code>s[start:end]</code>. Defaults for <b>start</b> and <b>end</b> and interpretation of negative
484.753 - values are the same as for slices.
484.754 -
484.755 -<br><br>
484.756 -<a href="func:lower(s)">lower(s)</a>
484.757 -
484.758 -<br><br>
484.759 - Return a copy of <b>s</b>, but with upper case letters converted to lower case.
484.760 -
484.761 -<br><br>
484.762 -<a href="func:split(s[, sep[, maxsplit]])">split(s[, sep[, maxsplit]])</a>
484.763 -
484.764 -<br><br>
484.765 - Return a list of the words of the string <b>s</b>. If the optional second argument
484.766 - <b>sep</b> is absent or <code>None</code>, the words are separated by arbitrary strings of
484.767 - whitespace characters (space, tab, newline, return, formfeed). If the second
484.768 - argument <b>sep</b> is present and not <code>None</code>, it specifies a string to be used as
484.769 - the word separator. The returned list will then have one more item than the
484.770 - number of non-overlapping occurrences of the separator in the string. The
484.771 - optional third argument <b>maxsplit</b> defaults to 0. If it is nonzero, at most
484.772 - <b>maxsplit</b> number of splits occur, and the remainder of the string is returned
484.773 - as the final element of the list (thus, the list will have at most
484.774 - <code>maxsplit+1</code> elements).
484.775 -
484.776 -<br><br>
484.777 - The behavior of split on an empty string depends on the value of <b>sep</b>. If <b>sep</b>
484.778 - is not specified, or specified as <code>None</code>, the result will be an empty list.
484.779 - If <b>sep</b> is specified as any string, the result will be a list containing one
484.780 - element which is an empty string.
484.781 -
484.782 -<br><br>
484.783 -<a href="func:rsplit(s[, sep[, maxsplit]])">rsplit(s[, sep[, maxsplit]])</a>
484.784 -
484.785 -<br><br>
484.786 - Return a list of the words of the string <b>s</b>, scanning <b>s</b> from the end. To all
484.787 - intents and purposes, the resulting list of words is the same as returned by
484.788 - <a href="func:split">split</a>, except when the optional third argument <b>maxsplit</b> is explicitly
484.789 - specified and nonzero. When <b>maxsplit</b> is nonzero, at most <b>maxsplit</b> number of
484.790 - splits -- the <b>rightmost</b> ones -- occur, and the remainder of the string is
484.791 - returned as the first element of the list (thus, the list will have at most
484.792 - <code>maxsplit+1</code> elements).
484.793 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.4
484.794 -</div>
484.795 -<a href="func:splitfields(s[, sep[, maxsplit]])">splitfields(s[, sep[, maxsplit]])</a>
484.796 - This function behaves identically to <a href="func:split">split</a>. (In the past, <a href="func:split">split</a>
484.797 - was only used with one argument, while <a href="func:splitfields">splitfields</a> was only used with
484.798 - two arguments.)
484.799 -
484.800 -<br><br>
484.801 -<a href="func:join(words[, sep])">join(words[, sep])</a>
484.802 -
484.803 -<br><br>
484.804 - Concatenate a list or tuple of words with intervening occurrences of <b>sep</b>.
484.805 - The default value for <b>sep</b> is a single space character. It is always true that
484.806 - <code>string.join(string.split(s, sep), sep)</code> equals <b>s</b>.
484.807 -
484.808 -<br><br>
484.809 -<a href="func:joinfields(words[, sep])">joinfields(words[, sep])</a>
484.810 -
484.811 -<br><br>
484.812 - This function behaves identically to <a href="func:join">join</a>. (In the past, <a href="func:join">join</a>
484.813 - was only used with one argument, while <a href="func:joinfields">joinfields</a> was only used with two
484.814 - arguments.) Note that there is no <a href="meth:joinfields">joinfields</a> method on string objects;
484.815 - use the <a href="meth:join">join</a> method instead.
484.816 -
484.817 -<br><br>
484.818 -<a href="func:lstrip(s[, chars])">lstrip(s[, chars])</a>
484.819 -
484.820 -<br><br>
484.821 - Return a copy of the string with leading characters removed. If <b>chars</b> is
484.822 - omitted or <code>None</code>, whitespace characters are removed. If given and not
484.823 - <code>None</code>, <b>chars</b> must be a string; the characters in the string will be
484.824 - stripped from the beginning of the string this method is called on.
484.825 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.2.3
484.826 - The <b>chars</b> parameter was added. The <b>chars</b> parameter cannot be passed in
484.827 - earlier 2.2 versions.
484.828 -</div>
484.829 -<a href="func:rstrip(s[, chars])">rstrip(s[, chars])</a>
484.830 - Return a copy of the string with trailing characters removed. If <b>chars</b> is
484.831 - omitted or <code>None</code>, whitespace characters are removed. If given and not
484.832 - <code>None</code>, <b>chars</b> must be a string; the characters in the string will be
484.833 - stripped from the end of the string this method is called on.
484.834 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.2.3
484.835 - The <b>chars</b> parameter was added. The <b>chars</b> parameter cannot be passed in
484.836 - earlier 2.2 versions.
484.837 -</div>
484.838 -<a href="func:strip(s[, chars])">strip(s[, chars])</a>
484.839 - Return a copy of the string with leading and trailing characters removed. If
484.840 - <b>chars</b> is omitted or <code>None</code>, whitespace characters are removed. If given and
484.841 - not <code>None</code>, <b>chars</b> must be a string; the characters in the string will be
484.842 - stripped from the both ends of the string this method is called on.
484.843 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.2.3
484.844 - The <b>chars</b> parameter was added. The <b>chars</b> parameter cannot be passed in
484.845 - earlier 2.2 versions.
484.846 -</div>
484.847 -<a href="func:swapcase(s)">swapcase(s)</a>
484.848 - Return a copy of <b>s</b>, but with lower case letters converted to upper case and
484.849 - vice versa.
484.850 -
484.851 -<br><br>
484.852 -<a href="func:translate(s, table[, deletechars])">translate(s, table[, deletechars])</a>
484.853 -
484.854 -<br><br>
484.855 - Delete all characters from <b>s</b> that are in <b>deletechars</b> (if present), and then
484.856 - translate the characters using <b>table</b>, which must be a 256-character string
484.857 - giving the translation for each character value, indexed by its ordinal. If
484.858 - <b>table</b> is <code>None</code>, then only the character deletion step is performed.
484.859 -
484.860 -<br><br>
484.861 -<a href="func:upper(s)">upper(s)</a>
484.862 -
484.863 -<br><br>
484.864 - Return a copy of <b>s</b>, but with lower case letters converted to upper case.
484.865 -
484.866 -<br><br>
484.867 -<a href="func:ljust(s, width)">ljust(s, width)</a>
484.868 - rjust(s, width)
484.869 - center(s, width)
484.870 -
484.871 -<br><br>
484.872 - These functions respectively left-justify, right-justify and center a string in
484.873 - a field of given width. They return a string that is at least <b>width</b>
484.874 - characters wide, created by padding the string <b>s</b> with spaces until the given
484.875 - width on the right, left or both sides. The string is never truncated.
484.876 -
484.877 -<br><br>
484.878 -<a href="func:zfill(s, width)">zfill(s, width)</a>
484.879 -
484.880 -<br><br>
484.881 - Pad a numeric string on the left with zero digits until the given width is
484.882 - reached. Strings starting with a sign are handled correctly.
484.883 -
484.884 -<br><br>
484.885 -<a href="func:replace(str, old, new[, maxreplace])">replace(str, old, new[, maxreplace])</a>
484.886 -
484.887 -<br><br>
484.888 - Return a copy of string <b>str</b> with all occurrences of substring <b>old</b> replaced
484.889 - by <b>new</b>. If the optional argument <b>maxreplace</b> is given, the first
484.890 - <b>maxreplace</b> occurrences are replaced.
484.891 -</body></html>
485.1 --- a/python.editor/test/unit/data/testfiles/rst/string.rst.indexed Sun Jan 04 13:11:53 2015 -0600
485.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
485.3 @@ -1,82 +0,0 @@
485.4 -
485.5 -
485.6 -Document 0
485.7 -Searchable Keys:
485.8 - class : Formatter
485.9 - class-ig : formatter
485.10 - in : string
485.11 - member : check_unused_args;F;|DOCUMENTED|DOC_ONLY|;used_args,args,kwargs;
485.12 - member : convert_field;F;|DOCUMENTED|DOC_ONLY|;value,conversion;
485.13 - member : format;F;|DOCUMENTED|DOC_ONLY|;format_string,*args,*kwargs;
485.14 - member : format_field;F;|DOCUMENTED|DOC_ONLY|;value,format_spec;
485.15 - member : get_field;F;|DOCUMENTED|DOC_ONLY|;field_name,args,kwargs;
485.16 - member : get_value;F;|DOCUMENTED|DOC_ONLY|;key,args,kwargs;
485.17 - member : parse;F;|DOCUMENTED|DOC_ONLY|;format_string;
485.18 - member : vformat;F;|DOCUMENTED|DOC_ONLY|;format_string,args,kwargs;
485.19 -
485.20 -Not Searchable Keys:
485.21 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
485.22 -
485.23 -
485.24 -Document 1
485.25 -Searchable Keys:
485.26 - class : Template
485.27 - class-ig : template
485.28 - in : string
485.29 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;template;
485.30 - member : safe_substitute;F;|DOCUMENTED|DOC_ONLY|;mapping,**kws;
485.31 - member : substitute;F;|DOCUMENTED|DOC_ONLY|;mapping,**kws;
485.32 -
485.33 -Not Searchable Keys:
485.34 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
485.35 -
485.36 -
485.37 -Document 2
485.38 -Searchable Keys:
485.39 - item : Formatter;C;|DOCUMENTED|DOC_ONLY|;
485.40 - item : Template;C;|DOCUMENTED|DOC_ONLY|;
485.41 - item : ascii_letters;D;|DOCUMENTED|DOC_ONLY|;
485.42 - item : ascii_lowercase;D;|DOCUMENTED|DOC_ONLY|;
485.43 - item : ascii_uppercase;D;|DOCUMENTED|DOC_ONLY|;
485.44 - item : atof;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;s;
485.45 - item : atoi;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;s,base;
485.46 - item : atol;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;s,base;
485.47 - item : capitalize;F;|DOCUMENTED|DOC_ONLY|;word;
485.48 - item : capwords;F;|DOCUMENTED|DOC_ONLY|;s;
485.49 - item : center;F;|DOCUMENTED|DOC_ONLY|;s,width;
485.50 - item : count;F;|DOCUMENTED|DOC_ONLY|;s,sub,start,end;
485.51 - item : digits;D;|DOCUMENTED|DOC_ONLY|;
485.52 - item : expandtabs;F;|DOCUMENTED|DOC_ONLY|;s,tabsize;
485.53 - item : find;F;|DOCUMENTED|DOC_ONLY|;s,sub,start,end;
485.54 - item : hexdigits;D;|DOCUMENTED|DOC_ONLY|;
485.55 - item : index;F;|DOCUMENTED|DOC_ONLY|;s,sub,start,end;
485.56 - item : join;F;|DOCUMENTED|DOC_ONLY|;words,sep;
485.57 - item : joinfields;F;|DOCUMENTED|DOC_ONLY|;words,sep;
485.58 - item : letters;D;|DOCUMENTED|DOC_ONLY|;
485.59 - item : ljust;F;|DOCUMENTED|DOC_ONLY|;s,width;
485.60 - item : lower;F;|DOCUMENTED|DOC_ONLY|;s;
485.61 - item : lowercase;D;|DOCUMENTED|DOC_ONLY|;
485.62 - item : lstrip;F;|DOCUMENTED|DOC_ONLY|;s,chars;
485.63 - item : maketrans;F;|DOCUMENTED|DOC_ONLY|;from,to;
485.64 - item : octdigits;D;|DOCUMENTED|DOC_ONLY|;
485.65 - item : printable;D;|DOCUMENTED|DOC_ONLY|;
485.66 - item : punctuation;D;|DOCUMENTED|DOC_ONLY|;
485.67 - item : replace;F;|DOCUMENTED|DOC_ONLY|;str,old,new,maxreplace;
485.68 - item : rfind;F;|DOCUMENTED|DOC_ONLY|;s,sub,start,end;
485.69 - item : rindex;F;|DOCUMENTED|DOC_ONLY|;s,sub,start,end;
485.70 - item : rjust;F;|DOCUMENTED|DOC_ONLY|;s,width;
485.71 - item : rsplit;F;|DOCUMENTED|DOC_ONLY|;s,sep,maxsplit;
485.72 - item : rstrip;F;|DOCUMENTED|DOC_ONLY|;s,chars;
485.73 - item : split;F;|DOCUMENTED|DOC_ONLY|;s,sep,maxsplit;
485.74 - item : splitfields;F;|DOCUMENTED|DOC_ONLY|;s,sep,maxsplit;
485.75 - item : strip;F;|DOCUMENTED|DOC_ONLY|;s,chars;
485.76 - item : swapcase;F;|DOCUMENTED|DOC_ONLY|;s;
485.77 - item : translate;F;|DOCUMENTED|DOC_ONLY|;s,table,deletechars;
485.78 - item : upper;F;|DOCUMENTED|DOC_ONLY|;s;
485.79 - item : uppercase;D;|DOCUMENTED|DOC_ONLY|;
485.80 - item : whitespace;D;|DOCUMENTED|DOC_ONLY|;
485.81 - item : zfill;F;|DOCUMENTED|DOC_ONLY|;s,width;
485.82 - module : string
485.83 -
485.84 -Not Searchable Keys:
485.85 - modattrs : S
486.1 --- a/python.editor/test/unit/data/testfiles/rst/stub_missing.rst Sun Jan 04 13:11:53 2015 -0600
486.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
486.3 @@ -1,2367 +0,0 @@
486.4 -NetBeans extra documentation:
486.5 -Documentation for APIs missing from the RST documentation shipping with Python.
486.6 -This is generated from introspecting python code using extract_rst.py.
486.7 -Python version stats:
486.8 -2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04)
486.9 -[GCC 4.0.1 (Apple Computer, Inc. build 5370)]
486.10 -
486.11 -
486.12 -.. class:: int
486.13 -
486.14 - int(x[, base]) -> integer
486.15 -
486.16 - Convert a string or number to an integer, if possible. A floating point
486.17 - argument will be truncated towards zero (this does not include a string
486.18 - representation of a floating point number!) When converting a string, use
486.19 - the optional base. It is an error to supply a base when converting a
486.20 - non-string. If base is zero, the proper base is guessed based on the
486.21 - string content. If the argument is outside the integer range a
486.22 - long object will be returned instead.
486.23 -
486.24 -
486.25 -.. attribute:: __class__
486.26 -
486.27 - int(x[, base]) -> integer
486.28 -
486.29 - Convert a string or number to an integer, if possible. A floating point
486.30 - argument will be truncated towards zero (this does not include a string
486.31 - representation of a floating point number!) When converting a string, use
486.32 - the optional base. It is an error to supply a base when converting a
486.33 - non-string. If base is zero, the proper base is guessed based on the
486.34 - string content. If the argument is outside the integer range a
486.35 - long object will be returned instead.
486.36 -
486.37 -
486.38 -.. method:: __cmp__(y)
486.39 -
486.40 - x.__cmp__(y) <==> cmp(x,y)
486.41 -
486.42 -
486.43 -.. method:: __coerce__(y)
486.44 -
486.45 - x.__coerce__(y) <==> coerce(x, y)
486.46 -
486.47 -
486.48 -.. method:: __delattr__(name)
486.49 -
486.50 - x.__delattr__('name') <==> del x.name
486.51 -
486.52 -
486.53 -.. method:: __divmod__(y)
486.54 -
486.55 - x.__divmod__(y) <==> divmod(x, y)
486.56 -
486.57 -
486.58 -.. attribute:: __doc__
486.59 -
486.60 - str(object) -> string
486.61 -
486.62 - Return a nice string representation of the object.
486.63 - If the argument is a string, the return value is the same object.
486.64 -
486.65 -
486.66 -.. method:: __float__()
486.67 -
486.68 - x.__float__() <==> float(x)
486.69 -
486.70 -
486.71 -.. method:: __format__()
486.72 -
486.73 - .. versionadded:: 2.6
486.74 -
486.75 -.. method:: __getattribute__(name)
486.76 -
486.77 - x.__getattribute__('name') <==> x.name
486.78 -
486.79 -
486.80 -.. method:: __getnewargs__()
486.81 -
486.82 -
486.83 -.. method:: __hash__()
486.84 -
486.85 - x.__hash__() <==> hash(x)
486.86 -
486.87 -
486.88 -.. method:: __hex__()
486.89 -
486.90 - x.__hex__() <==> hex(x)
486.91 -
486.92 -
486.93 -.. method:: __init__()
486.94 -
486.95 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
486.96 -
486.97 -
486.98 -.. method:: __int__()
486.99 -
486.100 - x.__int__() <==> int(x)
486.101 -
486.102 -
486.103 -.. method:: __long__()
486.104 -
486.105 - x.__long__() <==> long(x)
486.106 -
486.107 -
486.108 -.. method:: __new__(S, ___)
486.109 -
486.110 - T.__new__(S, ...) -> a new object with type S, a subtype of T
486.111 -
486.112 -
486.113 -.. method:: __nonzero__()
486.114 -
486.115 - x.__nonzero__() <==> x != 0
486.116 -
486.117 -
486.118 -.. method:: __oct__()
486.119 -
486.120 - x.__oct__() <==> oct(x)
486.121 -
486.122 -
486.123 -.. method:: __radd__(y)
486.124 -
486.125 - x.__radd__(y) <==> y+x
486.126 -
486.127 -
486.128 -.. method:: __rand__(y)
486.129 -
486.130 - x.__rand__(y) <==> y&x
486.131 -
486.132 -
486.133 -.. method:: __rdiv__(y)
486.134 -
486.135 - x.__rdiv__(y) <==> y/x
486.136 -
486.137 -
486.138 -.. method:: __rdivmod__(y)
486.139 -
486.140 - x.__rdivmod__(y) <==> divmod(y, x)
486.141 -
486.142 -
486.143 -.. method:: __reduce__()
486.144 -
486.145 - helper for pickle
486.146 -
486.147 -
486.148 -.. method:: __reduce_ex__()
486.149 -
486.150 - helper for pickle
486.151 -
486.152 -
486.153 -.. method:: __repr__()
486.154 -
486.155 - x.__repr__() <==> repr(x)
486.156 -
486.157 -
486.158 -.. method:: __rfloordiv__(y)
486.159 -
486.160 - x.__rfloordiv__(y) <==> y//x
486.161 -
486.162 -
486.163 -.. method:: __rlshift__(y)
486.164 -
486.165 - x.__rlshift__(y) <==> y<<x
486.166 -
486.167 -
486.168 -.. method:: __rmod__(y)
486.169 -
486.170 - x.__rmod__(y) <==> y%x
486.171 -
486.172 -
486.173 -.. method:: __rmul__(y)
486.174 -
486.175 - x.__rmul__(y) <==> y*x
486.176 -
486.177 -
486.178 -.. method:: __ror__(y)
486.179 -
486.180 - x.__ror__(y) <==> y|x
486.181 -
486.182 -
486.183 -.. method:: __rpow__(x)
486.184 -
486.185 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
486.186 -
486.187 -
486.188 -.. method:: __rrshift__(y)
486.189 -
486.190 - x.__rrshift__(y) <==> y>>x
486.191 -
486.192 -
486.193 -.. method:: __rsub__(y)
486.194 -
486.195 - x.__rsub__(y) <==> y-x
486.196 -
486.197 -
486.198 -.. method:: __rtruediv__(y)
486.199 -
486.200 - x.__rtruediv__(y) <==> y/x
486.201 -
486.202 -
486.203 -.. method:: __rxor__(y)
486.204 -
486.205 - x.__rxor__(y) <==> y^x
486.206 -
486.207 -
486.208 -.. method:: __setattr__(name, value)
486.209 -
486.210 - x.__setattr__('name', value) <==> x.name = value
486.211 -
486.212 -
486.213 -.. method:: __sizeof__()
486.214 -
486.215 - __sizeof__() -> size of object in memory, in bytes
486.216 -
486.217 - .. versionadded:: 2.6
486.218 -
486.219 -.. method:: __str__()
486.220 -
486.221 - x.__str__() <==> str(x)
486.222 -
486.223 -
486.224 -.. method:: __subclasshook__()
486.225 -
486.226 - Abstract classes can override this to customize issubclass().
486.227 -
486.228 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
486.229 - It should return True, False or NotImplemented. If it returns
486.230 - NotImplemented, the normal algorithm is used. Otherwise, it
486.231 - overrides the normal algorithm (and the outcome is cached).
486.232 -
486.233 -
486.234 - .. versionadded:: 2.6
486.235 -
486.236 -.. method:: __trunc__()
486.237 -
486.238 - Truncating an Integral returns itself.
486.239 -
486.240 - .. versionadded:: 2.6
486.241 -
486.242 -.. method:: conjugate()
486.243 -
486.244 - Returns self, the complex conjugate of any int.
486.245 -
486.246 - .. versionadded:: 2.6
486.247 -
486.248 -.. attribute:: denominator
486.249 -
486.250 - int(x[, base]) -> integer
486.251 -
486.252 - Convert a string or number to an integer, if possible. A floating point
486.253 - argument will be truncated towards zero (this does not include a string
486.254 - representation of a floating point number!) When converting a string, use
486.255 - the optional base. It is an error to supply a base when converting a
486.256 - non-string. If base is zero, the proper base is guessed based on the
486.257 - string content. If the argument is outside the integer range a
486.258 - long object will be returned instead.
486.259 -
486.260 - .. versionadded:: 2.6
486.261 -
486.262 -.. attribute:: imag
486.263 -
486.264 - int(x[, base]) -> integer
486.265 -
486.266 - Convert a string or number to an integer, if possible. A floating point
486.267 - argument will be truncated towards zero (this does not include a string
486.268 - representation of a floating point number!) When converting a string, use
486.269 - the optional base. It is an error to supply a base when converting a
486.270 - non-string. If base is zero, the proper base is guessed based on the
486.271 - string content. If the argument is outside the integer range a
486.272 - long object will be returned instead.
486.273 -
486.274 - .. versionadded:: 2.6
486.275 -
486.276 -.. attribute:: numerator
486.277 -
486.278 - int(x[, base]) -> integer
486.279 -
486.280 - Convert a string or number to an integer, if possible. A floating point
486.281 - argument will be truncated towards zero (this does not include a string
486.282 - representation of a floating point number!) When converting a string, use
486.283 - the optional base. It is an error to supply a base when converting a
486.284 - non-string. If base is zero, the proper base is guessed based on the
486.285 - string content. If the argument is outside the integer range a
486.286 - long object will be returned instead.
486.287 -
486.288 - .. versionadded:: 2.6
486.289 -
486.290 -.. attribute:: real
486.291 -
486.292 - int(x[, base]) -> integer
486.293 -
486.294 - Convert a string or number to an integer, if possible. A floating point
486.295 - argument will be truncated towards zero (this does not include a string
486.296 - representation of a floating point number!) When converting a string, use
486.297 - the optional base. It is an error to supply a base when converting a
486.298 - non-string. If base is zero, the proper base is guessed based on the
486.299 - string content. If the argument is outside the integer range a
486.300 - long object will be returned instead.
486.301 -
486.302 - .. versionadded:: 2.6
486.303 -
486.304 -.. class:: float
486.305 -
486.306 - float(x) -> floating point number
486.307 -
486.308 - Convert a string or number to a floating point number, if possible.
486.309 -
486.310 -
486.311 -.. attribute:: __class__
486.312 -
486.313 - float(x) -> floating point number
486.314 -
486.315 - Convert a string or number to a floating point number, if possible.
486.316 -
486.317 -
486.318 -.. method:: __coerce__(y)
486.319 -
486.320 - x.__coerce__(y) <==> coerce(x, y)
486.321 -
486.322 -
486.323 -.. method:: __delattr__(name)
486.324 -
486.325 - x.__delattr__('name') <==> del x.name
486.326 -
486.327 -
486.328 -.. method:: __divmod__(y)
486.329 -
486.330 - x.__divmod__(y) <==> divmod(x, y)
486.331 -
486.332 -
486.333 -.. attribute:: __doc__
486.334 -
486.335 - str(object) -> string
486.336 -
486.337 - Return a nice string representation of the object.
486.338 - If the argument is a string, the return value is the same object.
486.339 -
486.340 -
486.341 -.. method:: __float__()
486.342 -
486.343 - x.__float__() <==> float(x)
486.344 -
486.345 -
486.346 -.. method:: __format__(format_spec)
486.347 -
486.348 - float.__format__(format_spec) -> string
486.349 -
486.350 - Formats the float according to format_spec.
486.351 -
486.352 - .. versionadded:: 2.6
486.353 -
486.354 -.. method:: __getattribute__(name)
486.355 -
486.356 - x.__getattribute__('name') <==> x.name
486.357 -
486.358 -
486.359 -.. method:: __getformat__(typestr)
486.360 -
486.361 - float.__getformat__(typestr) -> string
486.362 -
486.363 - You probably don't want to use this function. It exists mainly to be
486.364 - used in Python's test suite.
486.365 -
486.366 - typestr must be 'double' or 'float'. This function returns whichever of
486.367 - 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the
486.368 - format of floating point numbers used by the C type named by typestr.
486.369 -
486.370 -
486.371 -.. method:: __getnewargs__()
486.372 -
486.373 -
486.374 -.. method:: __hash__()
486.375 -
486.376 - x.__hash__() <==> hash(x)
486.377 -
486.378 -
486.379 -.. method:: __init__()
486.380 -
486.381 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
486.382 -
486.383 -
486.384 -.. method:: __int__()
486.385 -
486.386 - x.__int__() <==> int(x)
486.387 -
486.388 -
486.389 -.. method:: __long__()
486.390 -
486.391 - x.__long__() <==> long(x)
486.392 -
486.393 -
486.394 -.. method:: __new__(S, ___)
486.395 -
486.396 - T.__new__(S, ...) -> a new object with type S, a subtype of T
486.397 -
486.398 -
486.399 -.. method:: __nonzero__()
486.400 -
486.401 - x.__nonzero__() <==> x != 0
486.402 -
486.403 -
486.404 -.. method:: __radd__(y)
486.405 -
486.406 - x.__radd__(y) <==> y+x
486.407 -
486.408 -
486.409 -.. method:: __rdiv__(y)
486.410 -
486.411 - x.__rdiv__(y) <==> y/x
486.412 -
486.413 -
486.414 -.. method:: __rdivmod__(y)
486.415 -
486.416 - x.__rdivmod__(y) <==> divmod(y, x)
486.417 -
486.418 -
486.419 -.. method:: __reduce__()
486.420 -
486.421 - helper for pickle
486.422 -
486.423 -
486.424 -.. method:: __reduce_ex__()
486.425 -
486.426 - helper for pickle
486.427 -
486.428 -
486.429 -.. method:: __repr__()
486.430 -
486.431 - x.__repr__() <==> repr(x)
486.432 -
486.433 -
486.434 -.. method:: __rfloordiv__(y)
486.435 -
486.436 - x.__rfloordiv__(y) <==> y//x
486.437 -
486.438 -
486.439 -.. method:: __rmod__(y)
486.440 -
486.441 - x.__rmod__(y) <==> y%x
486.442 -
486.443 -
486.444 -.. method:: __rmul__(y)
486.445 -
486.446 - x.__rmul__(y) <==> y*x
486.447 -
486.448 -
486.449 -.. method:: __rpow__(x)
486.450 -
486.451 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
486.452 -
486.453 -
486.454 -.. method:: __rsub__(y)
486.455 -
486.456 - x.__rsub__(y) <==> y-x
486.457 -
486.458 -
486.459 -.. method:: __rtruediv__(y)
486.460 -
486.461 - x.__rtruediv__(y) <==> y/x
486.462 -
486.463 -
486.464 -.. method:: __setattr__(name, value)
486.465 -
486.466 - x.__setattr__('name', value) <==> x.name = value
486.467 -
486.468 -
486.469 -.. method:: __setformat__(typestr, fmt)
486.470 -
486.471 - float.__setformat__(typestr, fmt) -> None
486.472 -
486.473 - You probably don't want to use this function. It exists mainly to be
486.474 - used in Python's test suite.
486.475 -
486.476 - typestr must be 'double' or 'float'. fmt must be one of 'unknown',
486.477 - 'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be
486.478 - one of the latter two if it appears to match the underlying C reality.
486.479 -
486.480 - Overrides the automatic determination of C-level floating point type.
486.481 - This affects how floats are converted to and from binary strings.
486.482 -
486.483 -
486.484 -.. method:: __sizeof__()
486.485 -
486.486 - __sizeof__() -> size of object in memory, in bytes
486.487 -
486.488 - .. versionadded:: 2.6
486.489 -
486.490 -.. method:: __str__()
486.491 -
486.492 - x.__str__() <==> str(x)
486.493 -
486.494 -
486.495 -.. method:: __subclasshook__()
486.496 -
486.497 - Abstract classes can override this to customize issubclass().
486.498 -
486.499 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
486.500 - It should return True, False or NotImplemented. If it returns
486.501 - NotImplemented, the normal algorithm is used. Otherwise, it
486.502 - overrides the normal algorithm (and the outcome is cached).
486.503 -
486.504 -
486.505 - .. versionadded:: 2.6
486.506 -
486.507 -.. method:: __trunc__()
486.508 -
486.509 - Returns the Integral closest to x between 0 and x.
486.510 -
486.511 - .. versionadded:: 2.6
486.512 -
486.513 -.. method:: conjugate()
486.514 -
486.515 - Returns self, the complex conjugate of any float.
486.516 -
486.517 - .. versionadded:: 2.6
486.518 -
486.519 -.. attribute:: imag
486.520 -
486.521 - float(x) -> floating point number
486.522 -
486.523 - Convert a string or number to a floating point number, if possible.
486.524 -
486.525 - .. versionadded:: 2.6
486.526 -
486.527 -.. method:: is_integer()
486.528 -
486.529 - Returns True if the float is an integer.
486.530 -
486.531 - .. versionadded:: 2.6
486.532 -
486.533 -.. attribute:: real
486.534 -
486.535 - float(x) -> floating point number
486.536 -
486.537 - Convert a string or number to a floating point number, if possible.
486.538 -
486.539 - .. versionadded:: 2.6
486.540 -
486.541 -.. class:: long
486.542 -
486.543 - long(x[, base]) -> integer
486.544 -
486.545 - Convert a string or number to a long integer, if possible. A floating
486.546 - point argument will be truncated towards zero (this does not include a
486.547 - string representation of a floating point number!) When converting a
486.548 - string, use the optional base. It is an error to supply a base when
486.549 - converting a non-string.
486.550 -
486.551 -
486.552 -.. attribute:: __class__
486.553 -
486.554 - long(x[, base]) -> integer
486.555 -
486.556 - Convert a string or number to a long integer, if possible. A floating
486.557 - point argument will be truncated towards zero (this does not include a
486.558 - string representation of a floating point number!) When converting a
486.559 - string, use the optional base. It is an error to supply a base when
486.560 - converting a non-string.
486.561 -
486.562 -
486.563 -.. method:: __cmp__(y)
486.564 -
486.565 - x.__cmp__(y) <==> cmp(x,y)
486.566 -
486.567 -
486.568 -.. method:: __coerce__(y)
486.569 -
486.570 - x.__coerce__(y) <==> coerce(x, y)
486.571 -
486.572 -
486.573 -.. method:: __delattr__(name)
486.574 -
486.575 - x.__delattr__('name') <==> del x.name
486.576 -
486.577 -
486.578 -.. method:: __divmod__(y)
486.579 -
486.580 - x.__divmod__(y) <==> divmod(x, y)
486.581 -
486.582 -
486.583 -.. attribute:: __doc__
486.584 -
486.585 - str(object) -> string
486.586 -
486.587 - Return a nice string representation of the object.
486.588 - If the argument is a string, the return value is the same object.
486.589 -
486.590 -
486.591 -.. method:: __float__()
486.592 -
486.593 - x.__float__() <==> float(x)
486.594 -
486.595 -
486.596 -.. method:: __format__()
486.597 -
486.598 - .. versionadded:: 2.6
486.599 -
486.600 -.. method:: __getattribute__(name)
486.601 -
486.602 - x.__getattribute__('name') <==> x.name
486.603 -
486.604 -
486.605 -.. method:: __getnewargs__()
486.606 -
486.607 -
486.608 -.. method:: __hash__()
486.609 -
486.610 - x.__hash__() <==> hash(x)
486.611 -
486.612 -
486.613 -.. method:: __hex__()
486.614 -
486.615 - x.__hex__() <==> hex(x)
486.616 -
486.617 -
486.618 -.. method:: __init__()
486.619 -
486.620 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
486.621 -
486.622 -
486.623 -.. method:: __int__()
486.624 -
486.625 - x.__int__() <==> int(x)
486.626 -
486.627 -
486.628 -.. method:: __long__()
486.629 -
486.630 - x.__long__() <==> long(x)
486.631 -
486.632 -
486.633 -.. method:: __new__(S, ___)
486.634 -
486.635 - T.__new__(S, ...) -> a new object with type S, a subtype of T
486.636 -
486.637 -
486.638 -.. method:: __nonzero__()
486.639 -
486.640 - x.__nonzero__() <==> x != 0
486.641 -
486.642 -
486.643 -.. method:: __oct__()
486.644 -
486.645 - x.__oct__() <==> oct(x)
486.646 -
486.647 -
486.648 -.. method:: __radd__(y)
486.649 -
486.650 - x.__radd__(y) <==> y+x
486.651 -
486.652 -
486.653 -.. method:: __rand__(y)
486.654 -
486.655 - x.__rand__(y) <==> y&x
486.656 -
486.657 -
486.658 -.. method:: __rdiv__(y)
486.659 -
486.660 - x.__rdiv__(y) <==> y/x
486.661 -
486.662 -
486.663 -.. method:: __rdivmod__(y)
486.664 -
486.665 - x.__rdivmod__(y) <==> divmod(y, x)
486.666 -
486.667 -
486.668 -.. method:: __reduce__()
486.669 -
486.670 - helper for pickle
486.671 -
486.672 -
486.673 -.. method:: __reduce_ex__()
486.674 -
486.675 - helper for pickle
486.676 -
486.677 -
486.678 -.. method:: __repr__()
486.679 -
486.680 - x.__repr__() <==> repr(x)
486.681 -
486.682 -
486.683 -.. method:: __rfloordiv__(y)
486.684 -
486.685 - x.__rfloordiv__(y) <==> y//x
486.686 -
486.687 -
486.688 -.. method:: __rlshift__(y)
486.689 -
486.690 - x.__rlshift__(y) <==> y<<x
486.691 -
486.692 -
486.693 -.. method:: __rmod__(y)
486.694 -
486.695 - x.__rmod__(y) <==> y%x
486.696 -
486.697 -
486.698 -.. method:: __rmul__(y)
486.699 -
486.700 - x.__rmul__(y) <==> y*x
486.701 -
486.702 -
486.703 -.. method:: __ror__(y)
486.704 -
486.705 - x.__ror__(y) <==> y|x
486.706 -
486.707 -
486.708 -.. method:: __rpow__(x)
486.709 -
486.710 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
486.711 -
486.712 -
486.713 -.. method:: __rrshift__(y)
486.714 -
486.715 - x.__rrshift__(y) <==> y>>x
486.716 -
486.717 -
486.718 -.. method:: __rsub__(y)
486.719 -
486.720 - x.__rsub__(y) <==> y-x
486.721 -
486.722 -
486.723 -.. method:: __rtruediv__(y)
486.724 -
486.725 - x.__rtruediv__(y) <==> y/x
486.726 -
486.727 -
486.728 -.. method:: __rxor__(y)
486.729 -
486.730 - x.__rxor__(y) <==> y^x
486.731 -
486.732 -
486.733 -.. method:: __setattr__(name, value)
486.734 -
486.735 - x.__setattr__('name', value) <==> x.name = value
486.736 -
486.737 -
486.738 -.. method:: __sizeof__()
486.739 -
486.740 - Returns size in memory, in bytes
486.741 -
486.742 - .. versionadded:: 2.6
486.743 -
486.744 -.. method:: __str__()
486.745 -
486.746 - x.__str__() <==> str(x)
486.747 -
486.748 -
486.749 -.. method:: __subclasshook__()
486.750 -
486.751 - Abstract classes can override this to customize issubclass().
486.752 -
486.753 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
486.754 - It should return True, False or NotImplemented. If it returns
486.755 - NotImplemented, the normal algorithm is used. Otherwise, it
486.756 - overrides the normal algorithm (and the outcome is cached).
486.757 -
486.758 -
486.759 - .. versionadded:: 2.6
486.760 -
486.761 -.. method:: __trunc__()
486.762 -
486.763 - Truncating an Integral returns itself.
486.764 -
486.765 - .. versionadded:: 2.6
486.766 -
486.767 -.. method:: conjugate()
486.768 -
486.769 - Returns self, the complex conjugate of any long.
486.770 -
486.771 - .. versionadded:: 2.6
486.772 -
486.773 -.. attribute:: denominator
486.774 -
486.775 - long(x[, base]) -> integer
486.776 -
486.777 - Convert a string or number to a long integer, if possible. A floating
486.778 - point argument will be truncated towards zero (this does not include a
486.779 - string representation of a floating point number!) When converting a
486.780 - string, use the optional base. It is an error to supply a base when
486.781 - converting a non-string.
486.782 -
486.783 - .. versionadded:: 2.6
486.784 -
486.785 -.. attribute:: imag
486.786 -
486.787 - long(x[, base]) -> integer
486.788 -
486.789 - Convert a string or number to a long integer, if possible. A floating
486.790 - point argument will be truncated towards zero (this does not include a
486.791 - string representation of a floating point number!) When converting a
486.792 - string, use the optional base. It is an error to supply a base when
486.793 - converting a non-string.
486.794 -
486.795 - .. versionadded:: 2.6
486.796 -
486.797 -.. attribute:: numerator
486.798 -
486.799 - long(x[, base]) -> integer
486.800 -
486.801 - Convert a string or number to a long integer, if possible. A floating
486.802 - point argument will be truncated towards zero (this does not include a
486.803 - string representation of a floating point number!) When converting a
486.804 - string, use the optional base. It is an error to supply a base when
486.805 - converting a non-string.
486.806 -
486.807 - .. versionadded:: 2.6
486.808 -
486.809 -.. attribute:: real
486.810 -
486.811 - long(x[, base]) -> integer
486.812 -
486.813 - Convert a string or number to a long integer, if possible. A floating
486.814 - point argument will be truncated towards zero (this does not include a
486.815 - string representation of a floating point number!) When converting a
486.816 - string, use the optional base. It is an error to supply a base when
486.817 - converting a non-string.
486.818 -
486.819 - .. versionadded:: 2.6
486.820 -
486.821 -.. class:: bool
486.822 -
486.823 - bool(x) -> bool
486.824 -
486.825 - Returns True when the argument x is true, False otherwise.
486.826 - The builtins True and False are the only two instances of the class bool.
486.827 - The class bool is a subclass of the class int, and cannot be subclassed.
486.828 -
486.829 -
486.830 -.. method:: __abs__()
486.831 -
486.832 - x.__abs__() <==> abs(x)
486.833 -
486.834 -
486.835 -.. method:: __add__(y)
486.836 -
486.837 - x.__add__(y) <==> x+y
486.838 -
486.839 -
486.840 -.. method:: __and__(y)
486.841 -
486.842 - x.__and__(y) <==> x&y
486.843 -
486.844 -
486.845 -.. attribute:: __class__
486.846 -
486.847 - bool(x) -> bool
486.848 -
486.849 - Returns True when the argument x is true, False otherwise.
486.850 - The builtins True and False are the only two instances of the class bool.
486.851 - The class bool is a subclass of the class int, and cannot be subclassed.
486.852 -
486.853 -
486.854 -.. method:: __cmp__(y)
486.855 -
486.856 - x.__cmp__(y) <==> cmp(x,y)
486.857 -
486.858 -
486.859 -.. method:: __coerce__(y)
486.860 -
486.861 - x.__coerce__(y) <==> coerce(x, y)
486.862 -
486.863 -
486.864 -.. method:: __delattr__(name)
486.865 -
486.866 - x.__delattr__('name') <==> del x.name
486.867 -
486.868 -
486.869 -.. method:: __div__(y)
486.870 -
486.871 - x.__div__(y) <==> x/y
486.872 -
486.873 -
486.874 -.. method:: __divmod__(y)
486.875 -
486.876 - x.__divmod__(y) <==> divmod(x, y)
486.877 -
486.878 -
486.879 -.. attribute:: __doc__
486.880 -
486.881 - str(object) -> string
486.882 -
486.883 - Return a nice string representation of the object.
486.884 - If the argument is a string, the return value is the same object.
486.885 -
486.886 -
486.887 -.. method:: __float__()
486.888 -
486.889 - x.__float__() <==> float(x)
486.890 -
486.891 -
486.892 -.. method:: __floordiv__(y)
486.893 -
486.894 - x.__floordiv__(y) <==> x//y
486.895 -
486.896 -
486.897 -.. method:: __format__()
486.898 -
486.899 - .. versionadded:: 2.6
486.900 -
486.901 -.. method:: __getattribute__(name)
486.902 -
486.903 - x.__getattribute__('name') <==> x.name
486.904 -
486.905 -
486.906 -.. method:: __getnewargs__()
486.907 -
486.908 -
486.909 -.. method:: __hash__()
486.910 -
486.911 - x.__hash__() <==> hash(x)
486.912 -
486.913 -
486.914 -.. method:: __hex__()
486.915 -
486.916 - x.__hex__() <==> hex(x)
486.917 -
486.918 -
486.919 -.. method:: __index__()
486.920 -
486.921 - x[y:z] <==> x[y.__index__():z.__index__()]
486.922 -
486.923 -
486.924 -.. method:: __init__()
486.925 -
486.926 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
486.927 -
486.928 -
486.929 -.. method:: __int__()
486.930 -
486.931 - x.__int__() <==> int(x)
486.932 -
486.933 -
486.934 -.. method:: __invert__()
486.935 -
486.936 - x.__invert__() <==> ~x
486.937 -
486.938 -
486.939 -.. method:: __long__()
486.940 -
486.941 - x.__long__() <==> long(x)
486.942 -
486.943 -
486.944 -.. method:: __lshift__(y)
486.945 -
486.946 - x.__lshift__(y) <==> x<<y
486.947 -
486.948 -
486.949 -.. method:: __mod__(y)
486.950 -
486.951 - x.__mod__(y) <==> x%y
486.952 -
486.953 -
486.954 -.. method:: __mul__(y)
486.955 -
486.956 - x.__mul__(y) <==> x*y
486.957 -
486.958 -
486.959 -.. method:: __neg__()
486.960 -
486.961 - x.__neg__() <==> -x
486.962 -
486.963 -
486.964 -.. method:: __new__(S, ___)
486.965 -
486.966 - T.__new__(S, ...) -> a new object with type S, a subtype of T
486.967 -
486.968 -
486.969 -.. method:: __nonzero__()
486.970 -
486.971 - x.__nonzero__() <==> x != 0
486.972 -
486.973 -
486.974 -.. method:: __oct__()
486.975 -
486.976 - x.__oct__() <==> oct(x)
486.977 -
486.978 -
486.979 -.. method:: __or__(y)
486.980 -
486.981 - x.__or__(y) <==> x|y
486.982 -
486.983 -
486.984 -.. method:: __pos__()
486.985 -
486.986 - x.__pos__() <==> +x
486.987 -
486.988 -
486.989 -.. method:: __pow__(y)
486.990 -
486.991 - x.__pow__(y[, z]) <==> pow(x, y[, z])
486.992 -
486.993 -
486.994 -.. method:: __radd__(y)
486.995 -
486.996 - x.__radd__(y) <==> y+x
486.997 -
486.998 -
486.999 -.. method:: __rand__(y)
486.1000 -
486.1001 - x.__rand__(y) <==> y&x
486.1002 -
486.1003 -
486.1004 -.. method:: __rdiv__(y)
486.1005 -
486.1006 - x.__rdiv__(y) <==> y/x
486.1007 -
486.1008 -
486.1009 -.. method:: __rdivmod__(y)
486.1010 -
486.1011 - x.__rdivmod__(y) <==> divmod(y, x)
486.1012 -
486.1013 -
486.1014 -.. method:: __reduce__()
486.1015 -
486.1016 - helper for pickle
486.1017 -
486.1018 -
486.1019 -.. method:: __reduce_ex__()
486.1020 -
486.1021 - helper for pickle
486.1022 -
486.1023 -
486.1024 -.. method:: __repr__()
486.1025 -
486.1026 - x.__repr__() <==> repr(x)
486.1027 -
486.1028 -
486.1029 -.. method:: __rfloordiv__(y)
486.1030 -
486.1031 - x.__rfloordiv__(y) <==> y//x
486.1032 -
486.1033 -
486.1034 -.. method:: __rlshift__(y)
486.1035 -
486.1036 - x.__rlshift__(y) <==> y<<x
486.1037 -
486.1038 -
486.1039 -.. method:: __rmod__(y)
486.1040 -
486.1041 - x.__rmod__(y) <==> y%x
486.1042 -
486.1043 -
486.1044 -.. method:: __rmul__(y)
486.1045 -
486.1046 - x.__rmul__(y) <==> y*x
486.1047 -
486.1048 -
486.1049 -.. method:: __ror__(y)
486.1050 -
486.1051 - x.__ror__(y) <==> y|x
486.1052 -
486.1053 -
486.1054 -.. method:: __rpow__(x)
486.1055 -
486.1056 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
486.1057 -
486.1058 -
486.1059 -.. method:: __rrshift__(y)
486.1060 -
486.1061 - x.__rrshift__(y) <==> y>>x
486.1062 -
486.1063 -
486.1064 -.. method:: __rshift__(y)
486.1065 -
486.1066 - x.__rshift__(y) <==> x>>y
486.1067 -
486.1068 -
486.1069 -.. method:: __rsub__(y)
486.1070 -
486.1071 - x.__rsub__(y) <==> y-x
486.1072 -
486.1073 -
486.1074 -.. method:: __rtruediv__(y)
486.1075 -
486.1076 - x.__rtruediv__(y) <==> y/x
486.1077 -
486.1078 -
486.1079 -.. method:: __rxor__(y)
486.1080 -
486.1081 - x.__rxor__(y) <==> y^x
486.1082 -
486.1083 -
486.1084 -.. method:: __setattr__(name, value)
486.1085 -
486.1086 - x.__setattr__('name', value) <==> x.name = value
486.1087 -
486.1088 -
486.1089 -.. method:: __sizeof__()
486.1090 -
486.1091 - __sizeof__() -> size of object in memory, in bytes
486.1092 -
486.1093 - .. versionadded:: 2.6
486.1094 -
486.1095 -.. method:: __str__()
486.1096 -
486.1097 - x.__str__() <==> str(x)
486.1098 -
486.1099 -
486.1100 -.. method:: __sub__(y)
486.1101 -
486.1102 - x.__sub__(y) <==> x-y
486.1103 -
486.1104 -
486.1105 -.. method:: __subclasshook__()
486.1106 -
486.1107 - Abstract classes can override this to customize issubclass().
486.1108 -
486.1109 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
486.1110 - It should return True, False or NotImplemented. If it returns
486.1111 - NotImplemented, the normal algorithm is used. Otherwise, it
486.1112 - overrides the normal algorithm (and the outcome is cached).
486.1113 -
486.1114 -
486.1115 - .. versionadded:: 2.6
486.1116 -
486.1117 -.. method:: __truediv__(y)
486.1118 -
486.1119 - x.__truediv__(y) <==> x/y
486.1120 -
486.1121 -
486.1122 -.. method:: __trunc__()
486.1123 -
486.1124 - Truncating an Integral returns itself.
486.1125 -
486.1126 - .. versionadded:: 2.6
486.1127 -
486.1128 -.. method:: __xor__(y)
486.1129 -
486.1130 - x.__xor__(y) <==> x^y
486.1131 -
486.1132 -
486.1133 -.. method:: conjugate()
486.1134 -
486.1135 - Returns self, the complex conjugate of any int.
486.1136 -
486.1137 - .. versionadded:: 2.6
486.1138 -
486.1139 -.. attribute:: denominator
486.1140 -
486.1141 - int(x[, base]) -> integer
486.1142 -
486.1143 - Convert a string or number to an integer, if possible. A floating point
486.1144 - argument will be truncated towards zero (this does not include a string
486.1145 - representation of a floating point number!) When converting a string, use
486.1146 - the optional base. It is an error to supply a base when converting a
486.1147 - non-string. If base is zero, the proper base is guessed based on the
486.1148 - string content. If the argument is outside the integer range a
486.1149 - long object will be returned instead.
486.1150 -
486.1151 - .. versionadded:: 2.6
486.1152 -
486.1153 -.. attribute:: imag
486.1154 -
486.1155 - int(x[, base]) -> integer
486.1156 -
486.1157 - Convert a string or number to an integer, if possible. A floating point
486.1158 - argument will be truncated towards zero (this does not include a string
486.1159 - representation of a floating point number!) When converting a string, use
486.1160 - the optional base. It is an error to supply a base when converting a
486.1161 - non-string. If base is zero, the proper base is guessed based on the
486.1162 - string content. If the argument is outside the integer range a
486.1163 - long object will be returned instead.
486.1164 -
486.1165 - .. versionadded:: 2.6
486.1166 -
486.1167 -.. attribute:: numerator
486.1168 -
486.1169 - int(x[, base]) -> integer
486.1170 -
486.1171 - Convert a string or number to an integer, if possible. A floating point
486.1172 - argument will be truncated towards zero (this does not include a string
486.1173 - representation of a floating point number!) When converting a string, use
486.1174 - the optional base. It is an error to supply a base when converting a
486.1175 - non-string. If base is zero, the proper base is guessed based on the
486.1176 - string content. If the argument is outside the integer range a
486.1177 - long object will be returned instead.
486.1178 -
486.1179 - .. versionadded:: 2.6
486.1180 -
486.1181 -.. attribute:: real
486.1182 -
486.1183 - int(x[, base]) -> integer
486.1184 -
486.1185 - Convert a string or number to an integer, if possible. A floating point
486.1186 - argument will be truncated towards zero (this does not include a string
486.1187 - representation of a floating point number!) When converting a string, use
486.1188 - the optional base. It is an error to supply a base when converting a
486.1189 - non-string. If base is zero, the proper base is guessed based on the
486.1190 - string content. If the argument is outside the integer range a
486.1191 - long object will be returned instead.
486.1192 -
486.1193 - .. versionadded:: 2.6
486.1194 -
486.1195 -.. class:: complex
486.1196 -
486.1197 - complex(real[, imag]) -> complex number
486.1198 -
486.1199 - Create a complex number from a real part and an optional imaginary part.
486.1200 - This is equivalent to (real + imag*1j) where imag defaults to 0.
486.1201 -
486.1202 -
486.1203 -.. attribute:: __class__
486.1204 -
486.1205 - complex(real[, imag]) -> complex number
486.1206 -
486.1207 - Create a complex number from a real part and an optional imaginary part.
486.1208 - This is equivalent to (real + imag*1j) where imag defaults to 0.
486.1209 -
486.1210 -
486.1211 -.. method:: __coerce__(y)
486.1212 -
486.1213 - x.__coerce__(y) <==> coerce(x, y)
486.1214 -
486.1215 -
486.1216 -.. method:: __delattr__(name)
486.1217 -
486.1218 - x.__delattr__('name') <==> del x.name
486.1219 -
486.1220 -
486.1221 -.. method:: __divmod__(y)
486.1222 -
486.1223 - x.__divmod__(y) <==> divmod(x, y)
486.1224 -
486.1225 -
486.1226 -.. attribute:: __doc__
486.1227 -
486.1228 - str(object) -> string
486.1229 -
486.1230 - Return a nice string representation of the object.
486.1231 - If the argument is a string, the return value is the same object.
486.1232 -
486.1233 -
486.1234 -.. method:: __float__()
486.1235 -
486.1236 - x.__float__() <==> float(x)
486.1237 -
486.1238 -
486.1239 -.. method:: __format__()
486.1240 -
486.1241 - default object formatter
486.1242 -
486.1243 - .. versionadded:: 2.6
486.1244 -
486.1245 -.. method:: __getattribute__(name)
486.1246 -
486.1247 - x.__getattribute__('name') <==> x.name
486.1248 -
486.1249 -
486.1250 -.. method:: __getnewargs__()
486.1251 -
486.1252 -
486.1253 -.. method:: __hash__()
486.1254 -
486.1255 - x.__hash__() <==> hash(x)
486.1256 -
486.1257 -
486.1258 -.. method:: __init__()
486.1259 -
486.1260 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
486.1261 -
486.1262 -
486.1263 -.. method:: __int__()
486.1264 -
486.1265 - x.__int__() <==> int(x)
486.1266 -
486.1267 -
486.1268 -.. method:: __long__()
486.1269 -
486.1270 - x.__long__() <==> long(x)
486.1271 -
486.1272 -
486.1273 -.. method:: __new__(S, ___)
486.1274 -
486.1275 - T.__new__(S, ...) -> a new object with type S, a subtype of T
486.1276 -
486.1277 -
486.1278 -.. method:: __nonzero__()
486.1279 -
486.1280 - x.__nonzero__() <==> x != 0
486.1281 -
486.1282 -
486.1283 -.. method:: __radd__(y)
486.1284 -
486.1285 - x.__radd__(y) <==> y+x
486.1286 -
486.1287 -
486.1288 -.. method:: __rdiv__(y)
486.1289 -
486.1290 - x.__rdiv__(y) <==> y/x
486.1291 -
486.1292 -
486.1293 -.. method:: __rdivmod__(y)
486.1294 -
486.1295 - x.__rdivmod__(y) <==> divmod(y, x)
486.1296 -
486.1297 -
486.1298 -.. method:: __reduce__()
486.1299 -
486.1300 - helper for pickle
486.1301 -
486.1302 -
486.1303 -.. method:: __reduce_ex__()
486.1304 -
486.1305 - helper for pickle
486.1306 -
486.1307 -
486.1308 -.. method:: __repr__()
486.1309 -
486.1310 - x.__repr__() <==> repr(x)
486.1311 -
486.1312 -
486.1313 -.. method:: __rfloordiv__(y)
486.1314 -
486.1315 - x.__rfloordiv__(y) <==> y//x
486.1316 -
486.1317 -
486.1318 -.. method:: __rmod__(y)
486.1319 -
486.1320 - x.__rmod__(y) <==> y%x
486.1321 -
486.1322 -
486.1323 -.. method:: __rmul__(y)
486.1324 -
486.1325 - x.__rmul__(y) <==> y*x
486.1326 -
486.1327 -
486.1328 -.. method:: __rpow__(x)
486.1329 -
486.1330 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
486.1331 -
486.1332 -
486.1333 -.. method:: __rsub__(y)
486.1334 -
486.1335 - x.__rsub__(y) <==> y-x
486.1336 -
486.1337 -
486.1338 -.. method:: __rtruediv__(y)
486.1339 -
486.1340 - x.__rtruediv__(y) <==> y/x
486.1341 -
486.1342 -
486.1343 -.. method:: __setattr__(name, value)
486.1344 -
486.1345 - x.__setattr__('name', value) <==> x.name = value
486.1346 -
486.1347 -
486.1348 -.. method:: __sizeof__()
486.1349 -
486.1350 - __sizeof__() -> size of object in memory, in bytes
486.1351 -
486.1352 - .. versionadded:: 2.6
486.1353 -
486.1354 -.. method:: __str__()
486.1355 -
486.1356 - x.__str__() <==> str(x)
486.1357 -
486.1358 -
486.1359 -.. method:: __subclasshook__()
486.1360 -
486.1361 - Abstract classes can override this to customize issubclass().
486.1362 -
486.1363 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
486.1364 - It should return True, False or NotImplemented. If it returns
486.1365 - NotImplemented, the normal algorithm is used. Otherwise, it
486.1366 - overrides the normal algorithm (and the outcome is cached).
486.1367 -
486.1368 -
486.1369 - .. versionadded:: 2.6
486.1370 -
486.1371 -.. method:: conjugate()
486.1372 -
486.1373 - complex.conjugate() -> complex
486.1374 -
486.1375 - Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
486.1376 -
486.1377 -
486.1378 -.. attribute:: imag
486.1379 -
486.1380 - float(x) -> floating point number
486.1381 -
486.1382 - Convert a string or number to a floating point number, if possible.
486.1383 -
486.1384 -
486.1385 -.. attribute:: real
486.1386 -
486.1387 - float(x) -> floating point number
486.1388 -
486.1389 - Convert a string or number to a floating point number, if possible.
486.1390 -
486.1391 -
486.1392 -.. class:: list
486.1393 -
486.1394 - list() -> new list
486.1395 - list(sequence) -> new list initialized from sequence's items
486.1396 -
486.1397 -
486.1398 -.. attribute:: __class__
486.1399 -
486.1400 - list() -> new list
486.1401 - list(sequence) -> new list initialized from sequence's items
486.1402 -
486.1403 -
486.1404 -.. method:: __delattr__(name)
486.1405 -
486.1406 - x.__delattr__('name') <==> del x.name
486.1407 -
486.1408 -
486.1409 -.. attribute:: __doc__
486.1410 -
486.1411 - str(object) -> string
486.1412 -
486.1413 - Return a nice string representation of the object.
486.1414 - If the argument is a string, the return value is the same object.
486.1415 -
486.1416 -
486.1417 -.. method:: __format__()
486.1418 -
486.1419 - default object formatter
486.1420 -
486.1421 - .. versionadded:: 2.6
486.1422 -
486.1423 -.. method:: __getattribute__(name)
486.1424 -
486.1425 - x.__getattribute__('name') <==> x.name
486.1426 -
486.1427 -
486.1428 -.. attribute:: __hash__
486.1429 -
486.1430 -
486.1431 -.. method:: __init__()
486.1432 -
486.1433 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
486.1434 -
486.1435 -
486.1436 -.. method:: __iter__()
486.1437 -
486.1438 - x.__iter__() <==> iter(x)
486.1439 -
486.1440 -
486.1441 -.. method:: __len__()
486.1442 -
486.1443 - x.__len__() <==> len(x)
486.1444 -
486.1445 -
486.1446 -.. method:: __new__(S, ___)
486.1447 -
486.1448 - T.__new__(S, ...) -> a new object with type S, a subtype of T
486.1449 -
486.1450 -
486.1451 -.. method:: __reduce__()
486.1452 -
486.1453 - helper for pickle
486.1454 -
486.1455 -
486.1456 -.. method:: __reduce_ex__()
486.1457 -
486.1458 - helper for pickle
486.1459 -
486.1460 -
486.1461 -.. method:: __repr__()
486.1462 -
486.1463 - x.__repr__() <==> repr(x)
486.1464 -
486.1465 -
486.1466 -.. method:: __reversed__()
486.1467 -
486.1468 - L.__reversed__() -- return a reverse iterator over the list
486.1469 -
486.1470 -
486.1471 -.. method:: __rmul__(n)
486.1472 -
486.1473 - x.__rmul__(n) <==> n*x
486.1474 -
486.1475 -
486.1476 -.. method:: __setattr__(name, value)
486.1477 -
486.1478 - x.__setattr__('name', value) <==> x.name = value
486.1479 -
486.1480 -
486.1481 -.. method:: __sizeof__()
486.1482 -
486.1483 - L.__sizeof__() -- size of L in memory, in bytes
486.1484 -
486.1485 - .. versionadded:: 2.6
486.1486 -
486.1487 -.. method:: __str__()
486.1488 -
486.1489 - x.__str__() <==> str(x)
486.1490 -
486.1491 -
486.1492 -.. method:: __subclasshook__()
486.1493 -
486.1494 - Abstract classes can override this to customize issubclass().
486.1495 -
486.1496 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
486.1497 - It should return True, False or NotImplemented. If it returns
486.1498 - NotImplemented, the normal algorithm is used. Otherwise, it
486.1499 - overrides the normal algorithm (and the outcome is cached).
486.1500 -
486.1501 -
486.1502 - .. versionadded:: 2.6
486.1503 -
486.1504 -.. method:: append()
486.1505 -
486.1506 - L.append(object) -- append object to end
486.1507 -
486.1508 -
486.1509 -.. method:: count(value)
486.1510 -
486.1511 - L.count(value) -> integer -- return number of occurrences of value
486.1512 -
486.1513 -
486.1514 -.. method:: extend()
486.1515 -
486.1516 - L.extend(iterable) -- extend list by appending elements from the iterable
486.1517 -
486.1518 -
486.1519 -.. method:: insert()
486.1520 -
486.1521 - L.insert(index, object) -- insert object before index
486.1522 -
486.1523 -
486.1524 -.. method:: pop()
486.1525 -
486.1526 - L.pop([index]) -> item -- remove and return item at index (default last)
486.1527 -
486.1528 -
486.1529 -.. method:: remove()
486.1530 -
486.1531 - L.remove(value) -- remove first occurrence of value
486.1532 -
486.1533 -
486.1534 -.. method:: reverse()
486.1535 -
486.1536 - L.reverse() -- reverse *IN PLACE*
486.1537 -
486.1538 -
486.1539 -.. method:: sort(cmp=None, key=None, reverse=False) __ stable sort *IN PLACE*;
486.1540 -cmp(x, y)
486.1541 -
486.1542 - L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
486.1543 - cmp(x, y) -> -1, 0, 1
486.1544 -
486.1545 -
486.1546 -.. class:: dict
486.1547 -
486.1548 - dict() -> new empty dictionary.
486.1549 - dict(mapping) -> new dictionary initialized from a mapping object's
486.1550 - (key, value) pairs.
486.1551 - dict(seq) -> new dictionary initialized as if via:
486.1552 - d = {}
486.1553 - for k, v in seq:
486.1554 - d[k] = v
486.1555 - dict(**kwargs) -> new dictionary initialized with the name=value pairs
486.1556 - in the keyword argument list. For example: dict(one=1, two=2)
486.1557 -
486.1558 -
486.1559 -.. attribute:: __class__
486.1560 -
486.1561 - dict() -> new empty dictionary.
486.1562 - dict(mapping) -> new dictionary initialized from a mapping object's
486.1563 - (key, value) pairs.
486.1564 - dict(seq) -> new dictionary initialized as if via:
486.1565 - d = {}
486.1566 - for k, v in seq:
486.1567 - d[k] = v
486.1568 - dict(**kwargs) -> new dictionary initialized with the name=value pairs
486.1569 - in the keyword argument list. For example: dict(one=1, two=2)
486.1570 -
486.1571 -
486.1572 -.. method:: __cmp__(y)
486.1573 -
486.1574 - x.__cmp__(y) <==> cmp(x,y)
486.1575 -
486.1576 -
486.1577 -.. method:: __delattr__(name)
486.1578 -
486.1579 - x.__delattr__('name') <==> del x.name
486.1580 -
486.1581 -
486.1582 -.. attribute:: __doc__
486.1583 -
486.1584 - str(object) -> string
486.1585 -
486.1586 - Return a nice string representation of the object.
486.1587 - If the argument is a string, the return value is the same object.
486.1588 -
486.1589 -
486.1590 -.. method:: __format__()
486.1591 -
486.1592 - default object formatter
486.1593 -
486.1594 - .. versionadded:: 2.6
486.1595 -
486.1596 -.. method:: __getattribute__(name)
486.1597 -
486.1598 - x.__getattribute__('name') <==> x.name
486.1599 -
486.1600 -
486.1601 -.. attribute:: __hash__
486.1602 -
486.1603 -
486.1604 -.. method:: __iter__()
486.1605 -
486.1606 - x.__iter__() <==> iter(x)
486.1607 -
486.1608 -
486.1609 -.. method:: __len__()
486.1610 -
486.1611 - x.__len__() <==> len(x)
486.1612 -
486.1613 -
486.1614 -.. method:: __new__(S, ___)
486.1615 -
486.1616 - T.__new__(S, ...) -> a new object with type S, a subtype of T
486.1617 -
486.1618 -
486.1619 -.. method:: __reduce__()
486.1620 -
486.1621 - helper for pickle
486.1622 -
486.1623 -
486.1624 -.. method:: __reduce_ex__()
486.1625 -
486.1626 - helper for pickle
486.1627 -
486.1628 -
486.1629 -.. method:: __repr__()
486.1630 -
486.1631 - x.__repr__() <==> repr(x)
486.1632 -
486.1633 -
486.1634 -.. method:: __setattr__(name, value)
486.1635 -
486.1636 - x.__setattr__('name', value) <==> x.name = value
486.1637 -
486.1638 -
486.1639 -.. method:: __sizeof__()
486.1640 -
486.1641 - D.__sizeof__() -> size of D in memory, in bytes
486.1642 -
486.1643 - .. versionadded:: 2.6
486.1644 -
486.1645 -.. method:: __str__()
486.1646 -
486.1647 - x.__str__() <==> str(x)
486.1648 -
486.1649 -
486.1650 -.. method:: __subclasshook__()
486.1651 -
486.1652 - Abstract classes can override this to customize issubclass().
486.1653 -
486.1654 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
486.1655 - It should return True, False or NotImplemented. If it returns
486.1656 - NotImplemented, the normal algorithm is used. Otherwise, it
486.1657 - overrides the normal algorithm (and the outcome is cached).
486.1658 -
486.1659 -
486.1660 - .. versionadded:: 2.6
486.1661 -
486.1662 -.. class:: tuple
486.1663 -
486.1664 - tuple() -> an empty tuple
486.1665 - tuple(sequence) -> tuple initialized from sequence's items
486.1666 -
486.1667 - If the argument is a tuple, the return value is the same object.
486.1668 -
486.1669 -
486.1670 -.. attribute:: __class__
486.1671 -
486.1672 - tuple() -> an empty tuple
486.1673 - tuple(sequence) -> tuple initialized from sequence's items
486.1674 -
486.1675 - If the argument is a tuple, the return value is the same object.
486.1676 -
486.1677 -
486.1678 -.. method:: __delattr__(name)
486.1679 -
486.1680 - x.__delattr__('name') <==> del x.name
486.1681 -
486.1682 -
486.1683 -.. attribute:: __doc__
486.1684 -
486.1685 - str(object) -> string
486.1686 -
486.1687 - Return a nice string representation of the object.
486.1688 - If the argument is a string, the return value is the same object.
486.1689 -
486.1690 -
486.1691 -.. method:: __format__()
486.1692 -
486.1693 - default object formatter
486.1694 -
486.1695 - .. versionadded:: 2.6
486.1696 -
486.1697 -.. method:: __getattribute__(name)
486.1698 -
486.1699 - x.__getattribute__('name') <==> x.name
486.1700 -
486.1701 -
486.1702 -.. method:: __getnewargs__()
486.1703 -
486.1704 -
486.1705 -.. method:: __hash__()
486.1706 -
486.1707 - x.__hash__() <==> hash(x)
486.1708 -
486.1709 -
486.1710 -.. method:: __init__()
486.1711 -
486.1712 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
486.1713 -
486.1714 -
486.1715 -.. method:: __iter__()
486.1716 -
486.1717 - x.__iter__() <==> iter(x)
486.1718 -
486.1719 -
486.1720 -.. method:: __len__()
486.1721 -
486.1722 - x.__len__() <==> len(x)
486.1723 -
486.1724 -
486.1725 -.. method:: __new__(S, ___)
486.1726 -
486.1727 - T.__new__(S, ...) -> a new object with type S, a subtype of T
486.1728 -
486.1729 -
486.1730 -.. method:: __reduce__()
486.1731 -
486.1732 - helper for pickle
486.1733 -
486.1734 -
486.1735 -.. method:: __reduce_ex__()
486.1736 -
486.1737 - helper for pickle
486.1738 -
486.1739 -
486.1740 -.. method:: __repr__()
486.1741 -
486.1742 - x.__repr__() <==> repr(x)
486.1743 -
486.1744 -
486.1745 -.. method:: __rmul__(n)
486.1746 -
486.1747 - x.__rmul__(n) <==> n*x
486.1748 -
486.1749 -
486.1750 -.. method:: __setattr__(name, value)
486.1751 -
486.1752 - x.__setattr__('name', value) <==> x.name = value
486.1753 -
486.1754 -
486.1755 -.. method:: __sizeof__()
486.1756 -
486.1757 - T.__sizeof__() -- size of T in memory, in bytes
486.1758 -
486.1759 - .. versionadded:: 2.6
486.1760 -
486.1761 -.. method:: __str__()
486.1762 -
486.1763 - x.__str__() <==> str(x)
486.1764 -
486.1765 -
486.1766 -.. method:: __subclasshook__()
486.1767 -
486.1768 - Abstract classes can override this to customize issubclass().
486.1769 -
486.1770 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
486.1771 - It should return True, False or NotImplemented. If it returns
486.1772 - NotImplemented, the normal algorithm is used. Otherwise, it
486.1773 - overrides the normal algorithm (and the outcome is cached).
486.1774 -
486.1775 -
486.1776 - .. versionadded:: 2.6
486.1777 -
486.1778 -.. method:: count(value)
486.1779 -
486.1780 - T.count(value) -> integer -- return number of occurrences of value
486.1781 -
486.1782 - .. versionadded:: 2.6
486.1783 -
486.1784 -.. class:: str
486.1785 -
486.1786 - str(object) -> string
486.1787 -
486.1788 - Return a nice string representation of the object.
486.1789 - If the argument is a string, the return value is the same object.
486.1790 -
486.1791 -
486.1792 -.. attribute:: __class__
486.1793 -
486.1794 - str(object) -> string
486.1795 -
486.1796 - Return a nice string representation of the object.
486.1797 - If the argument is a string, the return value is the same object.
486.1798 -
486.1799 -
486.1800 -.. method:: __delattr__(name)
486.1801 -
486.1802 - x.__delattr__('name') <==> del x.name
486.1803 -
486.1804 -
486.1805 -.. attribute:: __doc__
486.1806 -
486.1807 - str(object) -> string
486.1808 -
486.1809 - Return a nice string representation of the object.
486.1810 - If the argument is a string, the return value is the same object.
486.1811 -
486.1812 -
486.1813 -.. method:: __format__(format_spec)
486.1814 -
486.1815 - S.__format__(format_spec) -> unicode
486.1816 -
486.1817 -
486.1818 -
486.1819 - .. versionadded:: 2.6
486.1820 -
486.1821 -.. method:: __getattribute__(name)
486.1822 -
486.1823 - x.__getattribute__('name') <==> x.name
486.1824 -
486.1825 -
486.1826 -.. method:: __getnewargs__()
486.1827 -
486.1828 -
486.1829 -.. method:: __hash__()
486.1830 -
486.1831 - x.__hash__() <==> hash(x)
486.1832 -
486.1833 -
486.1834 -.. method:: __init__()
486.1835 -
486.1836 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
486.1837 -
486.1838 -
486.1839 -.. method:: __len__()
486.1840 -
486.1841 - x.__len__() <==> len(x)
486.1842 -
486.1843 -
486.1844 -.. method:: __new__(S, ___)
486.1845 -
486.1846 - T.__new__(S, ...) -> a new object with type S, a subtype of T
486.1847 -
486.1848 -
486.1849 -.. method:: __reduce__()
486.1850 -
486.1851 - helper for pickle
486.1852 -
486.1853 -
486.1854 -.. method:: __reduce_ex__()
486.1855 -
486.1856 - helper for pickle
486.1857 -
486.1858 -
486.1859 -.. method:: __repr__()
486.1860 -
486.1861 - x.__repr__() <==> repr(x)
486.1862 -
486.1863 -
486.1864 -.. method:: __rmod__(y)
486.1865 -
486.1866 - x.__rmod__(y) <==> y%x
486.1867 -
486.1868 -
486.1869 -.. method:: __rmul__(n)
486.1870 -
486.1871 - x.__rmul__(n) <==> n*x
486.1872 -
486.1873 -
486.1874 -.. method:: __setattr__(name, value)
486.1875 -
486.1876 - x.__setattr__('name', value) <==> x.name = value
486.1877 -
486.1878 -
486.1879 -.. method:: __sizeof__()
486.1880 -
486.1881 - S.__sizeof__() -> size of S in memory, in bytes
486.1882 -
486.1883 - .. versionadded:: 2.6
486.1884 -
486.1885 -.. method:: __str__()
486.1886 -
486.1887 - x.__str__() <==> str(x)
486.1888 -
486.1889 -
486.1890 -.. method:: __subclasshook__()
486.1891 -
486.1892 - Abstract classes can override this to customize issubclass().
486.1893 -
486.1894 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
486.1895 - It should return True, False or NotImplemented. If it returns
486.1896 - NotImplemented, the normal algorithm is used. Otherwise, it
486.1897 - overrides the normal algorithm (and the outcome is cached).
486.1898 -
486.1899 -
486.1900 - .. versionadded:: 2.6
486.1901 -
486.1902 -.. method:: _formatter_field_name_split()
486.1903 -
486.1904 - .. versionadded:: 2.6
486.1905 -
486.1906 -.. method:: _formatter_parser()
486.1907 -
486.1908 - .. versionadded:: 2.6
486.1909 -
486.1910 -.. class:: unicode
486.1911 -
486.1912 - unicode(string [, encoding[, errors]]) -> object
486.1913 -
486.1914 - Create a new Unicode object from the given encoded string.
486.1915 - encoding defaults to the current default string encoding.
486.1916 - errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.
486.1917 -
486.1918 -
486.1919 -.. attribute:: __class__
486.1920 -
486.1921 - unicode(string [, encoding[, errors]]) -> object
486.1922 -
486.1923 - Create a new Unicode object from the given encoded string.
486.1924 - encoding defaults to the current default string encoding.
486.1925 - errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.
486.1926 -
486.1927 -
486.1928 -.. method:: __delattr__(name)
486.1929 -
486.1930 - x.__delattr__('name') <==> del x.name
486.1931 -
486.1932 -
486.1933 -.. attribute:: __doc__
486.1934 -
486.1935 - str(object) -> string
486.1936 -
486.1937 - Return a nice string representation of the object.
486.1938 - If the argument is a string, the return value is the same object.
486.1939 -
486.1940 -
486.1941 -.. method:: __format__(format_spec)
486.1942 -
486.1943 - S.__format__(format_spec) -> unicode
486.1944 -
486.1945 -
486.1946 -
486.1947 - .. versionadded:: 2.6
486.1948 -
486.1949 -.. method:: __getattribute__(name)
486.1950 -
486.1951 - x.__getattribute__('name') <==> x.name
486.1952 -
486.1953 -
486.1954 -.. method:: __getnewargs__()
486.1955 -
486.1956 -
486.1957 -.. method:: __hash__()
486.1958 -
486.1959 - x.__hash__() <==> hash(x)
486.1960 -
486.1961 -
486.1962 -.. method:: __init__()
486.1963 -
486.1964 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
486.1965 -
486.1966 -
486.1967 -.. method:: __len__()
486.1968 -
486.1969 - x.__len__() <==> len(x)
486.1970 -
486.1971 -
486.1972 -.. method:: __new__(S, ___)
486.1973 -
486.1974 - T.__new__(S, ...) -> a new object with type S, a subtype of T
486.1975 -
486.1976 -
486.1977 -.. method:: __reduce__()
486.1978 -
486.1979 - helper for pickle
486.1980 -
486.1981 -
486.1982 -.. method:: __reduce_ex__()
486.1983 -
486.1984 - helper for pickle
486.1985 -
486.1986 -
486.1987 -.. method:: __repr__()
486.1988 -
486.1989 - x.__repr__() <==> repr(x)
486.1990 -
486.1991 -
486.1992 -.. method:: __rmod__(y)
486.1993 -
486.1994 - x.__rmod__(y) <==> y%x
486.1995 -
486.1996 -
486.1997 -.. method:: __rmul__(n)
486.1998 -
486.1999 - x.__rmul__(n) <==> n*x
486.2000 -
486.2001 -
486.2002 -.. method:: __setattr__(name, value)
486.2003 -
486.2004 - x.__setattr__('name', value) <==> x.name = value
486.2005 -
486.2006 -
486.2007 -.. method:: __sizeof__()
486.2008 -
486.2009 - S.__sizeof__() -> size of S in memory, in bytes
486.2010 -
486.2011 -
486.2012 -
486.2013 - .. versionadded:: 2.6
486.2014 -
486.2015 -.. method:: __str__()
486.2016 -
486.2017 - x.__str__() <==> str(x)
486.2018 -
486.2019 -
486.2020 -.. method:: __subclasshook__()
486.2021 -
486.2022 - Abstract classes can override this to customize issubclass().
486.2023 -
486.2024 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
486.2025 - It should return True, False or NotImplemented. If it returns
486.2026 - NotImplemented, the normal algorithm is used. Otherwise, it
486.2027 - overrides the normal algorithm (and the outcome is cached).
486.2028 -
486.2029 -
486.2030 - .. versionadded:: 2.6
486.2031 -
486.2032 -.. method:: _formatter_field_name_split()
486.2033 -
486.2034 - .. versionadded:: 2.6
486.2035 -
486.2036 -.. method:: _formatter_parser()
486.2037 -
486.2038 - .. versionadded:: 2.6
486.2039 -
486.2040 -.. method:: capitalize()
486.2041 -
486.2042 - S.capitalize() -> unicode
486.2043 -
486.2044 - Return a capitalized version of S, i.e. make the first character
486.2045 - have upper case.
486.2046 -
486.2047 -
486.2048 -.. method:: center(width)
486.2049 -
486.2050 - S.center(width[, fillchar]) -> unicode
486.2051 -
486.2052 - Return S centered in a Unicode string of length width. Padding is
486.2053 - done using the specified fill character (default is a space)
486.2054 -
486.2055 -
486.2056 -.. method:: count(sub)
486.2057 -
486.2058 - S.count(sub[, start[, end]]) -> int
486.2059 -
486.2060 - Return the number of non-overlapping occurrences of substring sub in
486.2061 - Unicode string S[start:end]. Optional arguments start and end are
486.2062 - interpreted as in slice notation.
486.2063 -
486.2064 -
486.2065 -.. method:: decode()
486.2066 -
486.2067 - S.decode([encoding[,errors]]) -> string or unicode
486.2068 -
486.2069 - Decodes S using the codec registered for encoding. encoding defaults
486.2070 - to the default encoding. errors may be given to set a different error
486.2071 - handling scheme. Default is 'strict' meaning that encoding errors raise
486.2072 - a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
486.2073 - as well as any other name registerd with codecs.register_error that is
486.2074 - able to handle UnicodeDecodeErrors.
486.2075 -
486.2076 -
486.2077 -.. method:: encode()
486.2078 -
486.2079 - S.encode([encoding[,errors]]) -> string or unicode
486.2080 -
486.2081 - Encodes S using the codec registered for encoding. encoding defaults
486.2082 - to the default encoding. errors may be given to set a different error
486.2083 - handling scheme. Default is 'strict' meaning that encoding errors raise
486.2084 - a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
486.2085 - 'xmlcharrefreplace' as well as any other name registered with
486.2086 - codecs.register_error that can handle UnicodeEncodeErrors.
486.2087 -
486.2088 -
486.2089 -.. method:: endswith(suffix)
486.2090 -
486.2091 - S.endswith(suffix[, start[, end]]) -> bool
486.2092 -
486.2093 - Return True if S ends with the specified suffix, False otherwise.
486.2094 - With optional start, test S beginning at that position.
486.2095 - With optional end, stop comparing S at that position.
486.2096 - suffix can also be a tuple of strings to try.
486.2097 -
486.2098 -
486.2099 -.. method:: expandtabs()
486.2100 -
486.2101 - S.expandtabs([tabsize]) -> unicode
486.2102 -
486.2103 - Return a copy of S where all tab characters are expanded using spaces.
486.2104 - If tabsize is not given, a tab size of 8 characters is assumed.
486.2105 -
486.2106 -
486.2107 -.. method:: find(sub )
486.2108 -
486.2109 - S.find(sub [,start [,end]]) -> int
486.2110 -
486.2111 - Return the lowest index in S where substring sub is found,
486.2112 - such that sub is contained within s[start:end]. Optional
486.2113 - arguments start and end are interpreted as in slice notation.
486.2114 -
486.2115 - Return -1 on failure.
486.2116 -
486.2117 -
486.2118 -.. method:: format(*args, **kwargs)
486.2119 -
486.2120 - S.format(*args, **kwargs) -> unicode
486.2121 -
486.2122 -
486.2123 -
486.2124 - .. versionadded:: 2.6
486.2125 -
486.2126 -.. method:: isalnum()
486.2127 -
486.2128 - S.isalnum() -> bool
486.2129 -
486.2130 - Return True if all characters in S are alphanumeric
486.2131 - and there is at least one character in S, False otherwise.
486.2132 -
486.2133 -
486.2134 -.. method:: isalpha()
486.2135 -
486.2136 - S.isalpha() -> bool
486.2137 -
486.2138 - Return True if all characters in S are alphabetic
486.2139 - and there is at least one character in S, False otherwise.
486.2140 -
486.2141 -
486.2142 -.. method:: isdigit()
486.2143 -
486.2144 - S.isdigit() -> bool
486.2145 -
486.2146 - Return True if all characters in S are digits
486.2147 - and there is at least one character in S, False otherwise.
486.2148 -
486.2149 -
486.2150 -.. method:: islower()
486.2151 -
486.2152 - S.islower() -> bool
486.2153 -
486.2154 - Return True if all cased characters in S are lowercase and there is
486.2155 - at least one cased character in S, False otherwise.
486.2156 -
486.2157 -
486.2158 -.. method:: isspace()
486.2159 -
486.2160 - S.isspace() -> bool
486.2161 -
486.2162 - Return True if all characters in S are whitespace
486.2163 - and there is at least one character in S, False otherwise.
486.2164 -
486.2165 -
486.2166 -.. method:: istitle()
486.2167 -
486.2168 - S.istitle() -> bool
486.2169 -
486.2170 - Return True if S is a titlecased string and there is at least one
486.2171 - character in S, i.e. upper- and titlecase characters may only
486.2172 - follow uncased characters and lowercase characters only cased ones.
486.2173 - Return False otherwise.
486.2174 -
486.2175 -
486.2176 -.. method:: isupper()
486.2177 -
486.2178 - S.isupper() -> bool
486.2179 -
486.2180 - Return True if all cased characters in S are uppercase and there is
486.2181 - at least one cased character in S, False otherwise.
486.2182 -
486.2183 -
486.2184 -.. method:: join(sequence)
486.2185 -
486.2186 - S.join(sequence) -> unicode
486.2187 -
486.2188 - Return a string which is the concatenation of the strings in the
486.2189 - sequence. The separator between elements is S.
486.2190 -
486.2191 -
486.2192 -.. method:: ljust(width)
486.2193 -
486.2194 - S.ljust(width[, fillchar]) -> int
486.2195 -
486.2196 - Return S left justified in a Unicode string of length width. Padding is
486.2197 - done using the specified fill character (default is a space).
486.2198 -
486.2199 -
486.2200 -.. method:: lower()
486.2201 -
486.2202 - S.lower() -> unicode
486.2203 -
486.2204 - Return a copy of the string S converted to lowercase.
486.2205 -
486.2206 -
486.2207 -.. method:: lstrip()
486.2208 -
486.2209 - S.lstrip([chars]) -> unicode
486.2210 -
486.2211 - Return a copy of the string S with leading whitespace removed.
486.2212 - If chars is given and not None, remove characters in chars instead.
486.2213 - If chars is a str, it will be converted to unicode before stripping
486.2214 -
486.2215 -
486.2216 -.. method:: partition(sep)
486.2217 -
486.2218 - S.partition(sep) -> (head, sep, tail)
486.2219 -
486.2220 - Searches for the separator sep in S, and returns the part before it,
486.2221 - the separator itself, and the part after it. If the separator is not
486.2222 - found, returns S and two empty strings.
486.2223 -
486.2224 -
486.2225 -.. method:: replace(old, new)
486.2226 -
486.2227 - S.replace (old, new[, count]) -> unicode
486.2228 -
486.2229 - Return a copy of S with all occurrences of substring
486.2230 - old replaced by new. If the optional argument count is
486.2231 - given, only the first count occurrences are replaced.
486.2232 -
486.2233 -
486.2234 -.. method:: rfind(sub )
486.2235 -
486.2236 - S.rfind(sub [,start [,end]]) -> int
486.2237 -
486.2238 - Return the highest index in S where substring sub is found,
486.2239 - such that sub is contained within s[start:end]. Optional
486.2240 - arguments start and end are interpreted as in slice notation.
486.2241 -
486.2242 - Return -1 on failure.
486.2243 -
486.2244 -
486.2245 -.. method:: rindex(sub )
486.2246 -
486.2247 - S.rindex(sub [,start [,end]]) -> int
486.2248 -
486.2249 - Like S.rfind() but raise ValueError when the substring is not found.
486.2250 -
486.2251 -
486.2252 -.. method:: rjust(width)
486.2253 -
486.2254 - S.rjust(width[, fillchar]) -> unicode
486.2255 -
486.2256 - Return S right justified in a Unicode string of length width. Padding is
486.2257 - done using the specified fill character (default is a space).
486.2258 -
486.2259 -
486.2260 -.. method:: rpartition(sep)
486.2261 -
486.2262 - S.rpartition(sep) -> (tail, sep, head)
486.2263 -
486.2264 - Searches for the separator sep in S, starting at the end of S, and returns
486.2265 - the part before it, the separator itself, and the part after it. If the
486.2266 - separator is not found, returns two empty strings and S.
486.2267 -
486.2268 -
486.2269 -.. method:: rsplit()
486.2270 -
486.2271 - S.rsplit([sep [,maxsplit]]) -> list of strings
486.2272 -
486.2273 - Return a list of the words in S, using sep as the
486.2274 - delimiter string, starting at the end of the string and
486.2275 - working to the front. If maxsplit is given, at most maxsplit
486.2276 - splits are done. If sep is not specified, any whitespace string
486.2277 - is a separator.
486.2278 -
486.2279 -
486.2280 -.. method:: rstrip()
486.2281 -
486.2282 - S.rstrip([chars]) -> unicode
486.2283 -
486.2284 - Return a copy of the string S with trailing whitespace removed.
486.2285 - If chars is given and not None, remove characters in chars instead.
486.2286 - If chars is a str, it will be converted to unicode before stripping
486.2287 -
486.2288 -
486.2289 -.. method:: split()
486.2290 -
486.2291 - S.split([sep [,maxsplit]]) -> list of strings
486.2292 -
486.2293 - Return a list of the words in S, using sep as the
486.2294 - delimiter string. If maxsplit is given, at most maxsplit
486.2295 - splits are done. If sep is not specified or is None, any
486.2296 - whitespace string is a separator and empty strings are
486.2297 - removed from the result.
486.2298 -
486.2299 -
486.2300 -.. method:: splitlines()
486.2301 -
486.2302 - S.splitlines([keepends]]) -> list of strings
486.2303 -
486.2304 - Return a list of the lines in S, breaking at line boundaries.
486.2305 - Line breaks are not included in the resulting list unless keepends
486.2306 - is given and true.
486.2307 -
486.2308 -
486.2309 -.. method:: startswith(prefix)
486.2310 -
486.2311 - S.startswith(prefix[, start[, end]]) -> bool
486.2312 -
486.2313 - Return True if S starts with the specified prefix, False otherwise.
486.2314 - With optional start, test S beginning at that position.
486.2315 - With optional end, stop comparing S at that position.
486.2316 - prefix can also be a tuple of strings to try.
486.2317 -
486.2318 -
486.2319 -.. method:: strip()
486.2320 -
486.2321 - S.strip([chars]) -> unicode
486.2322 -
486.2323 - Return a copy of the string S with leading and trailing
486.2324 - whitespace removed.
486.2325 - If chars is given and not None, remove characters in chars instead.
486.2326 - If chars is a str, it will be converted to unicode before stripping
486.2327 -
486.2328 -
486.2329 -.. method:: swapcase()
486.2330 -
486.2331 - S.swapcase() -> unicode
486.2332 -
486.2333 - Return a copy of S with uppercase characters converted to lowercase
486.2334 - and vice versa.
486.2335 -
486.2336 -
486.2337 -.. method:: title()
486.2338 -
486.2339 - S.title() -> unicode
486.2340 -
486.2341 - Return a titlecased version of S, i.e. words start with title case
486.2342 - characters, all remaining cased characters have lower case.
486.2343 -
486.2344 -
486.2345 -.. method:: translate(table)
486.2346 -
486.2347 - S.translate(table) -> unicode
486.2348 -
486.2349 - Return a copy of the string S, where all characters have been mapped
486.2350 - through the given translation table, which must be a mapping of
486.2351 - Unicode ordinals to Unicode ordinals, Unicode strings or None.
486.2352 - Unmapped characters are left untouched. Characters mapped to None
486.2353 - are deleted.
486.2354 -
486.2355 -
486.2356 -.. method:: upper()
486.2357 -
486.2358 - S.upper() -> unicode
486.2359 -
486.2360 - Return a copy of S converted to uppercase.
486.2361 -
486.2362 -
486.2363 -.. method:: zfill(width)
486.2364 -
486.2365 - S.zfill(width) -> unicode
486.2366 -
486.2367 - Pad a numeric string S with zeros on the left, to fill a field
486.2368 - of the specified width. The string S is never truncated.
486.2369 -
486.2370 -
487.1 --- a/python.editor/test/unit/data/testfiles/rst/stub_missing.rst.html Sun Jan 04 13:11:53 2015 -0600
487.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
487.3 @@ -1,2638 +0,0 @@
487.4 -<html><body>
487.5 -NetBeans extra documentation:
487.6 -Documentation for APIs missing from the RST documentation shipping with Python.
487.7 -This is generated from introspecting python code using extract_rst.py.
487.8 -Python version stats:
487.9 -2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04)
487.10 -[GCC 4.0.1 (Apple Computer, Inc. build 5370)]
487.11 -
487.12 -<br><br>
487.13 -<a href="class:int">int</a>
487.14 -
487.15 -<br><br>
487.16 - int(x[, base]) -> integer
487.17 -
487.18 -<br><br>
487.19 - Convert a string or number to an integer, if possible. A floating point
487.20 - argument will be truncated towards zero (this does not include a string
487.21 - representation of a floating point number!) When converting a string, use
487.22 - the optional base. It is an error to supply a base when converting a
487.23 - non-string. If base is zero, the proper base is guessed based on the
487.24 - string content. If the argument is outside the integer range a
487.25 - long object will be returned instead.
487.26 -
487.27 -<br><br>
487.28 -<a href="attr:__class__">__class__</a>
487.29 -
487.30 -<br><br>
487.31 - int(x[, base]) -> integer
487.32 -
487.33 -<br><br>
487.34 - Convert a string or number to an integer, if possible. A floating point
487.35 - argument will be truncated towards zero (this does not include a string
487.36 - representation of a floating point number!) When converting a string, use
487.37 - the optional base. It is an error to supply a base when converting a
487.38 - non-string. If base is zero, the proper base is guessed based on the
487.39 - string content. If the argument is outside the integer range a
487.40 - long object will be returned instead.
487.41 -
487.42 -<br><br>
487.43 -<a href="meth:__cmp__(y)">__cmp__(y)</a>
487.44 -
487.45 -<br><br>
487.46 - x.__cmp__(y) <==> cmp(x,y)
487.47 -
487.48 -<br><br>
487.49 -<a href="meth:__coerce__(y)">__coerce__(y)</a>
487.50 -
487.51 -<br><br>
487.52 - x.__coerce__(y) <==> coerce(x, y)
487.53 -
487.54 -<br><br>
487.55 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
487.56 -
487.57 -<br><br>
487.58 - x.__delattr__('name') <==> del x.name
487.59 -
487.60 -<br><br>
487.61 -<a href="meth:__divmod__(y)">__divmod__(y)</a>
487.62 -
487.63 -<br><br>
487.64 - x.__divmod__(y) <==> divmod(x, y)
487.65 -
487.66 -<br><br>
487.67 -<a href="attr:__doc__">__doc__</a>
487.68 -
487.69 -<br><br>
487.70 - str(object) -> string
487.71 -
487.72 -<br><br>
487.73 - Return a nice string representation of the object.
487.74 - If the argument is a string, the return value is the same object.
487.75 -
487.76 -<br><br>
487.77 -<a href="meth:__float__()">__float__()</a>
487.78 -
487.79 -<br><br>
487.80 - x.__float__() <==> float(x)
487.81 -
487.82 -<br><br>
487.83 -<a href="meth:__format__()">__format__()</a>
487.84 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.85 -</div>
487.86 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
487.87 - x.__getattribute__('name') <==> x.name
487.88 -
487.89 -<br><br>
487.90 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
487.91 -
487.92 -<br><br>
487.93 -<a href="meth:__hash__()">__hash__()</a>
487.94 -
487.95 -<br><br>
487.96 - x.__hash__() <==> hash(x)
487.97 -
487.98 -<br><br>
487.99 -<a href="meth:__hex__()">__hex__()</a>
487.100 -
487.101 -<br><br>
487.102 - x.__hex__() <==> hex(x)
487.103 -
487.104 -<br><br>
487.105 -<a href="meth:__init__()">__init__()</a>
487.106 -
487.107 -<br><br>
487.108 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
487.109 -
487.110 -<br><br>
487.111 -<a href="meth:__int__()">__int__()</a>
487.112 -
487.113 -<br><br>
487.114 - x.__int__() <==> int(x)
487.115 -
487.116 -<br><br>
487.117 -<a href="meth:__long__()">__long__()</a>
487.118 -
487.119 -<br><br>
487.120 - x.__long__() <==> long(x)
487.121 -
487.122 -<br><br>
487.123 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
487.124 -
487.125 -<br><br>
487.126 - T.__new__(S, ...) -> a new object with type S, a subtype of T
487.127 -
487.128 -<br><br>
487.129 -<a href="meth:__nonzero__()">__nonzero__()</a>
487.130 -
487.131 -<br><br>
487.132 - x.__nonzero__() <==> x != 0
487.133 -
487.134 -<br><br>
487.135 -<a href="meth:__oct__()">__oct__()</a>
487.136 -
487.137 -<br><br>
487.138 - x.__oct__() <==> oct(x)
487.139 -
487.140 -<br><br>
487.141 -<a href="meth:__radd__(y)">__radd__(y)</a>
487.142 -
487.143 -<br><br>
487.144 - x.__radd__(y) <==> y+x
487.145 -
487.146 -<br><br>
487.147 -<a href="meth:__rand__(y)">__rand__(y)</a>
487.148 -
487.149 -<br><br>
487.150 - x.__rand__(y) <==> y&x
487.151 -
487.152 -<br><br>
487.153 -<a href="meth:__rdiv__(y)">__rdiv__(y)</a>
487.154 -
487.155 -<br><br>
487.156 - x.__rdiv__(y) <==> y/x
487.157 -
487.158 -<br><br>
487.159 -<a href="meth:__rdivmod__(y)">__rdivmod__(y)</a>
487.160 -
487.161 -<br><br>
487.162 - x.__rdivmod__(y) <==> divmod(y, x)
487.163 -
487.164 -<br><br>
487.165 -<a href="meth:__reduce__()">__reduce__()</a>
487.166 -
487.167 -<br><br>
487.168 - helper for pickle
487.169 -
487.170 -<br><br>
487.171 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
487.172 -
487.173 -<br><br>
487.174 - helper for pickle
487.175 -
487.176 -<br><br>
487.177 -<a href="meth:__repr__()">__repr__()</a>
487.178 -
487.179 -<br><br>
487.180 - x.__repr__() <==> repr(x)
487.181 -
487.182 -<br><br>
487.183 -<a href="meth:__rfloordiv__(y)">__rfloordiv__(y)</a>
487.184 -
487.185 -<br><br>
487.186 - x.__rfloordiv__(y) <==> y//x
487.187 -
487.188 -<br><br>
487.189 -<a href="meth:__rlshift__(y)">__rlshift__(y)</a>
487.190 -
487.191 -<br><br>
487.192 - x.__rlshift__(y) <==> y<<x
487.193 -
487.194 -<br><br>
487.195 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
487.196 -
487.197 -<br><br>
487.198 - x.__rmod__(y) <==> y%x
487.199 -
487.200 -<br><br>
487.201 -<a href="meth:__rmul__(y)">__rmul__(y)</a>
487.202 -
487.203 -<br><br>
487.204 - x.__rmul__(y) <==> y*x
487.205 -
487.206 -<br><br>
487.207 -<a href="meth:__ror__(y)">__ror__(y)</a>
487.208 -
487.209 -<br><br>
487.210 - x.__ror__(y) <==> y|x
487.211 -
487.212 -<br><br>
487.213 -<a href="meth:__rpow__(x)">__rpow__(x)</a>
487.214 -
487.215 -<br><br>
487.216 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
487.217 -
487.218 -<br><br>
487.219 -<a href="meth:__rrshift__(y)">__rrshift__(y)</a>
487.220 -
487.221 -<br><br>
487.222 - x.__rrshift__(y) <==> y>>x
487.223 -
487.224 -<br><br>
487.225 -<a href="meth:__rsub__(y)">__rsub__(y)</a>
487.226 -
487.227 -<br><br>
487.228 - x.__rsub__(y) <==> y-x
487.229 -
487.230 -<br><br>
487.231 -<a href="meth:__rtruediv__(y)">__rtruediv__(y)</a>
487.232 -
487.233 -<br><br>
487.234 - x.__rtruediv__(y) <==> y/x
487.235 -
487.236 -<br><br>
487.237 -<a href="meth:__rxor__(y)">__rxor__(y)</a>
487.238 -
487.239 -<br><br>
487.240 - x.__rxor__(y) <==> y^x
487.241 -
487.242 -<br><br>
487.243 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
487.244 -
487.245 -<br><br>
487.246 - x.__setattr__('name', value) <==> x.name = value
487.247 -
487.248 -<br><br>
487.249 -<a href="meth:__sizeof__()">__sizeof__()</a>
487.250 -
487.251 -<br><br>
487.252 - __sizeof__() -> size of object in memory, in bytes
487.253 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.254 -</div>
487.255 -<a href="meth:__str__()">__str__()</a>
487.256 - x.__str__() <==> str(x)
487.257 -
487.258 -<br><br>
487.259 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
487.260 -
487.261 -<br><br>
487.262 - Abstract classes can override this to customize issubclass().
487.263 -
487.264 -<br><br>
487.265 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
487.266 - It should return True, False or NotImplemented. If it returns
487.267 - NotImplemented, the normal algorithm is used. Otherwise, it
487.268 - overrides the normal algorithm (and the outcome is cached).
487.269 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.270 -</div>
487.271 -<a href="meth:__trunc__()">__trunc__()</a>
487.272 - Truncating an Integral returns itself.
487.273 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.274 -</div>
487.275 -<a href="meth:conjugate()">conjugate()</a>
487.276 - Returns self, the complex conjugate of any int.
487.277 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.278 -</div>
487.279 -<a href="attr:denominator">denominator</a>
487.280 - int(x[, base]) -> integer
487.281 -
487.282 -<br><br>
487.283 - Convert a string or number to an integer, if possible. A floating point
487.284 - argument will be truncated towards zero (this does not include a string
487.285 - representation of a floating point number!) When converting a string, use
487.286 - the optional base. It is an error to supply a base when converting a
487.287 - non-string. If base is zero, the proper base is guessed based on the
487.288 - string content. If the argument is outside the integer range a
487.289 - long object will be returned instead.
487.290 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.291 -</div>
487.292 -<a href="attr:imag">imag</a>
487.293 - int(x[, base]) -> integer
487.294 -
487.295 -<br><br>
487.296 - Convert a string or number to an integer, if possible. A floating point
487.297 - argument will be truncated towards zero (this does not include a string
487.298 - representation of a floating point number!) When converting a string, use
487.299 - the optional base. It is an error to supply a base when converting a
487.300 - non-string. If base is zero, the proper base is guessed based on the
487.301 - string content. If the argument is outside the integer range a
487.302 - long object will be returned instead.
487.303 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.304 -</div>
487.305 -<a href="attr:numerator">numerator</a>
487.306 - int(x[, base]) -> integer
487.307 -
487.308 -<br><br>
487.309 - Convert a string or number to an integer, if possible. A floating point
487.310 - argument will be truncated towards zero (this does not include a string
487.311 - representation of a floating point number!) When converting a string, use
487.312 - the optional base. It is an error to supply a base when converting a
487.313 - non-string. If base is zero, the proper base is guessed based on the
487.314 - string content. If the argument is outside the integer range a
487.315 - long object will be returned instead.
487.316 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.317 -</div>
487.318 -<a href="attr:real">real</a>
487.319 - int(x[, base]) -> integer
487.320 -
487.321 -<br><br>
487.322 - Convert a string or number to an integer, if possible. A floating point
487.323 - argument will be truncated towards zero (this does not include a string
487.324 - representation of a floating point number!) When converting a string, use
487.325 - the optional base. It is an error to supply a base when converting a
487.326 - non-string. If base is zero, the proper base is guessed based on the
487.327 - string content. If the argument is outside the integer range a
487.328 - long object will be returned instead.
487.329 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.330 -</div>
487.331 -<a href="class:float">float</a>
487.332 - float(x) -> floating point number
487.333 -
487.334 -<br><br>
487.335 - Convert a string or number to a floating point number, if possible.
487.336 -
487.337 -<br><br>
487.338 -<a href="attr:__class__">__class__</a>
487.339 -
487.340 -<br><br>
487.341 - float(x) -> floating point number
487.342 -
487.343 -<br><br>
487.344 - Convert a string or number to a floating point number, if possible.
487.345 -
487.346 -<br><br>
487.347 -<a href="meth:__coerce__(y)">__coerce__(y)</a>
487.348 -
487.349 -<br><br>
487.350 - x.__coerce__(y) <==> coerce(x, y)
487.351 -
487.352 -<br><br>
487.353 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
487.354 -
487.355 -<br><br>
487.356 - x.__delattr__('name') <==> del x.name
487.357 -
487.358 -<br><br>
487.359 -<a href="meth:__divmod__(y)">__divmod__(y)</a>
487.360 -
487.361 -<br><br>
487.362 - x.__divmod__(y) <==> divmod(x, y)
487.363 -
487.364 -<br><br>
487.365 -<a href="attr:__doc__">__doc__</a>
487.366 -
487.367 -<br><br>
487.368 - str(object) -> string
487.369 -
487.370 -<br><br>
487.371 - Return a nice string representation of the object.
487.372 - If the argument is a string, the return value is the same object.
487.373 -
487.374 -<br><br>
487.375 -<a href="meth:__float__()">__float__()</a>
487.376 -
487.377 -<br><br>
487.378 - x.__float__() <==> float(x)
487.379 -
487.380 -<br><br>
487.381 -<a href="meth:__format__(format_spec)">__format__(format_spec)</a>
487.382 -
487.383 -<br><br>
487.384 - float.__format__(format_spec) -> string
487.385 -
487.386 -<br><br>
487.387 - Formats the float according to format_spec.
487.388 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.389 -</div>
487.390 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
487.391 - x.__getattribute__('name') <==> x.name
487.392 -
487.393 -<br><br>
487.394 -<a href="meth:__getformat__(typestr)">__getformat__(typestr)</a>
487.395 -
487.396 -<br><br>
487.397 - float.__getformat__(typestr) -> string
487.398 -
487.399 -<br><br>
487.400 - You probably don't want to use this function. It exists mainly to be
487.401 - used in Python's test suite.
487.402 -
487.403 -<br><br>
487.404 - typestr must be 'double' or 'float'. This function returns whichever of
487.405 - 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the
487.406 - format of floating point numbers used by the C type named by typestr.
487.407 -
487.408 -<br><br>
487.409 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
487.410 -
487.411 -<br><br>
487.412 -<a href="meth:__hash__()">__hash__()</a>
487.413 -
487.414 -<br><br>
487.415 - x.__hash__() <==> hash(x)
487.416 -
487.417 -<br><br>
487.418 -<a href="meth:__init__()">__init__()</a>
487.419 -
487.420 -<br><br>
487.421 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
487.422 -
487.423 -<br><br>
487.424 -<a href="meth:__int__()">__int__()</a>
487.425 -
487.426 -<br><br>
487.427 - x.__int__() <==> int(x)
487.428 -
487.429 -<br><br>
487.430 -<a href="meth:__long__()">__long__()</a>
487.431 -
487.432 -<br><br>
487.433 - x.__long__() <==> long(x)
487.434 -
487.435 -<br><br>
487.436 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
487.437 -
487.438 -<br><br>
487.439 - T.__new__(S, ...) -> a new object with type S, a subtype of T
487.440 -
487.441 -<br><br>
487.442 -<a href="meth:__nonzero__()">__nonzero__()</a>
487.443 -
487.444 -<br><br>
487.445 - x.__nonzero__() <==> x != 0
487.446 -
487.447 -<br><br>
487.448 -<a href="meth:__radd__(y)">__radd__(y)</a>
487.449 -
487.450 -<br><br>
487.451 - x.__radd__(y) <==> y+x
487.452 -
487.453 -<br><br>
487.454 -<a href="meth:__rdiv__(y)">__rdiv__(y)</a>
487.455 -
487.456 -<br><br>
487.457 - x.__rdiv__(y) <==> y/x
487.458 -
487.459 -<br><br>
487.460 -<a href="meth:__rdivmod__(y)">__rdivmod__(y)</a>
487.461 -
487.462 -<br><br>
487.463 - x.__rdivmod__(y) <==> divmod(y, x)
487.464 -
487.465 -<br><br>
487.466 -<a href="meth:__reduce__()">__reduce__()</a>
487.467 -
487.468 -<br><br>
487.469 - helper for pickle
487.470 -
487.471 -<br><br>
487.472 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
487.473 -
487.474 -<br><br>
487.475 - helper for pickle
487.476 -
487.477 -<br><br>
487.478 -<a href="meth:__repr__()">__repr__()</a>
487.479 -
487.480 -<br><br>
487.481 - x.__repr__() <==> repr(x)
487.482 -
487.483 -<br><br>
487.484 -<a href="meth:__rfloordiv__(y)">__rfloordiv__(y)</a>
487.485 -
487.486 -<br><br>
487.487 - x.__rfloordiv__(y) <==> y//x
487.488 -
487.489 -<br><br>
487.490 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
487.491 -
487.492 -<br><br>
487.493 - x.__rmod__(y) <==> y%x
487.494 -
487.495 -<br><br>
487.496 -<a href="meth:__rmul__(y)">__rmul__(y)</a>
487.497 -
487.498 -<br><br>
487.499 - x.__rmul__(y) <==> y*x
487.500 -
487.501 -<br><br>
487.502 -<a href="meth:__rpow__(x)">__rpow__(x)</a>
487.503 -
487.504 -<br><br>
487.505 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
487.506 -
487.507 -<br><br>
487.508 -<a href="meth:__rsub__(y)">__rsub__(y)</a>
487.509 -
487.510 -<br><br>
487.511 - x.__rsub__(y) <==> y-x
487.512 -
487.513 -<br><br>
487.514 -<a href="meth:__rtruediv__(y)">__rtruediv__(y)</a>
487.515 -
487.516 -<br><br>
487.517 - x.__rtruediv__(y) <==> y/x
487.518 -
487.519 -<br><br>
487.520 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
487.521 -
487.522 -<br><br>
487.523 - x.__setattr__('name', value) <==> x.name = value
487.524 -
487.525 -<br><br>
487.526 -<a href="meth:__setformat__(typestr, fmt)">__setformat__(typestr, fmt)</a>
487.527 -
487.528 -<br><br>
487.529 - float.__setformat__(typestr, fmt) -> None
487.530 -
487.531 -<br><br>
487.532 - You probably don't want to use this function. It exists mainly to be
487.533 - used in Python's test suite.
487.534 -
487.535 -<br><br>
487.536 - typestr must be 'double' or 'float'. fmt must be one of 'unknown',
487.537 - 'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be
487.538 - one of the latter two if it appears to match the underlying C reality.
487.539 -
487.540 -<br><br>
487.541 - Overrides the automatic determination of C-level floating point type.
487.542 - This affects how floats are converted to and from binary strings.
487.543 -
487.544 -<br><br>
487.545 -<a href="meth:__sizeof__()">__sizeof__()</a>
487.546 -
487.547 -<br><br>
487.548 - __sizeof__() -> size of object in memory, in bytes
487.549 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.550 -</div>
487.551 -<a href="meth:__str__()">__str__()</a>
487.552 - x.__str__() <==> str(x)
487.553 -
487.554 -<br><br>
487.555 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
487.556 -
487.557 -<br><br>
487.558 - Abstract classes can override this to customize issubclass().
487.559 -
487.560 -<br><br>
487.561 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
487.562 - It should return True, False or NotImplemented. If it returns
487.563 - NotImplemented, the normal algorithm is used. Otherwise, it
487.564 - overrides the normal algorithm (and the outcome is cached).
487.565 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.566 -</div>
487.567 -<a href="meth:__trunc__()">__trunc__()</a>
487.568 - Returns the Integral closest to x between 0 and x.
487.569 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.570 -</div>
487.571 -<a href="meth:conjugate()">conjugate()</a>
487.572 - Returns self, the complex conjugate of any float.
487.573 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.574 -</div>
487.575 -<a href="attr:imag">imag</a>
487.576 - float(x) -> floating point number
487.577 -
487.578 -<br><br>
487.579 - Convert a string or number to a floating point number, if possible.
487.580 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.581 -</div>
487.582 -<a href="meth:is_integer()">is_integer()</a>
487.583 - Returns True if the float is an integer.
487.584 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.585 -</div>
487.586 -<a href="attr:real">real</a>
487.587 - float(x) -> floating point number
487.588 -
487.589 -<br><br>
487.590 - Convert a string or number to a floating point number, if possible.
487.591 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.592 -</div>
487.593 -<a href="class:long">long</a>
487.594 - long(x[, base]) -> integer
487.595 -
487.596 -<br><br>
487.597 - Convert a string or number to a long integer, if possible. A floating
487.598 - point argument will be truncated towards zero (this does not include a
487.599 - string representation of a floating point number!) When converting a
487.600 - string, use the optional base. It is an error to supply a base when
487.601 - converting a non-string.
487.602 -
487.603 -<br><br>
487.604 -<a href="attr:__class__">__class__</a>
487.605 -
487.606 -<br><br>
487.607 - long(x[, base]) -> integer
487.608 -
487.609 -<br><br>
487.610 - Convert a string or number to a long integer, if possible. A floating
487.611 - point argument will be truncated towards zero (this does not include a
487.612 - string representation of a floating point number!) When converting a
487.613 - string, use the optional base. It is an error to supply a base when
487.614 - converting a non-string.
487.615 -
487.616 -<br><br>
487.617 -<a href="meth:__cmp__(y)">__cmp__(y)</a>
487.618 -
487.619 -<br><br>
487.620 - x.__cmp__(y) <==> cmp(x,y)
487.621 -
487.622 -<br><br>
487.623 -<a href="meth:__coerce__(y)">__coerce__(y)</a>
487.624 -
487.625 -<br><br>
487.626 - x.__coerce__(y) <==> coerce(x, y)
487.627 -
487.628 -<br><br>
487.629 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
487.630 -
487.631 -<br><br>
487.632 - x.__delattr__('name') <==> del x.name
487.633 -
487.634 -<br><br>
487.635 -<a href="meth:__divmod__(y)">__divmod__(y)</a>
487.636 -
487.637 -<br><br>
487.638 - x.__divmod__(y) <==> divmod(x, y)
487.639 -
487.640 -<br><br>
487.641 -<a href="attr:__doc__">__doc__</a>
487.642 -
487.643 -<br><br>
487.644 - str(object) -> string
487.645 -
487.646 -<br><br>
487.647 - Return a nice string representation of the object.
487.648 - If the argument is a string, the return value is the same object.
487.649 -
487.650 -<br><br>
487.651 -<a href="meth:__float__()">__float__()</a>
487.652 -
487.653 -<br><br>
487.654 - x.__float__() <==> float(x)
487.655 -
487.656 -<br><br>
487.657 -<a href="meth:__format__()">__format__()</a>
487.658 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.659 -</div>
487.660 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
487.661 - x.__getattribute__('name') <==> x.name
487.662 -
487.663 -<br><br>
487.664 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
487.665 -
487.666 -<br><br>
487.667 -<a href="meth:__hash__()">__hash__()</a>
487.668 -
487.669 -<br><br>
487.670 - x.__hash__() <==> hash(x)
487.671 -
487.672 -<br><br>
487.673 -<a href="meth:__hex__()">__hex__()</a>
487.674 -
487.675 -<br><br>
487.676 - x.__hex__() <==> hex(x)
487.677 -
487.678 -<br><br>
487.679 -<a href="meth:__init__()">__init__()</a>
487.680 -
487.681 -<br><br>
487.682 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
487.683 -
487.684 -<br><br>
487.685 -<a href="meth:__int__()">__int__()</a>
487.686 -
487.687 -<br><br>
487.688 - x.__int__() <==> int(x)
487.689 -
487.690 -<br><br>
487.691 -<a href="meth:__long__()">__long__()</a>
487.692 -
487.693 -<br><br>
487.694 - x.__long__() <==> long(x)
487.695 -
487.696 -<br><br>
487.697 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
487.698 -
487.699 -<br><br>
487.700 - T.__new__(S, ...) -> a new object with type S, a subtype of T
487.701 -
487.702 -<br><br>
487.703 -<a href="meth:__nonzero__()">__nonzero__()</a>
487.704 -
487.705 -<br><br>
487.706 - x.__nonzero__() <==> x != 0
487.707 -
487.708 -<br><br>
487.709 -<a href="meth:__oct__()">__oct__()</a>
487.710 -
487.711 -<br><br>
487.712 - x.__oct__() <==> oct(x)
487.713 -
487.714 -<br><br>
487.715 -<a href="meth:__radd__(y)">__radd__(y)</a>
487.716 -
487.717 -<br><br>
487.718 - x.__radd__(y) <==> y+x
487.719 -
487.720 -<br><br>
487.721 -<a href="meth:__rand__(y)">__rand__(y)</a>
487.722 -
487.723 -<br><br>
487.724 - x.__rand__(y) <==> y&x
487.725 -
487.726 -<br><br>
487.727 -<a href="meth:__rdiv__(y)">__rdiv__(y)</a>
487.728 -
487.729 -<br><br>
487.730 - x.__rdiv__(y) <==> y/x
487.731 -
487.732 -<br><br>
487.733 -<a href="meth:__rdivmod__(y)">__rdivmod__(y)</a>
487.734 -
487.735 -<br><br>
487.736 - x.__rdivmod__(y) <==> divmod(y, x)
487.737 -
487.738 -<br><br>
487.739 -<a href="meth:__reduce__()">__reduce__()</a>
487.740 -
487.741 -<br><br>
487.742 - helper for pickle
487.743 -
487.744 -<br><br>
487.745 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
487.746 -
487.747 -<br><br>
487.748 - helper for pickle
487.749 -
487.750 -<br><br>
487.751 -<a href="meth:__repr__()">__repr__()</a>
487.752 -
487.753 -<br><br>
487.754 - x.__repr__() <==> repr(x)
487.755 -
487.756 -<br><br>
487.757 -<a href="meth:__rfloordiv__(y)">__rfloordiv__(y)</a>
487.758 -
487.759 -<br><br>
487.760 - x.__rfloordiv__(y) <==> y//x
487.761 -
487.762 -<br><br>
487.763 -<a href="meth:__rlshift__(y)">__rlshift__(y)</a>
487.764 -
487.765 -<br><br>
487.766 - x.__rlshift__(y) <==> y<<x
487.767 -
487.768 -<br><br>
487.769 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
487.770 -
487.771 -<br><br>
487.772 - x.__rmod__(y) <==> y%x
487.773 -
487.774 -<br><br>
487.775 -<a href="meth:__rmul__(y)">__rmul__(y)</a>
487.776 -
487.777 -<br><br>
487.778 - x.__rmul__(y) <==> y*x
487.779 -
487.780 -<br><br>
487.781 -<a href="meth:__ror__(y)">__ror__(y)</a>
487.782 -
487.783 -<br><br>
487.784 - x.__ror__(y) <==> y|x
487.785 -
487.786 -<br><br>
487.787 -<a href="meth:__rpow__(x)">__rpow__(x)</a>
487.788 -
487.789 -<br><br>
487.790 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
487.791 -
487.792 -<br><br>
487.793 -<a href="meth:__rrshift__(y)">__rrshift__(y)</a>
487.794 -
487.795 -<br><br>
487.796 - x.__rrshift__(y) <==> y>>x
487.797 -
487.798 -<br><br>
487.799 -<a href="meth:__rsub__(y)">__rsub__(y)</a>
487.800 -
487.801 -<br><br>
487.802 - x.__rsub__(y) <==> y-x
487.803 -
487.804 -<br><br>
487.805 -<a href="meth:__rtruediv__(y)">__rtruediv__(y)</a>
487.806 -
487.807 -<br><br>
487.808 - x.__rtruediv__(y) <==> y/x
487.809 -
487.810 -<br><br>
487.811 -<a href="meth:__rxor__(y)">__rxor__(y)</a>
487.812 -
487.813 -<br><br>
487.814 - x.__rxor__(y) <==> y^x
487.815 -
487.816 -<br><br>
487.817 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
487.818 -
487.819 -<br><br>
487.820 - x.__setattr__('name', value) <==> x.name = value
487.821 -
487.822 -<br><br>
487.823 -<a href="meth:__sizeof__()">__sizeof__()</a>
487.824 -
487.825 -<br><br>
487.826 - Returns size in memory, in bytes
487.827 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.828 -</div>
487.829 -<a href="meth:__str__()">__str__()</a>
487.830 - x.__str__() <==> str(x)
487.831 -
487.832 -<br><br>
487.833 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
487.834 -
487.835 -<br><br>
487.836 - Abstract classes can override this to customize issubclass().
487.837 -
487.838 -<br><br>
487.839 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
487.840 - It should return True, False or NotImplemented. If it returns
487.841 - NotImplemented, the normal algorithm is used. Otherwise, it
487.842 - overrides the normal algorithm (and the outcome is cached).
487.843 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.844 -</div>
487.845 -<a href="meth:__trunc__()">__trunc__()</a>
487.846 - Truncating an Integral returns itself.
487.847 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.848 -</div>
487.849 -<a href="meth:conjugate()">conjugate()</a>
487.850 - Returns self, the complex conjugate of any long.
487.851 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.852 -</div>
487.853 -<a href="attr:denominator">denominator</a>
487.854 - long(x[, base]) -> integer
487.855 -
487.856 -<br><br>
487.857 - Convert a string or number to a long integer, if possible. A floating
487.858 - point argument will be truncated towards zero (this does not include a
487.859 - string representation of a floating point number!) When converting a
487.860 - string, use the optional base. It is an error to supply a base when
487.861 - converting a non-string.
487.862 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.863 -</div>
487.864 -<a href="attr:imag">imag</a>
487.865 - long(x[, base]) -> integer
487.866 -
487.867 -<br><br>
487.868 - Convert a string or number to a long integer, if possible. A floating
487.869 - point argument will be truncated towards zero (this does not include a
487.870 - string representation of a floating point number!) When converting a
487.871 - string, use the optional base. It is an error to supply a base when
487.872 - converting a non-string.
487.873 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.874 -</div>
487.875 -<a href="attr:numerator">numerator</a>
487.876 - long(x[, base]) -> integer
487.877 -
487.878 -<br><br>
487.879 - Convert a string or number to a long integer, if possible. A floating
487.880 - point argument will be truncated towards zero (this does not include a
487.881 - string representation of a floating point number!) When converting a
487.882 - string, use the optional base. It is an error to supply a base when
487.883 - converting a non-string.
487.884 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.885 -</div>
487.886 -<a href="attr:real">real</a>
487.887 - long(x[, base]) -> integer
487.888 -
487.889 -<br><br>
487.890 - Convert a string or number to a long integer, if possible. A floating
487.891 - point argument will be truncated towards zero (this does not include a
487.892 - string representation of a floating point number!) When converting a
487.893 - string, use the optional base. It is an error to supply a base when
487.894 - converting a non-string.
487.895 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.896 -</div>
487.897 -<a href="class:bool">bool</a>
487.898 - bool(x) -> bool
487.899 -
487.900 -<br><br>
487.901 - Returns True when the argument x is true, False otherwise.
487.902 - The builtins True and False are the only two instances of the class bool.
487.903 - The class bool is a subclass of the class int, and cannot be subclassed.
487.904 -
487.905 -<br><br>
487.906 -<a href="meth:__abs__()">__abs__()</a>
487.907 -
487.908 -<br><br>
487.909 - x.__abs__() <==> abs(x)
487.910 -
487.911 -<br><br>
487.912 -<a href="meth:__add__(y)">__add__(y)</a>
487.913 -
487.914 -<br><br>
487.915 - x.__add__(y) <==> x+y
487.916 -
487.917 -<br><br>
487.918 -<a href="meth:__and__(y)">__and__(y)</a>
487.919 -
487.920 -<br><br>
487.921 - x.__and__(y) <==> x&y
487.922 -
487.923 -<br><br>
487.924 -<a href="attr:__class__">__class__</a>
487.925 -
487.926 -<br><br>
487.927 - bool(x) -> bool
487.928 -
487.929 -<br><br>
487.930 - Returns True when the argument x is true, False otherwise.
487.931 - The builtins True and False are the only two instances of the class bool.
487.932 - The class bool is a subclass of the class int, and cannot be subclassed.
487.933 -
487.934 -<br><br>
487.935 -<a href="meth:__cmp__(y)">__cmp__(y)</a>
487.936 -
487.937 -<br><br>
487.938 - x.__cmp__(y) <==> cmp(x,y)
487.939 -
487.940 -<br><br>
487.941 -<a href="meth:__coerce__(y)">__coerce__(y)</a>
487.942 -
487.943 -<br><br>
487.944 - x.__coerce__(y) <==> coerce(x, y)
487.945 -
487.946 -<br><br>
487.947 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
487.948 -
487.949 -<br><br>
487.950 - x.__delattr__('name') <==> del x.name
487.951 -
487.952 -<br><br>
487.953 -<a href="meth:__div__(y)">__div__(y)</a>
487.954 -
487.955 -<br><br>
487.956 - x.__div__(y) <==> x/y
487.957 -
487.958 -<br><br>
487.959 -<a href="meth:__divmod__(y)">__divmod__(y)</a>
487.960 -
487.961 -<br><br>
487.962 - x.__divmod__(y) <==> divmod(x, y)
487.963 -
487.964 -<br><br>
487.965 -<a href="attr:__doc__">__doc__</a>
487.966 -
487.967 -<br><br>
487.968 - str(object) -> string
487.969 -
487.970 -<br><br>
487.971 - Return a nice string representation of the object.
487.972 - If the argument is a string, the return value is the same object.
487.973 -
487.974 -<br><br>
487.975 -<a href="meth:__float__()">__float__()</a>
487.976 -
487.977 -<br><br>
487.978 - x.__float__() <==> float(x)
487.979 -
487.980 -<br><br>
487.981 -<a href="meth:__floordiv__(y)">__floordiv__(y)</a>
487.982 -
487.983 -<br><br>
487.984 - x.__floordiv__(y) <==> x//y
487.985 -
487.986 -<br><br>
487.987 -<a href="meth:__format__()">__format__()</a>
487.988 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.989 -</div>
487.990 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
487.991 - x.__getattribute__('name') <==> x.name
487.992 -
487.993 -<br><br>
487.994 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
487.995 -
487.996 -<br><br>
487.997 -<a href="meth:__hash__()">__hash__()</a>
487.998 -
487.999 -<br><br>
487.1000 - x.__hash__() <==> hash(x)
487.1001 -
487.1002 -<br><br>
487.1003 -<a href="meth:__hex__()">__hex__()</a>
487.1004 -
487.1005 -<br><br>
487.1006 - x.__hex__() <==> hex(x)
487.1007 -
487.1008 -<br><br>
487.1009 -<a href="meth:__index__()">__index__()</a>
487.1010 -
487.1011 -<br><br>
487.1012 - x[y:z] <==> x[y.__index__():z.__index__()]
487.1013 -
487.1014 -<br><br>
487.1015 -<a href="meth:__init__()">__init__()</a>
487.1016 -
487.1017 -<br><br>
487.1018 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
487.1019 -
487.1020 -<br><br>
487.1021 -<a href="meth:__int__()">__int__()</a>
487.1022 -
487.1023 -<br><br>
487.1024 - x.__int__() <==> int(x)
487.1025 -
487.1026 -<br><br>
487.1027 -<a href="meth:__invert__()">__invert__()</a>
487.1028 -
487.1029 -<br><br>
487.1030 - x.__invert__() <==> ~x
487.1031 -
487.1032 -<br><br>
487.1033 -<a href="meth:__long__()">__long__()</a>
487.1034 -
487.1035 -<br><br>
487.1036 - x.__long__() <==> long(x)
487.1037 -
487.1038 -<br><br>
487.1039 -<a href="meth:__lshift__(y)">__lshift__(y)</a>
487.1040 -
487.1041 -<br><br>
487.1042 - x.__lshift__(y) <==> x<<y
487.1043 -
487.1044 -<br><br>
487.1045 -<a href="meth:__mod__(y)">__mod__(y)</a>
487.1046 -
487.1047 -<br><br>
487.1048 - x.__mod__(y) <==> x%y
487.1049 -
487.1050 -<br><br>
487.1051 -<a href="meth:__mul__(y)">__mul__(y)</a>
487.1052 -
487.1053 -<br><br>
487.1054 - x.__mul__(y) <==> x*y
487.1055 -
487.1056 -<br><br>
487.1057 -<a href="meth:__neg__()">__neg__()</a>
487.1058 -
487.1059 -<br><br>
487.1060 - x.__neg__() <==> -x
487.1061 -
487.1062 -<br><br>
487.1063 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
487.1064 -
487.1065 -<br><br>
487.1066 - T.__new__(S, ...) -> a new object with type S, a subtype of T
487.1067 -
487.1068 -<br><br>
487.1069 -<a href="meth:__nonzero__()">__nonzero__()</a>
487.1070 -
487.1071 -<br><br>
487.1072 - x.__nonzero__() <==> x != 0
487.1073 -
487.1074 -<br><br>
487.1075 -<a href="meth:__oct__()">__oct__()</a>
487.1076 -
487.1077 -<br><br>
487.1078 - x.__oct__() <==> oct(x)
487.1079 -
487.1080 -<br><br>
487.1081 -<a href="meth:__or__(y)">__or__(y)</a>
487.1082 -
487.1083 -<br><br>
487.1084 - x.__or__(y) <==> x|y
487.1085 -
487.1086 -<br><br>
487.1087 -<a href="meth:__pos__()">__pos__()</a>
487.1088 -
487.1089 -<br><br>
487.1090 - x.__pos__() <==> +x
487.1091 -
487.1092 -<br><br>
487.1093 -<a href="meth:__pow__(y)">__pow__(y)</a>
487.1094 -
487.1095 -<br><br>
487.1096 - x.__pow__(y[, z]) <==> pow(x, y[, z])
487.1097 -
487.1098 -<br><br>
487.1099 -<a href="meth:__radd__(y)">__radd__(y)</a>
487.1100 -
487.1101 -<br><br>
487.1102 - x.__radd__(y) <==> y+x
487.1103 -
487.1104 -<br><br>
487.1105 -<a href="meth:__rand__(y)">__rand__(y)</a>
487.1106 -
487.1107 -<br><br>
487.1108 - x.__rand__(y) <==> y&x
487.1109 -
487.1110 -<br><br>
487.1111 -<a href="meth:__rdiv__(y)">__rdiv__(y)</a>
487.1112 -
487.1113 -<br><br>
487.1114 - x.__rdiv__(y) <==> y/x
487.1115 -
487.1116 -<br><br>
487.1117 -<a href="meth:__rdivmod__(y)">__rdivmod__(y)</a>
487.1118 -
487.1119 -<br><br>
487.1120 - x.__rdivmod__(y) <==> divmod(y, x)
487.1121 -
487.1122 -<br><br>
487.1123 -<a href="meth:__reduce__()">__reduce__()</a>
487.1124 -
487.1125 -<br><br>
487.1126 - helper for pickle
487.1127 -
487.1128 -<br><br>
487.1129 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
487.1130 -
487.1131 -<br><br>
487.1132 - helper for pickle
487.1133 -
487.1134 -<br><br>
487.1135 -<a href="meth:__repr__()">__repr__()</a>
487.1136 -
487.1137 -<br><br>
487.1138 - x.__repr__() <==> repr(x)
487.1139 -
487.1140 -<br><br>
487.1141 -<a href="meth:__rfloordiv__(y)">__rfloordiv__(y)</a>
487.1142 -
487.1143 -<br><br>
487.1144 - x.__rfloordiv__(y) <==> y//x
487.1145 -
487.1146 -<br><br>
487.1147 -<a href="meth:__rlshift__(y)">__rlshift__(y)</a>
487.1148 -
487.1149 -<br><br>
487.1150 - x.__rlshift__(y) <==> y<<x
487.1151 -
487.1152 -<br><br>
487.1153 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
487.1154 -
487.1155 -<br><br>
487.1156 - x.__rmod__(y) <==> y%x
487.1157 -
487.1158 -<br><br>
487.1159 -<a href="meth:__rmul__(y)">__rmul__(y)</a>
487.1160 -
487.1161 -<br><br>
487.1162 - x.__rmul__(y) <==> y*x
487.1163 -
487.1164 -<br><br>
487.1165 -<a href="meth:__ror__(y)">__ror__(y)</a>
487.1166 -
487.1167 -<br><br>
487.1168 - x.__ror__(y) <==> y|x
487.1169 -
487.1170 -<br><br>
487.1171 -<a href="meth:__rpow__(x)">__rpow__(x)</a>
487.1172 -
487.1173 -<br><br>
487.1174 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
487.1175 -
487.1176 -<br><br>
487.1177 -<a href="meth:__rrshift__(y)">__rrshift__(y)</a>
487.1178 -
487.1179 -<br><br>
487.1180 - x.__rrshift__(y) <==> y>>x
487.1181 -
487.1182 -<br><br>
487.1183 -<a href="meth:__rshift__(y)">__rshift__(y)</a>
487.1184 -
487.1185 -<br><br>
487.1186 - x.__rshift__(y) <==> x>>y
487.1187 -
487.1188 -<br><br>
487.1189 -<a href="meth:__rsub__(y)">__rsub__(y)</a>
487.1190 -
487.1191 -<br><br>
487.1192 - x.__rsub__(y) <==> y-x
487.1193 -
487.1194 -<br><br>
487.1195 -<a href="meth:__rtruediv__(y)">__rtruediv__(y)</a>
487.1196 -
487.1197 -<br><br>
487.1198 - x.__rtruediv__(y) <==> y/x
487.1199 -
487.1200 -<br><br>
487.1201 -<a href="meth:__rxor__(y)">__rxor__(y)</a>
487.1202 -
487.1203 -<br><br>
487.1204 - x.__rxor__(y) <==> y^x
487.1205 -
487.1206 -<br><br>
487.1207 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
487.1208 -
487.1209 -<br><br>
487.1210 - x.__setattr__('name', value) <==> x.name = value
487.1211 -
487.1212 -<br><br>
487.1213 -<a href="meth:__sizeof__()">__sizeof__()</a>
487.1214 -
487.1215 -<br><br>
487.1216 - __sizeof__() -> size of object in memory, in bytes
487.1217 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1218 -</div>
487.1219 -<a href="meth:__str__()">__str__()</a>
487.1220 - x.__str__() <==> str(x)
487.1221 -
487.1222 -<br><br>
487.1223 -<a href="meth:__sub__(y)">__sub__(y)</a>
487.1224 -
487.1225 -<br><br>
487.1226 - x.__sub__(y) <==> x-y
487.1227 -
487.1228 -<br><br>
487.1229 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
487.1230 -
487.1231 -<br><br>
487.1232 - Abstract classes can override this to customize issubclass().
487.1233 -
487.1234 -<br><br>
487.1235 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
487.1236 - It should return True, False or NotImplemented. If it returns
487.1237 - NotImplemented, the normal algorithm is used. Otherwise, it
487.1238 - overrides the normal algorithm (and the outcome is cached).
487.1239 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1240 -</div>
487.1241 -<a href="meth:__truediv__(y)">__truediv__(y)</a>
487.1242 - x.__truediv__(y) <==> x/y
487.1243 -
487.1244 -<br><br>
487.1245 -<a href="meth:__trunc__()">__trunc__()</a>
487.1246 -
487.1247 -<br><br>
487.1248 - Truncating an Integral returns itself.
487.1249 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1250 -</div>
487.1251 -<a href="meth:__xor__(y)">__xor__(y)</a>
487.1252 - x.__xor__(y) <==> x^y
487.1253 -
487.1254 -<br><br>
487.1255 -<a href="meth:conjugate()">conjugate()</a>
487.1256 -
487.1257 -<br><br>
487.1258 - Returns self, the complex conjugate of any int.
487.1259 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1260 -</div>
487.1261 -<a href="attr:denominator">denominator</a>
487.1262 - int(x[, base]) -> integer
487.1263 -
487.1264 -<br><br>
487.1265 - Convert a string or number to an integer, if possible. A floating point
487.1266 - argument will be truncated towards zero (this does not include a string
487.1267 - representation of a floating point number!) When converting a string, use
487.1268 - the optional base. It is an error to supply a base when converting a
487.1269 - non-string. If base is zero, the proper base is guessed based on the
487.1270 - string content. If the argument is outside the integer range a
487.1271 - long object will be returned instead.
487.1272 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1273 -</div>
487.1274 -<a href="attr:imag">imag</a>
487.1275 - int(x[, base]) -> integer
487.1276 -
487.1277 -<br><br>
487.1278 - Convert a string or number to an integer, if possible. A floating point
487.1279 - argument will be truncated towards zero (this does not include a string
487.1280 - representation of a floating point number!) When converting a string, use
487.1281 - the optional base. It is an error to supply a base when converting a
487.1282 - non-string. If base is zero, the proper base is guessed based on the
487.1283 - string content. If the argument is outside the integer range a
487.1284 - long object will be returned instead.
487.1285 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1286 -</div>
487.1287 -<a href="attr:numerator">numerator</a>
487.1288 - int(x[, base]) -> integer
487.1289 -
487.1290 -<br><br>
487.1291 - Convert a string or number to an integer, if possible. A floating point
487.1292 - argument will be truncated towards zero (this does not include a string
487.1293 - representation of a floating point number!) When converting a string, use
487.1294 - the optional base. It is an error to supply a base when converting a
487.1295 - non-string. If base is zero, the proper base is guessed based on the
487.1296 - string content. If the argument is outside the integer range a
487.1297 - long object will be returned instead.
487.1298 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1299 -</div>
487.1300 -<a href="attr:real">real</a>
487.1301 - int(x[, base]) -> integer
487.1302 -
487.1303 -<br><br>
487.1304 - Convert a string or number to an integer, if possible. A floating point
487.1305 - argument will be truncated towards zero (this does not include a string
487.1306 - representation of a floating point number!) When converting a string, use
487.1307 - the optional base. It is an error to supply a base when converting a
487.1308 - non-string. If base is zero, the proper base is guessed based on the
487.1309 - string content. If the argument is outside the integer range a
487.1310 - long object will be returned instead.
487.1311 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1312 -</div>
487.1313 -<a href="class:complex">complex</a>
487.1314 - complex(real[, imag]) -> complex number
487.1315 -
487.1316 -<br><br>
487.1317 - Create a complex number from a real part and an optional imaginary part.
487.1318 - This is equivalent to (real + imag*1j) where imag defaults to 0.
487.1319 -
487.1320 -<br><br>
487.1321 -<a href="attr:__class__">__class__</a>
487.1322 -
487.1323 -<br><br>
487.1324 - complex(real[, imag]) -> complex number
487.1325 -
487.1326 -<br><br>
487.1327 - Create a complex number from a real part and an optional imaginary part.
487.1328 - This is equivalent to (real + imag*1j) where imag defaults to 0.
487.1329 -
487.1330 -<br><br>
487.1331 -<a href="meth:__coerce__(y)">__coerce__(y)</a>
487.1332 -
487.1333 -<br><br>
487.1334 - x.__coerce__(y) <==> coerce(x, y)
487.1335 -
487.1336 -<br><br>
487.1337 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
487.1338 -
487.1339 -<br><br>
487.1340 - x.__delattr__('name') <==> del x.name
487.1341 -
487.1342 -<br><br>
487.1343 -<a href="meth:__divmod__(y)">__divmod__(y)</a>
487.1344 -
487.1345 -<br><br>
487.1346 - x.__divmod__(y) <==> divmod(x, y)
487.1347 -
487.1348 -<br><br>
487.1349 -<a href="attr:__doc__">__doc__</a>
487.1350 -
487.1351 -<br><br>
487.1352 - str(object) -> string
487.1353 -
487.1354 -<br><br>
487.1355 - Return a nice string representation of the object.
487.1356 - If the argument is a string, the return value is the same object.
487.1357 -
487.1358 -<br><br>
487.1359 -<a href="meth:__float__()">__float__()</a>
487.1360 -
487.1361 -<br><br>
487.1362 - x.__float__() <==> float(x)
487.1363 -
487.1364 -<br><br>
487.1365 -<a href="meth:__format__()">__format__()</a>
487.1366 -
487.1367 -<br><br>
487.1368 - default object formatter
487.1369 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1370 -</div>
487.1371 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
487.1372 - x.__getattribute__('name') <==> x.name
487.1373 -
487.1374 -<br><br>
487.1375 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
487.1376 -
487.1377 -<br><br>
487.1378 -<a href="meth:__hash__()">__hash__()</a>
487.1379 -
487.1380 -<br><br>
487.1381 - x.__hash__() <==> hash(x)
487.1382 -
487.1383 -<br><br>
487.1384 -<a href="meth:__init__()">__init__()</a>
487.1385 -
487.1386 -<br><br>
487.1387 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
487.1388 -
487.1389 -<br><br>
487.1390 -<a href="meth:__int__()">__int__()</a>
487.1391 -
487.1392 -<br><br>
487.1393 - x.__int__() <==> int(x)
487.1394 -
487.1395 -<br><br>
487.1396 -<a href="meth:__long__()">__long__()</a>
487.1397 -
487.1398 -<br><br>
487.1399 - x.__long__() <==> long(x)
487.1400 -
487.1401 -<br><br>
487.1402 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
487.1403 -
487.1404 -<br><br>
487.1405 - T.__new__(S, ...) -> a new object with type S, a subtype of T
487.1406 -
487.1407 -<br><br>
487.1408 -<a href="meth:__nonzero__()">__nonzero__()</a>
487.1409 -
487.1410 -<br><br>
487.1411 - x.__nonzero__() <==> x != 0
487.1412 -
487.1413 -<br><br>
487.1414 -<a href="meth:__radd__(y)">__radd__(y)</a>
487.1415 -
487.1416 -<br><br>
487.1417 - x.__radd__(y) <==> y+x
487.1418 -
487.1419 -<br><br>
487.1420 -<a href="meth:__rdiv__(y)">__rdiv__(y)</a>
487.1421 -
487.1422 -<br><br>
487.1423 - x.__rdiv__(y) <==> y/x
487.1424 -
487.1425 -<br><br>
487.1426 -<a href="meth:__rdivmod__(y)">__rdivmod__(y)</a>
487.1427 -
487.1428 -<br><br>
487.1429 - x.__rdivmod__(y) <==> divmod(y, x)
487.1430 -
487.1431 -<br><br>
487.1432 -<a href="meth:__reduce__()">__reduce__()</a>
487.1433 -
487.1434 -<br><br>
487.1435 - helper for pickle
487.1436 -
487.1437 -<br><br>
487.1438 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
487.1439 -
487.1440 -<br><br>
487.1441 - helper for pickle
487.1442 -
487.1443 -<br><br>
487.1444 -<a href="meth:__repr__()">__repr__()</a>
487.1445 -
487.1446 -<br><br>
487.1447 - x.__repr__() <==> repr(x)
487.1448 -
487.1449 -<br><br>
487.1450 -<a href="meth:__rfloordiv__(y)">__rfloordiv__(y)</a>
487.1451 -
487.1452 -<br><br>
487.1453 - x.__rfloordiv__(y) <==> y//x
487.1454 -
487.1455 -<br><br>
487.1456 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
487.1457 -
487.1458 -<br><br>
487.1459 - x.__rmod__(y) <==> y%x
487.1460 -
487.1461 -<br><br>
487.1462 -<a href="meth:__rmul__(y)">__rmul__(y)</a>
487.1463 -
487.1464 -<br><br>
487.1465 - x.__rmul__(y) <==> y*x
487.1466 -
487.1467 -<br><br>
487.1468 -<a href="meth:__rpow__(x)">__rpow__(x)</a>
487.1469 -
487.1470 -<br><br>
487.1471 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
487.1472 -
487.1473 -<br><br>
487.1474 -<a href="meth:__rsub__(y)">__rsub__(y)</a>
487.1475 -
487.1476 -<br><br>
487.1477 - x.__rsub__(y) <==> y-x
487.1478 -
487.1479 -<br><br>
487.1480 -<a href="meth:__rtruediv__(y)">__rtruediv__(y)</a>
487.1481 -
487.1482 -<br><br>
487.1483 - x.__rtruediv__(y) <==> y/x
487.1484 -
487.1485 -<br><br>
487.1486 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
487.1487 -
487.1488 -<br><br>
487.1489 - x.__setattr__('name', value) <==> x.name = value
487.1490 -
487.1491 -<br><br>
487.1492 -<a href="meth:__sizeof__()">__sizeof__()</a>
487.1493 -
487.1494 -<br><br>
487.1495 - __sizeof__() -> size of object in memory, in bytes
487.1496 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1497 -</div>
487.1498 -<a href="meth:__str__()">__str__()</a>
487.1499 - x.__str__() <==> str(x)
487.1500 -
487.1501 -<br><br>
487.1502 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
487.1503 -
487.1504 -<br><br>
487.1505 - Abstract classes can override this to customize issubclass().
487.1506 -
487.1507 -<br><br>
487.1508 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
487.1509 - It should return True, False or NotImplemented. If it returns
487.1510 - NotImplemented, the normal algorithm is used. Otherwise, it
487.1511 - overrides the normal algorithm (and the outcome is cached).
487.1512 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1513 -</div>
487.1514 -<a href="meth:conjugate()">conjugate()</a>
487.1515 - complex.conjugate() -> complex
487.1516 -
487.1517 -<br><br>
487.1518 - Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
487.1519 -
487.1520 -<br><br>
487.1521 -<a href="attr:imag">imag</a>
487.1522 -
487.1523 -<br><br>
487.1524 - float(x) -> floating point number
487.1525 -
487.1526 -<br><br>
487.1527 - Convert a string or number to a floating point number, if possible.
487.1528 -
487.1529 -<br><br>
487.1530 -<a href="attr:real">real</a>
487.1531 -
487.1532 -<br><br>
487.1533 - float(x) -> floating point number
487.1534 -
487.1535 -<br><br>
487.1536 - Convert a string or number to a floating point number, if possible.
487.1537 -
487.1538 -<br><br>
487.1539 -<a href="class:list">list</a>
487.1540 -
487.1541 -<br><br>
487.1542 - list() -> new list
487.1543 - list(sequence) -> new list initialized from sequence's items
487.1544 -
487.1545 -<br><br>
487.1546 -<a href="attr:__class__">__class__</a>
487.1547 -
487.1548 -<br><br>
487.1549 - list() -> new list
487.1550 - list(sequence) -> new list initialized from sequence's items
487.1551 -
487.1552 -<br><br>
487.1553 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
487.1554 -
487.1555 -<br><br>
487.1556 - x.__delattr__('name') <==> del x.name
487.1557 -
487.1558 -<br><br>
487.1559 -<a href="attr:__doc__">__doc__</a>
487.1560 -
487.1561 -<br><br>
487.1562 - str(object) -> string
487.1563 -
487.1564 -<br><br>
487.1565 - Return a nice string representation of the object.
487.1566 - If the argument is a string, the return value is the same object.
487.1567 -
487.1568 -<br><br>
487.1569 -<a href="meth:__format__()">__format__()</a>
487.1570 -
487.1571 -<br><br>
487.1572 - default object formatter
487.1573 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1574 -</div>
487.1575 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
487.1576 - x.__getattribute__('name') <==> x.name
487.1577 -
487.1578 -<br><br>
487.1579 -<a href="attr:__hash__">__hash__</a>
487.1580 -
487.1581 -<br><br>
487.1582 -<a href="meth:__init__()">__init__()</a>
487.1583 -
487.1584 -<br><br>
487.1585 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
487.1586 -
487.1587 -<br><br>
487.1588 -<a href="meth:__iter__()">__iter__()</a>
487.1589 -
487.1590 -<br><br>
487.1591 - x.__iter__() <==> iter(x)
487.1592 -
487.1593 -<br><br>
487.1594 -<a href="meth:__len__()">__len__()</a>
487.1595 -
487.1596 -<br><br>
487.1597 - x.__len__() <==> len(x)
487.1598 -
487.1599 -<br><br>
487.1600 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
487.1601 -
487.1602 -<br><br>
487.1603 - T.__new__(S, ...) -> a new object with type S, a subtype of T
487.1604 -
487.1605 -<br><br>
487.1606 -<a href="meth:__reduce__()">__reduce__()</a>
487.1607 -
487.1608 -<br><br>
487.1609 - helper for pickle
487.1610 -
487.1611 -<br><br>
487.1612 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
487.1613 -
487.1614 -<br><br>
487.1615 - helper for pickle
487.1616 -
487.1617 -<br><br>
487.1618 -<a href="meth:__repr__()">__repr__()</a>
487.1619 -
487.1620 -<br><br>
487.1621 - x.__repr__() <==> repr(x)
487.1622 -
487.1623 -<br><br>
487.1624 -<a href="meth:__reversed__()">__reversed__()</a>
487.1625 -
487.1626 -<br><br>
487.1627 - L.__reversed__() -- return a reverse iterator over the list
487.1628 -
487.1629 -<br><br>
487.1630 -<a href="meth:__rmul__(n)">__rmul__(n)</a>
487.1631 -
487.1632 -<br><br>
487.1633 - x.__rmul__(n) <==> n*x
487.1634 -
487.1635 -<br><br>
487.1636 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
487.1637 -
487.1638 -<br><br>
487.1639 - x.__setattr__('name', value) <==> x.name = value
487.1640 -
487.1641 -<br><br>
487.1642 -<a href="meth:__sizeof__()">__sizeof__()</a>
487.1643 -
487.1644 -<br><br>
487.1645 - L.__sizeof__() -- size of L in memory, in bytes
487.1646 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1647 -</div>
487.1648 -<a href="meth:__str__()">__str__()</a>
487.1649 - x.__str__() <==> str(x)
487.1650 -
487.1651 -<br><br>
487.1652 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
487.1653 -
487.1654 -<br><br>
487.1655 - Abstract classes can override this to customize issubclass().
487.1656 -
487.1657 -<br><br>
487.1658 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
487.1659 - It should return True, False or NotImplemented. If it returns
487.1660 - NotImplemented, the normal algorithm is used. Otherwise, it
487.1661 - overrides the normal algorithm (and the outcome is cached).
487.1662 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1663 -</div>
487.1664 -<a href="meth:append()">append()</a>
487.1665 - L.append(object) -- append object to end
487.1666 -
487.1667 -<br><br>
487.1668 -<a href="meth:count(value)">count(value)</a>
487.1669 -
487.1670 -<br><br>
487.1671 - L.count(value) -> integer -- return number of occurrences of value
487.1672 -
487.1673 -<br><br>
487.1674 -<a href="meth:extend()">extend()</a>
487.1675 -
487.1676 -<br><br>
487.1677 - L.extend(iterable) -- extend list by appending elements from the iterable
487.1678 -
487.1679 -<br><br>
487.1680 -<a href="meth:insert()">insert()</a>
487.1681 -
487.1682 -<br><br>
487.1683 - L.insert(index, object) -- insert object before index
487.1684 -
487.1685 -<br><br>
487.1686 -<a href="meth:pop()">pop()</a>
487.1687 -
487.1688 -<br><br>
487.1689 - L.pop([index]) -> item -- remove and return item at index (default last)
487.1690 -
487.1691 -<br><br>
487.1692 -<a href="meth:remove()">remove()</a>
487.1693 -
487.1694 -<br><br>
487.1695 - L.remove(value) -- remove first occurrence of value
487.1696 -
487.1697 -<br><br>
487.1698 -<a href="meth:reverse()">reverse()</a>
487.1699 -
487.1700 -<br><br>
487.1701 - L.reverse() -- reverse *IN PLACE*
487.1702 -
487.1703 -<br><br>
487.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>
487.1705 -cmp(x, y)
487.1706 -
487.1707 -<br><br>
487.1708 - L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
487.1709 - cmp(x, y) -> -1, 0, 1
487.1710 -
487.1711 -<br><br>
487.1712 -<a href="class:dict">dict</a>
487.1713 -
487.1714 -<br><br>
487.1715 - dict() -> new empty dictionary.
487.1716 - dict(mapping) -> new dictionary initialized from a mapping object's
487.1717 - (key, value) pairs.
487.1718 - dict(seq) -> new dictionary initialized as if via:
487.1719 - d = {}
487.1720 - for k, v in seq:
487.1721 - d[k] = v
487.1722 - dict(**kwargs) -> new dictionary initialized with the name=value pairs
487.1723 - in the keyword argument list. For example: dict(one=1, two=2)
487.1724 -
487.1725 -<br><br>
487.1726 -<a href="attr:__class__">__class__</a>
487.1727 -
487.1728 -<br><br>
487.1729 - dict() -> new empty dictionary.
487.1730 - dict(mapping) -> new dictionary initialized from a mapping object's
487.1731 - (key, value) pairs.
487.1732 - dict(seq) -> new dictionary initialized as if via:
487.1733 - d = {}
487.1734 - for k, v in seq:
487.1735 - d[k] = v
487.1736 - dict(**kwargs) -> new dictionary initialized with the name=value pairs
487.1737 - in the keyword argument list. For example: dict(one=1, two=2)
487.1738 -
487.1739 -<br><br>
487.1740 -<a href="meth:__cmp__(y)">__cmp__(y)</a>
487.1741 -
487.1742 -<br><br>
487.1743 - x.__cmp__(y) <==> cmp(x,y)
487.1744 -
487.1745 -<br><br>
487.1746 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
487.1747 -
487.1748 -<br><br>
487.1749 - x.__delattr__('name') <==> del x.name
487.1750 -
487.1751 -<br><br>
487.1752 -<a href="attr:__doc__">__doc__</a>
487.1753 -
487.1754 -<br><br>
487.1755 - str(object) -> string
487.1756 -
487.1757 -<br><br>
487.1758 - Return a nice string representation of the object.
487.1759 - If the argument is a string, the return value is the same object.
487.1760 -
487.1761 -<br><br>
487.1762 -<a href="meth:__format__()">__format__()</a>
487.1763 -
487.1764 -<br><br>
487.1765 - default object formatter
487.1766 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1767 -</div>
487.1768 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
487.1769 - x.__getattribute__('name') <==> x.name
487.1770 -
487.1771 -<br><br>
487.1772 -<a href="attr:__hash__">__hash__</a>
487.1773 -
487.1774 -<br><br>
487.1775 -<a href="meth:__iter__()">__iter__()</a>
487.1776 -
487.1777 -<br><br>
487.1778 - x.__iter__() <==> iter(x)
487.1779 -
487.1780 -<br><br>
487.1781 -<a href="meth:__len__()">__len__()</a>
487.1782 -
487.1783 -<br><br>
487.1784 - x.__len__() <==> len(x)
487.1785 -
487.1786 -<br><br>
487.1787 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
487.1788 -
487.1789 -<br><br>
487.1790 - T.__new__(S, ...) -> a new object with type S, a subtype of T
487.1791 -
487.1792 -<br><br>
487.1793 -<a href="meth:__reduce__()">__reduce__()</a>
487.1794 -
487.1795 -<br><br>
487.1796 - helper for pickle
487.1797 -
487.1798 -<br><br>
487.1799 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
487.1800 -
487.1801 -<br><br>
487.1802 - helper for pickle
487.1803 -
487.1804 -<br><br>
487.1805 -<a href="meth:__repr__()">__repr__()</a>
487.1806 -
487.1807 -<br><br>
487.1808 - x.__repr__() <==> repr(x)
487.1809 -
487.1810 -<br><br>
487.1811 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
487.1812 -
487.1813 -<br><br>
487.1814 - x.__setattr__('name', value) <==> x.name = value
487.1815 -
487.1816 -<br><br>
487.1817 -<a href="meth:__sizeof__()">__sizeof__()</a>
487.1818 -
487.1819 -<br><br>
487.1820 - D.__sizeof__() -> size of D in memory, in bytes
487.1821 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1822 -</div>
487.1823 -<a href="meth:__str__()">__str__()</a>
487.1824 - x.__str__() <==> str(x)
487.1825 -
487.1826 -<br><br>
487.1827 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
487.1828 -
487.1829 -<br><br>
487.1830 - Abstract classes can override this to customize issubclass().
487.1831 -
487.1832 -<br><br>
487.1833 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
487.1834 - It should return True, False or NotImplemented. If it returns
487.1835 - NotImplemented, the normal algorithm is used. Otherwise, it
487.1836 - overrides the normal algorithm (and the outcome is cached).
487.1837 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1838 -</div>
487.1839 -<a href="class:tuple">tuple</a>
487.1840 - tuple() -> an empty tuple
487.1841 - tuple(sequence) -> tuple initialized from sequence's items
487.1842 -
487.1843 -<br><br>
487.1844 - If the argument is a tuple, the return value is the same object.
487.1845 -
487.1846 -<br><br>
487.1847 -<a href="attr:__class__">__class__</a>
487.1848 -
487.1849 -<br><br>
487.1850 - tuple() -> an empty tuple
487.1851 - tuple(sequence) -> tuple initialized from sequence's items
487.1852 -
487.1853 -<br><br>
487.1854 - If the argument is a tuple, the return value is the same object.
487.1855 -
487.1856 -<br><br>
487.1857 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
487.1858 -
487.1859 -<br><br>
487.1860 - x.__delattr__('name') <==> del x.name
487.1861 -
487.1862 -<br><br>
487.1863 -<a href="attr:__doc__">__doc__</a>
487.1864 -
487.1865 -<br><br>
487.1866 - str(object) -> string
487.1867 -
487.1868 -<br><br>
487.1869 - Return a nice string representation of the object.
487.1870 - If the argument is a string, the return value is the same object.
487.1871 -
487.1872 -<br><br>
487.1873 -<a href="meth:__format__()">__format__()</a>
487.1874 -
487.1875 -<br><br>
487.1876 - default object formatter
487.1877 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1878 -</div>
487.1879 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
487.1880 - x.__getattribute__('name') <==> x.name
487.1881 -
487.1882 -<br><br>
487.1883 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
487.1884 -
487.1885 -<br><br>
487.1886 -<a href="meth:__hash__()">__hash__()</a>
487.1887 -
487.1888 -<br><br>
487.1889 - x.__hash__() <==> hash(x)
487.1890 -
487.1891 -<br><br>
487.1892 -<a href="meth:__init__()">__init__()</a>
487.1893 -
487.1894 -<br><br>
487.1895 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
487.1896 -
487.1897 -<br><br>
487.1898 -<a href="meth:__iter__()">__iter__()</a>
487.1899 -
487.1900 -<br><br>
487.1901 - x.__iter__() <==> iter(x)
487.1902 -
487.1903 -<br><br>
487.1904 -<a href="meth:__len__()">__len__()</a>
487.1905 -
487.1906 -<br><br>
487.1907 - x.__len__() <==> len(x)
487.1908 -
487.1909 -<br><br>
487.1910 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
487.1911 -
487.1912 -<br><br>
487.1913 - T.__new__(S, ...) -> a new object with type S, a subtype of T
487.1914 -
487.1915 -<br><br>
487.1916 -<a href="meth:__reduce__()">__reduce__()</a>
487.1917 -
487.1918 -<br><br>
487.1919 - helper for pickle
487.1920 -
487.1921 -<br><br>
487.1922 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
487.1923 -
487.1924 -<br><br>
487.1925 - helper for pickle
487.1926 -
487.1927 -<br><br>
487.1928 -<a href="meth:__repr__()">__repr__()</a>
487.1929 -
487.1930 -<br><br>
487.1931 - x.__repr__() <==> repr(x)
487.1932 -
487.1933 -<br><br>
487.1934 -<a href="meth:__rmul__(n)">__rmul__(n)</a>
487.1935 -
487.1936 -<br><br>
487.1937 - x.__rmul__(n) <==> n*x
487.1938 -
487.1939 -<br><br>
487.1940 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
487.1941 -
487.1942 -<br><br>
487.1943 - x.__setattr__('name', value) <==> x.name = value
487.1944 -
487.1945 -<br><br>
487.1946 -<a href="meth:__sizeof__()">__sizeof__()</a>
487.1947 -
487.1948 -<br><br>
487.1949 - T.__sizeof__() -- size of T in memory, in bytes
487.1950 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1951 -</div>
487.1952 -<a href="meth:__str__()">__str__()</a>
487.1953 - x.__str__() <==> str(x)
487.1954 -
487.1955 -<br><br>
487.1956 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
487.1957 -
487.1958 -<br><br>
487.1959 - Abstract classes can override this to customize issubclass().
487.1960 -
487.1961 -<br><br>
487.1962 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
487.1963 - It should return True, False or NotImplemented. If it returns
487.1964 - NotImplemented, the normal algorithm is used. Otherwise, it
487.1965 - overrides the normal algorithm (and the outcome is cached).
487.1966 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1967 -</div>
487.1968 -<a href="meth:count(value)">count(value)</a>
487.1969 - T.count(value) -> integer -- return number of occurrences of value
487.1970 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.1971 -</div>
487.1972 -<a href="class:str">str</a>
487.1973 - str(object) -> string
487.1974 -
487.1975 -<br><br>
487.1976 - Return a nice string representation of the object.
487.1977 - If the argument is a string, the return value is the same object.
487.1978 -
487.1979 -<br><br>
487.1980 -<a href="attr:__class__">__class__</a>
487.1981 -
487.1982 -<br><br>
487.1983 - str(object) -> string
487.1984 -
487.1985 -<br><br>
487.1986 - Return a nice string representation of the object.
487.1987 - If the argument is a string, the return value is the same object.
487.1988 -
487.1989 -<br><br>
487.1990 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
487.1991 -
487.1992 -<br><br>
487.1993 - x.__delattr__('name') <==> del x.name
487.1994 -
487.1995 -<br><br>
487.1996 -<a href="attr:__doc__">__doc__</a>
487.1997 -
487.1998 -<br><br>
487.1999 - str(object) -> string
487.2000 -
487.2001 -<br><br>
487.2002 - Return a nice string representation of the object.
487.2003 - If the argument is a string, the return value is the same object.
487.2004 -
487.2005 -<br><br>
487.2006 -<a href="meth:__format__(format_spec)">__format__(format_spec)</a>
487.2007 -
487.2008 -<br><br>
487.2009 - S.__format__(format_spec) -> unicode
487.2010 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.2011 -</div>
487.2012 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
487.2013 - x.__getattribute__('name') <==> x.name
487.2014 -
487.2015 -<br><br>
487.2016 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
487.2017 -
487.2018 -<br><br>
487.2019 -<a href="meth:__hash__()">__hash__()</a>
487.2020 -
487.2021 -<br><br>
487.2022 - x.__hash__() <==> hash(x)
487.2023 -
487.2024 -<br><br>
487.2025 -<a href="meth:__init__()">__init__()</a>
487.2026 -
487.2027 -<br><br>
487.2028 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
487.2029 -
487.2030 -<br><br>
487.2031 -<a href="meth:__len__()">__len__()</a>
487.2032 -
487.2033 -<br><br>
487.2034 - x.__len__() <==> len(x)
487.2035 -
487.2036 -<br><br>
487.2037 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
487.2038 -
487.2039 -<br><br>
487.2040 - T.__new__(S, ...) -> a new object with type S, a subtype of T
487.2041 -
487.2042 -<br><br>
487.2043 -<a href="meth:__reduce__()">__reduce__()</a>
487.2044 -
487.2045 -<br><br>
487.2046 - helper for pickle
487.2047 -
487.2048 -<br><br>
487.2049 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
487.2050 -
487.2051 -<br><br>
487.2052 - helper for pickle
487.2053 -
487.2054 -<br><br>
487.2055 -<a href="meth:__repr__()">__repr__()</a>
487.2056 -
487.2057 -<br><br>
487.2058 - x.__repr__() <==> repr(x)
487.2059 -
487.2060 -<br><br>
487.2061 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
487.2062 -
487.2063 -<br><br>
487.2064 - x.__rmod__(y) <==> y%x
487.2065 -
487.2066 -<br><br>
487.2067 -<a href="meth:__rmul__(n)">__rmul__(n)</a>
487.2068 -
487.2069 -<br><br>
487.2070 - x.__rmul__(n) <==> n*x
487.2071 -
487.2072 -<br><br>
487.2073 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
487.2074 -
487.2075 -<br><br>
487.2076 - x.__setattr__('name', value) <==> x.name = value
487.2077 -
487.2078 -<br><br>
487.2079 -<a href="meth:__sizeof__()">__sizeof__()</a>
487.2080 -
487.2081 -<br><br>
487.2082 - S.__sizeof__() -> size of S in memory, in bytes
487.2083 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.2084 -</div>
487.2085 -<a href="meth:__str__()">__str__()</a>
487.2086 - x.__str__() <==> str(x)
487.2087 -
487.2088 -<br><br>
487.2089 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
487.2090 -
487.2091 -<br><br>
487.2092 - Abstract classes can override this to customize issubclass().
487.2093 -
487.2094 -<br><br>
487.2095 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
487.2096 - It should return True, False or NotImplemented. If it returns
487.2097 - NotImplemented, the normal algorithm is used. Otherwise, it
487.2098 - overrides the normal algorithm (and the outcome is cached).
487.2099 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.2100 -</div>
487.2101 -<a href="meth:_formatter_field_name_split()">_formatter_field_name_split()</a>
487.2102 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.2103 -</div>
487.2104 -<a href="meth:_formatter_parser()">_formatter_parser()</a>
487.2105 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.2106 -</div>
487.2107 -<a href="class:unicode">unicode</a>
487.2108 - unicode(string [, encoding[, errors]]) -> object
487.2109 -
487.2110 -<br><br>
487.2111 - Create a new Unicode object from the given encoded string.
487.2112 - encoding defaults to the current default string encoding.
487.2113 - errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.
487.2114 -
487.2115 -<br><br>
487.2116 -<a href="attr:__class__">__class__</a>
487.2117 -
487.2118 -<br><br>
487.2119 - unicode(string [, encoding[, errors]]) -> object
487.2120 -
487.2121 -<br><br>
487.2122 - Create a new Unicode object from the given encoded string.
487.2123 - encoding defaults to the current default string encoding.
487.2124 - errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.
487.2125 -
487.2126 -<br><br>
487.2127 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
487.2128 -
487.2129 -<br><br>
487.2130 - x.__delattr__('name') <==> del x.name
487.2131 -
487.2132 -<br><br>
487.2133 -<a href="attr:__doc__">__doc__</a>
487.2134 -
487.2135 -<br><br>
487.2136 - str(object) -> string
487.2137 -
487.2138 -<br><br>
487.2139 - Return a nice string representation of the object.
487.2140 - If the argument is a string, the return value is the same object.
487.2141 -
487.2142 -<br><br>
487.2143 -<a href="meth:__format__(format_spec)">__format__(format_spec)</a>
487.2144 -
487.2145 -<br><br>
487.2146 - S.__format__(format_spec) -> unicode
487.2147 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.2148 -</div>
487.2149 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
487.2150 - x.__getattribute__('name') <==> x.name
487.2151 -
487.2152 -<br><br>
487.2153 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
487.2154 -
487.2155 -<br><br>
487.2156 -<a href="meth:__hash__()">__hash__()</a>
487.2157 -
487.2158 -<br><br>
487.2159 - x.__hash__() <==> hash(x)
487.2160 -
487.2161 -<br><br>
487.2162 -<a href="meth:__init__()">__init__()</a>
487.2163 -
487.2164 -<br><br>
487.2165 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
487.2166 -
487.2167 -<br><br>
487.2168 -<a href="meth:__len__()">__len__()</a>
487.2169 -
487.2170 -<br><br>
487.2171 - x.__len__() <==> len(x)
487.2172 -
487.2173 -<br><br>
487.2174 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
487.2175 -
487.2176 -<br><br>
487.2177 - T.__new__(S, ...) -> a new object with type S, a subtype of T
487.2178 -
487.2179 -<br><br>
487.2180 -<a href="meth:__reduce__()">__reduce__()</a>
487.2181 -
487.2182 -<br><br>
487.2183 - helper for pickle
487.2184 -
487.2185 -<br><br>
487.2186 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
487.2187 -
487.2188 -<br><br>
487.2189 - helper for pickle
487.2190 -
487.2191 -<br><br>
487.2192 -<a href="meth:__repr__()">__repr__()</a>
487.2193 -
487.2194 -<br><br>
487.2195 - x.__repr__() <==> repr(x)
487.2196 -
487.2197 -<br><br>
487.2198 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
487.2199 -
487.2200 -<br><br>
487.2201 - x.__rmod__(y) <==> y%x
487.2202 -
487.2203 -<br><br>
487.2204 -<a href="meth:__rmul__(n)">__rmul__(n)</a>
487.2205 -
487.2206 -<br><br>
487.2207 - x.__rmul__(n) <==> n*x
487.2208 -
487.2209 -<br><br>
487.2210 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
487.2211 -
487.2212 -<br><br>
487.2213 - x.__setattr__('name', value) <==> x.name = value
487.2214 -
487.2215 -<br><br>
487.2216 -<a href="meth:__sizeof__()">__sizeof__()</a>
487.2217 -
487.2218 -<br><br>
487.2219 - S.__sizeof__() -> size of S in memory, in bytes
487.2220 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.2221 -</div>
487.2222 -<a href="meth:__str__()">__str__()</a>
487.2223 - x.__str__() <==> str(x)
487.2224 -
487.2225 -<br><br>
487.2226 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
487.2227 -
487.2228 -<br><br>
487.2229 - Abstract classes can override this to customize issubclass().
487.2230 -
487.2231 -<br><br>
487.2232 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
487.2233 - It should return True, False or NotImplemented. If it returns
487.2234 - NotImplemented, the normal algorithm is used. Otherwise, it
487.2235 - overrides the normal algorithm (and the outcome is cached).
487.2236 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.2237 -</div>
487.2238 -<a href="meth:_formatter_field_name_split()">_formatter_field_name_split()</a>
487.2239 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.2240 -</div>
487.2241 -<a href="meth:_formatter_parser()">_formatter_parser()</a>
487.2242 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.2243 -</div>
487.2244 -<a href="meth:capitalize()">capitalize()</a>
487.2245 - S.capitalize() -> unicode
487.2246 -
487.2247 -<br><br>
487.2248 - Return a capitalized version of S, i.e. make the first character
487.2249 - have upper case.
487.2250 -
487.2251 -<br><br>
487.2252 -<a href="meth:center(width)">center(width)</a>
487.2253 -
487.2254 -<br><br>
487.2255 - S.center(width[, fillchar]) -> unicode
487.2256 -
487.2257 -<br><br>
487.2258 - Return S centered in a Unicode string of length width. Padding is
487.2259 - done using the specified fill character (default is a space)
487.2260 -
487.2261 -<br><br>
487.2262 -<a href="meth:count(sub)">count(sub)</a>
487.2263 -
487.2264 -<br><br>
487.2265 - S.count(sub[, start[, end]]) -> int
487.2266 -
487.2267 -<br><br>
487.2268 - Return the number of non-overlapping occurrences of substring sub in
487.2269 - Unicode string S[start:end]. Optional arguments start and end are
487.2270 - interpreted as in slice notation.
487.2271 -
487.2272 -<br><br>
487.2273 -<a href="meth:decode()">decode()</a>
487.2274 -
487.2275 -<br><br>
487.2276 - S.decode([encoding[,errors]]) -> string or unicode
487.2277 -
487.2278 -<br><br>
487.2279 - Decodes S using the codec registered for encoding. encoding defaults
487.2280 - to the default encoding. errors may be given to set a different error
487.2281 - handling scheme. Default is 'strict' meaning that encoding errors raise
487.2282 - a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
487.2283 - as well as any other name registerd with codecs.register_error that is
487.2284 - able to handle UnicodeDecodeErrors.
487.2285 -
487.2286 -<br><br>
487.2287 -<a href="meth:encode()">encode()</a>
487.2288 -
487.2289 -<br><br>
487.2290 - S.encode([encoding[,errors]]) -> string or unicode
487.2291 -
487.2292 -<br><br>
487.2293 - Encodes S using the codec registered for encoding. encoding defaults
487.2294 - to the default encoding. errors may be given to set a different error
487.2295 - handling scheme. Default is 'strict' meaning that encoding errors raise
487.2296 - a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
487.2297 - 'xmlcharrefreplace' as well as any other name registered with
487.2298 - codecs.register_error that can handle UnicodeEncodeErrors.
487.2299 -
487.2300 -<br><br>
487.2301 -<a href="meth:endswith(suffix)">endswith(suffix)</a>
487.2302 -
487.2303 -<br><br>
487.2304 - S.endswith(suffix[, start[, end]]) -> bool
487.2305 -
487.2306 -<br><br>
487.2307 - Return True if S ends with the specified suffix, False otherwise.
487.2308 - With optional start, test S beginning at that position.
487.2309 - With optional end, stop comparing S at that position.
487.2310 - suffix can also be a tuple of strings to try.
487.2311 -
487.2312 -<br><br>
487.2313 -<a href="meth:expandtabs()">expandtabs()</a>
487.2314 -
487.2315 -<br><br>
487.2316 - S.expandtabs([tabsize]) -> unicode
487.2317 -
487.2318 -<br><br>
487.2319 - Return a copy of S where all tab characters are expanded using spaces.
487.2320 - If tabsize is not given, a tab size of 8 characters is assumed.
487.2321 -
487.2322 -<br><br>
487.2323 -<a href="meth:find(sub )">find(sub )</a>
487.2324 -
487.2325 -<br><br>
487.2326 - S.find(sub [,start [,end]]) -> int
487.2327 -
487.2328 -<br><br>
487.2329 - Return the lowest index in S where substring sub is found,
487.2330 - such that sub is contained within s[start:end]. Optional
487.2331 - arguments start and end are interpreted as in slice notation.
487.2332 -
487.2333 -<br><br>
487.2334 - Return -1 on failure.
487.2335 -
487.2336 -<br><br>
487.2337 -<a href="meth:format(*args, **kwargs)">format(*args, **kwargs)</a>
487.2338 -
487.2339 -<br><br>
487.2340 - S.format(*args, **kwargs) -> unicode
487.2341 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
487.2342 -</div>
487.2343 -<a href="meth:isalnum()">isalnum()</a>
487.2344 - S.isalnum() -> bool
487.2345 -
487.2346 -<br><br>
487.2347 - Return True if all characters in S are alphanumeric
487.2348 - and there is at least one character in S, False otherwise.
487.2349 -
487.2350 -<br><br>
487.2351 -<a href="meth:isalpha()">isalpha()</a>
487.2352 -
487.2353 -<br><br>
487.2354 - S.isalpha() -> bool
487.2355 -
487.2356 -<br><br>
487.2357 - Return True if all characters in S are alphabetic
487.2358 - and there is at least one character in S, False otherwise.
487.2359 -
487.2360 -<br><br>
487.2361 -<a href="meth:isdigit()">isdigit()</a>
487.2362 -
487.2363 -<br><br>
487.2364 - S.isdigit() -> bool
487.2365 -
487.2366 -<br><br>
487.2367 - Return True if all characters in S are digits
487.2368 - and there is at least one character in S, False otherwise.
487.2369 -
487.2370 -<br><br>
487.2371 -<a href="meth:islower()">islower()</a>
487.2372 -
487.2373 -<br><br>
487.2374 - S.islower() -> bool
487.2375 -
487.2376 -<br><br>
487.2377 - Return True if all cased characters in S are lowercase and there is
487.2378 - at least one cased character in S, False otherwise.
487.2379 -
487.2380 -<br><br>
487.2381 -<a href="meth:isspace()">isspace()</a>
487.2382 -
487.2383 -<br><br>
487.2384 - S.isspace() -> bool
487.2385 -
487.2386 -<br><br>
487.2387 - Return True if all characters in S are whitespace
487.2388 - and there is at least one character in S, False otherwise.
487.2389 -
487.2390 -<br><br>
487.2391 -<a href="meth:istitle()">istitle()</a>
487.2392 -
487.2393 -<br><br>
487.2394 - S.istitle() -> bool
487.2395 -
487.2396 -<br><br>
487.2397 - Return True if S is a titlecased string and there is at least one
487.2398 - character in S, i.e. upper- and titlecase characters may only
487.2399 - follow uncased characters and lowercase characters only cased ones.
487.2400 - Return False otherwise.
487.2401 -
487.2402 -<br><br>
487.2403 -<a href="meth:isupper()">isupper()</a>
487.2404 -
487.2405 -<br><br>
487.2406 - S.isupper() -> bool
487.2407 -
487.2408 -<br><br>
487.2409 - Return True if all cased characters in S are uppercase and there is
487.2410 - at least one cased character in S, False otherwise.
487.2411 -
487.2412 -<br><br>
487.2413 -<a href="meth:join(sequence)">join(sequence)</a>
487.2414 -
487.2415 -<br><br>
487.2416 - S.join(sequence) -> unicode
487.2417 -
487.2418 -<br><br>
487.2419 - Return a string which is the concatenation of the strings in the
487.2420 - sequence. The separator between elements is S.
487.2421 -
487.2422 -<br><br>
487.2423 -<a href="meth:ljust(width)">ljust(width)</a>
487.2424 -
487.2425 -<br><br>
487.2426 - S.ljust(width[, fillchar]) -> int
487.2427 -
487.2428 -<br><br>
487.2429 - Return S left justified in a Unicode string of length width. Padding is
487.2430 - done using the specified fill character (default is a space).
487.2431 -
487.2432 -<br><br>
487.2433 -<a href="meth:lower()">lower()</a>
487.2434 -
487.2435 -<br><br>
487.2436 - S.lower() -> unicode
487.2437 -
487.2438 -<br><br>
487.2439 - Return a copy of the string S converted to lowercase.
487.2440 -
487.2441 -<br><br>
487.2442 -<a href="meth:lstrip()">lstrip()</a>
487.2443 -
487.2444 -<br><br>
487.2445 - S.lstrip([chars]) -> unicode
487.2446 -
487.2447 -<br><br>
487.2448 - Return a copy of the string S with leading whitespace removed.
487.2449 - If chars is given and not None, remove characters in chars instead.
487.2450 - If chars is a str, it will be converted to unicode before stripping
487.2451 -
487.2452 -<br><br>
487.2453 -<a href="meth:partition(sep)">partition(sep)</a>
487.2454 -
487.2455 -<br><br>
487.2456 - S.partition(sep) -> (head, sep, tail)
487.2457 -
487.2458 -<br><br>
487.2459 - Searches for the separator sep in S, and returns the part before it,
487.2460 - the separator itself, and the part after it. If the separator is not
487.2461 - found, returns S and two empty strings.
487.2462 -
487.2463 -<br><br>
487.2464 -<a href="meth:replace(old, new)">replace(old, new)</a>
487.2465 -
487.2466 -<br><br>
487.2467 - S.replace (old, new[, count]) -> unicode
487.2468 -
487.2469 -<br><br>
487.2470 - Return a copy of S with all occurrences of substring
487.2471 - old replaced by new. If the optional argument count is
487.2472 - given, only the first count occurrences are replaced.
487.2473 -
487.2474 -<br><br>
487.2475 -<a href="meth:rfind(sub )">rfind(sub )</a>
487.2476 -
487.2477 -<br><br>
487.2478 - S.rfind(sub [,start [,end]]) -> int
487.2479 -
487.2480 -<br><br>
487.2481 - Return the highest index in S where substring sub is found,
487.2482 - such that sub is contained within s[start:end]. Optional
487.2483 - arguments start and end are interpreted as in slice notation.
487.2484 -
487.2485 -<br><br>
487.2486 - Return -1 on failure.
487.2487 -
487.2488 -<br><br>
487.2489 -<a href="meth:rindex(sub )">rindex(sub )</a>
487.2490 -
487.2491 -<br><br>
487.2492 - S.rindex(sub [,start [,end]]) -> int
487.2493 -
487.2494 -<br><br>
487.2495 - Like S.rfind() but raise ValueError when the substring is not found.
487.2496 -
487.2497 -<br><br>
487.2498 -<a href="meth:rjust(width)">rjust(width)</a>
487.2499 -
487.2500 -<br><br>
487.2501 - S.rjust(width[, fillchar]) -> unicode
487.2502 -
487.2503 -<br><br>
487.2504 - Return S right justified in a Unicode string of length width. Padding is
487.2505 - done using the specified fill character (default is a space).
487.2506 -
487.2507 -<br><br>
487.2508 -<a href="meth:rpartition(sep)">rpartition(sep)</a>
487.2509 -
487.2510 -<br><br>
487.2511 - S.rpartition(sep) -> (tail, sep, head)
487.2512 -
487.2513 -<br><br>
487.2514 - Searches for the separator sep in S, starting at the end of S, and returns
487.2515 - the part before it, the separator itself, and the part after it. If the
487.2516 - separator is not found, returns two empty strings and S.
487.2517 -
487.2518 -<br><br>
487.2519 -<a href="meth:rsplit()">rsplit()</a>
487.2520 -
487.2521 -<br><br>
487.2522 - S.rsplit([sep [,maxsplit]]) -> list of strings
487.2523 -
487.2524 -<br><br>
487.2525 - Return a list of the words in S, using sep as the
487.2526 - delimiter string, starting at the end of the string and
487.2527 - working to the front. If maxsplit is given, at most maxsplit
487.2528 - splits are done. If sep is not specified, any whitespace string
487.2529 - is a separator.
487.2530 -
487.2531 -<br><br>
487.2532 -<a href="meth:rstrip()">rstrip()</a>
487.2533 -
487.2534 -<br><br>
487.2535 - S.rstrip([chars]) -> unicode
487.2536 -
487.2537 -<br><br>
487.2538 - Return a copy of the string S with trailing whitespace removed.
487.2539 - If chars is given and not None, remove characters in chars instead.
487.2540 - If chars is a str, it will be converted to unicode before stripping
487.2541 -
487.2542 -<br><br>
487.2543 -<a href="meth:split()">split()</a>
487.2544 -
487.2545 -<br><br>
487.2546 - S.split([sep [,maxsplit]]) -> list of strings
487.2547 -
487.2548 -<br><br>
487.2549 - Return a list of the words in S, using sep as the
487.2550 - delimiter string. If maxsplit is given, at most maxsplit
487.2551 - splits are done. If sep is not specified or is None, any
487.2552 - whitespace string is a separator and empty strings are
487.2553 - removed from the result.
487.2554 -
487.2555 -<br><br>
487.2556 -<a href="meth:splitlines()">splitlines()</a>
487.2557 -
487.2558 -<br><br>
487.2559 - S.splitlines([keepends]]) -> list of strings
487.2560 -
487.2561 -<br><br>
487.2562 - Return a list of the lines in S, breaking at line boundaries.
487.2563 - Line breaks are not included in the resulting list unless keepends
487.2564 - is given and true.
487.2565 -
487.2566 -<br><br>
487.2567 -<a href="meth:startswith(prefix)">startswith(prefix)</a>
487.2568 -
487.2569 -<br><br>
487.2570 - S.startswith(prefix[, start[, end]]) -> bool
487.2571 -
487.2572 -<br><br>
487.2573 - Return True if S starts with the specified prefix, False otherwise.
487.2574 - With optional start, test S beginning at that position.
487.2575 - With optional end, stop comparing S at that position.
487.2576 - prefix can also be a tuple of strings to try.
487.2577 -
487.2578 -<br><br>
487.2579 -<a href="meth:strip()">strip()</a>
487.2580 -
487.2581 -<br><br>
487.2582 - S.strip([chars]) -> unicode
487.2583 -
487.2584 -<br><br>
487.2585 - Return a copy of the string S with leading and trailing
487.2586 - whitespace removed.
487.2587 - If chars is given and not None, remove characters in chars instead.
487.2588 - If chars is a str, it will be converted to unicode before stripping
487.2589 -
487.2590 -<br><br>
487.2591 -<a href="meth:swapcase()">swapcase()</a>
487.2592 -
487.2593 -<br><br>
487.2594 - S.swapcase() -> unicode
487.2595 -
487.2596 -<br><br>
487.2597 - Return a copy of S with uppercase characters converted to lowercase
487.2598 - and vice versa.
487.2599 -
487.2600 -<br><br>
487.2601 -<a href="meth:title()">title()</a>
487.2602 -
487.2603 -<br><br>
487.2604 - S.title() -> unicode
487.2605 -
487.2606 -<br><br>
487.2607 - Return a titlecased version of S, i.e. words start with title case
487.2608 - characters, all remaining cased characters have lower case.
487.2609 -
487.2610 -<br><br>
487.2611 -<a href="meth:translate(table)">translate(table)</a>
487.2612 -
487.2613 -<br><br>
487.2614 - S.translate(table) -> unicode
487.2615 -
487.2616 -<br><br>
487.2617 - Return a copy of the string S, where all characters have been mapped
487.2618 - through the given translation table, which must be a mapping of
487.2619 - Unicode ordinals to Unicode ordinals, Unicode strings or None.
487.2620 - Unmapped characters are left untouched. Characters mapped to None
487.2621 - are deleted.
487.2622 -
487.2623 -<br><br>
487.2624 -<a href="meth:upper()">upper()</a>
487.2625 -
487.2626 -<br><br>
487.2627 - S.upper() -> unicode
487.2628 -
487.2629 -<br><br>
487.2630 - Return a copy of S converted to uppercase.
487.2631 -
487.2632 -<br><br>
487.2633 -<a href="meth:zfill(width)">zfill(width)</a>
487.2634 -
487.2635 -<br><br>
487.2636 - S.zfill(width) -> unicode
487.2637 -
487.2638 -<br><br>
487.2639 - Pad a numeric string S with zeros on the left, to fill a field
487.2640 - of the specified width. The string S is never truncated.
487.2641 -</body></html>
488.1 --- a/python.editor/test/unit/data/testfiles/rst/stub_missing.rst.indexed Sun Jan 04 13:11:53 2015 -0600
488.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
488.3 @@ -1,486 +0,0 @@
488.4 -
488.5 -
488.6 -Document 0
488.7 -Searchable Keys:
488.8 - class : bool
488.9 - class-ig : bool
488.10 - in : stub_missing
488.11 - member : __abs__;F;|DOCUMENTED|DOC_ONLY|;;
488.12 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;y;
488.13 - member : __and__;F;|DOCUMENTED|DOC_ONLY|;y;
488.14 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
488.15 - member : __cmp__;F;|DOCUMENTED|DOC_ONLY|;y;
488.16 - member : __coerce__;F;|DOCUMENTED|DOC_ONLY|;y;
488.17 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
488.18 - member : __div__;F;|DOCUMENTED|DOC_ONLY|;y;
488.19 - member : __divmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.20 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
488.21 - member : __float__;F;|DOCUMENTED|DOC_ONLY|;;
488.22 - member : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.23 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
488.24 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
488.25 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
488.26 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
488.27 - member : __hex__;F;|DOCUMENTED|DOC_ONLY|;;
488.28 - member : __index__;F;|DOCUMENTED|DOC_ONLY|;;
488.29 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
488.30 - member : __int__;F;|DOCUMENTED|DOC_ONLY|;;
488.31 - member : __invert__;F;|DOCUMENTED|DOC_ONLY|;;
488.32 - member : __long__;F;|DOCUMENTED|DOC_ONLY|;;
488.33 - member : __lshift__;F;|DOCUMENTED|DOC_ONLY|;y;
488.34 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.35 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;y;
488.36 - member : __neg__;F;|DOCUMENTED|DOC_ONLY|;;
488.37 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
488.38 - member : __nonzero__;F;|DOCUMENTED|DOC_ONLY|;;
488.39 - member : __oct__;F;|DOCUMENTED|DOC_ONLY|;;
488.40 - member : __or__;F;|DOCUMENTED|DOC_ONLY|;y;
488.41 - member : __pos__;F;|DOCUMENTED|DOC_ONLY|;;
488.42 - member : __pow__;F;|DOCUMENTED|DOC_ONLY|;y;
488.43 - member : __radd__;F;|DOCUMENTED|DOC_ONLY|;y;
488.44 - member : __rand__;F;|DOCUMENTED|DOC_ONLY|;y;
488.45 - member : __rdiv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.46 - member : __rdivmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.47 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
488.48 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
488.49 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
488.50 - member : __rfloordiv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.51 - member : __rlshift__;F;|DOCUMENTED|DOC_ONLY|;y;
488.52 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.53 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;y;
488.54 - member : __ror__;F;|DOCUMENTED|DOC_ONLY|;y;
488.55 - member : __rpow__;F;|DOCUMENTED|DOC_ONLY|;x;
488.56 - member : __rrshift__;F;|DOCUMENTED|DOC_ONLY|;y;
488.57 - member : __rshift__;F;|DOCUMENTED|DOC_ONLY|;y;
488.58 - member : __rsub__;F;|DOCUMENTED|DOC_ONLY|;y;
488.59 - member : __rtruediv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.60 - member : __rxor__;F;|DOCUMENTED|DOC_ONLY|;y;
488.61 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
488.62 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
488.63 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
488.64 - member : __sub__;F;|DOCUMENTED|DOC_ONLY|;y;
488.65 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
488.66 - member : __truediv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.67 - member : __trunc__;F;|DOCUMENTED|DOC_ONLY|;;
488.68 - member : __xor__;F;|DOCUMENTED|DOC_ONLY|;y;
488.69 - member : conjugate;F;|DOCUMENTED|DOC_ONLY|;;
488.70 - member : denominator;A;|DOCUMENTED|DOC_ONLY|;
488.71 - member : imag;A;|DOCUMENTED|DOC_ONLY|;
488.72 - member : numerator;A;|DOCUMENTED|DOC_ONLY|;
488.73 - member : real;A;|DOCUMENTED|DOC_ONLY|;
488.74 -
488.75 -Not Searchable Keys:
488.76 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
488.77 -
488.78 -
488.79 -Document 1
488.80 -Searchable Keys:
488.81 - class : complex
488.82 - class-ig : complex
488.83 - in : stub_missing
488.84 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
488.85 - member : __coerce__;F;|DOCUMENTED|DOC_ONLY|;y;
488.86 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
488.87 - member : __divmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.88 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
488.89 - member : __float__;F;|DOCUMENTED|DOC_ONLY|;;
488.90 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
488.91 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
488.92 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
488.93 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
488.94 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
488.95 - member : __int__;F;|DOCUMENTED|DOC_ONLY|;;
488.96 - member : __long__;F;|DOCUMENTED|DOC_ONLY|;;
488.97 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
488.98 - member : __nonzero__;F;|DOCUMENTED|DOC_ONLY|;;
488.99 - member : __radd__;F;|DOCUMENTED|DOC_ONLY|;y;
488.100 - member : __rdiv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.101 - member : __rdivmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.102 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
488.103 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
488.104 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
488.105 - member : __rfloordiv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.106 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.107 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;y;
488.108 - member : __rpow__;F;|DOCUMENTED|DOC_ONLY|;x;
488.109 - member : __rsub__;F;|DOCUMENTED|DOC_ONLY|;y;
488.110 - member : __rtruediv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.111 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
488.112 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
488.113 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
488.114 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
488.115 - member : conjugate;F;|DOCUMENTED|DOC_ONLY|;;
488.116 - member : imag;A;|DOCUMENTED|DOC_ONLY|;
488.117 - member : real;A;|DOCUMENTED|DOC_ONLY|;
488.118 -
488.119 -Not Searchable Keys:
488.120 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
488.121 -
488.122 -
488.123 -Document 2
488.124 -Searchable Keys:
488.125 - class : dict
488.126 - class-ig : dict
488.127 - in : stub_missing
488.128 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
488.129 - member : __cmp__;F;|DOCUMENTED|DOC_ONLY|;y;
488.130 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
488.131 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
488.132 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
488.133 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
488.134 - member : __hash__;A;|DOCUMENTED|DOC_ONLY|;
488.135 - member : __iter__;F;|DOCUMENTED|DOC_ONLY|;;
488.136 - member : __len__;F;|DOCUMENTED|DOC_ONLY|;;
488.137 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
488.138 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
488.139 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
488.140 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
488.141 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
488.142 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
488.143 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
488.144 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
488.145 -
488.146 -Not Searchable Keys:
488.147 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
488.148 -
488.149 -
488.150 -Document 3
488.151 -Searchable Keys:
488.152 - class : float
488.153 - class-ig : float
488.154 - in : stub_missing
488.155 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
488.156 - member : __coerce__;F;|DOCUMENTED|DOC_ONLY|;y;
488.157 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
488.158 - member : __divmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.159 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
488.160 - member : __float__;F;|DOCUMENTED|DOC_ONLY|;;
488.161 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;format_spec;
488.162 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
488.163 - member : __getformat__;F;|DOCUMENTED|DOC_ONLY|;typestr;
488.164 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
488.165 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
488.166 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
488.167 - member : __int__;F;|DOCUMENTED|DOC_ONLY|;;
488.168 - member : __long__;F;|DOCUMENTED|DOC_ONLY|;;
488.169 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
488.170 - member : __nonzero__;F;|DOCUMENTED|DOC_ONLY|;;
488.171 - member : __radd__;F;|DOCUMENTED|DOC_ONLY|;y;
488.172 - member : __rdiv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.173 - member : __rdivmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.174 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
488.175 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
488.176 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
488.177 - member : __rfloordiv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.178 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.179 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;y;
488.180 - member : __rpow__;F;|DOCUMENTED|DOC_ONLY|;x;
488.181 - member : __rsub__;F;|DOCUMENTED|DOC_ONLY|;y;
488.182 - member : __rtruediv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.183 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
488.184 - member : __setformat__;F;|DOCUMENTED|DOC_ONLY|;typestr,fmt;
488.185 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
488.186 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
488.187 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
488.188 - member : __trunc__;F;|DOCUMENTED|DOC_ONLY|;;
488.189 - member : conjugate;F;|DOCUMENTED|DOC_ONLY|;;
488.190 - member : imag;A;|DOCUMENTED|DOC_ONLY|;
488.191 - member : is_integer;F;|DOCUMENTED|DOC_ONLY|;;
488.192 - member : real;A;|DOCUMENTED|DOC_ONLY|;
488.193 -
488.194 -Not Searchable Keys:
488.195 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
488.196 -
488.197 -
488.198 -Document 4
488.199 -Searchable Keys:
488.200 - class : int
488.201 - class-ig : int
488.202 - in : stub_missing
488.203 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
488.204 - member : __cmp__;F;|DOCUMENTED|DOC_ONLY|;y;
488.205 - member : __coerce__;F;|DOCUMENTED|DOC_ONLY|;y;
488.206 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
488.207 - member : __divmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.208 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
488.209 - member : __float__;F;|DOCUMENTED|DOC_ONLY|;;
488.210 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
488.211 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
488.212 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
488.213 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
488.214 - member : __hex__;F;|DOCUMENTED|DOC_ONLY|;;
488.215 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
488.216 - member : __int__;F;|DOCUMENTED|DOC_ONLY|;;
488.217 - member : __long__;F;|DOCUMENTED|DOC_ONLY|;;
488.218 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
488.219 - member : __nonzero__;F;|DOCUMENTED|DOC_ONLY|;;
488.220 - member : __oct__;F;|DOCUMENTED|DOC_ONLY|;;
488.221 - member : __radd__;F;|DOCUMENTED|DOC_ONLY|;y;
488.222 - member : __rand__;F;|DOCUMENTED|DOC_ONLY|;y;
488.223 - member : __rdiv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.224 - member : __rdivmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.225 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
488.226 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
488.227 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
488.228 - member : __rfloordiv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.229 - member : __rlshift__;F;|DOCUMENTED|DOC_ONLY|;y;
488.230 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.231 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;y;
488.232 - member : __ror__;F;|DOCUMENTED|DOC_ONLY|;y;
488.233 - member : __rpow__;F;|DOCUMENTED|DOC_ONLY|;x;
488.234 - member : __rrshift__;F;|DOCUMENTED|DOC_ONLY|;y;
488.235 - member : __rsub__;F;|DOCUMENTED|DOC_ONLY|;y;
488.236 - member : __rtruediv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.237 - member : __rxor__;F;|DOCUMENTED|DOC_ONLY|;y;
488.238 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
488.239 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
488.240 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
488.241 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
488.242 - member : __trunc__;F;|DOCUMENTED|DOC_ONLY|;;
488.243 - member : conjugate;F;|DOCUMENTED|DOC_ONLY|;;
488.244 - member : denominator;A;|DOCUMENTED|DOC_ONLY|;
488.245 - member : imag;A;|DOCUMENTED|DOC_ONLY|;
488.246 - member : numerator;A;|DOCUMENTED|DOC_ONLY|;
488.247 - member : real;A;|DOCUMENTED|DOC_ONLY|;
488.248 -
488.249 -Not Searchable Keys:
488.250 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
488.251 -
488.252 -
488.253 -Document 5
488.254 -Searchable Keys:
488.255 - class : list
488.256 - class-ig : list
488.257 - in : stub_missing
488.258 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
488.259 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
488.260 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
488.261 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
488.262 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
488.263 - member : __hash__;A;|DOCUMENTED|DOC_ONLY|;
488.264 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
488.265 - member : __iter__;F;|DOCUMENTED|DOC_ONLY|;;
488.266 - member : __len__;F;|DOCUMENTED|DOC_ONLY|;;
488.267 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
488.268 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
488.269 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
488.270 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
488.271 - member : __reversed__;F;|DOCUMENTED|DOC_ONLY|;;
488.272 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;n;
488.273 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
488.274 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
488.275 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
488.276 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
488.277 - member : append;F;|DOCUMENTED|DOC_ONLY|;;
488.278 - member : count;F;|DOCUMENTED|DOC_ONLY|;value;
488.279 - member : extend;F;|DOCUMENTED|DOC_ONLY|;;
488.280 - member : insert;F;|DOCUMENTED|DOC_ONLY|;;
488.281 - member : pop;F;|DOCUMENTED|DOC_ONLY|;;
488.282 - member : remove;F;|DOCUMENTED|DOC_ONLY|;;
488.283 - member : reverse;F;|DOCUMENTED|DOC_ONLY|;;
488.284 - member : sort;F;|DOCUMENTED|DOC_ONLY|;cmp,key,reverse;
488.285 -
488.286 -Not Searchable Keys:
488.287 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
488.288 -
488.289 -
488.290 -Document 6
488.291 -Searchable Keys:
488.292 - class : long
488.293 - class-ig : long
488.294 - in : stub_missing
488.295 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
488.296 - member : __cmp__;F;|DOCUMENTED|DOC_ONLY|;y;
488.297 - member : __coerce__;F;|DOCUMENTED|DOC_ONLY|;y;
488.298 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
488.299 - member : __divmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.300 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
488.301 - member : __float__;F;|DOCUMENTED|DOC_ONLY|;;
488.302 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
488.303 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
488.304 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
488.305 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
488.306 - member : __hex__;F;|DOCUMENTED|DOC_ONLY|;;
488.307 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
488.308 - member : __int__;F;|DOCUMENTED|DOC_ONLY|;;
488.309 - member : __long__;F;|DOCUMENTED|DOC_ONLY|;;
488.310 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
488.311 - member : __nonzero__;F;|DOCUMENTED|DOC_ONLY|;;
488.312 - member : __oct__;F;|DOCUMENTED|DOC_ONLY|;;
488.313 - member : __radd__;F;|DOCUMENTED|DOC_ONLY|;y;
488.314 - member : __rand__;F;|DOCUMENTED|DOC_ONLY|;y;
488.315 - member : __rdiv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.316 - member : __rdivmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.317 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
488.318 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
488.319 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
488.320 - member : __rfloordiv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.321 - member : __rlshift__;F;|DOCUMENTED|DOC_ONLY|;y;
488.322 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.323 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;y;
488.324 - member : __ror__;F;|DOCUMENTED|DOC_ONLY|;y;
488.325 - member : __rpow__;F;|DOCUMENTED|DOC_ONLY|;x;
488.326 - member : __rrshift__;F;|DOCUMENTED|DOC_ONLY|;y;
488.327 - member : __rsub__;F;|DOCUMENTED|DOC_ONLY|;y;
488.328 - member : __rtruediv__;F;|DOCUMENTED|DOC_ONLY|;y;
488.329 - member : __rxor__;F;|DOCUMENTED|DOC_ONLY|;y;
488.330 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
488.331 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
488.332 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
488.333 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
488.334 - member : __trunc__;F;|DOCUMENTED|DOC_ONLY|;;
488.335 - member : conjugate;F;|DOCUMENTED|DOC_ONLY|;;
488.336 - member : denominator;A;|DOCUMENTED|DOC_ONLY|;
488.337 - member : imag;A;|DOCUMENTED|DOC_ONLY|;
488.338 - member : numerator;A;|DOCUMENTED|DOC_ONLY|;
488.339 - member : real;A;|DOCUMENTED|DOC_ONLY|;
488.340 -
488.341 -Not Searchable Keys:
488.342 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
488.343 -
488.344 -
488.345 -Document 7
488.346 -Searchable Keys:
488.347 - class : str
488.348 - class-ig : str
488.349 - in : stub_missing
488.350 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
488.351 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
488.352 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
488.353 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;format_spec;
488.354 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
488.355 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
488.356 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
488.357 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
488.358 - member : __len__;F;|DOCUMENTED|DOC_ONLY|;;
488.359 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
488.360 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
488.361 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
488.362 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
488.363 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.364 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;n;
488.365 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
488.366 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
488.367 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
488.368 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
488.369 - member : _formatter_field_name_split;F;|DOCUMENTED|PRIVATE|DOC_ONLY|;;
488.370 - member : _formatter_parser;F;|DOCUMENTED|PRIVATE|DOC_ONLY|;;
488.371 -
488.372 -Not Searchable Keys:
488.373 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
488.374 -
488.375 -
488.376 -Document 8
488.377 -Searchable Keys:
488.378 - class : tuple
488.379 - class-ig : tuple
488.380 - in : stub_missing
488.381 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
488.382 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
488.383 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
488.384 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
488.385 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
488.386 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
488.387 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
488.388 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
488.389 - member : __iter__;F;|DOCUMENTED|DOC_ONLY|;;
488.390 - member : __len__;F;|DOCUMENTED|DOC_ONLY|;;
488.391 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
488.392 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
488.393 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
488.394 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
488.395 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;n;
488.396 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
488.397 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
488.398 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
488.399 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
488.400 - member : count;F;|DOCUMENTED|DOC_ONLY|;value;
488.401 -
488.402 -Not Searchable Keys:
488.403 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
488.404 -
488.405 -
488.406 -Document 9
488.407 -Searchable Keys:
488.408 - class : unicode
488.409 - class-ig : unicode
488.410 - in : stub_missing
488.411 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
488.412 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
488.413 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
488.414 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;format_spec;
488.415 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
488.416 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
488.417 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
488.418 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
488.419 - member : __len__;F;|DOCUMENTED|DOC_ONLY|;;
488.420 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
488.421 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
488.422 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
488.423 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
488.424 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
488.425 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;n;
488.426 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
488.427 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
488.428 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
488.429 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
488.430 - member : _formatter_field_name_split;F;|DOCUMENTED|PRIVATE|DOC_ONLY|;;
488.431 - member : _formatter_parser;F;|DOCUMENTED|PRIVATE|DOC_ONLY|;;
488.432 - member : capitalize;F;|DOCUMENTED|DOC_ONLY|;;
488.433 - member : center;F;|DOCUMENTED|DOC_ONLY|;width;
488.434 - member : count;F;|DOCUMENTED|DOC_ONLY|;sub;
488.435 - member : decode;F;|DOCUMENTED|DOC_ONLY|;;
488.436 - member : encode;F;|DOCUMENTED|DOC_ONLY|;;
488.437 - member : endswith;F;|DOCUMENTED|DOC_ONLY|;suffix;
488.438 - member : expandtabs;F;|DOCUMENTED|DOC_ONLY|;;
488.439 - member : find;F;|DOCUMENTED|DOC_ONLY|;sub;
488.440 - member : format;F;|DOCUMENTED|DOC_ONLY|;*args,**kwargs;
488.441 - member : isalnum;F;|DOCUMENTED|DOC_ONLY|;;
488.442 - member : isalpha;F;|DOCUMENTED|DOC_ONLY|;;
488.443 - member : isdigit;F;|DOCUMENTED|DOC_ONLY|;;
488.444 - member : islower;F;|DOCUMENTED|DOC_ONLY|;;
488.445 - member : isspace;F;|DOCUMENTED|DOC_ONLY|;;
488.446 - member : istitle;F;|DOCUMENTED|DOC_ONLY|;;
488.447 - member : isupper;F;|DOCUMENTED|DOC_ONLY|;;
488.448 - member : join;F;|DOCUMENTED|DOC_ONLY|;sequence;
488.449 - member : ljust;F;|DOCUMENTED|DOC_ONLY|;width;
488.450 - member : lower;F;|DOCUMENTED|DOC_ONLY|;;
488.451 - member : lstrip;F;|DOCUMENTED|DOC_ONLY|;;
488.452 - member : partition;F;|DOCUMENTED|DOC_ONLY|;sep;
488.453 - member : replace;F;|DOCUMENTED|DOC_ONLY|;old,new;
488.454 - member : rfind;F;|DOCUMENTED|DOC_ONLY|;sub;
488.455 - member : rindex;F;|DOCUMENTED|DOC_ONLY|;sub;
488.456 - member : rjust;F;|DOCUMENTED|DOC_ONLY|;width;
488.457 - member : rpartition;F;|DOCUMENTED|DOC_ONLY|;sep;
488.458 - member : rsplit;F;|DOCUMENTED|DOC_ONLY|;;
488.459 - member : rstrip;F;|DOCUMENTED|DOC_ONLY|;;
488.460 - member : split;F;|DOCUMENTED|DOC_ONLY|;;
488.461 - member : splitlines;F;|DOCUMENTED|DOC_ONLY|;;
488.462 - member : startswith;F;|DOCUMENTED|DOC_ONLY|;prefix;
488.463 - member : strip;F;|DOCUMENTED|DOC_ONLY|;;
488.464 - member : swapcase;F;|DOCUMENTED|DOC_ONLY|;;
488.465 - member : title;F;|DOCUMENTED|DOC_ONLY|;;
488.466 - member : translate;F;|DOCUMENTED|DOC_ONLY|;table;
488.467 - member : upper;F;|DOCUMENTED|DOC_ONLY|;;
488.468 - member : zfill;F;|DOCUMENTED|DOC_ONLY|;width;
488.469 -
488.470 -Not Searchable Keys:
488.471 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
488.472 -
488.473 -
488.474 -Document 10
488.475 -Searchable Keys:
488.476 - item : bool;C;|DOCUMENTED|DOC_ONLY|;
488.477 - item : complex;C;|DOCUMENTED|DOC_ONLY|;
488.478 - item : dict;C;|DOCUMENTED|DOC_ONLY|;
488.479 - item : float;C;|DOCUMENTED|DOC_ONLY|;
488.480 - item : int;C;|DOCUMENTED|DOC_ONLY|;
488.481 - item : list;C;|DOCUMENTED|DOC_ONLY|;
488.482 - item : long;C;|DOCUMENTED|DOC_ONLY|;
488.483 - item : str;C;|DOCUMENTED|DOC_ONLY|;
488.484 - item : tuple;C;|DOCUMENTED|DOC_ONLY|;
488.485 - item : unicode;C;|DOCUMENTED|DOC_ONLY|;
488.486 - module : stub_missing
488.487 -
488.488 -Not Searchable Keys:
488.489 - modattrs : S
489.1 --- a/python.editor/test/unit/data/testfiles/rst/zipfile.rst Sun Jan 04 13:11:53 2015 -0600
489.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
489.3 @@ -1,451 +0,0 @@
489.4 -
489.5 -:mod:`zipfile` --- Work with ZIP archives
489.6 -=========================================
489.7 -
489.8 -.. module:: zipfile
489.9 - :synopsis: Read and write ZIP-format archive files.
489.10 -.. moduleauthor:: James C. Ahlstrom <jim@interet.com>
489.11 -.. sectionauthor:: James C. Ahlstrom <jim@interet.com>
489.12 -
489.13 -.. versionadded:: 1.6
489.14 -
489.15 -The ZIP file format is a common archive and compression standard. This module
489.16 -provides tools to create, read, write, append, and list a ZIP file. Any
489.17 -advanced use of this module will require an understanding of the format, as
489.18 -defined in `PKZIP Application Note
489.19 -<http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_.
489.20 -
489.21 -This module does not currently handle multi-disk ZIP files, or ZIP files
489.22 -which have appended comments (although it correctly handles comments
489.23 -added to individual archive members---for which see the :ref:`zipinfo-objects`
489.24 -documentation). It can handle ZIP files that use the ZIP64 extensions
489.25 -(that is ZIP files that are more than 4 GByte in size). It supports
489.26 -decryption of encrypted files in ZIP archives, but it currently cannot
489.27 -create an encrypted file. Decryption is extremely slow as it is
489.28 -implemented in native python rather than C.
489.29 -
489.30 -For other archive formats, see the :mod:`bz2`, :mod:`gzip`, and
489.31 -:mod:`tarfile` modules.
489.32 -
489.33 -The module defines the following items:
489.34 -
489.35 -.. exception:: BadZipfile
489.36 -
489.37 - The error raised for bad ZIP files (old name: ``zipfile.error``).
489.38 -
489.39 -
489.40 -.. exception:: LargeZipFile
489.41 -
489.42 - The error raised when a ZIP file would require ZIP64 functionality but that has
489.43 - not been enabled.
489.44 -
489.45 -
489.46 -.. class:: ZipFile
489.47 -
489.48 - The class for reading and writing ZIP files. See section
489.49 - :ref:`zipfile-objects` for constructor details.
489.50 -
489.51 -
489.52 -.. class:: PyZipFile
489.53 -
489.54 - Class for creating ZIP archives containing Python libraries.
489.55 -
489.56 -
489.57 -.. class:: ZipInfo([filename[, date_time]])
489.58 -
489.59 - Class used to represent information about a member of an archive. Instances
489.60 - of this class are returned by the :meth:`getinfo` and :meth:`infolist`
489.61 - methods of :class:`ZipFile` objects. Most users of the :mod:`zipfile` module
489.62 - will not need to create these, but only use those created by this
489.63 - module. *filename* should be the full name of the archive member, and
489.64 - *date_time* should be a tuple containing six fields which describe the time
489.65 - of the last modification to the file; the fields are described in section
489.66 - :ref:`zipinfo-objects`.
489.67 -
489.68 -
489.69 -.. function:: is_zipfile(filename)
489.70 -
489.71 - Returns ``True`` if *filename* is a valid ZIP file based on its magic number,
489.72 - otherwise returns ``False``. This module does not currently handle ZIP files
489.73 - which have appended comments.
489.74 -
489.75 -
489.76 -.. data:: ZIP_STORED
489.77 -
489.78 - The numeric constant for an uncompressed archive member.
489.79 -
489.80 -
489.81 -.. data:: ZIP_DEFLATED
489.82 -
489.83 - The numeric constant for the usual ZIP compression method. This requires the
489.84 - zlib module. No other compression methods are currently supported.
489.85 -
489.86 -
489.87 -.. seealso::
489.88 -
489.89 - `PKZIP Application Note <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_
489.90 - Documentation on the ZIP file format by Phil Katz, the creator of the format and
489.91 - algorithms used.
489.92 -
489.93 - `Info-ZIP Home Page <http://www.info-zip.org/>`_
489.94 - Information about the Info-ZIP project's ZIP archive programs and development
489.95 - libraries.
489.96 -
489.97 -
489.98 -.. _zipfile-objects:
489.99 -
489.100 -ZipFile Objects
489.101 ----------------
489.102 -
489.103 -
489.104 -.. class:: ZipFile(file[, mode[, compression[, allowZip64]]])
489.105 -
489.106 - Open a ZIP file, where *file* can be either a path to a file (a string) or a
489.107 - file-like object. The *mode* parameter should be ``'r'`` to read an existing
489.108 - file, ``'w'`` to truncate and write a new file, or ``'a'`` to append to an
489.109 - existing file. If *mode* is ``'a'`` and *file* refers to an existing ZIP file,
489.110 - then additional files are added to it. If *file* does not refer to a ZIP file,
489.111 - then a new ZIP archive is appended to the file. This is meant for adding a ZIP
489.112 - archive to another file, such as :file:`python.exe`. Using ::
489.113 -
489.114 - cat myzip.zip >> python.exe
489.115 -
489.116 - also works, and at least :program:`WinZip` can read such files. If *mode* is
489.117 - ``a`` and the file does not exist at all, it is created. *compression* is the
489.118 - ZIP compression method to use when writing the archive, and should be
489.119 - :const:`ZIP_STORED` or :const:`ZIP_DEFLATED`; unrecognized values will cause
489.120 - :exc:`RuntimeError` to be raised. If :const:`ZIP_DEFLATED` is specified but the
489.121 - :mod:`zlib` module is not available, :exc:`RuntimeError` is also raised. The
489.122 - default is :const:`ZIP_STORED`. If *allowZip64* is ``True`` zipfile will create
489.123 - ZIP files that use the ZIP64 extensions when the zipfile is larger than 2 GB. If
489.124 - it is false (the default) :mod:`zipfile` will raise an exception when the ZIP
489.125 - file would require ZIP64 extensions. ZIP64 extensions are disabled by default
489.126 - because the default :program:`zip` and :program:`unzip` commands on Unix (the
489.127 - InfoZIP utilities) don't support these extensions.
489.128 -
489.129 - .. versionchanged:: 2.6
489.130 - If the file does not exist, it is created if the mode is 'a'.
489.131 -
489.132 -
489.133 -.. method:: ZipFile.close()
489.134 -
489.135 - Close the archive file. You must call :meth:`close` before exiting your program
489.136 - or essential records will not be written.
489.137 -
489.138 -
489.139 -.. method:: ZipFile.getinfo(name)
489.140 -
489.141 - Return a :class:`ZipInfo` object with information about the archive member
489.142 - *name*. Calling :meth:`getinfo` for a name not currently contained in the
489.143 - archive will raise a :exc:`KeyError`.
489.144 -
489.145 -
489.146 -.. method:: ZipFile.infolist()
489.147 -
489.148 - Return a list containing a :class:`ZipInfo` object for each member of the
489.149 - archive. The objects are in the same order as their entries in the actual ZIP
489.150 - file on disk if an existing archive was opened.
489.151 -
489.152 -
489.153 -.. method:: ZipFile.namelist()
489.154 -
489.155 - Return a list of archive members by name.
489.156 -
489.157 -
489.158 -.. method:: ZipFile.open(name[, mode[, pwd]])
489.159 -
489.160 - Extract a member from the archive as a file-like object (ZipExtFile). *name* is
489.161 - the name of the file in the archive, or a :class:`ZipInfo` object. The *mode*
489.162 - parameter, if included, must be one of the following: ``'r'`` (the default),
489.163 - ``'U'``, or ``'rU'``. Choosing ``'U'`` or ``'rU'`` will enable universal newline
489.164 - support in the read-only object. *pwd* is the password used for encrypted files.
489.165 - Calling :meth:`open` on a closed ZipFile will raise a :exc:`RuntimeError`.
489.166 -
489.167 - .. note::
489.168 -
489.169 - The file-like object is read-only and provides the following methods:
489.170 - :meth:`read`, :meth:`readline`, :meth:`readlines`, :meth:`__iter__`,
489.171 - :meth:`next`.
489.172 -
489.173 - .. note::
489.174 -
489.175 - If the ZipFile was created by passing in a file-like object as the first
489.176 - argument to the constructor, then the object returned by :meth:`.open` shares the
489.177 - ZipFile's file pointer. Under these circumstances, the object returned by
489.178 - :meth:`.open` should not be used after any additional operations are performed
489.179 - on the ZipFile object. If the ZipFile was created by passing in a string (the
489.180 - filename) as the first argument to the constructor, then :meth:`.open` will
489.181 - create a new file object that will be held by the ZipExtFile, allowing it to
489.182 - operate independently of the ZipFile.
489.183 -
489.184 - .. note::
489.185 -
489.186 - The :meth:`open`, :meth:`read` and :meth:`extract` methods can take a filename
489.187 - or a :class:`ZipInfo` object. You will appreciate this when trying to read a
489.188 - ZIP file that contains members with duplicate names.
489.189 -
489.190 - .. versionadded:: 2.6
489.191 -
489.192 -
489.193 -.. method:: ZipFile.extract(member[, path[, pwd]])
489.194 -
489.195 - Extract a member from the archive to the current working directory; *member*
489.196 - must be its full name or a :class:`ZipInfo` object). Its file information is
489.197 - extracted as accurately as possible. *path* specifies a different directory
489.198 - to extract to. *member* can be a filename or a :class:`ZipInfo` object.
489.199 - *pwd* is the password used for encrypted files.
489.200 -
489.201 - .. versionadded:: 2.6
489.202 -
489.203 -
489.204 -.. method:: ZipFile.extractall([path[, members[, pwd]]])
489.205 -
489.206 - Extract all members from the archive to the current working directory. *path*
489.207 - specifies a different directory to extract to. *members* is optional and must
489.208 - be a subset of the list returned by :meth:`namelist`. *pwd* is the password
489.209 - used for encrypted files.
489.210 -
489.211 - .. versionadded:: 2.6
489.212 -
489.213 -
489.214 -.. method:: ZipFile.printdir()
489.215 -
489.216 - Print a table of contents for the archive to ``sys.stdout``.
489.217 -
489.218 -
489.219 -.. method:: ZipFile.setpassword(pwd)
489.220 -
489.221 - Set *pwd* as default password to extract encrypted files.
489.222 -
489.223 - .. versionadded:: 2.6
489.224 -
489.225 -
489.226 -.. method:: ZipFile.read(name[, pwd])
489.227 -
489.228 - Return the bytes of the file *name* in the archive. *name* is the name of the
489.229 - file in the archive, or a :class:`ZipInfo` object. The archive must be open for
489.230 - read or append. *pwd* is the password used for encrypted files and, if specified,
489.231 - it will override the default password set with :meth:`setpassword`. Calling
489.232 - :meth:`read` on a closed ZipFile will raise a :exc:`RuntimeError`.
489.233 -
489.234 - .. versionchanged:: 2.6
489.235 - *pwd* was added, and *name* can now be a :class:`ZipInfo` object.
489.236 -
489.237 -
489.238 -.. method:: ZipFile.testzip()
489.239 -
489.240 - Read all the files in the archive and check their CRC's and file headers.
489.241 - Return the name of the first bad file, or else return ``None``. Calling
489.242 - :meth:`testzip` on a closed ZipFile will raise a :exc:`RuntimeError`.
489.243 -
489.244 -
489.245 -.. method:: ZipFile.write(filename[, arcname[, compress_type]])
489.246 -
489.247 - Write the file named *filename* to the archive, giving it the archive name
489.248 - *arcname* (by default, this will be the same as *filename*, but without a drive
489.249 - letter and with leading path separators removed). If given, *compress_type*
489.250 - overrides the value given for the *compression* parameter to the constructor for
489.251 - the new entry. The archive must be open with mode ``'w'`` or ``'a'`` -- calling
489.252 - :meth:`write` on a ZipFile created with mode ``'r'`` will raise a
489.253 - :exc:`RuntimeError`. Calling :meth:`write` on a closed ZipFile will raise a
489.254 - :exc:`RuntimeError`.
489.255 -
489.256 - .. note::
489.257 -
489.258 - There is no official file name encoding for ZIP files. If you have unicode file
489.259 - names, you must convert them to byte strings in your desired encoding before
489.260 - passing them to :meth:`write`. WinZip interprets all file names as encoded in
489.261 - CP437, also known as DOS Latin.
489.262 -
489.263 - .. note::
489.264 -
489.265 - Archive names should be relative to the archive root, that is, they should not
489.266 - start with a path separator.
489.267 -
489.268 - .. note::
489.269 -
489.270 - If ``arcname`` (or ``filename``, if ``arcname`` is not given) contains a null
489.271 - byte, the name of the file in the archive will be truncated at the null byte.
489.272 -
489.273 -
489.274 -.. method:: ZipFile.writestr(zinfo_or_arcname, bytes)
489.275 -
489.276 - Write the string *bytes* to the archive; *zinfo_or_arcname* is either the file
489.277 - name it will be given in the archive, or a :class:`ZipInfo` instance. If it's
489.278 - an instance, at least the filename, date, and time must be given. If it's a
489.279 - name, the date and time is set to the current date and time. The archive must be
489.280 - opened with mode ``'w'`` or ``'a'`` -- calling :meth:`writestr` on a ZipFile
489.281 - created with mode ``'r'`` will raise a :exc:`RuntimeError`. Calling
489.282 - :meth:`writestr` on a closed ZipFile will raise a :exc:`RuntimeError`.
489.283 -
489.284 - .. note::
489.285 -
489.286 - When passing a :class:`ZipInfo` instance as the *zinfo_or_acrname* parameter,
489.287 - the compression method used will be that specified in the *compress_type*
489.288 - member of the given :class:`ZipInfo` instance. By default, the
489.289 - :class:`ZipInfo` constructor sets this member to :const:`ZIP_STORED`.
489.290 -
489.291 -The following data attributes are also available:
489.292 -
489.293 -
489.294 -.. attribute:: ZipFile.debug
489.295 -
489.296 - The level of debug output to use. This may be set from ``0`` (the default, no
489.297 - output) to ``3`` (the most output). Debugging information is written to
489.298 - ``sys.stdout``.
489.299 -
489.300 -.. attribute:: ZipFile.comment
489.301 -
489.302 - The comment text associated with the ZIP file. If assigning a comment to a
489.303 - :class:`ZipFile` instance created with mode 'a' or 'w', this should be a
489.304 - string no longer than 65535 bytes. Comments longer than this will be
489.305 - truncated in the written archive when :meth:`ZipFile.close` is called.
489.306 -
489.307 -.. _pyzipfile-objects:
489.308 -
489.309 -PyZipFile Objects
489.310 ------------------
489.311 -
489.312 -The :class:`PyZipFile` constructor takes the same parameters as the
489.313 -:class:`ZipFile` constructor. Instances have one method in addition to those of
489.314 -:class:`ZipFile` objects.
489.315 -
489.316 -
489.317 -.. method:: PyZipFile.writepy(pathname[, basename])
489.318 -
489.319 - Search for files :file:`\*.py` and add the corresponding file to the archive.
489.320 - The corresponding file is a :file:`\*.pyo` file if available, else a
489.321 - :file:`\*.pyc` file, compiling if necessary. If the pathname is a file, the
489.322 - filename must end with :file:`.py`, and just the (corresponding
489.323 - :file:`\*.py[co]`) file is added at the top level (no path information). If the
489.324 - pathname is a file that does not end with :file:`.py`, a :exc:`RuntimeError`
489.325 - will be raised. If it is a directory, and the directory is not a package
489.326 - directory, then all the files :file:`\*.py[co]` are added at the top level. If
489.327 - the directory is a package directory, then all :file:`\*.py[co]` are added under
489.328 - the package name as a file path, and if any subdirectories are package
489.329 - directories, all of these are added recursively. *basename* is intended for
489.330 - internal use only. The :meth:`writepy` method makes archives with file names
489.331 - like this::
489.332 -
489.333 - string.pyc # Top level name
489.334 - test/__init__.pyc # Package directory
489.335 - test/test_support.pyc # Module test.test_support
489.336 - test/bogus/__init__.pyc # Subpackage directory
489.337 - test/bogus/myfile.pyc # Submodule test.bogus.myfile
489.338 -
489.339 -
489.340 -.. _zipinfo-objects:
489.341 -
489.342 -ZipInfo Objects
489.343 ----------------
489.344 -
489.345 -Instances of the :class:`ZipInfo` class are returned by the :meth:`getinfo` and
489.346 -:meth:`infolist` methods of :class:`ZipFile` objects. Each object stores
489.347 -information about a single member of the ZIP archive.
489.348 -
489.349 -Instances have the following attributes:
489.350 -
489.351 -
489.352 -.. attribute:: ZipInfo.filename
489.353 -
489.354 - Name of the file in the archive.
489.355 -
489.356 -
489.357 -.. attribute:: ZipInfo.date_time
489.358 -
489.359 - The time and date of the last modification to the archive member. This is a
489.360 - tuple of six values:
489.361 -
489.362 - +-------+--------------------------+
489.363 - | Index | Value |
489.364 - +=======+==========================+
489.365 - | ``0`` | Year |
489.366 - +-------+--------------------------+
489.367 - | ``1`` | Month (one-based) |
489.368 - +-------+--------------------------+
489.369 - | ``2`` | Day of month (one-based) |
489.370 - +-------+--------------------------+
489.371 - | ``3`` | Hours (zero-based) |
489.372 - +-------+--------------------------+
489.373 - | ``4`` | Minutes (zero-based) |
489.374 - +-------+--------------------------+
489.375 - | ``5`` | Seconds (zero-based) |
489.376 - +-------+--------------------------+
489.377 -
489.378 -
489.379 -.. attribute:: ZipInfo.compress_type
489.380 -
489.381 - Type of compression for the archive member.
489.382 -
489.383 -
489.384 -.. attribute:: ZipInfo.comment
489.385 -
489.386 - Comment for the individual archive member.
489.387 -
489.388 -
489.389 -.. attribute:: ZipInfo.extra
489.390 -
489.391 - Expansion field data. The `PKZIP Application Note
489.392 - <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_ contains
489.393 - some comments on the internal structure of the data contained in this string.
489.394 -
489.395 -
489.396 -.. attribute:: ZipInfo.create_system
489.397 -
489.398 - System which created ZIP archive.
489.399 -
489.400 -
489.401 -.. attribute:: ZipInfo.create_version
489.402 -
489.403 - PKZIP version which created ZIP archive.
489.404 -
489.405 -
489.406 -.. attribute:: ZipInfo.extract_version
489.407 -
489.408 - PKZIP version needed to extract archive.
489.409 -
489.410 -
489.411 -.. attribute:: ZipInfo.reserved
489.412 -
489.413 - Must be zero.
489.414 -
489.415 -
489.416 -.. attribute:: ZipInfo.flag_bits
489.417 -
489.418 - ZIP flag bits.
489.419 -
489.420 -
489.421 -.. attribute:: ZipInfo.volume
489.422 -
489.423 - Volume number of file header.
489.424 -
489.425 -
489.426 -.. attribute:: ZipInfo.internal_attr
489.427 -
489.428 - Internal attributes.
489.429 -
489.430 -
489.431 -.. attribute:: ZipInfo.external_attr
489.432 -
489.433 - External file attributes.
489.434 -
489.435 -
489.436 -.. attribute:: ZipInfo.header_offset
489.437 -
489.438 - Byte offset to the file header.
489.439 -
489.440 -
489.441 -.. attribute:: ZipInfo.CRC
489.442 -
489.443 - CRC-32 of the uncompressed file.
489.444 -
489.445 -
489.446 -.. attribute:: ZipInfo.compress_size
489.447 -
489.448 - Size of the compressed data.
489.449 -
489.450 -
489.451 -.. attribute:: ZipInfo.file_size
489.452 -
489.453 - Size of the uncompressed file.
489.454 -
490.1 --- a/python.editor/test/unit/data/testfiles/rst/zipfile.rst.html Sun Jan 04 13:11:53 2015 -0600
490.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
490.3 @@ -1,453 +0,0 @@
490.4 -<html><body>
490.5 -<h2><a href="mod:zipfile">zipfile</a> --- Work with ZIP archives
490.6 -</h2>
490.7 -<a href="module:zipfile">zipfile</a><br>
490.8 - Read and write ZIP-format archive files.
490.9 -<br>Module Author:</b> James C. Ahlstrom <jim@interet.com>
490.10 -<br>Section Author:</b> James C. Ahlstrom <jim@interet.com>
490.11 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 1.6
490.12 -</div>
490.13 -The ZIP file format is a common archive and compression standard. This module
490.14 -provides tools to create, read, write, append, and list a ZIP file. Any
490.15 -advanced use of this module will require an understanding of the format, as
490.16 -defined in `PKZIP Application Note
490.17 -<http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_.
490.18 -
490.19 -<br><br>
490.20 -This module does not currently handle multi-disk ZIP files, or ZIP files
490.21 -which have appended comments (although it correctly handles comments
490.22 -added to individual archive members---for which see the <code>zipinfo-objects</code>
490.23 -documentation). It can handle ZIP files that use the ZIP64 extensions
490.24 -(that is ZIP files that are more than 4 GByte in size). It supports
490.25 -decryption of encrypted files in ZIP archives, but it currently cannot
490.26 -create an encrypted file. Decryption is extremely slow as it is
490.27 -implemented in native python rather than C.
490.28 -
490.29 -<br><br>
490.30 -For other archive formats, see the <a href="mod:bz2">bz2</a>, <a href="mod:gzip">gzip</a>, and
490.31 -<a href="mod:tarfile">tarfile</a> modules.
490.32 -
490.33 -<br><br>
490.34 -The module defines the following items:
490.35 -
490.36 -<br><br>
490.37 -.. exception:: BadZipfile
490.38 -
490.39 -<br><br>
490.40 - The error raised for bad ZIP files (old name: <code>zipfile.error</code>).
490.41 -
490.42 -<br><br>
490.43 -.. exception:: LargeZipFile
490.44 -
490.45 -<br><br>
490.46 - The error raised when a ZIP file would require ZIP64 functionality but that has
490.47 - not been enabled.
490.48 -
490.49 -<br><br>
490.50 -<a href="class:ZipFile">ZipFile</a>
490.51 -
490.52 -<br><br>
490.53 - The class for reading and writing ZIP files. See section
490.54 - <code>zipfile-objects</code> for constructor details.
490.55 -
490.56 -<br><br>
490.57 -<a href="class:PyZipFile">PyZipFile</a>
490.58 -
490.59 -<br><br>
490.60 - Class for creating ZIP archives containing Python libraries.
490.61 -
490.62 -<br><br>
490.63 -<a href="class:ZipInfo([filename[, date_time]])">ZipInfo([filename[, date_time]])</a>
490.64 -
490.65 -<br><br>
490.66 - Class used to represent information about a member of an archive. Instances
490.67 - of this class are returned by the <a href="meth:getinfo">getinfo</a> and <a href="meth:infolist">infolist</a>
490.68 - methods of <a href="class:ZipFile">ZipFile</a> objects. Most users of the <a href="mod:zipfile">zipfile</a> module
490.69 - will not need to create these, but only use those created by this
490.70 - module. <b>filename</b> should be the full name of the archive member, and
490.71 - <b>date_time</b> should be a tuple containing six fields which describe the time
490.72 - of the last modification to the file; the fields are described in section
490.73 - <code>zipinfo-objects</code>.
490.74 -
490.75 -<br><br>
490.76 -<a href="func:is_zipfile(filename)">is_zipfile(filename)</a>
490.77 -
490.78 -<br><br>
490.79 - Returns <code>True</code> if <b>filename</b> is a valid ZIP file based on its magic number,
490.80 - otherwise returns <code>False</code>. This module does not currently handle ZIP files
490.81 - which have appended comments.
490.82 -
490.83 -<br><br>
490.84 -<a href="data:ZIP_STORED">ZIP_STORED</a>
490.85 -
490.86 -<br><br>
490.87 - The numeric constant for an uncompressed archive member.
490.88 -
490.89 -<br><br>
490.90 -<a href="data:ZIP_DEFLATED">ZIP_DEFLATED</a>
490.91 -
490.92 -<br><br>
490.93 - The numeric constant for the usual ZIP compression method. This requires the
490.94 - zlib module. No other compression methods are currently supported.
490.95 -<div style="margin: 5px 5px; background: #ddffdd; border-size: 1px; padding: 5px"><b>See Also</b>:
490.96 -
490.97 -<br><br>
490.98 - `PKZIP Application Note <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_
490.99 - Documentation on the ZIP file format by Phil Katz, the creator of the format and
490.100 - algorithms used.
490.101 -
490.102 -<br><br>
490.103 - `Info-ZIP Home Page <http://www.info-zip.org/>`_
490.104 - Information about the Info-ZIP project's ZIP archive programs and development
490.105 - libraries.
490.106 -</div>
490.107 -<h3>ZipFile Objects
490.108 -</h3>
490.109 -<a href="class:ZipFile(file[, mode[, compression[, allowZip64]]])">ZipFile(file[, mode[, compression[, allowZip64]]])</a>
490.110 -
490.111 -<br><br>
490.112 - Open a ZIP file, where <b>file</b> can be either a path to a file (a string) or a
490.113 - file-like object. The <b>mode</b> parameter should be <code>'r'</code> to read an existing
490.114 - file, <code>'w'</code> to truncate and write a new file, or <code>'a'</code> to append to an
490.115 - existing file. If <b>mode</b> is <code>'a'</code> and <b>file</b> refers to an existing ZIP file,
490.116 - then additional files are added to it. If <b>file</b> does not refer to a ZIP file,
490.117 - then a new ZIP archive is appended to the file. This is meant for adding a ZIP
490.118 - archive to another file, such as :file:`python.exe`. Using ::
490.119 -
490.120 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
490.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>
490.122 - also works, and at least :program:<code>WinZip</code> can read such files. If <b>mode</b> is
490.123 - <code>a</code> and the file does not exist at all, it is created. <b>compression</b> is the
490.124 - ZIP compression method to use when writing the archive, and should be
490.125 - :const:<code>ZIP_STORED</code> or :const:<code>ZIP_DEFLATED</code>; unrecognized values will cause
490.126 - <a href="exc:RuntimeError">RuntimeError</a> to be raised. If :const:<code>ZIP_DEFLATED</code> is specified but the
490.127 - <a href="mod:zlib">zlib</a> module is not available, <a href="exc:RuntimeError">RuntimeError</a> is also raised. The
490.128 - default is :const:<code>ZIP_STORED</code>. If <b>allowZip64</b> is <code>True</code> zipfile will create
490.129 - ZIP files that use the ZIP64 extensions when the zipfile is larger than 2 GB. If
490.130 - it is false (the default) <a href="mod:zipfile">zipfile</a> will raise an exception when the ZIP
490.131 - file would require ZIP64 extensions. ZIP64 extensions are disabled by default
490.132 - because the default :program:<code>zip</code> and :program:<code>unzip</code> commands on Unix (the
490.133 - InfoZIP utilities) don't support these extensions.
490.134 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
490.135 - If the file does not exist, it is created if the mode is 'a'.
490.136 -</div>
490.137 -<a href="meth:ZipFile.close()">ZipFile.close()</a>
490.138 - Close the archive file. You must call <a href="meth:close">close</a> before exiting your program
490.139 - or essential records will not be written.
490.140 -
490.141 -<br><br>
490.142 -<a href="meth:ZipFile.getinfo(name)">ZipFile.getinfo(name)</a>
490.143 -
490.144 -<br><br>
490.145 - Return a <a href="class:ZipInfo">ZipInfo</a> object with information about the archive member
490.146 - <b>name</b>. Calling <a href="meth:getinfo">getinfo</a> for a name not currently contained in the
490.147 - archive will raise a <a href="exc:KeyError">KeyError</a>.
490.148 -
490.149 -<br><br>
490.150 -<a href="meth:ZipFile.infolist()">ZipFile.infolist()</a>
490.151 -
490.152 -<br><br>
490.153 - Return a list containing a <a href="class:ZipInfo">ZipInfo</a> object for each member of the
490.154 - archive. The objects are in the same order as their entries in the actual ZIP
490.155 - file on disk if an existing archive was opened.
490.156 -
490.157 -<br><br>
490.158 -<a href="meth:ZipFile.namelist()">ZipFile.namelist()</a>
490.159 -
490.160 -<br><br>
490.161 - Return a list of archive members by name.
490.162 -
490.163 -<br><br>
490.164 -<a href="meth:ZipFile.open(name[, mode[, pwd]])">ZipFile.open(name[, mode[, pwd]])</a>
490.165 -
490.166 -<br><br>
490.167 - Extract a member from the archive as a file-like object (ZipExtFile). <b>name</b> is
490.168 - the name of the file in the archive, or a <a href="class:ZipInfo">ZipInfo</a> object. The <b>mode</b>
490.169 - parameter, if included, must be one of the following: <code>'r'</code> (the default),
490.170 - <code>'U'</code>, or <code>'rU'</code>. Choosing <code>'U'</code> or <code>'rU'</code> will enable universal newline
490.171 - support in the read-only object. <b>pwd</b> is the password used for encrypted files.
490.172 - Calling <a href="meth:open">open</a> on a closed ZipFile will raise a <a href="exc:RuntimeError">RuntimeError</a>.
490.173 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
490.174 -
490.175 -<br><br>
490.176 - The file-like object is read-only and provides the following methods:
490.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>,
490.178 - <a href="meth:next">next</a>.
490.179 -</div>
490.180 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
490.181 - If the ZipFile was created by passing in a file-like object as the first
490.182 - argument to the constructor, then the object returned by <a href="meth:.open">.open</a> shares the
490.183 - ZipFile's file pointer. Under these circumstances, the object returned by
490.184 - <a href="meth:.open">.open</a> should not be used after any additional operations are performed
490.185 - on the ZipFile object. If the ZipFile was created by passing in a string (the
490.186 - filename) as the first argument to the constructor, then <a href="meth:.open">.open</a> will
490.187 - create a new file object that will be held by the ZipExtFile, allowing it to
490.188 - operate independently of the ZipFile.
490.189 -</div>
490.190 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
490.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
490.192 - or a <a href="class:ZipInfo">ZipInfo</a> object. You will appreciate this when trying to read a
490.193 - ZIP file that contains members with duplicate names.
490.194 -</div>
490.195 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
490.196 -</div>
490.197 -<a href="meth:ZipFile.extract(member[, path[, pwd]])">ZipFile.extract(member[, path[, pwd]])</a>
490.198 - Extract a member from the archive to the current working directory; <b>member</b>
490.199 - must be its full name or a <a href="class:ZipInfo">ZipInfo</a> object). Its file information is
490.200 - extracted as accurately as possible. <b>path</b> specifies a different directory
490.201 - to extract to. <b>member</b> can be a filename or a <a href="class:ZipInfo">ZipInfo</a> object.
490.202 - <b>pwd</b> is the password used for encrypted files.
490.203 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
490.204 -</div>
490.205 -<a href="meth:ZipFile.extractall([path[, members[, pwd]]])">ZipFile.extractall([path[, members[, pwd]]])</a>
490.206 - Extract all members from the archive to the current working directory. <b>path</b>
490.207 - specifies a different directory to extract to. <b>members</b> is optional and must
490.208 - be a subset of the list returned by <a href="meth:namelist">namelist</a>. <b>pwd</b> is the password
490.209 - used for encrypted files.
490.210 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
490.211 -</div>
490.212 -<a href="meth:ZipFile.printdir()">ZipFile.printdir()</a>
490.213 - Print a table of contents for the archive to <code>sys.stdout</code>.
490.214 -
490.215 -<br><br>
490.216 -<a href="meth:ZipFile.setpassword(pwd)">ZipFile.setpassword(pwd)</a>
490.217 -
490.218 -<br><br>
490.219 - Set <b>pwd</b> as default password to extract encrypted files.
490.220 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
490.221 -</div>
490.222 -<a href="meth:ZipFile.read(name[, pwd])">ZipFile.read(name[, pwd])</a>
490.223 - Return the bytes of the file <b>name</b> in the archive. <b>name</b> is the name of the
490.224 - file in the archive, or a <a href="class:ZipInfo">ZipInfo</a> object. The archive must be open for
490.225 - read or append. <b>pwd</b> is the password used for encrypted files and, if specified,
490.226 - it will override the default password set with <a href="meth:setpassword">setpassword</a>. Calling
490.227 - <a href="meth:read">read</a> on a closed ZipFile will raise a <a href="exc:RuntimeError">RuntimeError</a>.
490.228 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
490.229 - <b>pwd</b> was added, and <b>name</b> can now be a <a href="class:ZipInfo">ZipInfo</a> object.
490.230 -</div>
490.231 -<a href="meth:ZipFile.testzip()">ZipFile.testzip()</a>
490.232 - Read all the files in the archive and check their CRC's and file headers.
490.233 - Return the name of the first bad file, or else return <code>None</code>. Calling
490.234 - <a href="meth:testzip">testzip</a> on a closed ZipFile will raise a <a href="exc:RuntimeError">RuntimeError</a>.
490.235 -
490.236 -<br><br>
490.237 -<a href="meth:ZipFile.write(filename[, arcname[, compress_type]])">ZipFile.write(filename[, arcname[, compress_type]])</a>
490.238 -
490.239 -<br><br>
490.240 - Write the file named <b>filename</b> to the archive, giving it the archive name
490.241 - <b>arcname</b> (by default, this will be the same as <b>filename</b>, but without a drive
490.242 - letter and with leading path separators removed). If given, <b>compress_type</b>
490.243 - overrides the value given for the <b>compression</b> parameter to the constructor for
490.244 - the new entry. The archive must be open with mode <code>'w'</code> or <code>'a'</code> -- calling
490.245 - <a href="meth:write">write</a> on a ZipFile created with mode <code>'r'</code> will raise a
490.246 - <a href="exc:RuntimeError">RuntimeError</a>. Calling <a href="meth:write">write</a> on a closed ZipFile will raise a
490.247 - <a href="exc:RuntimeError">RuntimeError</a>.
490.248 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
490.249 -
490.250 -<br><br>
490.251 - There is no official file name encoding for ZIP files. If you have unicode file
490.252 - names, you must convert them to byte strings in your desired encoding before
490.253 - passing them to <a href="meth:write">write</a>. WinZip interprets all file names as encoded in
490.254 - CP437, also known as DOS Latin.
490.255 -</div>
490.256 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
490.257 - Archive names should be relative to the archive root, that is, they should not
490.258 - start with a path separator.
490.259 -</div>
490.260 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
490.261 - If <code>arcname</code> (or <code>filename</code>, if <code>arcname</code> is not given) contains a null
490.262 - byte, the name of the file in the archive will be truncated at the null byte.
490.263 -</div>
490.264 -<a href="meth:ZipFile.writestr(zinfo_or_arcname, bytes)">ZipFile.writestr(zinfo_or_arcname, bytes)</a>
490.265 - Write the string <b>bytes</b> to the archive; <b>zinfo_or_arcname</b> is either the file
490.266 - name it will be given in the archive, or a <a href="class:ZipInfo">ZipInfo</a> instance. If it's
490.267 - an instance, at least the filename, date, and time must be given. If it's a
490.268 - name, the date and time is set to the current date and time. The archive must be
490.269 - opened with mode <code>'w'</code> or <code>'a'</code> -- calling <a href="meth:writestr">writestr</a> on a ZipFile
490.270 - created with mode <code>'r'</code> will raise a <a href="exc:RuntimeError">RuntimeError</a>. Calling
490.271 - <a href="meth:writestr">writestr</a> on a closed ZipFile will raise a <a href="exc:RuntimeError">RuntimeError</a>.
490.272 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
490.273 -
490.274 -<br><br>
490.275 - When passing a <a href="class:ZipInfo">ZipInfo</a> instance as the <b>zinfo_or_acrname</b> parameter,
490.276 - the compression method used will be that specified in the <b>compress_type</b>
490.277 - member of the given <a href="class:ZipInfo">ZipInfo</a> instance. By default, the
490.278 - <a href="class:ZipInfo">ZipInfo</a> constructor sets this member to :const:<code>ZIP_STORED</code>.
490.279 -</div>
490.280 -The following data attributes are also available:
490.281 -<a href="attr:ZipFile.debug">ZipFile.debug</a>
490.282 -
490.283 -<br><br>
490.284 - The level of debug output to use. This may be set from <code>0</code> (the default, no
490.285 - output) to <code>3</code> (the most output). Debugging information is written to
490.286 - <code>sys.stdout</code>.
490.287 -
490.288 -<br><br>
490.289 -<a href="attr:ZipFile.comment">ZipFile.comment</a>
490.290 -
490.291 -<br><br>
490.292 - The comment text associated with the ZIP file. If assigning a comment to a
490.293 - <a href="class:ZipFile">ZipFile</a> instance created with mode 'a' or 'w', this should be a
490.294 - string no longer than 65535 bytes. Comments longer than this will be
490.295 - truncated in the written archive when <a href="meth:ZipFile.close">ZipFile.close</a> is called.
490.296 -
490.297 -<br><br>
490.298 -
490.299 -<br><br>
490.300 -<h3>PyZipFile Objects
490.301 -</h3>
490.302 -The <a href="class:PyZipFile">PyZipFile</a> constructor takes the same parameters as the
490.303 -<a href="class:ZipFile">ZipFile</a> constructor. Instances have one method in addition to those of
490.304 -<a href="class:ZipFile">ZipFile</a> objects.
490.305 -
490.306 -<br><br>
490.307 -<a href="meth:PyZipFile.writepy(pathname[, basename])">PyZipFile.writepy(pathname[, basename])</a>
490.308 -
490.309 -<br><br>
490.310 - Search for files :file:`\*.py` and add the corresponding file to the archive.
490.311 - The corresponding file is a :file:`\*.pyo` file if available, else a
490.312 - :file:`\*.pyc` file, compiling if necessary. If the pathname is a file, the
490.313 - filename must end with :file:`.py`, and just the (corresponding
490.314 - :file:`\*.py[co]`) file is added at the top level (no path information). If the
490.315 - pathname is a file that does not end with :file:`.py`, a <a href="exc:RuntimeError">RuntimeError</a>
490.316 - will be raised. If it is a directory, and the directory is not a package
490.317 - directory, then all the files :file:`\*.py[co]` are added at the top level. If
490.318 - the directory is a package directory, then all :file:`\*.py[co]` are added under
490.319 - the package name as a file path, and if any subdirectories are package
490.320 - directories, all of these are added recursively. <b>basename</b> is intended for
490.321 - internal use only. The <a href="meth:writepy">writepy</a> method makes archives with file names
490.322 - like this::
490.323 -
490.324 -
490.325 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
490.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>
490.327 -<h3>ZipInfo Objects
490.328 -</h3>
490.329 -Instances of the <a href="class:ZipInfo">ZipInfo</a> class are returned by the <a href="meth:getinfo">getinfo</a> and
490.330 -<a href="meth:infolist">infolist</a> methods of <a href="class:ZipFile">ZipFile</a> objects. Each object stores
490.331 -information about a single member of the ZIP archive.
490.332 -
490.333 -<br><br>
490.334 -Instances have the following attributes:
490.335 -
490.336 -<br><br>
490.337 -<a href="attr:ZipInfo.filename">ZipInfo.filename</a>
490.338 -
490.339 -<br><br>
490.340 - Name of the file in the archive.
490.341 -
490.342 -<br><br>
490.343 -<a href="attr:ZipInfo.date_time">ZipInfo.date_time</a>
490.344 -
490.345 -<br><br>
490.346 - The time and date of the last modification to the archive member. This is a
490.347 - tuple of six values:
490.348 -
490.349 -<br><br>
490.350 -<pre> +-------+--------------------------+
490.351 - | Index | Value |
490.352 - +=======+==========================+
490.353 - | ``0`` | Year |
490.354 - +-------+--------------------------+
490.355 - | ``1`` | Month (one-based) |
490.356 - +-------+--------------------------+
490.357 - | ``2`` | Day of month (one-based) |
490.358 - +-------+--------------------------+
490.359 - | ``3`` | Hours (zero-based) |
490.360 - +-------+--------------------------+
490.361 - | ``4`` | Minutes (zero-based) |
490.362 - +-------+--------------------------+
490.363 - | ``5`` | Seconds (zero-based) |
490.364 - +-------+--------------------------+
490.365 -</pre>
490.366 -<a href="attr:ZipInfo.compress_type">ZipInfo.compress_type</a>
490.367 -
490.368 -<br><br>
490.369 - Type of compression for the archive member.
490.370 -
490.371 -<br><br>
490.372 -<a href="attr:ZipInfo.comment">ZipInfo.comment</a>
490.373 -
490.374 -<br><br>
490.375 - Comment for the individual archive member.
490.376 -
490.377 -<br><br>
490.378 -<a href="attr:ZipInfo.extra">ZipInfo.extra</a>
490.379 -
490.380 -<br><br>
490.381 - Expansion field data. The `PKZIP Application Note
490.382 - <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_ contains
490.383 - some comments on the internal structure of the data contained in this string.
490.384 -
490.385 -<br><br>
490.386 -<a href="attr:ZipInfo.create_system">ZipInfo.create_system</a>
490.387 -
490.388 -<br><br>
490.389 - System which created ZIP archive.
490.390 -
490.391 -<br><br>
490.392 -<a href="attr:ZipInfo.create_version">ZipInfo.create_version</a>
490.393 -
490.394 -<br><br>
490.395 - PKZIP version which created ZIP archive.
490.396 -
490.397 -<br><br>
490.398 -<a href="attr:ZipInfo.extract_version">ZipInfo.extract_version</a>
490.399 -
490.400 -<br><br>
490.401 - PKZIP version needed to extract archive.
490.402 -
490.403 -<br><br>
490.404 -<a href="attr:ZipInfo.reserved">ZipInfo.reserved</a>
490.405 -
490.406 -<br><br>
490.407 - Must be zero.
490.408 -
490.409 -<br><br>
490.410 -<a href="attr:ZipInfo.flag_bits">ZipInfo.flag_bits</a>
490.411 -
490.412 -<br><br>
490.413 - ZIP flag bits.
490.414 -
490.415 -<br><br>
490.416 -<a href="attr:ZipInfo.volume">ZipInfo.volume</a>
490.417 -
490.418 -<br><br>
490.419 - Volume number of file header.
490.420 -
490.421 -<br><br>
490.422 -<a href="attr:ZipInfo.internal_attr">ZipInfo.internal_attr</a>
490.423 -
490.424 -<br><br>
490.425 - Internal attributes.
490.426 -
490.427 -<br><br>
490.428 -<a href="attr:ZipInfo.external_attr">ZipInfo.external_attr</a>
490.429 -
490.430 -<br><br>
490.431 - External file attributes.
490.432 -
490.433 -<br><br>
490.434 -<a href="attr:ZipInfo.header_offset">ZipInfo.header_offset</a>
490.435 -
490.436 -<br><br>
490.437 - Byte offset to the file header.
490.438 -
490.439 -<br><br>
490.440 -<a href="attr:ZipInfo.CRC">ZipInfo.CRC</a>
490.441 -
490.442 -<br><br>
490.443 - CRC-32 of the uncompressed file.
490.444 -
490.445 -<br><br>
490.446 -<a href="attr:ZipInfo.compress_size">ZipInfo.compress_size</a>
490.447 -
490.448 -<br><br>
490.449 - Size of the compressed data.
490.450 -
490.451 -<br><br>
490.452 -<a href="attr:ZipInfo.file_size">ZipInfo.file_size</a>
490.453 -
490.454 -<br><br>
490.455 - Size of the uncompressed file.
490.456 -</body></html>
491.1 --- a/python.editor/test/unit/data/testfiles/rst/zipfile.rst.indexed Sun Jan 04 13:11:53 2015 -0600
491.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
491.3 @@ -1,113 +0,0 @@
491.4 -
491.5 -
491.6 -Document 0
491.7 -Searchable Keys:
491.8 - class : BadZipfile
491.9 - class-ig : badzipfile
491.10 - extends : Exception
491.11 - in : zipfile
491.12 -
491.13 -Not Searchable Keys:
491.14 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
491.15 -
491.16 -
491.17 -Document 1
491.18 -Searchable Keys:
491.19 - class : LargeZipFile
491.20 - class-ig : largezipfile
491.21 - extends : Exception
491.22 - in : zipfile
491.23 -
491.24 -Not Searchable Keys:
491.25 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
491.26 -
491.27 -
491.28 -Document 2
491.29 -Searchable Keys:
491.30 - class : PyZipFile
491.31 - class-ig : pyzipfile
491.32 - in : zipfile
491.33 - member : writepy;F;|DOCUMENTED|DOC_ONLY|;pathname,basename;
491.34 -
491.35 -Not Searchable Keys:
491.36 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
491.37 -
491.38 -
491.39 -Document 3
491.40 -Searchable Keys:
491.41 - class : ZipFile
491.42 - class-ig : zipfile
491.43 - in : zipfile
491.44 -
491.45 -Not Searchable Keys:
491.46 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
491.47 -
491.48 -
491.49 -Document 4
491.50 -Searchable Keys:
491.51 - class : ZipFile
491.52 - class-ig : zipfile
491.53 - in : zipfile
491.54 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;file,mode,compression,allowZip64;
491.55 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
491.56 - member : comment;A;|DOCUMENTED|DOC_ONLY|;
491.57 - member : debug;A;|DOCUMENTED|DOC_ONLY|;
491.58 - member : extract;F;|DOCUMENTED|DOC_ONLY|;member,path,pwd;
491.59 - member : extractall;F;|DOCUMENTED|DOC_ONLY|;path,members,pwd;
491.60 - member : getinfo;F;|DOCUMENTED|DOC_ONLY|;name;
491.61 - member : infolist;F;|DOCUMENTED|DOC_ONLY|;;
491.62 - member : namelist;F;|DOCUMENTED|DOC_ONLY|;;
491.63 - member : open;F;|DOCUMENTED|DOC_ONLY|;name,mode,pwd;
491.64 - member : printdir;F;|DOCUMENTED|DOC_ONLY|;;
491.65 - member : read;F;|DOCUMENTED|DOC_ONLY|;name,pwd;
491.66 - member : setpassword;F;|DOCUMENTED|DOC_ONLY|;pwd;
491.67 - member : testzip;F;|DOCUMENTED|DOC_ONLY|;;
491.68 - member : write;F;|DOCUMENTED|DOC_ONLY|;filename,arcname,compress_type;
491.69 - member : writestr;F;|DOCUMENTED|DOC_ONLY|;zinfo_or_arcname,bytes;
491.70 -
491.71 -Not Searchable Keys:
491.72 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
491.73 -
491.74 -
491.75 -Document 5
491.76 -Searchable Keys:
491.77 - class : ZipInfo
491.78 - class-ig : zipinfo
491.79 - in : zipfile
491.80 - member : CRC;A;|DOCUMENTED|DOC_ONLY|;
491.81 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;filename,date_time;
491.82 - member : comment;A;|DOCUMENTED|DOC_ONLY|;
491.83 - member : compress_size;A;|DOCUMENTED|DOC_ONLY|;
491.84 - member : compress_type;A;|DOCUMENTED|DOC_ONLY|;
491.85 - member : create_system;A;|DOCUMENTED|DOC_ONLY|;
491.86 - member : create_version;A;|DOCUMENTED|DOC_ONLY|;
491.87 - member : date_time;A;|DOCUMENTED|DOC_ONLY|;
491.88 - member : external_attr;A;|DOCUMENTED|DOC_ONLY|;
491.89 - member : extra;A;|DOCUMENTED|DOC_ONLY|;
491.90 - member : extract_version;A;|DOCUMENTED|DOC_ONLY|;
491.91 - member : file_size;A;|DOCUMENTED|DOC_ONLY|;
491.92 - member : filename;A;|DOCUMENTED|DOC_ONLY|;
491.93 - member : flag_bits;A;|DOCUMENTED|DOC_ONLY|;
491.94 - member : header_offset;A;|DOCUMENTED|DOC_ONLY|;
491.95 - member : internal_attr;A;|DOCUMENTED|DOC_ONLY|;
491.96 - member : reserved;A;|DOCUMENTED|DOC_ONLY|;
491.97 - member : volume;A;|DOCUMENTED|DOC_ONLY|;
491.98 -
491.99 -Not Searchable Keys:
491.100 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
491.101 -
491.102 -
491.103 -Document 6
491.104 -Searchable Keys:
491.105 - item : BadZipfile;C;|DOCUMENTED|DOC_ONLY|;
491.106 - item : LargeZipFile;C;|DOCUMENTED|DOC_ONLY|;
491.107 - item : PyZipFile;C;|DOCUMENTED|DOC_ONLY|;
491.108 - item : ZIP_DEFLATED;D;|DOCUMENTED|DOC_ONLY|;
491.109 - item : ZIP_STORED;D;|DOCUMENTED|DOC_ONLY|;
491.110 - item : ZipFile;C;|DOCUMENTED|DOC_ONLY|;
491.111 - item : ZipInfo;C;|DOCUMENTED|DOC_ONLY|;
491.112 - item : is_zipfile;F;|DOCUMENTED|DOC_ONLY|;filename;
491.113 - module : zipfile
491.114 -
491.115 -Not Searchable Keys:
491.116 - modattrs : S
492.1 --- a/python.editor/test/unit/data/testfiles/rst/zipfile.rst.testGetDoc1.html Sun Jan 04 13:11:53 2015 -0600
492.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
492.3 @@ -1,5 +0,0 @@
492.4 -<html><body><pre><b>ZIP_STORED</b></pre>
492.5 -
492.6 -<hr>
492.7 - The numeric constant for an uncompressed archive member.
492.8 -</body></html>
493.1 --- a/python.editor/test/unit/data/testfiles/rst/zipfile.rst.testGetDoc3.html Sun Jan 04 13:11:53 2015 -0600
493.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
493.3 @@ -1,27 +0,0 @@
493.4 -<html><body><pre><b>ZipFile.write</b><font color="#808080">(filename[, arcname[, compress_type]])</font></pre>
493.5 -<hr>
493.6 - Write the file named <b>filename</b> to the archive, giving it the archive name
493.7 - <b>arcname</b> (by default, this will be the same as <b>filename</b>, but without a drive
493.8 - letter and with leading path separators removed). If given, <b>compress_type</b>
493.9 - overrides the value given for the <b>compression</b> parameter to the constructor for
493.10 - the new entry. The archive must be open with mode <code>'w'</code> or <code>'a'</code> -- calling
493.11 - <a href="meth:write">write</a> on a ZipFile created with mode <code>'r'</code> will raise a
493.12 - <a href="exc:RuntimeError">RuntimeError</a>. Calling <a href="meth:write">write</a> on a closed ZipFile will raise a
493.13 - <a href="exc:RuntimeError">RuntimeError</a>.
493.14 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
493.15 -
493.16 -<br><br>
493.17 - There is no official file name encoding for ZIP files. If you have unicode file
493.18 - names, you must convert them to byte strings in your desired encoding before
493.19 - passing them to <a href="meth:write">write</a>. WinZip interprets all file names as encoded in
493.20 - CP437, also known as DOS Latin.
493.21 -</div>
493.22 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
493.23 - Archive names should be relative to the archive root, that is, they should not
493.24 - start with a path separator.
493.25 -</div>
493.26 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
493.27 - If <code>arcname</code> (or <code>filename</code>, if <code>arcname</code> is not given) contains a null
493.28 - byte, the name of the file in the archive will be truncated at the null byte.
493.29 -</div>
493.30 -</body></html>
494.1 --- a/python.editor/test/unit/data/testfiles/samelinedef.py Sun Jan 04 13:11:53 2015 -0600
494.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
494.3 @@ -1,7 +0,0 @@
494.4 - # To be overridden -- handlers for unknown objects
494.5 - def unknown_starttag(self, tag, attrs): pass
494.6 - def unknown_endtag(self, tag): pass
494.7 - def unknown_charref(self, ref): pass
494.8 - def unknown_entityref(self, name):
494.9 - self.syntax_error("reference to unknown entity `&%s;'" % name)
494.10 -
495.1 --- a/python.editor/test/unit/data/testfiles/scope.py Sun Jan 04 13:11:53 2015 -0600
495.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
495.3 @@ -1,33 +0,0 @@
495.4 -import module1
495.5 -import module2
495.6 -import module3 as module4
495.7 -
495.8 -toplevelvar = 1
495.9 -toplevelvar2 = 2
495.10 -toplevelvar3 = 3
495.11 -toplevelvar4 = 4
495.12 -
495.13 -def myfunc(funcparam):
495.14 - localvar = 1
495.15 - toplevelvar4 = 6
495.16 - print toplevelvar4
495.17 - pass
495.18 -
495.19 -class MyClass(SuperClass):
495.20 - var_in_class = 1
495.21 - def mymethod(self,param1,param2):
495.22 - in_method = 1
495.23 - in_method = 2
495.24 - print in_method
495.25 - print var_in_class
495.26 - print toplevelvar
495.27 - toplevelvar3 = 3
495.28 - def myfunc():
495.29 - in_func = 1
495.30 - print in_method
495.31 - print in_func
495.32 - in_method = 2
495.33 -
495.34 - def othermethod(self,param3):
495.35 - pass
495.36 -
496.1 --- a/python.editor/test/unit/data/testfiles/scope.py.indexed Sun Jan 04 13:11:53 2015 -0600
496.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
496.3 @@ -1,29 +0,0 @@
496.4 -
496.5 -
496.6 -Document 0
496.7 -Searchable Keys:
496.8 - class : MyClass
496.9 - class-ig : myclass
496.10 - extends : SuperClass
496.11 - in : scope
496.12 - member : mymethod;F;;self,param1,param2;
496.13 - member : othermethod;F;;self,param3;
496.14 - member : var_in_class;D;;
496.15 -
496.16 -Not Searchable Keys:
496.17 -
496.18 -
496.19 -Document 1
496.20 -Searchable Keys:
496.21 - item : MyClass;C;;
496.22 - item : module1;I;;
496.23 - item : module2;I;;
496.24 - item : module4;I;;
496.25 - item : myfunc;F;;funcparam;
496.26 - item : toplevelvar2;D;;
496.27 - item : toplevelvar3;D;;
496.28 - item : toplevelvar4;D;;
496.29 - item : toplevelvar;D;;
496.30 - module : scope
496.31 -
496.32 -Not Searchable Keys:
497.1 --- a/python.editor/test/unit/data/testfiles/scope.py.scopes Sun Jan 04 13:11:53 2015 -0600
497.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
497.3 @@ -1,46 +0,0 @@
497.4 -=============================================
497.5 -<file-top>: Module : OffsetRange[0,625>
497.6 -MyClass [bound][class][def][node=ClassDef]
497.7 -SuperClass [read][UNRESOLVED][node=Name]
497.8 -module1 [bound][imported][data][node=Import]
497.9 -module2 [bound][imported][data][node=Import]
497.10 -module4 [bound][imported][data][node=Import]
497.11 -myfunc [bound][function][def][node=FunctionDef]
497.12 -toplevelvar [bound][data][read][node=Name]
497.13 -toplevelvar2 [bound][data][node=Name]
497.14 -toplevelvar3 [bound][data][node=Name]
497.15 -toplevelvar4 [bound][data][node=Name]
497.16 -
497.17 - =============================================
497.18 - myfunc: FunctionDef : OffsetRange[125,219>
497.19 - funcparam [bound][param][data][unused][node=Name]
497.20 - localvar [bound][data][unused][node=Name]
497.21 - toplevelvar4 [bound][data][read][node=Name]
497.22 -
497.23 - =============================================
497.24 - class MyClass: ClassDef : OffsetRange[219,625>
497.25 - mymethod [bound][function][def][node=FunctionDef]
497.26 - othermethod [bound][function][def][node=FunctionDef]
497.27 - var_in_class [bound][data][node=Name]
497.28 -
497.29 - =============================================
497.30 - mymethod: FunctionDef : OffsetRange[271,581>
497.31 - in_method [bound][data][read][node=Name]
497.32 - myfunc [bound][function][def][node=FunctionDef]
497.33 - param1 [bound][param][data][unused][node=Name]
497.34 - param2 [bound][param][data][unused][node=Name]
497.35 - self [bound][param][data][unused][node=Name]
497.36 - toplevelvar [free][read][node=Name]
497.37 - toplevelvar3 [bound][data][unused][node=Name]
497.38 - var_in_class [free][read][node=Name]
497.39 -
497.40 - =============================================
497.41 - myfunc: FunctionDef : OffsetRange[459,581>
497.42 - in_func [bound][data][read][node=Name]
497.43 - in_method [bound][data][read][node=Name]
497.44 -
497.45 - =============================================
497.46 - othermethod: FunctionDef : OffsetRange[582,625>
497.47 - param3 [bound][param][data][unused][node=Name]
497.48 - self [bound][param][data][unused][node=Name]
497.49 -
498.1 --- a/python.editor/test/unit/data/testfiles/scope2.py Sun Jan 04 13:11:53 2015 -0600
498.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
498.3 @@ -1,4 +0,0 @@
498.4 -x = 1
498.5 -def foo():
498.6 - print x
498.7 -
499.1 --- a/python.editor/test/unit/data/testfiles/scope2.py.scopes Sun Jan 04 13:11:53 2015 -0600
499.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
499.3 @@ -1,9 +0,0 @@
499.4 -=============================================
499.5 -<file-top>: Module : OffsetRange[0,29>
499.6 -foo [bound][function][def][node=FunctionDef]
499.7 -x [bound][data][read][node=Name]
499.8 -
499.9 - =============================================
499.10 - foo: FunctionDef : OffsetRange[6,29>
499.11 - x [free][read][node=Name]
499.12 -
500.1 --- a/python.editor/test/unit/data/testfiles/scope3.py Sun Jan 04 13:11:53 2015 -0600
500.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
500.3 @@ -1,10 +0,0 @@
500.4 -__all__ = [ "MyPublicClass" ]
500.5 -
500.6 -class MyPublicClass:
500.7 - def mymethod(self):
500.8 - pass
500.9 -
500.10 -class MyPrivateClass:
500.11 - def mymethod2(self):
500.12 - pass
500.13 -
501.1 --- a/python.editor/test/unit/data/testfiles/scope3.py.scopes Sun Jan 04 13:11:53 2015 -0600
501.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
501.3 @@ -1,22 +0,0 @@
501.4 -=============================================
501.5 -<file-top>: Module : OffsetRange[0,150>
501.6 -MyPrivateClass [bound][private][class][def][node=ClassDef]
501.7 -MyPublicClass [bound][class][def][node=ClassDef]
501.8 -__all__ [bound][data][node=Name]
501.9 -
501.10 - =============================================
501.11 - class MyPublicClass: ClassDef : OffsetRange[31,90>
501.12 - mymethod [bound][function][def][node=FunctionDef]
501.13 -
501.14 - =============================================
501.15 - mymethod: FunctionDef : OffsetRange[56,90>
501.16 - self [bound][param][data][unused][node=Name]
501.17 -
501.18 - =============================================
501.19 - class MyPrivateClass: ClassDef : OffsetRange[90,150>
501.20 - mymethod2 [bound][private][function][def][node=FunctionDef]
501.21 -
501.22 - =============================================
501.23 - mymethod2: FunctionDef : OffsetRange[116,150>
501.24 - self [bound][param][private][data][unused][node=Name]
501.25 -
502.1 --- a/python.editor/test/unit/data/testfiles/simple.py Sun Jan 04 13:11:53 2015 -0600
502.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
502.3 @@ -1,2 +0,0 @@
502.4 -x = 1
502.5 -y = 2
503.1 --- a/python.editor/test/unit/data/testfiles/simple.py.testHint4.hints Sun Jan 04 13:11:53 2015 -0600
503.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
503.3 @@ -1,7 +0,0 @@
503.4 -x = 1
503.5 -
503.6 -HINT:Surround With...
503.7 -FIX:Surround With Try/Except
503.8 -FIX:Surround With Try/Except/Finally
503.9 -FIX:Surround With Try/Finally
503.10 -y = 2^
504.1 --- a/python.editor/test/unit/data/testfiles/socket.py Sun Jan 04 13:11:53 2015 -0600
504.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
504.3 @@ -1,1368 +0,0 @@
504.4 -"""
504.5 -This is an updated socket module for use on JVMs > 1.4; it is derived from the
504.6 -old jython socket module.
504.7 -The primary extra it provides is non-blocking support.
504.8 -
504.9 -XXX Restrictions:
504.10 -
504.11 -- Only INET sockets
504.12 -- No asynchronous behavior
504.13 -- No socket options
504.14 -- Can't do a very good gethostbyaddr() right...
504.15 -AMAK: 20050527: added socket timeouts
504.16 -AMAK: 20070515: Added non-blocking (asynchronous) support
504.17 -AMAK: 20070515: Added client-side SSL support
504.18 -AMAK: 20080513: Added support for options
504.19 -"""
504.20 -
504.21 -_defaulttimeout = None
504.22 -
504.23 -import errno
504.24 -import jarray
504.25 -import string
504.26 -import struct
504.27 -import sys
504.28 -import threading
504.29 -import time
504.30 -import types
504.31 -
504.32 -# Java.io classes
504.33 -import java.io.BufferedInputStream
504.34 -import java.io.BufferedOutputStream
504.35 -# Java.io exceptions
504.36 -import java.io.InterruptedIOException
504.37 -import java.io.IOException
504.38 -
504.39 -# Java.lang classes
504.40 -import java.lang.String
504.41 -# Java.lang exceptions
504.42 -import java.lang.Exception
504.43 -
504.44 -# Java.net classes
504.45 -import java.net.DatagramPacket
504.46 -import java.net.InetAddress
504.47 -import java.net.InetSocketAddress
504.48 -import java.net.Socket
504.49 -# Java.net exceptions
504.50 -import java.net.BindException
504.51 -import java.net.ConnectException
504.52 -import java.net.NoRouteToHostException
504.53 -import java.net.PortUnreachableException
504.54 -import java.net.ProtocolException
504.55 -import java.net.SocketException
504.56 -import java.net.SocketTimeoutException
504.57 -import java.net.UnknownHostException
504.58 -
504.59 -# Java.nio classes
504.60 -import java.nio.ByteBuffer
504.61 -import java.nio.channels.DatagramChannel
504.62 -import java.nio.channels.ServerSocketChannel
504.63 -import java.nio.channels.SocketChannel
504.64 -# Java.nio exceptions
504.65 -import java.nio.channels.AlreadyConnectedException
504.66 -import java.nio.channels.AsynchronousCloseException
504.67 -import java.nio.channels.CancelledKeyException
504.68 -import java.nio.channels.ClosedByInterruptException
504.69 -import java.nio.channels.ClosedChannelException
504.70 -import java.nio.channels.ClosedSelectorException
504.71 -import java.nio.channels.ConnectionPendingException
504.72 -import java.nio.channels.IllegalBlockingModeException
504.73 -import java.nio.channels.IllegalSelectorException
504.74 -import java.nio.channels.NoConnectionPendingException
504.75 -import java.nio.channels.NonReadableChannelException
504.76 -import java.nio.channels.NonWritableChannelException
504.77 -import java.nio.channels.NotYetBoundException
504.78 -import java.nio.channels.NotYetConnectedException
504.79 -import java.nio.channels.UnresolvedAddressException
504.80 -import java.nio.channels.UnsupportedAddressTypeException
504.81 -
504.82 -import javax.net.ssl.SSLSocketFactory
504.83 -
504.84 -import org.python.core.io.DatagramSocketIO
504.85 -import org.python.core.io.ServerSocketIO
504.86 -import org.python.core.io.SocketIO
504.87 -from org.python.core.Py import newString as asPyString
504.88 -
504.89 -class error(Exception): pass
504.90 -class herror(error): pass
504.91 -class gaierror(error): pass
504.92 -class timeout(error): pass
504.93 -
504.94 -ALL = None
504.95 -
504.96 -_exception_map = {
504.97 -
504.98 -# (<javaexception>, <circumstance>) : lambda: <code that raises the python equivalent>, or None to stub out as unmapped
504.99 -
504.100 -(java.io.IOException, ALL) : lambda: error(errno.ECONNRESET, 'Software caused connection abort'),
504.101 -(java.io.InterruptedIOException, ALL) : lambda: timeout('timed out'),
504.102 -
504.103 -(java.net.BindException, ALL) : lambda: error(errno.EADDRINUSE, 'Address already in use'),
504.104 -(java.net.ConnectException, ALL) : lambda: error(errno.ECONNREFUSED, 'Connection refused'),
504.105 -(java.net.NoRouteToHostException, ALL) : None,
504.106 -(java.net.PortUnreachableException, ALL) : None,
504.107 -(java.net.ProtocolException, ALL) : None,
504.108 -(java.net.SocketException, ALL) : None,
504.109 -(java.net.SocketTimeoutException, ALL) : lambda: timeout('timed out'),
504.110 -(java.net.UnknownHostException, ALL) : lambda: gaierror(errno.EGETADDRINFOFAILED, 'getaddrinfo failed'),
504.111 -
504.112 -(java.nio.channels.AlreadyConnectedException, ALL) : lambda: error(errno.EISCONN, 'Socket is already connected'),
504.113 -(java.nio.channels.AsynchronousCloseException, ALL) : None,
504.114 -(java.nio.channels.CancelledKeyException, ALL) : None,
504.115 -(java.nio.channels.ClosedByInterruptException, ALL) : None,
504.116 -(java.nio.channels.ClosedChannelException, ALL) : lambda: error(errno.EPIPE, 'Socket closed'),
504.117 -(java.nio.channels.ClosedSelectorException, ALL) : None,
504.118 -(java.nio.channels.ConnectionPendingException, ALL) : None,
504.119 -(java.nio.channels.IllegalBlockingModeException, ALL) : None,
504.120 -(java.nio.channels.IllegalSelectorException, ALL) : None,
504.121 -(java.nio.channels.NoConnectionPendingException, ALL) : None,
504.122 -(java.nio.channels.NonReadableChannelException, ALL) : None,
504.123 -(java.nio.channels.NonWritableChannelException, ALL) : None,
504.124 -(java.nio.channels.NotYetBoundException, ALL) : None,
504.125 -(java.nio.channels.NotYetConnectedException, ALL) : None,
504.126 -(java.nio.channels.UnresolvedAddressException, ALL) : lambda: gaierror(errno.EGETADDRINFOFAILED, 'getaddrinfo failed'),
504.127 -(java.nio.channels.UnsupportedAddressTypeException, ALL) : None,
504.128 -
504.129 -}
504.130 -
504.131 -def would_block_error(exc=None):
504.132 - return error(errno.EWOULDBLOCK, 'The socket operation could not complete without blocking')
504.133 -
504.134 -def _map_exception(exc, circumstance=ALL):
504.135 -# print "Mapping exception: %s" % exc
504.136 - mapped_exception = _exception_map.get((exc.__class__, circumstance))
504.137 - if mapped_exception:
504.138 - exception = mapped_exception()
504.139 - else:
504.140 - exception = error(-1, 'Unmapped exception: %s' % exc)
504.141 - exception.java_exception = exc
504.142 - return exception
504.143 -
504.144 -MODE_BLOCKING = 'block'
504.145 -MODE_NONBLOCKING = 'nonblock'
504.146 -MODE_TIMEOUT = 'timeout'
504.147 -
504.148 -_permitted_modes = (MODE_BLOCKING, MODE_NONBLOCKING, MODE_TIMEOUT)
504.149 -
504.150 -SHUT_RD = 0
504.151 -SHUT_WR = 1
504.152 -SHUT_RDWR = 2
504.153 -
504.154 -__all__ = ['AF_UNSPEC', 'AF_INET', 'AF_INET6', 'AI_PASSIVE', 'SOCK_DGRAM',
504.155 - 'SOCK_RAW', 'SOCK_RDM', 'SOCK_SEQPACKET', 'SOCK_STREAM', 'SOL_SOCKET',
504.156 - 'SO_BROADCAST', 'SO_ERROR', 'SO_KEEPALIVE', 'SO_LINGER', 'SO_OOBINLINE',
504.157 - 'SO_RCVBUF', 'SO_REUSEADDR', 'SO_SNDBUF', 'SO_TIMEOUT', 'TCP_NODELAY',
504.158 - 'SocketType', 'error', 'herror', 'gaierror', 'timeout',
504.159 - 'getfqdn', 'gethostbyaddr', 'gethostbyname', 'gethostname',
504.160 - 'socket', 'getaddrinfo', 'getdefaulttimeout', 'setdefaulttimeout',
504.161 - 'has_ipv6', 'htons', 'htonl', 'ntohs', 'ntohl',
504.162 - 'SHUT_RD', 'SHUT_WR', 'SHUT_RDWR',
504.163 - ]
504.164 -
504.165 -AF_UNSPEC = 0
504.166 -AF_INET = 2
504.167 -AF_INET6 = 23
504.168 -
504.169 -AI_PASSIVE=1
504.170 -
504.171 -SOCK_DGRAM = 1
504.172 -SOCK_STREAM = 2
504.173 -SOCK_RAW = 3 # not supported
504.174 -SOCK_RDM = 4 # not supported
504.175 -SOCK_SEQPACKET = 5 # not supported
504.176 -
504.177 -SOL_SOCKET = 0xFFFF
504.178 -
504.179 -SO_BROADCAST = 1
504.180 -SO_KEEPALIVE = 2
504.181 -SO_LINGER = 4
504.182 -SO_OOBINLINE = 8
504.183 -SO_RCVBUF = 16
504.184 -SO_REUSEADDR = 32
504.185 -SO_SNDBUF = 64
504.186 -SO_TIMEOUT = 128
504.187 -
504.188 -TCP_NODELAY = 256
504.189 -
504.190 -# Options with negative constants are not supported
504.191 -# They are being added here so that code that refers to them
504.192 -# will not break with an AttributeError
504.193 -
504.194 -SO_ACCEPTCONN = -1
504.195 -SO_DEBUG = -2
504.196 -SO_DONTROUTE = -4
504.197 -SO_ERROR = -8
504.198 -SO_EXCLUSIVEADDRUSE = -16
504.199 -SO_RCVLOWAT = -32
504.200 -SO_RCVTIMEO = -64
504.201 -SO_REUSEPORT = -128
504.202 -SO_SNDLOWAT = -256
504.203 -SO_SNDTIMEO = -512
504.204 -SO_TYPE = -1024
504.205 -SO_USELOOPBACK = -2048
504.206 -
504.207 -class _nio_impl:
504.208 -
504.209 - timeout = None
504.210 - mode = MODE_BLOCKING
504.211 -
504.212 - def read(self, buf):
504.213 - bytebuf = java.nio.ByteBuffer.wrap(buf)
504.214 - count = self.jchannel.read(bytebuf)
504.215 - return count
504.216 -
504.217 - def write(self, buf):
504.218 - bytebuf = java.nio.ByteBuffer.wrap(buf)
504.219 - count = self.jchannel.write(bytebuf)
504.220 - return count
504.221 -
504.222 - def getpeername(self):
504.223 - return (self.jsocket.getInetAddress().getHostAddress(), self.jsocket.getPort() )
504.224 -
504.225 - def config(self, mode, timeout):
504.226 - self.mode = mode
504.227 - if self.mode == MODE_BLOCKING:
504.228 - self.jchannel.configureBlocking(1)
504.229 - if self.mode == MODE_NONBLOCKING:
504.230 - self.jchannel.configureBlocking(0)
504.231 - if self.mode == MODE_TIMEOUT:
504.232 - self._timeout_millis = int(timeout*1000)
504.233 - self.jsocket.setSoTimeout(self._timeout_millis)
504.234 -
504.235 - def getsockopt(self, option):
504.236 - if self.options.has_key(option):
504.237 - result = getattr(self.jsocket, "get%s" % self.options[option])()
504.238 - if option == SO_LINGER:
504.239 - if result == -1:
504.240 - enabled, linger_time = 0, 0
504.241 - else:
504.242 - enabled, linger_time = 1, result
504.243 - return struct.pack('ii', enabled, linger_time)
504.244 - return result
504.245 - else:
504.246 - raise error(errno.ENOPROTOOPT, "Option not supported on socket(%s): %d" % (str(self.jsocket), option))
504.247 -
504.248 - def setsockopt(self, option, value):
504.249 - if self.options.has_key(option):
504.250 - if option == SO_LINGER:
504.251 - values = struct.unpack('ii', value)
504.252 - self.jsocket.setSoLinger(*values)
504.253 - else:
504.254 - getattr(self.jsocket, "set%s" % self.options[option])(value)
504.255 - else:
504.256 - raise error(errno.ENOPROTOOPT, "Option not supported on socket(%s): %d" % (str(self.jsocket), option))
504.257 -
504.258 - def close(self):
504.259 - self.jsocket.close()
504.260 -
504.261 - def shutdownInput(self):
504.262 - try:
504.263 - self.jsocket.shutdownInput()
504.264 - except AttributeError, ax:
504.265 - pass # Fail silently server sockets
504.266 - except java.lang.Exception, jlx:
504.267 - raise _map_exception(jlx)
504.268 -
504.269 - def shutdownOutput(self):
504.270 - try:
504.271 - self.jsocket.shutdownOutput()
504.272 - except AttributeError, ax:
504.273 - pass # Fail silently server sockets
504.274 - except java.lang.Exception, jlx:
504.275 - raise _map_exception(jlx)
504.276 -
504.277 - def getchannel(self):
504.278 - return self.jchannel
504.279 -
504.280 - def fileno(self):
504.281 - return self.socketio
504.282 -
504.283 -class _client_socket_impl(_nio_impl):
504.284 -
504.285 - options = {
504.286 - SO_KEEPALIVE: 'KeepAlive',
504.287 - SO_LINGER: 'SoLinger',
504.288 - SO_OOBINLINE: 'OOBInline',
504.289 - SO_RCVBUF: 'ReceiveBufferSize',
504.290 - SO_REUSEADDR: 'ReuseAddress',
504.291 - SO_SNDBUF: 'SendBufferSize',
504.292 - SO_TIMEOUT: 'SoTimeout',
504.293 - TCP_NODELAY: 'TcpNoDelay',
504.294 - }
504.295 -
504.296 - def __init__(self, socket=None):
504.297 - if socket:
504.298 - self.jchannel = socket.getChannel()
504.299 - self.host = socket.getInetAddress().getHostAddress()
504.300 - self.port = socket.getPort()
504.301 - else:
504.302 - self.jchannel = java.nio.channels.SocketChannel.open()
504.303 - self.host = None
504.304 - self.port = None
504.305 - self.jsocket = self.jchannel.socket()
504.306 - self.socketio = org.python.core.io.SocketIO(self.jchannel, 'rw')
504.307 -
504.308 - def bind(self, host, port, reuse_addr):
504.309 - self.jsocket.setReuseAddress(reuse_addr)
504.310 - self.jsocket.bind(java.net.InetSocketAddress(host, port))
504.311 -
504.312 - def connect(self, host, port):
504.313 - self.host = host
504.314 - self.port = port
504.315 - if self.mode == MODE_TIMEOUT:
504.316 - self.jsocket.connect(java.net.InetSocketAddress(self.host, self.port), self._timeout_millis)
504.317 - else:
504.318 - self.jchannel.connect(java.net.InetSocketAddress(self.host, self.port))
504.319 -
504.320 - def finish_connect(self):
504.321 - return self.jchannel.finishConnect()
504.322 -
504.323 -class _server_socket_impl(_nio_impl):
504.324 -
504.325 - options = {
504.326 - SO_RCVBUF: 'ReceiveBufferSize',
504.327 - SO_REUSEADDR: 'ReuseAddress',
504.328 - SO_TIMEOUT: 'SoTimeout',
504.329 - }
504.330 -
504.331 - def __init__(self, host, port, backlog, reuse_addr):
504.332 - self.jchannel = java.nio.channels.ServerSocketChannel.open()
504.333 - self.jsocket = self.jchannel.socket()
504.334 - if host:
504.335 - bindaddr = java.net.InetSocketAddress(host, port)
504.336 - else:
504.337 - bindaddr = java.net.InetSocketAddress(port)
504.338 - self.jsocket.setReuseAddress(reuse_addr)
504.339 - self.jsocket.bind(bindaddr, backlog)
504.340 - self.socketio = org.python.core.io.ServerSocketIO(self.jchannel, 'rw')
504.341 -
504.342 - def accept(self):
504.343 - if self.mode in (MODE_BLOCKING, MODE_NONBLOCKING):
504.344 - new_cli_chan = self.jchannel.accept()
504.345 - if new_cli_chan != None:
504.346 - return _client_socket_impl(new_cli_chan.socket())
504.347 - else:
504.348 - return None
504.349 - else:
504.350 - # In timeout mode now
504.351 - new_cli_sock = self.jsocket.accept()
504.352 - return _client_socket_impl(new_cli_sock)
504.353 -
504.354 -class _datagram_socket_impl(_nio_impl):
504.355 -
504.356 - options = {
504.357 - SO_BROADCAST: 'Broadcast',
504.358 - SO_RCVBUF: 'ReceiveBufferSize',
504.359 - SO_REUSEADDR: 'ReuseAddress',
504.360 - SO_SNDBUF: 'SendBufferSize',
504.361 - SO_TIMEOUT: 'SoTimeout',
504.362 - }
504.363 -
504.364 - def __init__(self, port=None, address=None, reuse_addr=0):
504.365 - self.jchannel = java.nio.channels.DatagramChannel.open()
504.366 - self.jsocket = self.jchannel.socket()
504.367 - if port:
504.368 - if address is not None:
504.369 - local_address = java.net.InetSocketAddress(address, port)
504.370 - else:
504.371 - local_address = java.net.InetSocketAddress(port)
504.372 - self.jsocket.setReuseAddress(reuse_addr)
504.373 - self.jsocket.bind(local_address)
504.374 - self.socketio = org.python.core.io.DatagramSocketIO(self.jchannel, 'rw')
504.375 -
504.376 - def connect(self, host, port):
504.377 - self.jchannel.connect(java.net.InetSocketAddress(host, port))
504.378 -
504.379 - def finish_connect(self):
504.380 - return self.jchannel.finishConnect()
504.381 -
504.382 - def disconnect(self):
504.383 - """
504.384 - Disconnect the datagram socket.
504.385 - cpython appears not to have this operation
504.386 - """
504.387 - self.jchannel.disconnect()
504.388 -
504.389 - def _do_send_net(self, byte_array, socket_address, flags):
504.390 - # Need two separate implementations because the java.nio APIs do not support timeouts
504.391 - num_bytes = len(byte_array)
504.392 - if socket_address:
504.393 - packet = java.net.DatagramPacket(byte_array, num_bytes, socket_address)
504.394 - else:
504.395 - packet = java.net.DatagramPacket(byte_array, num_bytes)
504.396 - self.jsocket.send(packet)
504.397 - return num_bytes
504.398 -
504.399 - def _do_send_nio(self, byte_array, socket_address, flags):
504.400 - byte_buf = java.nio.ByteBuffer.wrap(byte_array)
504.401 - bytes_sent = self.jchannel.send(byte_buf, socket_address)
504.402 - return bytes_sent
504.403 -
504.404 - def sendto(self, byte_array, host, port, flags):
504.405 - socket_address = java.net.InetSocketAddress(host, port)
504.406 - if self.mode == MODE_TIMEOUT:
504.407 - return self._do_send_net(byte_array, socket_address, flags)
504.408 - else:
504.409 - return self._do_send_nio(byte_array, socket_address, flags)
504.410 -
504.411 - def send(self, byte_array, flags):
504.412 - if self.mode == MODE_TIMEOUT:
504.413 - return self._do_send_net(byte_array, None, flags)
504.414 - else:
504.415 - return self._do_send_nio(byte_array, None, flags)
504.416 -
504.417 - def _do_receive_net(self, return_source_address, num_bytes, flags):
504.418 - byte_array = jarray.zeros(num_bytes, 'b')
504.419 - packet = java.net.DatagramPacket(byte_array, num_bytes)
504.420 - self.jsocket.receive(packet)
504.421 - bytes_rcvd = packet.getLength()
504.422 - if bytes_rcvd < num_bytes:
504.423 - byte_array = byte_array[:bytes_rcvd]
504.424 - return_data = byte_array.tostring()
504.425 - if return_source_address:
504.426 - host = None
504.427 - if packet.getAddress():
504.428 - host = packet.getAddress().getHostAddress()
504.429 - port = packet.getPort()
504.430 - return return_data, (host, port)
504.431 - else:
504.432 - return return_data
504.433 -
504.434 - def _do_receive_nio(self, return_source_address, num_bytes, flags):
504.435 - byte_array = jarray.zeros(num_bytes, 'b')
504.436 - byte_buf = java.nio.ByteBuffer.wrap(byte_array)
504.437 - source_address = self.jchannel.receive(byte_buf)
504.438 - if source_address is None and not self.jchannel.isBlocking():
504.439 - raise would_block_error()
504.440 - byte_buf.flip() ; bytes_read = byte_buf.remaining()
504.441 - if bytes_read < num_bytes:
504.442 - byte_array = byte_array[:bytes_read]
504.443 - return_data = byte_array.tostring()
504.444 - if return_source_address:
504.445 - return return_data, (source_address.getAddress().getHostAddress(), source_address.getPort())
504.446 - else:
504.447 - return return_data
504.448 -
504.449 - def recvfrom(self, num_bytes, flags):
504.450 - if self.mode == MODE_TIMEOUT:
504.451 - return self._do_receive_net(1, num_bytes, flags)
504.452 - else:
504.453 - return self._do_receive_nio(1, num_bytes, flags)
504.454 -
504.455 - def recv(self, num_bytes, flags):
504.456 - if self.mode == MODE_TIMEOUT:
504.457 - return self._do_receive_net(0, num_bytes, flags)
504.458 - else:
504.459 - return self._do_receive_nio(0, num_bytes, flags)
504.460 -
504.461 -# Name and address functions
504.462 -
504.463 -has_ipv6 = 1
504.464 -
504.465 -def _gethostbyaddr(name):
504.466 - # This is as close as I can get; at least the types are correct...
504.467 - addresses = java.net.InetAddress.getAllByName(gethostbyname(name))
504.468 - names = []
504.469 - addrs = []
504.470 - for addr in addresses:
504.471 - names.append(asPyString(addr.getHostName()))
504.472 - addrs.append(asPyString(addr.getHostAddress()))
504.473 - return (names, addrs)
504.474 -
504.475 -def getfqdn(name=None):
504.476 - """
504.477 - Return a fully qualified domain name for name. If name is omitted or empty
504.478 - it is interpreted as the local host. To find the fully qualified name,
504.479 - the hostname returned by gethostbyaddr() is checked, then aliases for the
504.480 - host, if available. The first name which includes a period is selected.
504.481 - In case no fully qualified domain name is available, the hostname is retur
504.482 - New in version 2.0.
504.483 - """
504.484 - if not name:
504.485 - name = gethostname()
504.486 - names, addrs = _gethostbyaddr(name)
504.487 - for a in names:
504.488 - if a.find(".") >= 0:
504.489 - return a
504.490 - return name
504.491 -
504.492 -def gethostname():
504.493 - try:
504.494 - return asPyString(java.net.InetAddress.getLocalHost().getHostName())
504.495 - except java.lang.Exception, jlx:
504.496 - raise _map_exception(jlx)
504.497 -
504.498 -def gethostbyname(name):
504.499 - try:
504.500 - return asPyString(java.net.InetAddress.getByName(name).getHostAddress())
504.501 - except java.lang.Exception, jlx:
504.502 - raise _map_exception(jlx)
504.503 -
504.504 -def gethostbyaddr(name):
504.505 - names, addrs = _gethostbyaddr(name)
504.506 - return (names[0], names, addrs)
504.507 -
504.508 -def getservbyname(servicename, protocolname=None):
504.509 - # http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071389
504.510 - # How complex is the structure of /etc/services?
504.511 - raise NotImplementedError("getservbyname not yet supported on jython.")
504.512 -
504.513 -def getservbyport(port, protocolname=None):
504.514 - # Same situation as above
504.515 - raise NotImplementedError("getservbyport not yet supported on jython.")
504.516 -
504.517 -def getprotobyname(protocolname=None):
504.518 - # Same situation as above
504.519 - raise NotImplementedError("getprotobyname not yet supported on jython.")
504.520 -
504.521 -def _realsocket(family = AF_INET, type = SOCK_STREAM, flags=0):
504.522 - assert family == AF_INET
504.523 - assert type in (SOCK_DGRAM, SOCK_STREAM)
504.524 - assert flags == 0
504.525 - if type == SOCK_STREAM:
504.526 - return _tcpsocket()
504.527 - else:
504.528 - return _udpsocket()
504.529 -
504.530 -def getaddrinfo(host, port, family=AF_INET, socktype=None, proto=0, flags=None):
504.531 - try:
504.532 - if not family in [AF_INET, AF_INET6, AF_UNSPEC]:
504.533 - raise gaierror(errno.EIO, 'ai_family not supported')
504.534 - filter_fns = []
504.535 - filter_fns.append({
504.536 - AF_INET: lambda x: isinstance(x, java.net.Inet4Address),
504.537 - AF_INET6: lambda x: isinstance(x, java.net.Inet6Address),
504.538 - AF_UNSPEC: lambda x: isinstance(x, java.net.InetAddress),
504.539 - }[family])
504.540 - # Cant see a way to support AI_PASSIVE right now.
504.541 - # if flags and flags & AI_PASSIVE:
504.542 - # pass
504.543 - results = []
504.544 - for a in java.net.InetAddress.getAllByName(host):
504.545 - if len([f for f in filter_fns if f(a)]):
504.546 - family = {java.net.Inet4Address: AF_INET, java.net.Inet6Address: AF_INET6}[a.getClass()]
504.547 - # TODO: Include flowinfo and scopeid in a 4-tuple for IPv6 addresses
504.548 - canonname = asPyString(a.getCanonicalHostName())
504.549 - sockname = asPyString(a.getHostAddress())
504.550 - results.append((family, socktype, proto, canonname, (sockname, port)))
504.551 - return results
504.552 - except java.lang.Exception, jlx:
504.553 - raise _map_exception(jlx)
504.554 -
504.555 -def getnameinfo(sock_addr, flags):
504.556 - raise NotImplementedError("getnameinfo not yet supported on jython.")
504.557 -
504.558 -def getdefaulttimeout():
504.559 - return _defaulttimeout
504.560 -
504.561 -def _calctimeoutvalue(value):
504.562 - if value is None:
504.563 - return None
504.564 - try:
504.565 - floatvalue = float(value)
504.566 - except:
504.567 - raise TypeError('Socket timeout value must be a number or None')
504.568 - if floatvalue < 0.0:
504.569 - raise ValueError("Socket timeout value cannot be negative")
504.570 - if floatvalue < 0.000001:
504.571 - return 0.0
504.572 - return floatvalue
504.573 -
504.574 -def setdefaulttimeout(timeout):
504.575 - global _defaulttimeout
504.576 - try:
504.577 - _defaulttimeout = _calctimeoutvalue(timeout)
504.578 - finally:
504.579 - _nonblocking_api_mixin.timeout = _defaulttimeout
504.580 -
504.581 -def htons(x): return x
504.582 -def htonl(x): return x
504.583 -def ntohs(x): return x
504.584 -def ntohl(x): return x
504.585 -
504.586 -class _nonblocking_api_mixin:
504.587 -
504.588 - timeout = _defaulttimeout
504.589 - mode = MODE_BLOCKING
504.590 - reference_count = 0
504.591 - close_lock = threading.Lock()
504.592 -
504.593 - def __init__(self):
504.594 - self.pending_options = {
504.595 - SO_REUSEADDR: 0,
504.596 - }
504.597 -
504.598 - def gettimeout(self):
504.599 - return self.timeout
504.600 -
504.601 - def settimeout(self, timeout):
504.602 - self.timeout = _calctimeoutvalue(timeout)
504.603 - if self.timeout is None:
504.604 - self.mode = MODE_BLOCKING
504.605 - elif self.timeout < 0.000001:
504.606 - self.mode = MODE_NONBLOCKING
504.607 - else:
504.608 - self.mode = MODE_TIMEOUT
504.609 - self._config()
504.610 -
504.611 - def setblocking(self, flag):
504.612 - if flag:
504.613 - self.mode = MODE_BLOCKING
504.614 - self.timeout = None
504.615 - else:
504.616 - self.mode = MODE_NONBLOCKING
504.617 - self.timeout = 0.0
504.618 - self._config()
504.619 -
504.620 - def getblocking(self):
504.621 - return self.mode == MODE_BLOCKING
504.622 -
504.623 - def setsockopt(self, level, optname, value):
504.624 - if level != SOL_SOCKET: return
504.625 - try:
504.626 - if self.sock_impl:
504.627 - self.sock_impl.setsockopt(optname, value)
504.628 - else:
504.629 - self.pending_options[optname] = value
504.630 - except java.lang.Exception, jlx:
504.631 - raise _map_exception(jlx)
504.632 -
504.633 - def getsockopt(self, level, optname):
504.634 - if level != SOL_SOCKET: return
504.635 - try:
504.636 - if self.sock_impl:
504.637 - return self.sock_impl.getsockopt(optname)
504.638 - else:
504.639 - return self.pending_options.get(optname, None)
504.640 - except java.lang.Exception, jlx:
504.641 - raise _map_exception(jlx)
504.642 -
504.643 - def _config(self):
504.644 - assert self.mode in _permitted_modes
504.645 - if self.sock_impl:
504.646 - self.sock_impl.config(self.mode, self.timeout)
504.647 - for k in self.pending_options.keys():
504.648 - if k != SO_REUSEADDR:
504.649 - self.sock_impl.setsockopt(k, self.pending_options[k])
504.650 -
504.651 - def getchannel(self):
504.652 - if not self.sock_impl:
504.653 - return None
504.654 - return self.sock_impl.getchannel()
504.655 -
504.656 - def fileno(self):
504.657 - if not self.sock_impl:
504.658 - return None
504.659 - return self.sock_impl.fileno()
504.660 -
504.661 - def _get_jsocket(self):
504.662 - return self.sock_impl.jsocket
504.663 -
504.664 -def _unpack_address_tuple(address_tuple, for_tx=False):
504.665 - # TODO: Upgrade to support the 4-tuples used for IPv6 addresses
504.666 - # which include flowinfo and scope_id.
504.667 - # To be upgraded in synch with getaddrinfo
504.668 - error_message = "Address must be a tuple of (hostname, port)"
504.669 - if not isinstance(address_tuple, tuple) or \
504.670 - not isinstance(address_tuple[0], basestring) or \
504.671 - not isinstance(address_tuple[1], (int, long)):
504.672 - raise TypeError(error_message)
504.673 - hostname = address_tuple[0]
504.674 - if isinstance(hostname, unicode):
504.675 - # XXX: Should be encode('idna') (See CPython
504.676 - # socketmodule::getsockaddrarg), but Jython's idna support is
504.677 - # currently broken
504.678 - hostname = hostname.encode()
504.679 - hostname = hostname.strip()
504.680 - if hostname == "<broadcast>":
504.681 - if for_tx:
504.682 - hostname = "255.255.255.255"
504.683 - else:
504.684 - hostname = "0.0.0.0"
504.685 - return hostname, address_tuple[1]
504.686 -
504.687 -class _tcpsocket(_nonblocking_api_mixin):
504.688 -
504.689 - sock_impl = None
504.690 - istream = None
504.691 - ostream = None
504.692 - local_addr = None
504.693 - server = 0
504.694 -
504.695 - def __init__(self):
504.696 - _nonblocking_api_mixin.__init__(self)
504.697 -
504.698 - def bind(self, addr):
504.699 - assert not self.sock_impl
504.700 - assert not self.local_addr
504.701 - # Do the address format check
504.702 - _unpack_address_tuple(addr)
504.703 - self.local_addr = addr
504.704 -
504.705 - def listen(self, backlog):
504.706 - "This signifies a server socket"
504.707 - try:
504.708 - assert not self.sock_impl
504.709 - self.server = 1
504.710 - if self.local_addr:
504.711 - host, port = _unpack_address_tuple(self.local_addr)
504.712 - else:
504.713 - host, port = "", 0
504.714 - self.sock_impl = _server_socket_impl(host, port, backlog, self.pending_options[SO_REUSEADDR])
504.715 - self._config()
504.716 - except java.lang.Exception, jlx:
504.717 - raise _map_exception(jlx)
504.718 -
504.719 - def accept(self):
504.720 - "This signifies a server socket"
504.721 - try:
504.722 - if not self.sock_impl:
504.723 - self.listen()
504.724 - assert self.server
504.725 - new_sock = self.sock_impl.accept()
504.726 - if not new_sock:
504.727 - raise would_block_error()
504.728 - cliconn = _tcpsocket()
504.729 - cliconn.pending_options[SO_REUSEADDR] = new_sock.jsocket.getReuseAddress()
504.730 - cliconn.sock_impl = new_sock
504.731 - cliconn._setup()
504.732 - return cliconn, new_sock.getpeername()
504.733 - except java.lang.Exception, jlx:
504.734 - raise _map_exception(jlx)
504.735 -
504.736 - def _get_host_port(self, addr):
504.737 - host, port = _unpack_address_tuple(addr)
504.738 - if host == "":
504.739 - host = java.net.InetAddress.getLocalHost()
504.740 - return host, port
504.741 -
504.742 - def _do_connect(self, addr):
504.743 - try:
504.744 - assert not self.sock_impl
504.745 - host, port = self._get_host_port(addr)
504.746 - self.sock_impl = _client_socket_impl()
504.747 - if self.local_addr: # Has the socket been bound to a local address?
504.748 - bind_host, bind_port = _unpack_address_tuple(self.local_addr)
504.749 - self.sock_impl.bind(bind_host, bind_port, self.pending_options[SO_REUSEADDR])
504.750 - self._config() # Configure timeouts, etc, now that the socket exists
504.751 - self.sock_impl.connect(host, port)
504.752 - except java.lang.Exception, jlx:
504.753 - raise _map_exception(jlx)
504.754 -
504.755 - def connect(self, addr):
504.756 - "This signifies a client socket"
504.757 - self._do_connect(addr)
504.758 - self._setup()
504.759 -
504.760 - def connect_ex(self, addr):
504.761 - "This signifies a client socket"
504.762 - if not self.sock_impl:
504.763 - self._do_connect(addr)
504.764 - if self.sock_impl.finish_connect():
504.765 - self._setup()
504.766 - if self.mode == MODE_NONBLOCKING:
504.767 - return errno.EISCONN
504.768 - return 0
504.769 - return errno.EINPROGRESS
504.770 -
504.771 - def _setup(self):
504.772 - if self.mode != MODE_NONBLOCKING:
504.773 - self.istream = self.sock_impl.jsocket.getInputStream()
504.774 - self.ostream = self.sock_impl.jsocket.getOutputStream()
504.775 -
504.776 - def recv(self, n):
504.777 - try:
504.778 - if not self.sock_impl: raise error(errno.ENOTCONN, 'Socket is not connected')
504.779 - if self.sock_impl.jchannel.isConnectionPending():
504.780 - self.sock_impl.jchannel.finishConnect()
504.781 - data = jarray.zeros(n, 'b')
504.782 - m = self.sock_impl.read(data)
504.783 - if m == -1:#indicates EOF has been reached, so we just return the empty string
504.784 - return ""
504.785 - elif m <= 0:
504.786 - if self.mode == MODE_NONBLOCKING:
504.787 - raise would_block_error()
504.788 - return ""
504.789 - if m < n:
504.790 - data = data[:m]
504.791 - return data.tostring()
504.792 - except java.lang.Exception, jlx:
504.793 - raise _map_exception(jlx)
504.794 -
504.795 - def recvfrom(self, n):
504.796 - return self.recv(n), None
504.797 -
504.798 - def send(self, s):
504.799 - try:
504.800 - if not self.sock_impl: raise error(errno.ENOTCONN, 'Socket is not connected')
504.801 - if self.sock_impl.jchannel.isConnectionPending():
504.802 - self.sock_impl.jchannel.finishConnect()
504.803 - numwritten = self.sock_impl.write(s)
504.804 - return numwritten
504.805 - except java.lang.Exception, jlx:
504.806 - raise _map_exception(jlx)
504.807 -
504.808 - sendall = send
504.809 -
504.810 - def getsockname(self):
504.811 - try:
504.812 - if not self.sock_impl:
504.813 - host, port = self.local_addr or ("", 0)
504.814 - host = java.net.InetAddress.getByName(host).getHostAddress()
504.815 - else:
504.816 - if self.server:
504.817 - host = self.sock_impl.jsocket.getInetAddress().getHostAddress()
504.818 - else:
504.819 - host = self.sock_impl.jsocket.getLocalAddress().getHostAddress()
504.820 - port = self.sock_impl.jsocket.getLocalPort()
504.821 - return (host, port)
504.822 - except java.lang.Exception, jlx:
504.823 - raise _map_exception(jlx)
504.824 -
504.825 - def getpeername(self):
504.826 - try:
504.827 - assert self.sock_impl
504.828 - assert not self.server
504.829 - host = self.sock_impl.jsocket.getInetAddress().getHostAddress()
504.830 - port = self.sock_impl.jsocket.getPort()
504.831 - return (host, port)
504.832 - except java.lang.Exception, jlx:
504.833 - raise _map_exception(jlx)
504.834 -
504.835 - def shutdown(self, how):
504.836 - if not self.sock_impl:
504.837 - raise error(errno.ENOTCONN, "Transport endpoint is not connected")
504.838 - assert how in (SHUT_RD, SHUT_WR, SHUT_RDWR)
504.839 - if how in (SHUT_RD, SHUT_RDWR):
504.840 - self.sock_impl.shutdownInput()
504.841 - if how in (SHUT_WR, SHUT_RDWR):
504.842 - self.sock_impl.shutdownOutput()
504.843 -
504.844 - def close(self):
504.845 - try:
504.846 - if self.istream:
504.847 - self.istream.close()
504.848 - if self.ostream:
504.849 - self.ostream.close()
504.850 - if self.sock_impl:
504.851 - self.sock_impl.close()
504.852 - except java.lang.Exception, jlx:
504.853 - raise _map_exception(jlx)
504.854 -
504.855 -
504.856 -class _udpsocket(_nonblocking_api_mixin):
504.857 -
504.858 - sock_impl = None
504.859 - addr = None
504.860 -
504.861 - def __init__(self):
504.862 - _nonblocking_api_mixin.__init__(self)
504.863 -
504.864 - def bind(self, addr):
504.865 - try:
504.866 - assert not self.sock_impl
504.867 - host, port = _unpack_address_tuple(addr)
504.868 - host_address = java.net.InetAddress.getByName(host)
504.869 - self.sock_impl = _datagram_socket_impl(port, host_address, self.pending_options[SO_REUSEADDR])
504.870 - self._config()
504.871 - except java.lang.Exception, jlx:
504.872 - raise _map_exception(jlx)
504.873 -
504.874 - def _do_connect(self, addr):
504.875 - try:
504.876 - host, port = _unpack_address_tuple(addr)
504.877 - assert not self.addr
504.878 - self.addr = addr
504.879 - if not self.sock_impl:
504.880 - self.sock_impl = _datagram_socket_impl()
504.881 - self._config()
504.882 - self.sock_impl.connect(host, port)
504.883 - except java.lang.Exception, jlx:
504.884 - raise _map_exception(jlx)
504.885 -
504.886 - def connect(self, addr):
504.887 - self._do_connect(addr)
504.888 -
504.889 - def connect_ex(self, addr):
504.890 - if not self.sock_impl:
504.891 - self._do_connect(addr)
504.892 - if self.sock_impl.finish_connect():
504.893 - if self.mode == MODE_NONBLOCKING:
504.894 - return errno.EISCONN
504.895 - return 0
504.896 - return errno.EINPROGRESS
504.897 -
504.898 - def sendto(self, data, p1, p2=None):
504.899 - try:
504.900 - if not p2:
504.901 - flags, addr = 0, p1
504.902 - else:
504.903 - flags, addr = 0, p2
504.904 - if not self.sock_impl:
504.905 - self.sock_impl = _datagram_socket_impl()
504.906 - self._config()
504.907 - host, port = _unpack_address_tuple(addr, True)
504.908 - byte_array = java.lang.String(data).getBytes('iso-8859-1')
504.909 - result = self.sock_impl.sendto(byte_array, host, port, flags)
504.910 - return result
504.911 - except java.lang.Exception, jlx:
504.912 - raise _map_exception(jlx)
504.913 -
504.914 - def send(self, data, flags=None):
504.915 - if not self.addr: raise error(errno.ENOTCONN, "Socket is not connected")
504.916 - byte_array = java.lang.String(data).getBytes('iso-8859-1')
504.917 - return self.sock_impl.send(byte_array, flags)
504.918 -
504.919 - def recvfrom(self, num_bytes, flags=None):
504.920 - """
504.921 - There is some disagreement as to what the behaviour should be if
504.922 - a recvfrom operation is requested on an unbound socket.
504.923 - See the following links for more information
504.924 - http://bugs.jython.org/issue1005
504.925 - http://bugs.sun.com/view_bug.do?bug_id=6621689
504.926 - """
504.927 - try:
504.928 - # This is the old 2.1 behaviour
504.929 - #assert self.sock_impl
504.930 - # This is amak's preferred interpretation
504.931 - #raise error(errno.ENOTCONN, "Recvfrom on unbound udp socket meaningless operation")
504.932 - # And this is the option for cpython compatibility
504.933 - if not self.sock_impl:
504.934 - self.sock_impl = _datagram_socket_impl()
504.935 - self._config()
504.936 - return self.sock_impl.recvfrom(num_bytes, flags)
504.937 - except java.lang.Exception, jlx:
504.938 - raise _map_exception(jlx)
504.939 -
504.940 - def recv(self, num_bytes, flags=None):
504.941 - if not self.sock_impl: raise error(errno.ENOTCONN, "Socket is not connected")
504.942 - try:
504.943 - return self.sock_impl.recv(num_bytes, flags)
504.944 - except java.lang.Exception, jlx:
504.945 - raise _map_exception(jlx)
504.946 -
504.947 - def getsockname(self):
504.948 - try:
504.949 - assert self.sock_impl
504.950 - host = self.sock_impl.jsocket.getLocalAddress().getHostAddress()
504.951 - port = self.sock_impl.jsocket.getLocalPort()
504.952 - return (host, port)
504.953 - except java.lang.Exception, jlx:
504.954 - raise _map_exception(jlx)
504.955 -
504.956 - def getpeername(self):
504.957 - try:
504.958 - assert self.sock
504.959 - host = self.sock_impl.jsocket.getInetAddress().getHostAddress()
504.960 - port = self.sock_impl.jsocket.getPort()
504.961 - return (host, port)
504.962 - except java.lang.Exception, jlx:
504.963 - raise _map_exception(jlx)
504.964 -
504.965 - def __del__(self):
504.966 - self.close()
504.967 -
504.968 - def close(self):
504.969 - try:
504.970 - if self.sock_impl:
504.971 - self.sock_impl.close()
504.972 - except java.lang.Exception, jlx:
504.973 - raise _map_exception(jlx)
504.974 -
504.975 -_socketmethods = (
504.976 - 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
504.977 - 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
504.978 - 'sendall', 'setblocking',
504.979 - 'settimeout', 'gettimeout', 'shutdown', 'getchannel')
504.980 -
504.981 -# All the method names that must be delegated to either the real socket
504.982 -# object or the _closedsocket object.
504.983 -_delegate_methods = ("recv", "recvfrom", "recv_into", "recvfrom_into",
504.984 - "send", "sendto")
504.985 -
504.986 -class _closedsocket(object):
504.987 - __slots__ = []
504.988 - def _dummy(*args):
504.989 - raise error(errno.EBADF, 'Bad file descriptor')
504.990 - # All _delegate_methods must also be initialized here.
504.991 - send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
504.992 - __getattr__ = _dummy
504.993 -
504.994 -class _socketobject(object):
504.995 -
504.996 - __doc__ = _realsocket.__doc__
504.997 -
504.998 - __slots__ = ["_sock", "__weakref__"] + list(_delegate_methods)
504.999 -
504.1000 - def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
504.1001 - if _sock is None:
504.1002 - _sock = _realsocket(family, type, proto)
504.1003 - _sock.reference_count += 1
504.1004 - elif isinstance(_sock, _nonblocking_api_mixin):
504.1005 - _sock.reference_count += 1
504.1006 - self._sock = _sock
504.1007 - for method in _delegate_methods:
504.1008 - meth = getattr(_sock, method, None)
504.1009 - if meth:
504.1010 - setattr(self, method, meth)
504.1011 -
504.1012 - def close(self):
504.1013 - _sock = self._sock
504.1014 - if isinstance(_sock, _nonblocking_api_mixin):
504.1015 - _sock.close_lock.acquire()
504.1016 - try:
504.1017 - _sock.reference_count -=1
504.1018 - if not _sock.reference_count:
504.1019 - _sock.close()
504.1020 - self._sock = _closedsocket()
504.1021 - dummy = self._sock._dummy
504.1022 - for method in _delegate_methods:
504.1023 - setattr(self, method, dummy)
504.1024 - self.send = self.recv = self.sendto = self.recvfrom = \
504.1025 - self._sock._dummy
504.1026 - finally:
504.1027 - _sock.close_lock.release()
504.1028 - #close.__doc__ = _realsocket.close.__doc__
504.1029 -
504.1030 - def accept(self):
504.1031 - sock, addr = self._sock.accept()
504.1032 - return _socketobject(_sock=sock), addr
504.1033 - #accept.__doc__ = _realsocket.accept.__doc__
504.1034 -
504.1035 - def dup(self):
504.1036 - """dup() -> socket object
504.1037 -
504.1038 - Return a new socket object connected to the same system resource."""
504.1039 - _sock = self._sock
504.1040 - if not isinstance(_sock, _nonblocking_api_mixin):
504.1041 - return _socketobject(_sock=_sock)
504.1042 -
504.1043 - _sock.close_lock.acquire()
504.1044 - try:
504.1045 - duped = _socketobject(_sock=_sock)
504.1046 - finally:
504.1047 - _sock.close_lock.release()
504.1048 - return duped
504.1049 -
504.1050 - def makefile(self, mode='r', bufsize=-1):
504.1051 - """makefile([mode[, bufsize]]) -> file object
504.1052 -
504.1053 - Return a regular file object corresponding to the socket. The mode
504.1054 - and bufsize arguments are as for the built-in open() function."""
504.1055 - _sock = self._sock
504.1056 - if not isinstance(_sock, _nonblocking_api_mixin):
504.1057 - return _fileobject(_sock, mode, bufsize)
504.1058 -
504.1059 - _sock.close_lock.acquire()
504.1060 - try:
504.1061 - fileobject = _fileobject(_sock, mode, bufsize)
504.1062 - finally:
504.1063 - _sock.close_lock.release()
504.1064 - return fileobject
504.1065 -
504.1066 - family = property(lambda self: self._sock.family, doc="the socket family")
504.1067 - type = property(lambda self: self._sock.type, doc="the socket type")
504.1068 - proto = property(lambda self: self._sock.proto, doc="the socket protocol")
504.1069 -
504.1070 - _s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
504.1071 - #"%s.__doc__ = _realsocket.%s.__doc__\n")
504.1072 - )
504.1073 - for _m in _socketmethods:
504.1074 - #exec _s % (_m, _m, _m, _m)
504.1075 - exec _s % (_m, _m)
504.1076 - del _m, _s
504.1077 -
504.1078 -socket = SocketType = _socketobject
504.1079 -
504.1080 -class _fileobject(object):
504.1081 - """Faux file object attached to a socket object."""
504.1082 -
504.1083 - default_bufsize = 8192
504.1084 - name = "<socket>"
504.1085 -
504.1086 - __slots__ = ["mode", "bufsize", "softspace",
504.1087 - # "closed" is a property, see below
504.1088 - "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf",
504.1089 - "_close"]
504.1090 -
504.1091 - def __init__(self, sock, mode='rb', bufsize=-1, close=False):
504.1092 - self._sock = sock
504.1093 - if isinstance(sock, _nonblocking_api_mixin):
504.1094 - sock.reference_count += 1
504.1095 - self.mode = mode # Not actually used in this version
504.1096 - if bufsize < 0:
504.1097 - bufsize = self.default_bufsize
504.1098 - self.bufsize = bufsize
504.1099 - self.softspace = False
504.1100 - if bufsize == 0:
504.1101 - self._rbufsize = 1
504.1102 - elif bufsize == 1:
504.1103 - self._rbufsize = self.default_bufsize
504.1104 - else:
504.1105 - self._rbufsize = bufsize
504.1106 - self._wbufsize = bufsize
504.1107 - self._rbuf = "" # A string
504.1108 - self._wbuf = [] # A list of strings
504.1109 - self._close = close
504.1110 -
504.1111 - def _getclosed(self):
504.1112 - return self._sock is None
504.1113 - closed = property(_getclosed, doc="True if the file is closed")
504.1114 -
504.1115 - def close(self):
504.1116 - try:
504.1117 - if self._sock:
504.1118 - self.flush()
504.1119 - finally:
504.1120 - if self._sock:
504.1121 - if isinstance(self._sock, _nonblocking_api_mixin):
504.1122 - self._sock.reference_count -= 1
504.1123 - if not self._sock.reference_count or self._close:
504.1124 - self._sock.close()
504.1125 - elif self._close:
504.1126 - self._sock.close()
504.1127 - self._sock = None
504.1128 -
504.1129 - def __del__(self):
504.1130 - try:
504.1131 - self.close()
504.1132 - except:
504.1133 - # close() may fail if __init__ didn't complete
504.1134 - pass
504.1135 -
504.1136 - def flush(self):
504.1137 - if self._wbuf:
504.1138 - buffer = "".join(self._wbuf)
504.1139 - self._wbuf = []
504.1140 - self._sock.sendall(buffer)
504.1141 -
504.1142 - def fileno(self):
504.1143 - return self._sock.fileno()
504.1144 -
504.1145 - def write(self, data):
504.1146 - data = str(data) # XXX Should really reject non-string non-buffers
504.1147 - if not data:
504.1148 - return
504.1149 - self._wbuf.append(data)
504.1150 - if (self._wbufsize == 0 or
504.1151 - self._wbufsize == 1 and '\n' in data or
504.1152 - self._get_wbuf_len() >= self._wbufsize):
504.1153 - self.flush()
504.1154 -
504.1155 - def writelines(self, list):
504.1156 - # XXX We could do better here for very long lists
504.1157 - # XXX Should really reject non-string non-buffers
504.1158 - self._wbuf.extend(filter(None, map(str, list)))
504.1159 - if (self._wbufsize <= 1 or
504.1160 - self._get_wbuf_len() >= self._wbufsize):
504.1161 - self.flush()
504.1162 -
504.1163 - def _get_wbuf_len(self):
504.1164 - buf_len = 0
504.1165 - for x in self._wbuf:
504.1166 - buf_len += len(x)
504.1167 - return buf_len
504.1168 -
504.1169 - def read(self, size=-1):
504.1170 - data = self._rbuf
504.1171 - if size < 0:
504.1172 - # Read until EOF
504.1173 - buffers = []
504.1174 - if data:
504.1175 - buffers.append(data)
504.1176 - self._rbuf = ""
504.1177 - if self._rbufsize <= 1:
504.1178 - recv_size = self.default_bufsize
504.1179 - else:
504.1180 - recv_size = self._rbufsize
504.1181 - while True:
504.1182 - data = self._sock.recv(recv_size)
504.1183 - if not data:
504.1184 - break
504.1185 - buffers.append(data)
504.1186 - return "".join(buffers)
504.1187 - else:
504.1188 - # Read until size bytes or EOF seen, whichever comes first
504.1189 - buf_len = len(data)
504.1190 - if buf_len >= size:
504.1191 - self._rbuf = data[size:]
504.1192 - return data[:size]
504.1193 - buffers = []
504.1194 - if data:
504.1195 - buffers.append(data)
504.1196 - self._rbuf = ""
504.1197 - while True:
504.1198 - left = size - buf_len
504.1199 - recv_size = min(self._rbufsize, left)
504.1200 - data = self._sock.recv(recv_size)
504.1201 - if not data:
504.1202 - break
504.1203 - buffers.append(data)
504.1204 - n = len(data)
504.1205 - if n >= left:
504.1206 - self._rbuf = data[left:]
504.1207 - buffers[-1] = data[:left]
504.1208 - break
504.1209 - buf_len += n
504.1210 - return "".join(buffers)
504.1211 -
504.1212 - def readline(self, size=-1):
504.1213 - data = self._rbuf
504.1214 - if size < 0:
504.1215 - # Read until \n or EOF, whichever comes first
504.1216 - if self._rbufsize <= 1:
504.1217 - # Speed up unbuffered case
504.1218 - assert data == ""
504.1219 - buffers = []
504.1220 - recv = self._sock.recv
504.1221 - while data != "\n":
504.1222 - data = recv(1)
504.1223 - if not data:
504.1224 - break
504.1225 - buffers.append(data)
504.1226 - return "".join(buffers)
504.1227 - nl = data.find('\n')
504.1228 - if nl >= 0:
504.1229 - nl += 1
504.1230 - self._rbuf = data[nl:]
504.1231 - return data[:nl]
504.1232 - buffers = []
504.1233 - if data:
504.1234 - buffers.append(data)
504.1235 - self._rbuf = ""
504.1236 - while True:
504.1237 - data = self._sock.recv(self._rbufsize)
504.1238 - if not data:
504.1239 - break
504.1240 - buffers.append(data)
504.1241 - nl = data.find('\n')
504.1242 - if nl >= 0:
504.1243 - nl += 1
504.1244 - self._rbuf = data[nl:]
504.1245 - buffers[-1] = data[:nl]
504.1246 - break
504.1247 - return "".join(buffers)
504.1248 - else:
504.1249 - # Read until size bytes or \n or EOF seen, whichever comes first
504.1250 - nl = data.find('\n', 0, size)
504.1251 - if nl >= 0:
504.1252 - nl += 1
504.1253 - self._rbuf = data[nl:]
504.1254 - return data[:nl]
504.1255 - buf_len = len(data)
504.1256 - if buf_len >= size:
504.1257 - self._rbuf = data[size:]
504.1258 - return data[:size]
504.1259 - buffers = []
504.1260 - if data:
504.1261 - buffers.append(data)
504.1262 - self._rbuf = ""
504.1263 - while True:
504.1264 - data = self._sock.recv(self._rbufsize)
504.1265 - if not data:
504.1266 - break
504.1267 - buffers.append(data)
504.1268 - left = size - buf_len
504.1269 - nl = data.find('\n', 0, left)
504.1270 - if nl >= 0:
504.1271 - nl += 1
504.1272 - self._rbuf = data[nl:]
504.1273 - buffers[-1] = data[:nl]
504.1274 - break
504.1275 - n = len(data)
504.1276 - if n >= left:
504.1277 - self._rbuf = data[left:]
504.1278 - buffers[-1] = data[:left]
504.1279 - break
504.1280 - buf_len += n
504.1281 - return "".join(buffers)
504.1282 -
504.1283 - def readlines(self, sizehint=0):
504.1284 - total = 0
504.1285 - list = []
504.1286 - while True:
504.1287 - line = self.readline()
504.1288 - if not line:
504.1289 - break
504.1290 - list.append(line)
504.1291 - total += len(line)
504.1292 - if sizehint and total >= sizehint:
504.1293 - break
504.1294 - return list
504.1295 -
504.1296 - # Iterator protocols
504.1297 -
504.1298 - def __iter__(self):
504.1299 - return self
504.1300 -
504.1301 - def next(self):
504.1302 - line = self.readline()
504.1303 - if not line:
504.1304 - raise StopIteration
504.1305 - return line
504.1306 -
504.1307 -
504.1308 -# Define the SSL support
504.1309 -
504.1310 -class ssl:
504.1311 -
504.1312 - def __init__(self, plain_sock, keyfile=None, certfile=None):
504.1313 - self.ssl_sock = self.make_ssl_socket(plain_sock)
504.1314 -
504.1315 - def make_ssl_socket(self, plain_socket, auto_close=0):
504.1316 - java_net_socket = plain_socket._get_jsocket()
504.1317 - assert isinstance(java_net_socket, java.net.Socket)
504.1318 - host = java_net_socket.getInetAddress().getHostAddress()
504.1319 - port = java_net_socket.getPort()
504.1320 - factory = javax.net.ssl.SSLSocketFactory.getDefault();
504.1321 - ssl_socket = factory.createSocket(java_net_socket, host, port, auto_close)
504.1322 - ssl_socket.setEnabledCipherSuites(ssl_socket.getSupportedCipherSuites())
504.1323 - ssl_socket.startHandshake()
504.1324 - return ssl_socket
504.1325 -
504.1326 - def read(self, n=4096):
504.1327 - # Probably needs some work on efficency
504.1328 - in_buf = java.io.BufferedInputStream(self.ssl_sock.getInputStream())
504.1329 - data = jarray.zeros(n, 'b')
504.1330 - m = in_buf.read(data, 0, n)
504.1331 - if m <= 0:
504.1332 - return ""
504.1333 - if m < n:
504.1334 - data = data[:m]
504.1335 - return data.tostring()
504.1336 -
504.1337 - def write(self, s):
504.1338 - # Probably needs some work on efficency
504.1339 - out = java.io.BufferedOutputStream(self.ssl_sock.getOutputStream())
504.1340 - out.write(s)
504.1341 - out.flush()
504.1342 -
504.1343 - def _get_server_cert(self):
504.1344 - return self.ssl_sock.getSession().getPeerCertificates()[0]
504.1345 -
504.1346 - def server(self):
504.1347 - cert = self._get_server_cert()
504.1348 - return cert.getSubjectDN().toString()
504.1349 -
504.1350 - def issuer(self):
504.1351 - cert = self._get_server_cert()
504.1352 - return cert.getIssuerDN().toString()
504.1353 -
504.1354 -_realssl = ssl
504.1355 -def ssl(sock, keyfile=None, certfile=None):
504.1356 - if hasattr(sock, "_sock"):
504.1357 - sock = sock._sock
504.1358 - return _realssl(sock, keyfile, certfile)
504.1359 -
504.1360 -def test():
504.1361 - s = socket(AF_INET, SOCK_STREAM)
504.1362 - s.connect(("", 80))
504.1363 - s.send("GET / HTTP/1.0\r\n\r\n")
504.1364 - while 1:
504.1365 - data = s.recv(2000)
504.1366 - print data
504.1367 - if not data:
504.1368 - break
504.1369 -
504.1370 -if __name__ == '__main__':
504.1371 - test()
505.1 --- a/python.editor/test/unit/data/testfiles/socket.py.indexed Sun Jan 04 13:11:53 2015 -0600
505.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
505.3 @@ -1,486 +0,0 @@
505.4 -
505.5 -
505.6 -Document 0
505.7 -Searchable Keys:
505.8 - class : SocketType
505.9 - class-ig : sockettype
505.10 - extends : object
505.11 - in : socket
505.12 - member : __doc__;D;|PRIVATE|;
505.13 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,family,type,proto,_sock;
505.14 - member : __slots__;D;|PRIVATE|;
505.15 - member : _m;D;|PRIVATE|;
505.16 - member : _s;D;|PRIVATE|;
505.17 - member : _sock;D;|PRIVATE|;
505.18 - member : accept;F;|PRIVATE|;self;
505.19 - member : close;F;|PRIVATE|;self;
505.20 - member : dup;F;|PRIVATE|;self;
505.21 - member : family;D;|PRIVATE|;
505.22 - member : makefile;F;|PRIVATE|;self,mode,bufsize;
505.23 - member : proto;D;|PRIVATE|;
505.24 - member : recv;D;;
505.25 - member : recvfrom;D;;
505.26 - member : send;D;;
505.27 - member : sendto;D;;
505.28 - member : type;D;|PRIVATE|;
505.29 -
505.30 -Not Searchable Keys:
505.31 -
505.32 -
505.33 -Document 1
505.34 -Searchable Keys:
505.35 - class : _client_socket_impl
505.36 - class-ig : _client_socket_impl
505.37 - extends : _nio_impl
505.38 - in : socket
505.39 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,socket;
505.40 - member : bind;F;|PRIVATE|;self,host,port,reuse_addr;
505.41 - member : connect;F;|PRIVATE|;self,host,port;
505.42 - member : finish_connect;F;|PRIVATE|;self;
505.43 - member : host;D;;
505.44 - member : jchannel;D;;
505.45 - member : jsocket;D;;
505.46 - member : options;D;|PRIVATE|;
505.47 - member : port;D;;
505.48 - member : socketio;D;;
505.49 -
505.50 -Not Searchable Keys:
505.51 - clzattrs : ;|PRIVATE|;
505.52 -
505.53 -
505.54 -Document 2
505.55 -Searchable Keys:
505.56 - class : _closedsocket
505.57 - class-ig : _closedsocket
505.58 - extends : object
505.59 - in : socket
505.60 - member : __getattr__;F;|PRIVATE|;args;
505.61 - member : __slots__;D;|PRIVATE|;
505.62 - member : _dummy;F;|PRIVATE|;args;
505.63 - member : recv;F;|PRIVATE|;args;
505.64 - member : recv_into;F;|PRIVATE|;args;
505.65 - member : recvfrom;F;|PRIVATE|;args;
505.66 - member : recvfrom_into;F;|PRIVATE|;args;
505.67 - member : send;F;|PRIVATE|;args;
505.68 - member : sendto;F;|PRIVATE|;args;
505.69 -
505.70 -Not Searchable Keys:
505.71 - clzattrs : ;|PRIVATE|;
505.72 -
505.73 -
505.74 -Document 3
505.75 -Searchable Keys:
505.76 - class : _datagram_socket_impl
505.77 - class-ig : _datagram_socket_impl
505.78 - extends : _nio_impl
505.79 - in : socket
505.80 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,port,address,reuse_addr;
505.81 - member : _do_receive_net;F;|PRIVATE|;self,return_source_address,num_bytes,flags;
505.82 - member : _do_receive_nio;F;|PRIVATE|;self,return_source_address,num_bytes,flags;
505.83 - member : _do_send_net;F;|PRIVATE|;self,byte_array,socket_address,flags;
505.84 - member : _do_send_nio;F;|PRIVATE|;self,byte_array,socket_address,flags;
505.85 - member : connect;F;|PRIVATE|;self,host,port;
505.86 - member : disconnect;F;|PRIVATE|;self;
505.87 - member : finish_connect;F;|PRIVATE|;self;
505.88 - member : jchannel;D;;
505.89 - member : jsocket;D;;
505.90 - member : options;D;|PRIVATE|;
505.91 - member : recv;F;|PRIVATE|;self,num_bytes,flags;
505.92 - member : recvfrom;F;|PRIVATE|;self,num_bytes,flags;
505.93 - member : send;F;|PRIVATE|;self,byte_array,flags;
505.94 - member : sendto;F;|PRIVATE|;self,byte_array,host,port,flags;
505.95 - member : socketio;D;;
505.96 -
505.97 -Not Searchable Keys:
505.98 - clzattrs : ;|PRIVATE|;
505.99 -
505.100 -
505.101 -Document 4
505.102 -Searchable Keys:
505.103 - class : _fileobject
505.104 - class-ig : _fileobject
505.105 - extends : object
505.106 - in : socket
505.107 - member : __del__;F;|PRIVATE|;self;
505.108 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,sock,mode,bufsize,close;
505.109 - member : __iter__;F;|PRIVATE|;self;
505.110 - member : __slots__;D;|PRIVATE|;
505.111 - member : _close;D;|PRIVATE|;
505.112 - member : _get_wbuf_len;F;|PRIVATE|;self;
505.113 - member : _getclosed;F;|PRIVATE|;self;
505.114 - member : _rbuf;D;|PRIVATE|;
505.115 - member : _rbufsize;D;|PRIVATE|;
505.116 - member : _sock;D;|PRIVATE|;
505.117 - member : _wbuf;D;|PRIVATE|;
505.118 - member : _wbufsize;D;|PRIVATE|;
505.119 - member : bufsize;D;;
505.120 - member : close;F;|PRIVATE|;self;
505.121 - member : closed;D;|PRIVATE|;
505.122 - member : default_bufsize;D;|PRIVATE|;
505.123 - member : fileno;F;|PRIVATE|;self;
505.124 - member : flush;F;|PRIVATE|;self;
505.125 - member : mode;D;;
505.126 - member : name;D;|PRIVATE|;
505.127 - member : next;F;|PRIVATE|;self;
505.128 - member : read;F;|PRIVATE|;self,size;
505.129 - member : readline;F;|PRIVATE|;self,size;
505.130 - member : readlines;F;|PRIVATE|;self,sizehint;
505.131 - member : softspace;D;;
505.132 - member : write;F;|PRIVATE|;self,data;
505.133 - member : writelines;F;|PRIVATE|;self,list;
505.134 -
505.135 -Not Searchable Keys:
505.136 - clzattrs : ;|PRIVATE|;
505.137 -
505.138 -
505.139 -Document 5
505.140 -Searchable Keys:
505.141 - class : _nio_impl
505.142 - class-ig : _nio_impl
505.143 - in : socket
505.144 - member : _timeout_millis;D;|PRIVATE|;
505.145 - member : close;F;|PRIVATE|;self;
505.146 - member : config;F;|PRIVATE|;self,mode,timeout;
505.147 - member : fileno;F;|PRIVATE|;self;
505.148 - member : getchannel;F;|PRIVATE|;self;
505.149 - member : getpeername;F;|PRIVATE|;self;
505.150 - member : getsockopt;F;|PRIVATE|;self,option;
505.151 - member : mode;D;;
505.152 - member : mode;D;|PRIVATE|;
505.153 - member : read;F;|PRIVATE|;self,buf;
505.154 - member : setsockopt;F;|PRIVATE|;self,option,value;
505.155 - member : shutdownInput;F;|PRIVATE|;self;
505.156 - member : shutdownOutput;F;|PRIVATE|;self;
505.157 - member : timeout;D;|PRIVATE|;
505.158 - member : write;F;|PRIVATE|;self,buf;
505.159 -
505.160 -Not Searchable Keys:
505.161 - clzattrs : ;|PRIVATE|;
505.162 -
505.163 -
505.164 -Document 6
505.165 -Searchable Keys:
505.166 - class : _nonblocking_api_mixin
505.167 - class-ig : _nonblocking_api_mixin
505.168 - in : socket
505.169 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self;
505.170 - member : _config;F;|PRIVATE|;self;
505.171 - member : _get_jsocket;F;|PRIVATE|;self;
505.172 - member : close_lock;D;|PRIVATE|;
505.173 - member : fileno;F;|PRIVATE|;self;
505.174 - member : getblocking;F;|PRIVATE|;self;
505.175 - member : getchannel;F;|PRIVATE|;self;
505.176 - member : getsockopt;F;|PRIVATE|;self,level,optname;
505.177 - member : gettimeout;F;|PRIVATE|;self;
505.178 - member : mode;D;;
505.179 - member : mode;D;|PRIVATE|;
505.180 - member : pending_options;D;;
505.181 - member : reference_count;D;|PRIVATE|;
505.182 - member : setblocking;F;|PRIVATE|;self,flag;
505.183 - member : setsockopt;F;|PRIVATE|;self,level,optname,value;
505.184 - member : settimeout;F;|PRIVATE|;self,timeout;
505.185 - member : timeout;D;;
505.186 - member : timeout;D;|PRIVATE|;
505.187 -
505.188 -Not Searchable Keys:
505.189 - clzattrs : ;|PRIVATE|;
505.190 -
505.191 -
505.192 -Document 7
505.193 -Searchable Keys:
505.194 - class : _realssl
505.195 - class-ig : _realssl
505.196 - in : socket
505.197 - member : __init__;c;|CONSTRUCTOR|;self,plain_sock,keyfile,certfile;
505.198 - member : _get_server_cert;F;|PRIVATE|;self;
505.199 - member : issuer;F;;self;
505.200 - member : make_ssl_socket;F;;self,plain_socket,auto_close;
505.201 - member : read;F;;self,n;
505.202 - member : server;F;;self;
505.203 - member : ssl_sock;D;;
505.204 - member : write;F;;self,s;
505.205 -
505.206 -Not Searchable Keys:
505.207 - clzattrs : ;|PRIVATE|;
505.208 -
505.209 -
505.210 -Document 8
505.211 -Searchable Keys:
505.212 - class : _server_socket_impl
505.213 - class-ig : _server_socket_impl
505.214 - extends : _nio_impl
505.215 - in : socket
505.216 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,host,port,backlog,reuse_addr;
505.217 - member : accept;F;|PRIVATE|;self;
505.218 - member : jchannel;D;;
505.219 - member : jsocket;D;;
505.220 - member : options;D;|PRIVATE|;
505.221 - member : socketio;D;;
505.222 -
505.223 -Not Searchable Keys:
505.224 - clzattrs : ;|PRIVATE|;
505.225 -
505.226 -
505.227 -Document 9
505.228 -Searchable Keys:
505.229 - class : _socketobject
505.230 - class-ig : _socketobject
505.231 - extends : object
505.232 - in : socket
505.233 - member : __doc__;D;|PRIVATE|;
505.234 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,family,type,proto,_sock;
505.235 - member : __slots__;D;|PRIVATE|;
505.236 - member : _m;D;|PRIVATE|;
505.237 - member : _s;D;|PRIVATE|;
505.238 - member : _sock;D;|PRIVATE|;
505.239 - member : accept;F;|PRIVATE|;self;
505.240 - member : close;F;|PRIVATE|;self;
505.241 - member : dup;F;|PRIVATE|;self;
505.242 - member : family;D;|PRIVATE|;
505.243 - member : makefile;F;|PRIVATE|;self,mode,bufsize;
505.244 - member : proto;D;|PRIVATE|;
505.245 - member : recv;D;;
505.246 - member : recvfrom;D;;
505.247 - member : send;D;;
505.248 - member : sendto;D;;
505.249 - member : type;D;|PRIVATE|;
505.250 -
505.251 -Not Searchable Keys:
505.252 - clzattrs : ;|PRIVATE|;
505.253 -
505.254 -
505.255 -Document 10
505.256 -Searchable Keys:
505.257 - class : _tcpsocket
505.258 - class-ig : _tcpsocket
505.259 - extends : _nonblocking_api_mixin
505.260 - in : socket
505.261 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self;
505.262 - member : _do_connect;F;|PRIVATE|;self,addr;
505.263 - member : _get_host_port;F;|PRIVATE|;self,addr;
505.264 - member : _setup;F;|PRIVATE|;self;
505.265 - member : accept;F;|PRIVATE|;self;
505.266 - member : bind;F;|PRIVATE|;self,addr;
505.267 - member : close;F;|PRIVATE|;self;
505.268 - member : connect;F;|PRIVATE|;self,addr;
505.269 - member : connect_ex;F;|PRIVATE|;self,addr;
505.270 - member : getpeername;F;|PRIVATE|;self;
505.271 - member : getsockname;F;|PRIVATE|;self;
505.272 - member : istream;D;;
505.273 - member : istream;D;|PRIVATE|;
505.274 - member : listen;F;|PRIVATE|;self,backlog;
505.275 - member : local_addr;D;;
505.276 - member : local_addr;D;|PRIVATE|;
505.277 - member : ostream;D;;
505.278 - member : ostream;D;|PRIVATE|;
505.279 - member : recv;F;|PRIVATE|;self,n;
505.280 - member : recvfrom;F;|PRIVATE|;self,n;
505.281 - member : send;F;|PRIVATE|;self,s;
505.282 - member : sendall;F;|PRIVATE|;self,s;
505.283 - member : server;D;;
505.284 - member : server;D;|PRIVATE|;
505.285 - member : shutdown;F;|PRIVATE|;self,how;
505.286 - member : sock_impl;D;;
505.287 - member : sock_impl;D;|PRIVATE|;
505.288 -
505.289 -Not Searchable Keys:
505.290 - clzattrs : ;|PRIVATE|;
505.291 -
505.292 -
505.293 -Document 11
505.294 -Searchable Keys:
505.295 - class : _udpsocket
505.296 - class-ig : _udpsocket
505.297 - extends : _nonblocking_api_mixin
505.298 - in : socket
505.299 - member : __del__;F;|PRIVATE|;self;
505.300 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self;
505.301 - member : _do_connect;F;|PRIVATE|;self,addr;
505.302 - member : addr;D;;
505.303 - member : addr;D;|PRIVATE|;
505.304 - member : bind;F;|PRIVATE|;self,addr;
505.305 - member : close;F;|PRIVATE|;self;
505.306 - member : connect;F;|PRIVATE|;self,addr;
505.307 - member : connect_ex;F;|PRIVATE|;self,addr;
505.308 - member : getpeername;F;|PRIVATE|;self;
505.309 - member : getsockname;F;|PRIVATE|;self;
505.310 - member : recv;F;|PRIVATE|;self,num_bytes,flags;
505.311 - member : recvfrom;F;|PRIVATE|;self,num_bytes,flags;
505.312 - member : send;F;|PRIVATE|;self,data,flags;
505.313 - member : sendto;F;|PRIVATE|;self,data,p1,p2;
505.314 - member : sock_impl;D;;
505.315 - member : sock_impl;D;|PRIVATE|;
505.316 -
505.317 -Not Searchable Keys:
505.318 - clzattrs : ;|PRIVATE|;
505.319 -
505.320 -
505.321 -Document 12
505.322 -Searchable Keys:
505.323 - class : error
505.324 - class-ig : error
505.325 - extends : Exception
505.326 - in : socket
505.327 -
505.328 -Not Searchable Keys:
505.329 -
505.330 -
505.331 -Document 13
505.332 -Searchable Keys:
505.333 - class : gaierror
505.334 - class-ig : gaierror
505.335 - extends : error
505.336 - in : socket
505.337 -
505.338 -Not Searchable Keys:
505.339 -
505.340 -
505.341 -Document 14
505.342 -Searchable Keys:
505.343 - class : herror
505.344 - class-ig : herror
505.345 - extends : error
505.346 - in : socket
505.347 -
505.348 -Not Searchable Keys:
505.349 -
505.350 -
505.351 -Document 15
505.352 -Searchable Keys:
505.353 - class : socket
505.354 - class-ig : socket
505.355 - extends : object
505.356 - in : socket
505.357 - member : __doc__;D;|PRIVATE|;
505.358 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,family,type,proto,_sock;
505.359 - member : __slots__;D;|PRIVATE|;
505.360 - member : _m;D;|PRIVATE|;
505.361 - member : _s;D;|PRIVATE|;
505.362 - member : _sock;D;|PRIVATE|;
505.363 - member : accept;F;|PRIVATE|;self;
505.364 - member : close;F;|PRIVATE|;self;
505.365 - member : dup;F;|PRIVATE|;self;
505.366 - member : family;D;|PRIVATE|;
505.367 - member : makefile;F;|PRIVATE|;self,mode,bufsize;
505.368 - member : proto;D;|PRIVATE|;
505.369 - member : recv;D;;
505.370 - member : recvfrom;D;;
505.371 - member : send;D;;
505.372 - member : sendto;D;;
505.373 - member : type;D;|PRIVATE|;
505.374 -
505.375 -Not Searchable Keys:
505.376 -
505.377 -
505.378 -Document 16
505.379 -Searchable Keys:
505.380 - class : timeout
505.381 - class-ig : timeout
505.382 - extends : error
505.383 - in : socket
505.384 -
505.385 -Not Searchable Keys:
505.386 -
505.387 -
505.388 -Document 17
505.389 -Searchable Keys:
505.390 - item : AF_INET6;D;;
505.391 - item : AF_INET;D;;
505.392 - item : AF_UNSPEC;D;;
505.393 - item : AI_PASSIVE;D;;
505.394 - item : ALL;D;|PRIVATE|;
505.395 - item : MODE_BLOCKING;D;|PRIVATE|;
505.396 - item : MODE_NONBLOCKING;D;|PRIVATE|;
505.397 - item : MODE_TIMEOUT;D;|PRIVATE|;
505.398 - item : SHUT_RD;D;;
505.399 - item : SHUT_RDWR;D;;
505.400 - item : SHUT_WR;D;;
505.401 - item : SOCK_DGRAM;D;;
505.402 - item : SOCK_RAW;D;;
505.403 - item : SOCK_RDM;D;;
505.404 - item : SOCK_SEQPACKET;D;;
505.405 - item : SOCK_STREAM;D;;
505.406 - item : SOL_SOCKET;D;;
505.407 - item : SO_ACCEPTCONN;D;|PRIVATE|;
505.408 - item : SO_BROADCAST;D;;
505.409 - item : SO_DEBUG;D;|PRIVATE|;
505.410 - item : SO_DONTROUTE;D;|PRIVATE|;
505.411 - item : SO_ERROR;D;;
505.412 - item : SO_EXCLUSIVEADDRUSE;D;|PRIVATE|;
505.413 - item : SO_KEEPALIVE;D;;
505.414 - item : SO_LINGER;D;;
505.415 - item : SO_OOBINLINE;D;;
505.416 - item : SO_RCVBUF;D;;
505.417 - item : SO_RCVLOWAT;D;|PRIVATE|;
505.418 - item : SO_RCVTIMEO;D;|PRIVATE|;
505.419 - item : SO_REUSEADDR;D;;
505.420 - item : SO_REUSEPORT;D;|PRIVATE|;
505.421 - item : SO_SNDBUF;D;;
505.422 - item : SO_SNDLOWAT;D;|PRIVATE|;
505.423 - item : SO_SNDTIMEO;D;|PRIVATE|;
505.424 - item : SO_TIMEOUT;D;;
505.425 - item : SO_TYPE;D;|PRIVATE|;
505.426 - item : SO_USELOOPBACK;D;|PRIVATE|;
505.427 - item : SocketType;C;;
505.428 - item : TCP_NODELAY;D;;
505.429 - item : __all__;D;;
505.430 - item : _calctimeoutvalue;F;|PRIVATE|;value;
505.431 - item : _client_socket_impl;C;|PRIVATE|;
505.432 - item : _closedsocket;C;|PRIVATE|;
505.433 - item : _datagram_socket_impl;C;|PRIVATE|;
505.434 - item : _defaulttimeout;D;|PRIVATE|;
505.435 - item : _delegate_methods;D;|PRIVATE|;
505.436 - item : _exception_map;D;|PRIVATE|;
505.437 - item : _fileobject;C;|PRIVATE|;
505.438 - item : _gethostbyaddr;F;|PRIVATE|;name;
505.439 - item : _map_exception;F;|PRIVATE|;exc,circumstance;
505.440 - item : _nio_impl;C;|PRIVATE|;
505.441 - item : _nonblocking_api_mixin;C;|PRIVATE|;
505.442 - item : _permitted_modes;D;|PRIVATE|;
505.443 - item : _realsocket;F;|PRIVATE|;family,type,flags;
505.444 - item : _realssl;C;|PRIVATE|;
505.445 - item : _server_socket_impl;C;|PRIVATE|;
505.446 - item : _socketmethods;D;|PRIVATE|;
505.447 - item : _socketobject;C;|PRIVATE|;
505.448 - item : _tcpsocket;C;|PRIVATE|;
505.449 - item : _udpsocket;C;|PRIVATE|;
505.450 - item : _unpack_address_tuple;F;|PRIVATE|;address_tuple,for_tx;
505.451 - item : asPyString;I;|PRIVATE|;
505.452 - item : errno;I;|PRIVATE|;
505.453 - item : error;C;;
505.454 - item : gaierror;C;;
505.455 - item : getaddrinfo;F;;host,port,family,socktype,proto,flags;
505.456 - item : getdefaulttimeout;F;;;
505.457 - item : getfqdn;F;;name;
505.458 - item : gethostbyaddr;F;;name;
505.459 - item : gethostbyname;F;;name;
505.460 - item : gethostname;F;;;
505.461 - item : getnameinfo;F;|PRIVATE|;sock_addr,flags;
505.462 - item : getprotobyname;F;|PRIVATE|;protocolname;
505.463 - item : getservbyname;F;|PRIVATE|;servicename,protocolname;
505.464 - item : getservbyport;F;|PRIVATE|;port,protocolname;
505.465 - item : has_ipv6;D;;
505.466 - item : herror;C;;
505.467 - item : htonl;F;;x;
505.468 - item : htons;F;;x;
505.469 - item : jarray;I;|PRIVATE|;
505.470 - item : java;I;|PRIVATE|;
505.471 - item : javax;I;|PRIVATE|;
505.472 - item : ntohl;F;;x;
505.473 - item : ntohs;F;;x;
505.474 - item : org;I;|PRIVATE|;
505.475 - item : setdefaulttimeout;F;;timeout;
505.476 - item : socket;C;;
505.477 - item : ssl;C;|PRIVATE|;
505.478 - item : string;I;|PRIVATE|;
505.479 - item : struct;I;|PRIVATE|;
505.480 - item : sys;I;|PRIVATE|;
505.481 - item : test;F;|PRIVATE|;;
505.482 - item : threading;I;|PRIVATE|;
505.483 - item : time;I;|PRIVATE|;
505.484 - item : timeout;C;;
505.485 - item : types;I;|PRIVATE|;
505.486 - item : would_block_error;F;|PRIVATE|;exc;
505.487 - module : socket
505.488 -
505.489 -Not Searchable Keys:
506.1 --- a/python.editor/test/unit/data/testfiles/split_imports.py Sun Jan 04 13:11:53 2015 -0600
506.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
506.3 @@ -1,10 +0,0 @@
506.4 -import os
506.5 -import sys
506.6 -import sys, os
506.7 -import sys, os, foobar
506.8 -import sys as foo, os
506.9 -import sys, os as bar
506.10 -import sys as whatever, os as bar
506.11 -from subprocess import Popen, PIPE
506.12 -
506.13 -
507.1 --- a/python.editor/test/unit/data/testfiles/split_imports.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
507.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
507.3 @@ -1,11 +0,0 @@
507.4 -import os
507.5 -import sys
507.6 -import sys
507.7 -import os
507.8 -import sys, os, foobar
507.9 -import sys as foo, os
507.10 -import sys, os as bar
507.11 -import sys as whatever, os as bar
507.12 -from subprocess import Popen, PIPE
507.13 -
507.14 -
508.1 --- a/python.editor/test/unit/data/testfiles/split_imports.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
508.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
508.3 @@ -1,11 +0,0 @@
508.4 -import os
508.5 -import sys
508.6 -import sys, os
508.7 -import sys, os, foobar
508.8 -import sys as foo, os
508.9 -import sys
508.10 -import os as bar
508.11 -import sys as whatever, os as bar
508.12 -from subprocess import Popen, PIPE
508.13 -
508.14 -
509.1 --- a/python.editor/test/unit/data/testfiles/split_imports.py.testHint1.hints Sun Jan 04 13:11:53 2015 -0600
509.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
509.3 @@ -1,20 +0,0 @@
509.4 -import sys, os
509.5 ---------------
509.6 -HINT:Multiple imports per import statement is discouraged
509.7 -FIX:Split import into individual import statements
509.8 -import sys, os, foobar
509.9 -----------------------
509.10 -HINT:Multiple imports per import statement is discouraged
509.11 -FIX:Split import into individual import statements
509.12 -import sys as foo, os
509.13 ----------------------
509.14 -HINT:Multiple imports per import statement is discouraged
509.15 -FIX:Split import into individual import statements
509.16 -import sys, os as bar
509.17 ----------------------
509.18 -HINT:Multiple imports per import statement is discouraged
509.19 -FIX:Split import into individual import statements
509.20 -import sys as whatever, os as bar
509.21 ----------------------------------
509.22 -HINT:Multiple imports per import statement is discouraged
509.23 -FIX:Split import into individual import statements
510.1 --- a/python.editor/test/unit/data/testfiles/star_arg.py Sun Jan 04 13:11:53 2015 -0600
510.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
510.3 @@ -1,12 +0,0 @@
510.4 -def myfunc(funcparam):
510.5 - localvar = 1
510.6 - toplevelvar4 = 6
510.7 - fn(*args)
510.8 - x*3
510.9 - print toplevelvar4
510.10 -
510.11 - x = myfunc
510.12 - myfunc(5)
510.13 - x()
510.14 - pass
510.15 -
511.1 --- a/python.editor/test/unit/data/testfiles/star_arg.py.formatted Sun Jan 04 13:11:53 2015 -0600
511.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
511.3 @@ -1,12 +0,0 @@
511.4 -def myfunc(funcparam):
511.5 - localvar = 1
511.6 - toplevelvar4 = 6
511.7 - fn(*args)
511.8 - x * 3
511.9 - print toplevelvar4
511.10 -
511.11 - x = myfunc
511.12 - myfunc(5)
511.13 - x()
511.14 - pass
511.15 -
512.1 --- a/python.editor/test/unit/data/testfiles/staticmethods.py Sun Jan 04 13:11:53 2015 -0600
512.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
512.3 @@ -1,14 +0,0 @@
512.4 -class Page(object):
512.5 - def __init__(self, name, entity=None):
512.6 - self.name = name
512.7 - self.entity = entity
512.8 -
512.9 - @staticmethod
512.10 - def load(name):
512.11 - pass
512.12 -
512.13 - @staticmethod
512.14 - def exists(name):
512.15 - pass
512.16 -
512.17 -
513.1 --- a/python.editor/test/unit/data/testfiles/staticmethods.py.offsets Sun Jan 04 13:11:53 2015 -0600
513.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
513.3 @@ -1,15 +0,0 @@
513.4 -
513.5 -<Module><ClassDef>class Page(<Name>object</Name>):
513.6 - <FunctionDef>def __init__(<Name>self</Name>, <Name>name</Name>, <Name>entity</Name>=<Name>None</Name>):
513.7 - <Assign><Attribute><Name>self</Name>.name</Attribute> = <Name>name</Name></Assign>
513.8 - <Assign><Attribute><Name>self</Name>.entity</Attribute> = <Name>entity</Name></Assign>
513.9 -
513.10 - </FunctionDef> <FunctionDef><Name>@staticmethod
513.11 -</Name> def load(<Name>name</Name>):
513.12 - <Pass>pass</Pass>
513.13 -
513.14 - </FunctionDef> <FunctionDef><Name>@staticmethod
513.15 -</Name> def exists(<Name>name</Name>):
513.16 - <Pass>pass</Pass>
513.17 -
513.18 -</FunctionDef></ClassDef></Module>
514.1 --- a/python.editor/test/unit/data/testfiles/staticmethods.py.semantic Sun Jan 04 13:11:53 2015 -0600
514.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
514.3 @@ -1,14 +0,0 @@
514.4 -class Page(object):
514.5 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:name<|, |>PARAMETER:entity<|=None):
514.6 - |>PARAMETER:self<|.name = |>PARAMETER:name<|
514.7 - |>PARAMETER:self<|.entity = |>PARAMETER:entity<|
514.8 -
514.9 - @staticmethod
514.10 - def |>METHOD:load<|(|>PARAMETER,UNUSED:name<|):
514.11 - pass
514.12 -
514.13 - @staticmethod
514.14 - def |>METHOD:exists<|(|>PARAMETER,UNUSED:name<|):
514.15 - pass
514.16 -
514.17 -
515.1 --- a/python.editor/test/unit/data/testfiles/surround.py Sun Jan 04 13:11:53 2015 -0600
515.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
515.3 @@ -1,7 +0,0 @@
515.4 -def loadstable(name,theglobals=None,thelocals=None,fromlist=None,level=-1):
515.5 - if name.split('.')[0]!=theglobals
515.6 - print "first"
515.7 - print "second"
515.8 - print "third"
515.9 -
515.10 -
516.1 --- a/python.editor/test/unit/data/testfiles/surround.py.testFix4.fixed Sun Jan 04 13:11:53 2015 -0600
516.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
516.3 @@ -1,10 +0,0 @@
516.4 -def loadstable(name,theglobals=None,thelocals=None,fromlist=None,level=-1):
516.5 - if name.split('.')[0]!=theglobals
516.6 - print "first"
516.7 - try:
516.8 - print "second"
516.9 - finally:
516.10 -
516.11 - print "third"
516.12 -
516.13 -
517.1 --- a/python.editor/test/unit/data/testfiles/syntax-string.py.txt Sun Jan 04 13:11:53 2015 -0600
517.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
517.3 @@ -1,63 +0,0 @@
517.4 -.t.e.s.t. Escapes
517.5 -Here's an \nescape, here's another one: \\, and here's several: \n\\\\\\
517.6 -Here's an unbalanced one \
517.7 -.e.o.f.
517.8 -
517.9 -.t.e.s.t. URLs
517.10 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
517.11 -See https://foobar/baz
517.12 -
517.13 -For more about DST than you ever wanted to know, see
517.14 -ftp://elsie.nci.nih.gov/pub/
517.15 -.e.o.f.
517.16 -
517.17 -.t.e.s.t. String 1
517.18 -
517.19 -This is the "example" module.
517.20 -
517.21 -The example module supplies one function, factorial(). For example,
517.22 -
517.23 ->>> factorial(5)
517.24 -120
517.25 -.e.o.f.
517.26 -
517.27 -.t.e.s.t. String 2
517.28 -Return the factorial of n, an exact integer >= 0.
517.29 -
517.30 - If the result is small enough to fit in an int, return an int.
517.31 - Else return a long.
517.32 -
517.33 - >>> [factorial(n) for n in range(6)]
517.34 - [1, 1, 2, 6, 24, 120]
517.35 - >>> [factorial(long(n)) for n in range(6)]
517.36 - [1, 1, 2, 6, 24, 120]
517.37 - >>> factorial(30)
517.38 - 265252859812191058636308480000000L
517.39 - >>> factorial(30L)
517.40 - 265252859812191058636308480000000L
517.41 - >>> factorial(-1)
517.42 - Traceback (most recent call last):
517.43 - ...
517.44 - ValueError: n must be >= 0
517.45 - x = \n foo
517.46 -
517.47 - Factorials of floats are OK, but the float must be an exact integer:
517.48 - >>> factorial(30.1)
517.49 - Traceback (most recent call last):
517.50 - ...
517.51 - ValueError: n must be exact integer
517.52 - >>> factorial(30.0)
517.53 - 265252859812191058636308480000000L
517.54 -
517.55 - It must also not be ridiculously large:
517.56 - >>> factorial(1e100)
517.57 - Traceback (most recent call last):
517.58 - ...
517.59 - OverflowError: n too large
517.60 -
517.61 -.e.o.f.
517.62 -.t.e.s.t. Errors
517.63 -Here's another one:
517.64 ->> Wrong
517.65 ->>>
517.66 -.e.o.f.
518.1 --- a/python.editor/test/unit/data/testfiles/syntax-string.py.txt.tokens.txt Sun Jan 04 13:11:53 2015 -0600
518.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
518.3 @@ -1,59 +0,0 @@
518.4 -.t.e.s.t. Escapes
518.5 -STRING_TEXT "Here's an ", la=1
518.6 -STRING_ESCAPE "\\n"
518.7 -STRING_TEXT "escape, here's another one: ", la=1
518.8 -STRING_ESCAPE "\\\\"
518.9 -STRING_TEXT ", and here's several: ", la=1
518.10 -STRING_ESCAPE "\\n"
518.11 -STRING_ESCAPE "\\\\"
518.12 -STRING_ESCAPE "\\\\"
518.13 -STRING_ESCAPE "\\\\"
518.14 -STRING_TEXT "\nHere's an unbalanced one ", la=1
518.15 -STRING_INVALID "\\", la=1
518.16 ------ EOF -----
518.17 -
518.18 -.t.e.s.t. URLs
518.19 -STRING_TEXT "See ", la=58
518.20 -URL "http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage", la=1
518.21 -STRING_TEXT "\nSee ", la=19
518.22 -URL "https://foobar/baz", la=1
518.23 -STRING_TEXT "\n\nFor more about DST than you ever wanted to know, see\n", la=29
518.24 -URL "ftp://elsie.nci.nih.gov/pub/", la=1
518.25 ------ EOF -----
518.26 -
518.27 -.t.e.s.t. String 1
518.28 -STRING_TEXT "This is the "example" module.\n\nThe example module supplies one function, factorial(). For example,\n\n", la=3
518.29 -EMBEDDED_PYTHON ">>> factorial(5)", la=1
518.30 -STRING_TEXT "\n120", la=1
518.31 ------ EOF -----
518.32 -
518.33 -.t.e.s.t. String 2
518.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
518.35 -EMBEDDED_PYTHON ">>> [factorial(n) for n in range(6)]", la=1
518.36 -STRING_TEXT "\n [1, 1, 2, 6, 24, 120]\n ", la=3
518.37 -EMBEDDED_PYTHON ">>> [factorial(long(n)) for n in range(6)]", la=1
518.38 -STRING_TEXT "\n [1, 1, 2, 6, 24, 120]\n ", la=3
518.39 -EMBEDDED_PYTHON ">>> factorial(30)", la=1
518.40 -STRING_TEXT "\n 265252859812191058636308480000000L\n ", la=3
518.41 -EMBEDDED_PYTHON ">>> factorial(30L)", la=1
518.42 -STRING_TEXT "\n 265252859812191058636308480000000L\n ", la=3
518.43 -EMBEDDED_PYTHON ">>> factorial(-1)", la=1
518.44 -STRING_TEXT "\n Traceback (most recent call last):\n ...\n ValueError: n must be >= 0\n x = ", la=1
518.45 -STRING_ESCAPE "\\n"
518.46 -STRING_TEXT " foo\n\n Factorials of floats are OK, but the float must be an exact integer:\n ", la=3
518.47 -EMBEDDED_PYTHON ">>> factorial(30.1)", la=1
518.48 -STRING_TEXT "\n Traceback (most recent call last):\n ...\n ValueError: n must be exact integer\n ", la=3
518.49 -EMBEDDED_PYTHON ">>> factorial(30.0)", la=1
518.50 -STRING_TEXT "\n 265252859812191058636308480000000L\n\n It must also not be ridiculously large:\n ", la=3
518.51 -EMBEDDED_PYTHON ">>> factorial(1e100)", la=1
518.52 -STRING_TEXT "\n Traceback (most recent call last):\n ...\n OverflowError: n too large\n ", la=1
518.53 ------ EOF -----
518.54 -
518.55 -.t.e.s.t. Errors
518.56 -STRING_TEXT "Here's another one:\n>> Wrong\n", la=3
518.57 -STRING_TEXT ">>>", la=1
518.58 ------ EOF -----
518.59 -
518.60 -<Unnamed test>
518.61 ------ EOF -----
518.62 -
519.1 --- a/python.editor/test/unit/data/testfiles/syntax.py.txt Sun Jan 04 13:11:53 2015 -0600
519.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
519.3 @@ -1,75 +0,0 @@
519.4 -.t.e.s.t. Keywords
519.5 -and del from not while
519.6 -as elif global or with
519.7 -assert else if pass yield
519.8 -break except import print
519.9 -class exec in raise
519.10 -continue finally is return
519.11 -def for lambda try
519.12 -.e.o.f.
519.13 -
519.14 -.t.e.s.t. Decorators
519.15 -@staticmethod
519.16 -@classmethod
519.17 -.e.o.f.
519.18 -
519.19 -.t.e.s.t. Strings
519.20 -r'foo'
519.21 -UR'foo'
519.22 -u"foo"
519.23 -'foo\bbar'
519.24 -"foo\nbar"
519.25 -'''triple'''
519.26 -"""when no section matches a requested option."""
519.27 -"""triple"""
519.28 -.e.o.f.
519.29 -
519.30 -.t.e.s.t. Integers and Long Integers
519.31 -7 2147483647 0177
519.32 -3L 79228162514264337593543950336L 0377L 0x100000000L
519.33 - 79228162514264337593543950336 0xdeadbeef
519.34 -.e.o.f.
519.35 -
519.36 -.t.e.s.t. Floating point numbers
519.37 -3.14 10. .001 1e100 3.14e-10 0e0
519.38 -.e.o.f.
519.39 -
519.40 -.t.e.s.t. Imaginary literals
519.41 -3.14j 10.j 10j .001j 1e100j 3.14e-10j
519.42 -.e.o.f.
519.43 -
519.44 -.t.e.s.t. Operators
519.45 -+ - * ** / // %
519.46 -<< >> & | ^ ~
519.47 -< > <= >= == != <>
519.48 -.e.o.f.
519.49 -
519.50 -.t.e.s.t. Delimiters
519.51 -( ) [ ] { } @
519.52 -, : . ` = ;
519.53 -+= -= *= /= //= %=
519.54 -&= |= ^= >>= <<= **=
519.55 -.e.o.f.
519.56 -
519.57 -.t.e.s.t. Comments
519.58 -# This is a line comment
519.59 -code()#More comments
519.60 -.e.o.f.
519.61 -
519.62 -.t.e.s.t. Identifiers
519.63 -a ab aB2 x
519.64 -yZ_
519.65 -z
519.66 -.e.o.f.
519.67 -
519.68 -.t.e.s.t. Joined Lines
519.69 -if 1900 < year < 2100 and 1 <= month <= 12 \
519.70 - and 1 <= day <= 31 and 0 <= hour < 24 \
519.71 - and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
519.72 - return 1
519.73 -.e.o.f.
519.74 -
519.75 -.t.e.s.t. Not an identifier, not a keyword
519.76 -2a
519.77 -None
519.78 -.e.o.f.
520.1 --- a/python.editor/test/unit/data/testfiles/syntax.py.txt.tokens.txt Sun Jan 04 13:11:53 2015 -0600
520.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
520.3 @@ -1,374 +0,0 @@
520.4 -.t.e.s.t. Keywords
520.5 -ANY_KEYWORD "and", la=1, st=INIT
520.6 -WHITESPACE " ", la=1, st=INIT
520.7 -ANY_KEYWORD "del", la=1, st=INIT
520.8 -WHITESPACE " ", la=1, st=INIT
520.9 -FROM "from", la=1, st=INIT
520.10 -WHITESPACE " ", la=1, st=INIT
520.11 -ANY_KEYWORD "not", la=1, st=INIT
520.12 -WHITESPACE " ", la=1, st=INIT
520.13 -ANY_KEYWORD "while", la=1, st=INIT
520.14 -WHITESPACE " ", la=1, st=INIT
520.15 -NEWLINE "\n", st=INIT
520.16 -ANY_KEYWORD "as", la=1, st=INIT
520.17 -WHITESPACE " ", la=1, st=INIT
520.18 -ELIF "elif", la=1, st=INIT
520.19 -WHITESPACE " ", la=1, st=INIT
520.20 -ANY_KEYWORD "global", la=1, st=INIT
520.21 -WHITESPACE " ", la=1, st=INIT
520.22 -ANY_KEYWORD "or", la=1, st=INIT
520.23 -WHITESPACE " ", la=1, st=INIT
520.24 -ANY_KEYWORD "with", la=1, st=INIT
520.25 -WHITESPACE " ", la=1, st=INIT
520.26 -NEWLINE "\n", st=INIT
520.27 -ANY_KEYWORD "assert", la=1, st=INIT
520.28 -WHITESPACE " ", la=1, st=INIT
520.29 -ELSE "else", la=1, st=INIT
520.30 -WHITESPACE " ", la=1, st=INIT
520.31 -IF "if", la=1, st=INIT
520.32 -WHITESPACE " ", la=1, st=INIT
520.33 -PASS "pass", la=1, st=INIT
520.34 -WHITESPACE " ", la=1, st=INIT
520.35 -ANY_KEYWORD "yield", la=1, st=INIT
520.36 -WHITESPACE " ", la=1, st=INIT
520.37 -NEWLINE "\n", st=INIT
520.38 -ANY_KEYWORD "break", la=1, st=INIT
520.39 -WHITESPACE " ", la=1, st=INIT
520.40 -EXCEPT "except", la=1, st=INIT
520.41 -WHITESPACE " ", la=1, st=INIT
520.42 -IMPORT "import", la=1, st=INIT
520.43 -WHITESPACE " ", la=1, st=INIT
520.44 -ANY_KEYWORD "print", la=1, st=INIT
520.45 -WHITESPACE " ", la=1, st=INIT
520.46 -NEWLINE "\n", st=INIT
520.47 -CLASS "class", la=1, st=INIT
520.48 -WHITESPACE " ", la=1, st=INIT
520.49 -ANY_KEYWORD "exec", la=1, st=INIT
520.50 -WHITESPACE " ", la=1, st=INIT
520.51 -ANY_KEYWORD "in", la=1, st=INIT
520.52 -WHITESPACE " ", la=1, st=INIT
520.53 -RAISE "raise", la=1, st=INIT
520.54 -WHITESPACE " ", la=1, st=INIT
520.55 -NEWLINE "\n", st=INIT
520.56 -ANY_KEYWORD "continue", la=1, st=INIT
520.57 -WHITESPACE " ", la=1, st=INIT
520.58 -FINALLY "finally", la=1, st=INIT
520.59 -WHITESPACE " ", la=1, st=INIT
520.60 -ANY_KEYWORD "is", la=1, st=INIT
520.61 -WHITESPACE " ", la=1, st=INIT
520.62 -RETURN "return", la=1, st=INIT
520.63 -WHITESPACE " ", la=1, st=INIT
520.64 -NEWLINE "\n", st=INIT
520.65 -DEF "def", la=1, st=INIT
520.66 -WHITESPACE " ", la=1, st=INIT
520.67 -ANY_KEYWORD "for", la=1, st=INIT
520.68 -WHITESPACE " ", la=1, st=INIT
520.69 -ANY_KEYWORD "lambda", la=1, st=INIT
520.70 -WHITESPACE " ", la=1, st=INIT
520.71 -TRY "try", la=1, st=INIT
520.72 ------ EOF -----
520.73 -
520.74 -.t.e.s.t. Decorators
520.75 -DECORATOR "@staticmethod", la=1, st=INIT
520.76 -NEWLINE "\n", st=INIT
520.77 -DECORATOR "@classmethod", la=1, st=INIT
520.78 ------ EOF -----
520.79 -
520.80 -.t.e.s.t. Strings
520.81 -STRING_BEGIN "r'", la=1, st=BEGIN_SHORTSTRING_SINGLE
520.82 -STRING_LITERAL "foo", la=1, st=END_SHORTSTRING_SINGLE
520.83 -STRING_END "'", st=INIT
520.84 -NEWLINE "\n", st=INIT
520.85 -STRING_BEGIN "UR'", la=1, st=BEGIN_SHORTSTRING_SINGLE
520.86 -STRING_LITERAL "foo", la=1, st=END_SHORTSTRING_SINGLE
520.87 -STRING_END "'", st=INIT
520.88 -NEWLINE "\n", st=INIT
520.89 -STRING_BEGIN "u"", la=1, st=BEGIN_SHORTSTRING_DOUBLE
520.90 -STRING_LITERAL "foo", la=1, st=END_SHORTSTRING_DOUBLE
520.91 -STRING_END """, st=INIT
520.92 -NEWLINE "\n", st=INIT
520.93 -STRING_BEGIN "'", la=1, st=BEGIN_SHORTSTRING_SINGLE
520.94 -STRING_LITERAL "foo\\bbar", la=1, st=END_SHORTSTRING_SINGLE
520.95 -STRING_END "'", st=INIT
520.96 -NEWLINE "\n", st=INIT
520.97 -STRING_BEGIN """, la=1, st=BEGIN_SHORTSTRING_DOUBLE
520.98 -STRING_LITERAL "foo\\nbar", la=1, st=END_SHORTSTRING_DOUBLE
520.99 -STRING_END """, st=INIT
520.100 -NEWLINE "\n", st=INIT
520.101 -STRING_BEGIN "'''", st=BEGIN_LONGSTRING_SINGLE
520.102 -STRING_LITERAL "triple", la=3, st=END_LONGSTRING_SINGLE
520.103 -STRING_END "'''", st=INIT
520.104 -NEWLINE "\n", st=INIT
520.105 -STRING_BEGIN """"", st=BEGIN_LONGSTRING_DOUBLE
520.106 -STRING_LITERAL "when no section matches a requested option.", la=3, st=END_LONGSTRING_DOUBLE
520.107 -STRING_END """"", st=INIT
520.108 -NEWLINE "\n", st=INIT
520.109 -STRING_BEGIN """"", st=BEGIN_LONGSTRING_DOUBLE
520.110 -STRING_LITERAL "triple", la=3, st=END_LONGSTRING_DOUBLE
520.111 -STRING_END """"", st=INIT
520.112 ------ EOF -----
520.113 -
520.114 -.t.e.s.t. Integers and Long Integers
520.115 -INT_LITERAL "7", la=1, st=INIT
520.116 -WHITESPACE " ", la=1, st=INIT
520.117 -INT_LITERAL "2147483647", la=1, st=INIT
520.118 -WHITESPACE " ", la=1, st=INIT
520.119 -INT_LITERAL "0177", la=1, st=INIT
520.120 -NEWLINE "\n", st=INIT
520.121 -INT_LITERAL "3L", st=INIT
520.122 -WHITESPACE " ", la=1, st=INIT
520.123 -INT_LITERAL "79228162514264337593543950336L", st=INIT
520.124 -WHITESPACE " ", la=1, st=INIT
520.125 -INT_LITERAL "0377L", st=INIT
520.126 -WHITESPACE " ", la=1, st=INIT
520.127 -INT_LITERAL "0x100000000L", st=INIT
520.128 -NEWLINE "\n", st=INIT
520.129 -WHITESPACE " ", la=1, st=INIT
520.130 -INT_LITERAL "79228162514264337593543950336", la=1, st=INIT
520.131 -WHITESPACE " ", la=1, st=INIT
520.132 -INT_LITERAL "0xdeadbeef", la=1, st=INIT
520.133 ------ EOF -----
520.134 -
520.135 -.t.e.s.t. Floating point numbers
520.136 -FLOAT_LITERAL "3.14", la=1, st=INIT
520.137 -WHITESPACE " ", la=1, st=INIT
520.138 -FLOAT_LITERAL "10.", la=1, st=INIT
520.139 -WHITESPACE " ", la=1, st=INIT
520.140 -FLOAT_LITERAL ".001", la=1, st=INIT
520.141 -WHITESPACE " ", la=1, st=INIT
520.142 -FLOAT_LITERAL "1e100", la=1, st=INIT
520.143 -WHITESPACE " ", la=1, st=INIT
520.144 -FLOAT_LITERAL "3.14e-10", la=1, st=INIT
520.145 -WHITESPACE " ", la=1, st=INIT
520.146 -FLOAT_LITERAL "0e0", la=1, st=INIT
520.147 ------ EOF -----
520.148 -
520.149 -.t.e.s.t. Imaginary literals
520.150 -FLOAT_LITERAL "3.14j", st=INIT
520.151 -WHITESPACE " ", la=1, st=INIT
520.152 -FLOAT_LITERAL "10.j", st=INIT
520.153 -WHITESPACE " ", la=1, st=INIT
520.154 -FLOAT_LITERAL "10j", st=INIT
520.155 -WHITESPACE " ", la=1, st=INIT
520.156 -FLOAT_LITERAL ".001j", st=INIT
520.157 -WHITESPACE " ", la=1, st=INIT
520.158 -FLOAT_LITERAL "1e100j", st=INIT
520.159 -WHITESPACE " ", la=1, st=INIT
520.160 -FLOAT_LITERAL "3.14e-10j", st=INIT
520.161 ------ EOF -----
520.162 -
520.163 -.t.e.s.t. Operators
520.164 -ANY_OPERATOR "+", la=1, st=INIT
520.165 -WHITESPACE " ", la=1, st=INIT
520.166 -ANY_OPERATOR "-", la=1, st=INIT
520.167 -WHITESPACE " ", la=1, st=INIT
520.168 -ANY_OPERATOR "*", la=1, st=INIT
520.169 -WHITESPACE " ", la=1, st=INIT
520.170 -ANY_OPERATOR "**", la=1, st=INIT
520.171 -WHITESPACE " ", la=1, st=INIT
520.172 -ANY_OPERATOR "/", la=1, st=INIT
520.173 -WHITESPACE " ", la=1, st=INIT
520.174 -ANY_OPERATOR "//", la=1, st=INIT
520.175 -WHITESPACE " ", la=1, st=INIT
520.176 -ANY_OPERATOR "%", la=1, st=INIT
520.177 -NEWLINE "\n", st=INIT
520.178 -ANY_OPERATOR "<<", la=1, st=INIT
520.179 -WHITESPACE " ", la=1, st=INIT
520.180 -ANY_OPERATOR ">>", la=1, st=INIT
520.181 -WHITESPACE " ", la=1, st=INIT
520.182 -ANY_OPERATOR "&", la=1, st=INIT
520.183 -WHITESPACE " ", la=1, st=INIT
520.184 -ANY_OPERATOR "|", la=1, st=INIT
520.185 -WHITESPACE " ", la=1, st=INIT
520.186 -ANY_OPERATOR "^", la=1, st=INIT
520.187 -WHITESPACE " ", la=1, st=INIT
520.188 -ANY_OPERATOR "~", st=INIT
520.189 -NEWLINE "\n", st=INIT
520.190 -ANY_OPERATOR "<", la=1, st=INIT
520.191 -WHITESPACE " ", la=1, st=INIT
520.192 -ANY_OPERATOR ">", la=1, st=INIT
520.193 -WHITESPACE " ", la=1, st=INIT
520.194 -ANY_OPERATOR "<=", st=INIT
520.195 -WHITESPACE " ", la=1, st=INIT
520.196 -ANY_OPERATOR ">=", st=INIT
520.197 -WHITESPACE " ", la=1, st=INIT
520.198 -ANY_OPERATOR "==", st=INIT
520.199 -WHITESPACE " ", la=1, st=INIT
520.200 -ANY_OPERATOR "!=", st=INIT
520.201 -WHITESPACE " ", la=1, st=INIT
520.202 -ANY_OPERATOR "<>", st=INIT
520.203 ------ EOF -----
520.204 -
520.205 -.t.e.s.t. Delimiters
520.206 -LPAREN "(", st=INIT
520.207 -WHITESPACE " ", la=1, st=INIT
520.208 -RPAREN ")", st=INIT
520.209 -WHITESPACE " ", la=1, st=INIT
520.210 -LBRACKET "[", st=INIT
520.211 -WHITESPACE " ", la=1, st=INIT
520.212 -RBRACKET "]", st=INIT
520.213 -WHITESPACE " ", la=1, st=INIT
520.214 -LBRACE "{", st=INIT
520.215 -WHITESPACE " ", la=1, st=INIT
520.216 -RBRACE "}", st=INIT
520.217 -WHITESPACE " ", la=1, st=INIT
520.218 -DECORATOR "@", la=1, st=INIT
520.219 -NEWLINE "\n", st=INIT
520.220 -COMMA ",", st=INIT
520.221 -WHITESPACE " ", la=1, st=INIT
520.222 -COLON ":", st=INIT
520.223 -WHITESPACE " ", la=1, st=INIT
520.224 -DOT ".", la=1, st=INIT
520.225 -WHITESPACE " ", la=1, st=INIT
520.226 -ANY_OPERATOR "`", st=INIT
520.227 -WHITESPACE " ", la=1, st=INIT
520.228 -ANY_OPERATOR "=", la=1, st=INIT
520.229 -WHITESPACE " ", la=1, st=INIT
520.230 -ANY_OPERATOR ";", st=INIT
520.231 -NEWLINE "\n", st=INIT
520.232 -ANY_OPERATOR "+=", st=INIT
520.233 -WHITESPACE " ", la=1, st=INIT
520.234 -ANY_OPERATOR "-=", st=INIT
520.235 -WHITESPACE " ", la=1, st=INIT
520.236 -ANY_OPERATOR "*=", st=INIT
520.237 -WHITESPACE " ", la=1, st=INIT
520.238 -ANY_OPERATOR "/=", st=INIT
520.239 -WHITESPACE " ", la=1, st=INIT
520.240 -ANY_OPERATOR "//=", st=INIT
520.241 -WHITESPACE " ", la=1, st=INIT
520.242 -ANY_OPERATOR "%=", st=INIT
520.243 -NEWLINE "\n", st=INIT
520.244 -ANY_OPERATOR "&=", st=INIT
520.245 -WHITESPACE " ", la=1, st=INIT
520.246 -ANY_OPERATOR "|=", st=INIT
520.247 -WHITESPACE " ", la=1, st=INIT
520.248 -ANY_OPERATOR "^=", st=INIT
520.249 -WHITESPACE " ", la=1, st=INIT
520.250 -ANY_OPERATOR ">>=", st=INIT
520.251 -WHITESPACE " ", la=1, st=INIT
520.252 -ANY_OPERATOR "<<=", st=INIT
520.253 -WHITESPACE " ", la=1, st=INIT
520.254 -ANY_OPERATOR "**=", st=INIT
520.255 ------ EOF -----
520.256 -
520.257 -.t.e.s.t. Comments
520.258 -COMMENT "# This is a line comment", la=1, st=INIT
520.259 -NEWLINE "\n", st=INIT
520.260 -IDENTIFIER "code", la=1, st=INIT
520.261 -LPAREN "(", st=INIT
520.262 -RPAREN ")", st=INIT
520.263 -COMMENT "#More comments", la=1, st=INIT
520.264 ------ EOF -----
520.265 -
520.266 -.t.e.s.t. Identifiers
520.267 -IDENTIFIER "a", la=1, st=INIT
520.268 -WHITESPACE " ", la=1, st=INIT
520.269 -IDENTIFIER "ab", la=1, st=INIT
520.270 -WHITESPACE " ", la=1, st=INIT
520.271 -IDENTIFIER "aB2", la=1, st=INIT
520.272 -WHITESPACE " ", la=1, st=INIT
520.273 -IDENTIFIER "x", la=1, st=INIT
520.274 -NEWLINE "\n", st=INIT
520.275 -IDENTIFIER "yZ_", la=1, st=INIT
520.276 -NEWLINE "\n", st=INIT
520.277 -IDENTIFIER "z", la=1, st=INIT
520.278 ------ EOF -----
520.279 -
520.280 -.t.e.s.t. Joined Lines
520.281 -IF "if", la=1, st=INIT
520.282 -WHITESPACE " ", la=1, st=INIT
520.283 -INT_LITERAL "1900", la=1, st=INIT
520.284 -WHITESPACE " ", la=1, st=INIT
520.285 -ANY_OPERATOR "<", la=1, st=INIT
520.286 -WHITESPACE " ", la=1, st=INIT
520.287 -IDENTIFIER "year", la=1, st=INIT
520.288 -WHITESPACE " ", la=1, st=INIT
520.289 -ANY_OPERATOR "<", la=1, st=INIT
520.290 -WHITESPACE " ", la=1, st=INIT
520.291 -INT_LITERAL "2100", la=1, st=INIT
520.292 -WHITESPACE " ", la=1, st=INIT
520.293 -ANY_KEYWORD "and", la=1, st=INIT
520.294 -WHITESPACE " ", la=1, st=INIT
520.295 -INT_LITERAL "1", la=1, st=INIT
520.296 -WHITESPACE " ", la=1, st=INIT
520.297 -ANY_OPERATOR "<=", st=INIT
520.298 -WHITESPACE " ", la=1, st=INIT
520.299 -IDENTIFIER "month", la=1, st=INIT
520.300 -WHITESPACE " ", la=1, st=INIT
520.301 -ANY_OPERATOR "<=", st=INIT
520.302 -WHITESPACE " ", la=1, st=INIT
520.303 -INT_LITERAL "12", la=1, st=INIT
520.304 -WHITESPACE " ", la=1, st=INIT
520.305 -ESC "\\", st=INIT
520.306 -NEWLINE "\n", st=INIT
520.307 -WHITESPACE " ", la=1, st=INIT
520.308 -ANY_KEYWORD "and", la=1, st=INIT
520.309 -WHITESPACE " ", la=1, st=INIT
520.310 -INT_LITERAL "1", la=1, st=INIT
520.311 -WHITESPACE " ", la=1, st=INIT
520.312 -ANY_OPERATOR "<=", st=INIT
520.313 -WHITESPACE " ", la=1, st=INIT
520.314 -IDENTIFIER "day", la=1, st=INIT
520.315 -WHITESPACE " ", la=1, st=INIT
520.316 -ANY_OPERATOR "<=", st=INIT
520.317 -WHITESPACE " ", la=1, st=INIT
520.318 -INT_LITERAL "31", la=1, st=INIT
520.319 -WHITESPACE " ", la=1, st=INIT
520.320 -ANY_KEYWORD "and", la=1, st=INIT
520.321 -WHITESPACE " ", la=1, st=INIT
520.322 -INT_LITERAL "0", la=1, st=INIT
520.323 -WHITESPACE " ", la=1, st=INIT
520.324 -ANY_OPERATOR "<=", st=INIT
520.325 -WHITESPACE " ", la=1, st=INIT
520.326 -IDENTIFIER "hour", la=1, st=INIT
520.327 -WHITESPACE " ", la=1, st=INIT
520.328 -ANY_OPERATOR "<", la=1, st=INIT
520.329 -WHITESPACE " ", la=1, st=INIT
520.330 -INT_LITERAL "24", la=1, st=INIT
520.331 -WHITESPACE " ", la=1, st=INIT
520.332 -ESC "\\", st=INIT
520.333 -NEWLINE "\n", st=INIT
520.334 -WHITESPACE " ", la=1, st=INIT
520.335 -ANY_KEYWORD "and", la=1, st=INIT
520.336 -WHITESPACE " ", la=1, st=INIT
520.337 -INT_LITERAL "0", la=1, st=INIT
520.338 -WHITESPACE " ", la=1, st=INIT
520.339 -ANY_OPERATOR "<=", st=INIT
520.340 -WHITESPACE " ", la=1, st=INIT
520.341 -IDENTIFIER "minute", la=1, st=INIT
520.342 -WHITESPACE " ", la=1, st=INIT
520.343 -ANY_OPERATOR "<", la=1, st=INIT
520.344 -WHITESPACE " ", la=1, st=INIT
520.345 -INT_LITERAL "60", la=1, st=INIT
520.346 -WHITESPACE " ", la=1, st=INIT
520.347 -ANY_KEYWORD "and", la=1, st=INIT
520.348 -WHITESPACE " ", la=1, st=INIT
520.349 -INT_LITERAL "0", la=1, st=INIT
520.350 -WHITESPACE " ", la=1, st=INIT
520.351 -ANY_OPERATOR "<=", st=INIT
520.352 -WHITESPACE " ", la=1, st=INIT
520.353 -IDENTIFIER "second", la=1, st=INIT
520.354 -WHITESPACE " ", la=1, st=INIT
520.355 -ANY_OPERATOR "<", la=1, st=INIT
520.356 -WHITESPACE " ", la=1, st=INIT
520.357 -INT_LITERAL "60", la=1, st=INIT
520.358 -COLON ":", st=INIT
520.359 -WHITESPACE " ", la=1, st=INIT
520.360 -COMMENT "# Looks like a valid date", la=1, st=INIT
520.361 -NEWLINE "\n", st=INIT
520.362 -WHITESPACE " ", la=1, st=INIT
520.363 -RETURN "return", la=1, st=INIT
520.364 -WHITESPACE " ", la=1, st=INIT
520.365 -INT_LITERAL "1", la=1, st=INIT
520.366 ------ EOF -----
520.367 -
520.368 -.t.e.s.t. Not an identifier, not a keyword
520.369 -INT_LITERAL "2", la=1, st=INIT
520.370 -IDENTIFIER "a", la=1, st=INIT
520.371 -NEWLINE "\n", st=INIT
520.372 -IDENTIFIER "None", la=1, st=INIT
520.373 ------ EOF -----
520.374 -
520.375 -<Unnamed test>
520.376 ------ EOF -----
520.377 -
521.1 --- a/python.editor/test/unit/data/testfiles/tarfile.py Sun Jan 04 13:11:53 2015 -0600
521.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
521.3 @@ -1,2176 +0,0 @@
521.4 -#!/usr/bin/env python
521.5 -# -*- coding: iso-8859-1 -*-
521.6 -#-------------------------------------------------------------------
521.7 -# tarfile.py
521.8 -#-------------------------------------------------------------------
521.9 -# Copyright (C) 2002 Lars Gustäbel <lars@gustaebel.de>
521.10 -# All rights reserved.
521.11 -#
521.12 -# Permission is hereby granted, free of charge, to any person
521.13 -# obtaining a copy of this software and associated documentation
521.14 -# files (the "Software"), to deal in the Software without
521.15 -# restriction, including without limitation the rights to use,
521.16 -# copy, modify, merge, publish, distribute, sublicense, and/or sell
521.17 -# copies of the Software, and to permit persons to whom the
521.18 -# Software is furnished to do so, subject to the following
521.19 -# conditions:
521.20 -#
521.21 -# The above copyright notice and this permission notice shall be
521.22 -# included in all copies or substantial portions of the Software.
521.23 -#
521.24 -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
521.25 -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
521.26 -# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
521.27 -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
521.28 -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
521.29 -# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
521.30 -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
521.31 -# OTHER DEALINGS IN THE SOFTWARE.
521.32 -#
521.33 -"""Read from and write to tar format archives.
521.34 -"""
521.35 -
521.36 -__version__ = "$Revision: 53162 $"
521.37 -# $Source$
521.38 -
521.39 -version = "0.8.0"
521.40 -__author__ = "Lars Gustäbel (lars@gustaebel.de)"
521.41 -__date__ = "$Date: 2006-12-27 21:36:58 +1100 (Wed, 27 Dec 2006) $"
521.42 -__cvsid__ = "$Id: tarfile.py 53162 2006-12-27 10:36:58Z lars.gustaebel $"
521.43 -__credits__ = "Gustavo Niemeyer, Niels Gustäbel, Richard Townsend."
521.44 -
521.45 -#---------
521.46 -# Imports
521.47 -#---------
521.48 -import sys
521.49 -import os
521.50 -import shutil
521.51 -import stat
521.52 -import errno
521.53 -import time
521.54 -import struct
521.55 -import copy
521.56 -
521.57 -if sys.platform == 'mac':
521.58 - # This module needs work for MacOS9, especially in the area of pathname
521.59 - # handling. In many places it is assumed a simple substitution of / by the
521.60 - # local os.path.sep is good enough to convert pathnames, but this does not
521.61 - # work with the mac rooted:path:name versus :nonrooted:path:name syntax
521.62 - raise ImportError, "tarfile does not work for platform==mac"
521.63 -
521.64 -try:
521.65 - import grp, pwd
521.66 -except ImportError:
521.67 - grp = pwd = None
521.68 -
521.69 -# from tarfile import *
521.70 -__all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError"]
521.71 -
521.72 -#---------------------------------------------------------
521.73 -# tar constants
521.74 -#---------------------------------------------------------
521.75 -NUL = "\0" # the null character
521.76 -BLOCKSIZE = 512 # length of processing blocks
521.77 -RECORDSIZE = BLOCKSIZE * 20 # length of records
521.78 -MAGIC = "ustar" # magic tar string
521.79 -VERSION = "00" # version number
521.80 -
521.81 -LENGTH_NAME = 100 # maximum length of a filename
521.82 -LENGTH_LINK = 100 # maximum length of a linkname
521.83 -LENGTH_PREFIX = 155 # maximum length of the prefix field
521.84 -MAXSIZE_MEMBER = 077777777777L # maximum size of a file (11 octal digits)
521.85 -
521.86 -REGTYPE = "0" # regular file
521.87 -AREGTYPE = "\0" # regular file
521.88 -LNKTYPE = "1" # link (inside tarfile)
521.89 -SYMTYPE = "2" # symbolic link
521.90 -CHRTYPE = "3" # character special device
521.91 -BLKTYPE = "4" # block special device
521.92 -DIRTYPE = "5" # directory
521.93 -FIFOTYPE = "6" # fifo special device
521.94 -CONTTYPE = "7" # contiguous file
521.95 -
521.96 -GNUTYPE_LONGNAME = "L" # GNU tar extension for longnames
521.97 -GNUTYPE_LONGLINK = "K" # GNU tar extension for longlink
521.98 -GNUTYPE_SPARSE = "S" # GNU tar extension for sparse file
521.99 -
521.100 -#---------------------------------------------------------
521.101 -# tarfile constants
521.102 -#---------------------------------------------------------
521.103 -SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE, # file types that tarfile
521.104 - SYMTYPE, DIRTYPE, FIFOTYPE, # can cope with.
521.105 - CONTTYPE, CHRTYPE, BLKTYPE,
521.106 - GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
521.107 - GNUTYPE_SPARSE)
521.108 -
521.109 -REGULAR_TYPES = (REGTYPE, AREGTYPE, # file types that somehow
521.110 - CONTTYPE, GNUTYPE_SPARSE) # represent regular files
521.111 -
521.112 -#---------------------------------------------------------
521.113 -# Bits used in the mode field, values in octal.
521.114 -#---------------------------------------------------------
521.115 -S_IFLNK = 0120000 # symbolic link
521.116 -S_IFREG = 0100000 # regular file
521.117 -S_IFBLK = 0060000 # block device
521.118 -S_IFDIR = 0040000 # directory
521.119 -S_IFCHR = 0020000 # character device
521.120 -S_IFIFO = 0010000 # fifo
521.121 -
521.122 -TSUID = 04000 # set UID on execution
521.123 -TSGID = 02000 # set GID on execution
521.124 -TSVTX = 01000 # reserved
521.125 -
521.126 -TUREAD = 0400 # read by owner
521.127 -TUWRITE = 0200 # write by owner
521.128 -TUEXEC = 0100 # execute/search by owner
521.129 -TGREAD = 0040 # read by group
521.130 -TGWRITE = 0020 # write by group
521.131 -TGEXEC = 0010 # execute/search by group
521.132 -TOREAD = 0004 # read by other
521.133 -TOWRITE = 0002 # write by other
521.134 -TOEXEC = 0001 # execute/search by other
521.135 -
521.136 -#---------------------------------------------------------
521.137 -# Some useful functions
521.138 -#---------------------------------------------------------
521.139 -
521.140 -def stn(s, length):
521.141 - """Convert a python string to a null-terminated string buffer.
521.142 - """
521.143 - return s[:length] + (length - len(s)) * NUL
521.144 -
521.145 -def nti(s):
521.146 - """Convert a number field to a python number.
521.147 - """
521.148 - # There are two possible encodings for a number field, see
521.149 - # itn() below.
521.150 - if s[0] != chr(0200):
521.151 - n = int(s.rstrip(NUL + " ") or "0", 8)
521.152 - else:
521.153 - n = 0L
521.154 - for i in xrange(len(s) - 1):
521.155 - n <<= 8
521.156 - n += ord(s[i + 1])
521.157 - return n
521.158 -
521.159 -def itn(n, digits=8, posix=False):
521.160 - """Convert a python number to a number field.
521.161 - """
521.162 - # POSIX 1003.1-1988 requires numbers to be encoded as a string of
521.163 - # octal digits followed by a null-byte, this allows values up to
521.164 - # (8**(digits-1))-1. GNU tar allows storing numbers greater than
521.165 - # that if necessary. A leading 0200 byte indicates this particular
521.166 - # encoding, the following digits-1 bytes are a big-endian
521.167 - # representation. This allows values up to (256**(digits-1))-1.
521.168 - if 0 <= n < 8 ** (digits - 1):
521.169 - s = "%0*o" % (digits - 1, n) + NUL
521.170 - else:
521.171 - if posix:
521.172 - raise ValueError("overflow in number field")
521.173 -
521.174 - if n < 0:
521.175 - # XXX We mimic GNU tar's behaviour with negative numbers,
521.176 - # this could raise OverflowError.
521.177 - n = struct.unpack("L", struct.pack("l", n))[0]
521.178 -
521.179 - s = ""
521.180 - for i in xrange(digits - 1):
521.181 - s = chr(n & 0377) + s
521.182 - n >>= 8
521.183 - s = chr(0200) + s
521.184 - return s
521.185 -
521.186 -def calc_chksums(buf):
521.187 - """Calculate the checksum for a member's header by summing up all
521.188 - characters except for the chksum field which is treated as if
521.189 - it was filled with spaces. According to the GNU tar sources,
521.190 - some tars (Sun and NeXT) calculate chksum with signed char,
521.191 - which will be different if there are chars in the buffer with
521.192 - the high bit set. So we calculate two checksums, unsigned and
521.193 - signed.
521.194 - """
521.195 - unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) + struct.unpack("356B", buf[156:512]))
521.196 - signed_chksum = 256 + sum(struct.unpack("148b", buf[:148]) + struct.unpack("356b", buf[156:512]))
521.197 - return unsigned_chksum, signed_chksum
521.198 -
521.199 -def copyfileobj(src, dst, length=None):
521.200 - """Copy length bytes from fileobj src to fileobj dst.
521.201 - If length is None, copy the entire content.
521.202 - """
521.203 - if length == 0:
521.204 - return
521.205 - if length is None:
521.206 - shutil.copyfileobj(src, dst)
521.207 - return
521.208 -
521.209 - BUFSIZE = 16 * 1024
521.210 - blocks, remainder = divmod(length, BUFSIZE)
521.211 - for b in xrange(blocks):
521.212 - buf = src.read(BUFSIZE)
521.213 - if len(buf) < BUFSIZE:
521.214 - raise IOError("end of file reached")
521.215 - dst.write(buf)
521.216 -
521.217 - if remainder != 0:
521.218 - buf = src.read(remainder)
521.219 - if len(buf) < remainder:
521.220 - raise IOError("end of file reached")
521.221 - dst.write(buf)
521.222 - return
521.223 -
521.224 -filemode_table = (
521.225 - ((S_IFLNK, "l"),
521.226 - (S_IFREG, "-"),
521.227 - (S_IFBLK, "b"),
521.228 - (S_IFDIR, "d"),
521.229 - (S_IFCHR, "c"),
521.230 - (S_IFIFO, "p")),
521.231 -
521.232 - ((TUREAD, "r"),),
521.233 - ((TUWRITE, "w"),),
521.234 - ((TUEXEC|TSUID, "s"),
521.235 - (TSUID, "S"),
521.236 - (TUEXEC, "x")),
521.237 -
521.238 - ((TGREAD, "r"),),
521.239 - ((TGWRITE, "w"),),
521.240 - ((TGEXEC|TSGID, "s"),
521.241 - (TSGID, "S"),
521.242 - (TGEXEC, "x")),
521.243 -
521.244 - ((TOREAD, "r"),),
521.245 - ((TOWRITE, "w"),),
521.246 - ((TOEXEC|TSVTX, "t"),
521.247 - (TSVTX, "T"),
521.248 - (TOEXEC, "x"))
521.249 -)
521.250 -
521.251 -def filemode(mode):
521.252 - """Convert a file's mode to a string of the form
521.253 - -rwxrwxrwx.
521.254 - Used by TarFile.list()
521.255 - """
521.256 - perm = []
521.257 - for table in filemode_table:
521.258 - for bit, char in table:
521.259 - if mode & bit == bit:
521.260 - perm.append(char)
521.261 - break
521.262 - else:
521.263 - perm.append("-")
521.264 - return "".join(perm)
521.265 -
521.266 -if os.sep != "/":
521.267 - normpath = lambda path: os.path.normpath(path).replace(os.sep, "/")
521.268 -else:
521.269 - normpath = os.path.normpath
521.270 -
521.271 -class TarError(Exception):
521.272 - """Base exception."""
521.273 - pass
521.274 -class ExtractError(TarError):
521.275 - """General exception for extract errors."""
521.276 - pass
521.277 -class ReadError(TarError):
521.278 - """Exception for unreadble tar archives."""
521.279 - pass
521.280 -class CompressionError(TarError):
521.281 - """Exception for unavailable compression methods."""
521.282 - pass
521.283 -class StreamError(TarError):
521.284 - """Exception for unsupported operations on stream-like TarFiles."""
521.285 - pass
521.286 -
521.287 -#---------------------------
521.288 -# internal stream interface
521.289 -#---------------------------
521.290 -class _LowLevelFile:
521.291 - """Low-level file object. Supports reading and writing.
521.292 - It is used instead of a regular file object for streaming
521.293 - access.
521.294 - """
521.295 -
521.296 - def __init__(self, name, mode):
521.297 - mode = {
521.298 - "r": os.O_RDONLY,
521.299 - "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
521.300 - }[mode]
521.301 - if hasattr(os, "O_BINARY"):
521.302 - mode |= os.O_BINARY
521.303 - self.fd = os.open(name, mode)
521.304 -
521.305 - def close(self):
521.306 - os.close(self.fd)
521.307 -
521.308 - def read(self, size):
521.309 - return os.read(self.fd, size)
521.310 -
521.311 - def write(self, s):
521.312 - os.write(self.fd, s)
521.313 -
521.314 -class _Stream:
521.315 - """Class that serves as an adapter between TarFile and
521.316 - a stream-like object. The stream-like object only
521.317 - needs to have a read() or write() method and is accessed
521.318 - blockwise. Use of gzip or bzip2 compression is possible.
521.319 - A stream-like object could be for example: sys.stdin,
521.320 - sys.stdout, a socket, a tape device etc.
521.321 -
521.322 - _Stream is intended to be used only internally.
521.323 - """
521.324 -
521.325 - def __init__(self, name, mode, comptype, fileobj, bufsize):
521.326 - """Construct a _Stream object.
521.327 - """
521.328 - self._extfileobj = True
521.329 - if fileobj is None:
521.330 - fileobj = _LowLevelFile(name, mode)
521.331 - self._extfileobj = False
521.332 -
521.333 - if comptype == '*':
521.334 - # Enable transparent compression detection for the
521.335 - # stream interface
521.336 - fileobj = _StreamProxy(fileobj)
521.337 - comptype = fileobj.getcomptype()
521.338 -
521.339 - self.name = name or ""
521.340 - self.mode = mode
521.341 - self.comptype = comptype
521.342 - self.fileobj = fileobj
521.343 - self.bufsize = bufsize
521.344 - self.buf = ""
521.345 - self.pos = 0L
521.346 - self.closed = False
521.347 -
521.348 - if comptype == "gz":
521.349 - try:
521.350 - import zlib
521.351 - except ImportError:
521.352 - raise CompressionError("zlib module is not available")
521.353 - self.zlib = zlib
521.354 - self.crc = zlib.crc32("")
521.355 - if mode == "r":
521.356 - self._init_read_gz()
521.357 - else:
521.358 - self._init_write_gz()
521.359 -
521.360 - if comptype == "bz2":
521.361 - try:
521.362 - import bz2
521.363 - except ImportError:
521.364 - raise CompressionError("bz2 module is not available")
521.365 - if mode == "r":
521.366 - self.dbuf = ""
521.367 - self.cmp = bz2.BZ2Decompressor()
521.368 - else:
521.369 - self.cmp = bz2.BZ2Compressor()
521.370 -
521.371 - def __del__(self):
521.372 - if hasattr(self, "closed") and not self.closed:
521.373 - self.close()
521.374 -
521.375 - def _init_write_gz(self):
521.376 - """Initialize for writing with gzip compression.
521.377 - """
521.378 - self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED,
521.379 - -self.zlib.MAX_WBITS,
521.380 - self.zlib.DEF_MEM_LEVEL,
521.381 - 0)
521.382 - timestamp = struct.pack("<L", long(time.time()))
521.383 - self.__write("\037\213\010\010%s\002\377" % timestamp)
521.384 - if self.name.endswith(".gz"):
521.385 - self.name = self.name[:-3]
521.386 - self.__write(self.name + NUL)
521.387 -
521.388 - def write(self, s):
521.389 - """Write string s to the stream.
521.390 - """
521.391 - if self.comptype == "gz":
521.392 - self.crc = self.zlib.crc32(s, self.crc)
521.393 - self.pos += len(s)
521.394 - if self.comptype != "tar":
521.395 - s = self.cmp.compress(s)
521.396 - self.__write(s)
521.397 -
521.398 - def __write(self, s):
521.399 - """Write string s to the stream if a whole new block
521.400 - is ready to be written.
521.401 - """
521.402 - self.buf += s
521.403 - while len(self.buf) > self.bufsize:
521.404 - self.fileobj.write(self.buf[:self.bufsize])
521.405 - self.buf = self.buf[self.bufsize:]
521.406 -
521.407 - def close(self):
521.408 - """Close the _Stream object. No operation should be
521.409 - done on it afterwards.
521.410 - """
521.411 - if self.closed:
521.412 - return
521.413 -
521.414 - if self.mode == "w" and self.comptype != "tar":
521.415 - self.buf += self.cmp.flush()
521.416 -
521.417 - if self.mode == "w" and self.buf:
521.418 - self.fileobj.write(self.buf)
521.419 - self.buf = ""
521.420 - if self.comptype == "gz":
521.421 - # The native zlib crc is an unsigned 32-bit integer, but
521.422 - # the Python wrapper implicitly casts that to a signed C
521.423 - # long. So, on a 32-bit box self.crc may "look negative",
521.424 - # while the same crc on a 64-bit box may "look positive".
521.425 - # To avoid irksome warnings from the `struct` module, force
521.426 - # it to look positive on all boxes.
521.427 - self.fileobj.write(struct.pack("<L", self.crc & 0xffffffffL))
521.428 - self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFFL))
521.429 -
521.430 - if not self._extfileobj:
521.431 - self.fileobj.close()
521.432 -
521.433 - self.closed = True
521.434 -
521.435 - def _init_read_gz(self):
521.436 - """Initialize for reading a gzip compressed fileobj.
521.437 - """
521.438 - self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS)
521.439 - self.dbuf = ""
521.440 -
521.441 - # taken from gzip.GzipFile with some alterations
521.442 - if self.__read(2) != "\037\213":
521.443 - raise ReadError("not a gzip file")
521.444 - if self.__read(1) != "\010":
521.445 - raise CompressionError("unsupported compression method")
521.446 -
521.447 - flag = ord(self.__read(1))
521.448 - self.__read(6)
521.449 -
521.450 - if flag & 4:
521.451 - xlen = ord(self.__read(1)) + 256 * ord(self.__read(1))
521.452 - self.read(xlen)
521.453 - if flag & 8:
521.454 - while True:
521.455 - s = self.__read(1)
521.456 - if not s or s == NUL:
521.457 - break
521.458 - if flag & 16:
521.459 - while True:
521.460 - s = self.__read(1)
521.461 - if not s or s == NUL:
521.462 - break
521.463 - if flag & 2:
521.464 - self.__read(2)
521.465 -
521.466 - def tell(self):
521.467 - """Return the stream's file pointer position.
521.468 - """
521.469 - return self.pos
521.470 -
521.471 - def seek(self, pos=0):
521.472 - """Set the stream's file pointer to pos. Negative seeking
521.473 - is forbidden.
521.474 - """
521.475 - if pos - self.pos >= 0:
521.476 - blocks, remainder = divmod(pos - self.pos, self.bufsize)
521.477 - for i in xrange(blocks):
521.478 - self.read(self.bufsize)
521.479 - self.read(remainder)
521.480 - else:
521.481 - raise StreamError("seeking backwards is not allowed")
521.482 - return self.pos
521.483 -
521.484 - def read(self, size=None):
521.485 - """Return the next size number of bytes from the stream.
521.486 - If size is not defined, return all bytes of the stream
521.487 - up to EOF.
521.488 - """
521.489 - if size is None:
521.490 - t = []
521.491 - while True:
521.492 - buf = self._read(self.bufsize)
521.493 - if not buf:
521.494 - break
521.495 - t.append(buf)
521.496 - buf = "".join(t)
521.497 - else:
521.498 - buf = self._read(size)
521.499 - self.pos += len(buf)
521.500 - return buf
521.501 -
521.502 - def _read(self, size):
521.503 - """Return size bytes from the stream.
521.504 - """
521.505 - if self.comptype == "tar":
521.506 - return self.__read(size)
521.507 -
521.508 - c = len(self.dbuf)
521.509 - t = [self.dbuf]
521.510 - while c < size:
521.511 - buf = self.__read(self.bufsize)
521.512 - if not buf:
521.513 - break
521.514 - buf = self.cmp.decompress(buf)
521.515 - t.append(buf)
521.516 - c += len(buf)
521.517 - t = "".join(t)
521.518 - self.dbuf = t[size:]
521.519 - return t[:size]
521.520 -
521.521 - def __read(self, size):
521.522 - """Return size bytes from stream. If internal buffer is empty,
521.523 - read another block from the stream.
521.524 - """
521.525 - c = len(self.buf)
521.526 - t = [self.buf]
521.527 - while c < size:
521.528 - buf = self.fileobj.read(self.bufsize)
521.529 - if not buf:
521.530 - break
521.531 - t.append(buf)
521.532 - c += len(buf)
521.533 - t = "".join(t)
521.534 - self.buf = t[size:]
521.535 - return t[:size]
521.536 -# class _Stream
521.537 -
521.538 -class _StreamProxy(object):
521.539 - """Small proxy class that enables transparent compression
521.540 - detection for the Stream interface (mode 'r|*').
521.541 - """
521.542 -
521.543 - def __init__(self, fileobj):
521.544 - self.fileobj = fileobj
521.545 - self.buf = self.fileobj.read(BLOCKSIZE)
521.546 -
521.547 - def read(self, size):
521.548 - self.read = self.fileobj.read
521.549 - return self.buf
521.550 -
521.551 - def getcomptype(self):
521.552 - if self.buf.startswith("\037\213\010"):
521.553 - return "gz"
521.554 - if self.buf.startswith("BZh91"):
521.555 - return "bz2"
521.556 - return "tar"
521.557 -
521.558 - def close(self):
521.559 - self.fileobj.close()
521.560 -# class StreamProxy
521.561 -
521.562 -class _BZ2Proxy(object):
521.563 - """Small proxy class that enables external file object
521.564 - support for "r:bz2" and "w:bz2" modes. This is actually
521.565 - a workaround for a limitation in bz2 module's BZ2File
521.566 - class which (unlike gzip.GzipFile) has no support for
521.567 - a file object argument.
521.568 - """
521.569 -
521.570 - blocksize = 16 * 1024
521.571 -
521.572 - def __init__(self, fileobj, mode):
521.573 - self.fileobj = fileobj
521.574 - self.mode = mode
521.575 - self.init()
521.576 -
521.577 - def init(self):
521.578 - import bz2
521.579 - self.pos = 0
521.580 - if self.mode == "r":
521.581 - self.bz2obj = bz2.BZ2Decompressor()
521.582 - self.fileobj.seek(0)
521.583 - self.buf = ""
521.584 - else:
521.585 - self.bz2obj = bz2.BZ2Compressor()
521.586 -
521.587 - def read(self, size):
521.588 - b = [self.buf]
521.589 - x = len(self.buf)
521.590 - while x < size:
521.591 - try:
521.592 - raw = self.fileobj.read(self.blocksize)
521.593 - data = self.bz2obj.decompress(raw)
521.594 - b.append(data)
521.595 - except EOFError:
521.596 - break
521.597 - x += len(data)
521.598 - self.buf = "".join(b)
521.599 -
521.600 - buf = self.buf[:size]
521.601 - self.buf = self.buf[size:]
521.602 - self.pos += len(buf)
521.603 - return buf
521.604 -
521.605 - def seek(self, pos):
521.606 - if pos < self.pos:
521.607 - self.init()
521.608 - self.read(pos - self.pos)
521.609 -
521.610 - def tell(self):
521.611 - return self.pos
521.612 -
521.613 - def write(self, data):
521.614 - self.pos += len(data)
521.615 - raw = self.bz2obj.compress(data)
521.616 - self.fileobj.write(raw)
521.617 -
521.618 - def close(self):
521.619 - if self.mode == "w":
521.620 - raw = self.bz2obj.flush()
521.621 - self.fileobj.write(raw)
521.622 - self.fileobj.close()
521.623 -# class _BZ2Proxy
521.624 -
521.625 -#------------------------
521.626 -# Extraction file object
521.627 -#------------------------
521.628 -class _FileInFile(object):
521.629 - """A thin wrapper around an existing file object that
521.630 - provides a part of its data as an individual file
521.631 - object.
521.632 - """
521.633 -
521.634 - def __init__(self, fileobj, offset, size, sparse=None):
521.635 - self.fileobj = fileobj
521.636 - self.offset = offset
521.637 - self.size = size
521.638 - self.sparse = sparse
521.639 - self.position = 0
521.640 -
521.641 - def tell(self):
521.642 - """Return the current file position.
521.643 - """
521.644 - return self.position
521.645 -
521.646 - def seek(self, position):
521.647 - """Seek to a position in the file.
521.648 - """
521.649 - self.position = position
521.650 -
521.651 - def read(self, size=None):
521.652 - """Read data from the file.
521.653 - """
521.654 - if size is None:
521.655 - size = self.size - self.position
521.656 - else:
521.657 - size = min(size, self.size - self.position)
521.658 -
521.659 - if self.sparse is None:
521.660 - return self.readnormal(size)
521.661 - else:
521.662 - return self.readsparse(size)
521.663 -
521.664 - def readnormal(self, size):
521.665 - """Read operation for regular files.
521.666 - """
521.667 - self.fileobj.seek(self.offset + self.position)
521.668 - self.position += size
521.669 - return self.fileobj.read(size)
521.670 -
521.671 - def readsparse(self, size):
521.672 - """Read operation for sparse files.
521.673 - """
521.674 - data = []
521.675 - while size > 0:
521.676 - buf = self.readsparsesection(size)
521.677 - if not buf:
521.678 - break
521.679 - size -= len(buf)
521.680 - data.append(buf)
521.681 - return "".join(data)
521.682 -
521.683 - def readsparsesection(self, size):
521.684 - """Read a single section of a sparse file.
521.685 - """
521.686 - section = self.sparse.find(self.position)
521.687 -
521.688 - if section is None:
521.689 - return ""
521.690 -
521.691 - size = min(size, section.offset + section.size - self.position)
521.692 -
521.693 - if isinstance(section, _data):
521.694 - realpos = section.realpos + self.position - section.offset
521.695 - self.fileobj.seek(self.offset + realpos)
521.696 - self.position += size
521.697 - return self.fileobj.read(size)
521.698 - else:
521.699 - self.position += size
521.700 - return NUL * size
521.701 -#class _FileInFile
521.702 -
521.703 -
521.704 -class ExFileObject(object):
521.705 - """File-like object for reading an archive member.
521.706 - Is returned by TarFile.extractfile().
521.707 - """
521.708 - blocksize = 1024
521.709 -
521.710 - def __init__(self, tarfile, tarinfo):
521.711 - self.fileobj = _FileInFile(tarfile.fileobj,
521.712 - tarinfo.offset_data,
521.713 - tarinfo.size,
521.714 - getattr(tarinfo, "sparse", None))
521.715 - self.name = tarinfo.name
521.716 - self.mode = "r"
521.717 - self.closed = False
521.718 - self.size = tarinfo.size
521.719 -
521.720 - self.position = 0
521.721 - self.buffer = ""
521.722 -
521.723 - def read(self, size=None):
521.724 - """Read at most size bytes from the file. If size is not
521.725 - present or None, read all data until EOF is reached.
521.726 - """
521.727 - if self.closed:
521.728 - raise ValueError("I/O operation on closed file")
521.729 -
521.730 - buf = ""
521.731 - if self.buffer:
521.732 - if size is None:
521.733 - buf = self.buffer
521.734 - self.buffer = ""
521.735 - else:
521.736 - buf = self.buffer[:size]
521.737 - self.buffer = self.buffer[size:]
521.738 -
521.739 - if size is None:
521.740 - buf += self.fileobj.read()
521.741 - else:
521.742 - buf += self.fileobj.read(size - len(buf))
521.743 -
521.744 - self.position += len(buf)
521.745 - return buf
521.746 -
521.747 - def readline(self, size=-1):
521.748 - """Read one entire line from the file. If size is present
521.749 - and non-negative, return a string with at most that
521.750 - size, which may be an incomplete line.
521.751 - """
521.752 - if self.closed:
521.753 - raise ValueError("I/O operation on closed file")
521.754 -
521.755 - if "\n" in self.buffer:
521.756 - pos = self.buffer.find("\n") + 1
521.757 - else:
521.758 - buffers = [self.buffer]
521.759 - while True:
521.760 - buf = self.fileobj.read(self.blocksize)
521.761 - buffers.append(buf)
521.762 - if not buf or "\n" in buf:
521.763 - self.buffer = "".join(buffers)
521.764 - pos = self.buffer.find("\n") + 1
521.765 - if pos == 0:
521.766 - # no newline found.
521.767 - pos = len(self.buffer)
521.768 - break
521.769 -
521.770 - if size != -1:
521.771 - pos = min(size, pos)
521.772 -
521.773 - buf = self.buffer[:pos]
521.774 - self.buffer = self.buffer[pos:]
521.775 - self.position += len(buf)
521.776 - return buf
521.777 -
521.778 - def readlines(self):
521.779 - """Return a list with all remaining lines.
521.780 - """
521.781 - result = []
521.782 - while True:
521.783 - line = self.readline()
521.784 - if not line: break
521.785 - result.append(line)
521.786 - return result
521.787 -
521.788 - def tell(self):
521.789 - """Return the current file position.
521.790 - """
521.791 - if self.closed:
521.792 - raise ValueError("I/O operation on closed file")
521.793 -
521.794 - return self.position
521.795 -
521.796 - def seek(self, pos, whence=os.SEEK_SET):
521.797 - """Seek to a position in the file.
521.798 - """
521.799 - if self.closed:
521.800 - raise ValueError("I/O operation on closed file")
521.801 -
521.802 - if whence == os.SEEK_SET:
521.803 - self.position = min(max(pos, 0), self.size)
521.804 - elif whence == os.SEEK_CUR:
521.805 - if pos < 0:
521.806 - self.position = max(self.position + pos, 0)
521.807 - else:
521.808 - self.position = min(self.position + pos, self.size)
521.809 - elif whence == os.SEEK_END:
521.810 - self.position = max(min(self.size + pos, self.size), 0)
521.811 - else:
521.812 - raise ValueError("Invalid argument")
521.813 -
521.814 - self.buffer = ""
521.815 - self.fileobj.seek(self.position)
521.816 -
521.817 - def close(self):
521.818 - """Close the file object.
521.819 - """
521.820 - self.closed = True
521.821 -
521.822 - def __iter__(self):
521.823 - """Get an iterator over the file's lines.
521.824 - """
521.825 - while True:
521.826 - line = self.readline()
521.827 - if not line:
521.828 - break
521.829 - yield line
521.830 -#class ExFileObject
521.831 -
521.832 -#------------------
521.833 -# Exported Classes
521.834 -#------------------
521.835 -class TarInfo(object):
521.836 - """Informational class which holds the details about an
521.837 - archive member given by a tar header block.
521.838 - TarInfo objects are returned by TarFile.getmember(),
521.839 - TarFile.getmembers() and TarFile.gettarinfo() and are
521.840 - usually created internally.
521.841 - """
521.842 -
521.843 - def __init__(self, name=""):
521.844 - """Construct a TarInfo object. name is the optional name
521.845 - of the member.
521.846 - """
521.847 - self.name = name # member name (dirnames must end with '/')
521.848 - self.mode = 0666 # file permissions
521.849 - self.uid = 0 # user id
521.850 - self.gid = 0 # group id
521.851 - self.size = 0 # file size
521.852 - self.mtime = 0 # modification time
521.853 - self.chksum = 0 # header checksum
521.854 - self.type = REGTYPE # member type
521.855 - self.linkname = "" # link name
521.856 - self.uname = "user" # user name
521.857 - self.gname = "group" # group name
521.858 - self.devmajor = 0 # device major number
521.859 - self.devminor = 0 # device minor number
521.860 -
521.861 - self.offset = 0 # the tar header starts here
521.862 - self.offset_data = 0 # the file's data starts here
521.863 -
521.864 - def __repr__(self):
521.865 - return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self))
521.866 -
521.867 - @classmethod
521.868 - def frombuf(cls, buf):
521.869 - """Construct a TarInfo object from a 512 byte string buffer.
521.870 - """
521.871 - if len(buf) != BLOCKSIZE:
521.872 - raise ValueError("truncated header")
521.873 - if buf.count(NUL) == BLOCKSIZE:
521.874 - raise ValueError("empty header")
521.875 -
521.876 - tarinfo = cls()
521.877 - tarinfo.buf = buf
521.878 - tarinfo.name = buf[0:100].rstrip(NUL)
521.879 - tarinfo.mode = nti(buf[100:108])
521.880 - tarinfo.uid = nti(buf[108:116])
521.881 - tarinfo.gid = nti(buf[116:124])
521.882 - tarinfo.size = nti(buf[124:136])
521.883 - tarinfo.mtime = nti(buf[136:148])
521.884 - tarinfo.chksum = nti(buf[148:156])
521.885 - tarinfo.type = buf[156:157]
521.886 - tarinfo.linkname = buf[157:257].rstrip(NUL)
521.887 - tarinfo.uname = buf[265:297].rstrip(NUL)
521.888 - tarinfo.gname = buf[297:329].rstrip(NUL)
521.889 - tarinfo.devmajor = nti(buf[329:337])
521.890 - tarinfo.devminor = nti(buf[337:345])
521.891 - prefix = buf[345:500].rstrip(NUL)
521.892 -
521.893 - if prefix and not tarinfo.issparse():
521.894 - tarinfo.name = prefix + "/" + tarinfo.name
521.895 -
521.896 - if tarinfo.chksum not in calc_chksums(buf):
521.897 - raise ValueError("invalid header")
521.898 - return tarinfo
521.899 -
521.900 - def tobuf(self, posix=False):
521.901 - """Return a tar header as a string of 512 byte blocks.
521.902 - """
521.903 - buf = ""
521.904 - type = self.type
521.905 - prefix = ""
521.906 -
521.907 - if self.name.endswith("/"):
521.908 - type = DIRTYPE
521.909 -
521.910 - if type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
521.911 - # Prevent "././@LongLink" from being normalized.
521.912 - name = self.name
521.913 - else:
521.914 - name = normpath(self.name)
521.915 -
521.916 - if type == DIRTYPE:
521.917 - # directories should end with '/'
521.918 - name += "/"
521.919 -
521.920 - linkname = self.linkname
521.921 - if linkname:
521.922 - # if linkname is empty we end up with a '.'
521.923 - linkname = normpath(linkname)
521.924 -
521.925 - if posix:
521.926 - if self.size > MAXSIZE_MEMBER:
521.927 - raise ValueError("file is too large (>= 8 GB)")
521.928 -
521.929 - if len(self.linkname) > LENGTH_LINK:
521.930 - raise ValueError("linkname is too long (>%d)" % (LENGTH_LINK))
521.931 -
521.932 - if len(name) > LENGTH_NAME:
521.933 - prefix = name[:LENGTH_PREFIX + 1]
521.934 - while prefix and prefix[-1] != "/":
521.935 - prefix = prefix[:-1]
521.936 -
521.937 - name = name[len(prefix):]
521.938 - prefix = prefix[:-1]
521.939 -
521.940 - if not prefix or len(name) > LENGTH_NAME:
521.941 - raise ValueError("name is too long")
521.942 -
521.943 - else:
521.944 - if len(self.linkname) > LENGTH_LINK:
521.945 - buf += self._create_gnulong(self.linkname, GNUTYPE_LONGLINK)
521.946 -
521.947 - if len(name) > LENGTH_NAME:
521.948 - buf += self._create_gnulong(name, GNUTYPE_LONGNAME)
521.949 -
521.950 - parts = [
521.951 - stn(name, 100),
521.952 - itn(self.mode & 07777, 8, posix),
521.953 - itn(self.uid, 8, posix),
521.954 - itn(self.gid, 8, posix),
521.955 - itn(self.size, 12, posix),
521.956 - itn(self.mtime, 12, posix),
521.957 - " ", # checksum field
521.958 - type,
521.959 - stn(self.linkname, 100),
521.960 - stn(MAGIC, 6),
521.961 - stn(VERSION, 2),
521.962 - stn(self.uname, 32),
521.963 - stn(self.gname, 32),
521.964 - itn(self.devmajor, 8, posix),
521.965 - itn(self.devminor, 8, posix),
521.966 - stn(prefix, 155)
521.967 - ]
521.968 -
521.969 - buf += struct.pack("%ds" % BLOCKSIZE, "".join(parts))
521.970 - chksum = calc_chksums(buf[-BLOCKSIZE:])[0]
521.971 - buf = buf[:-364] + "%06o\0" % chksum + buf[-357:]
521.972 - self.buf = buf
521.973 - return buf
521.974 -
521.975 - def _create_gnulong(self, name, type):
521.976 - """Create a GNU longname/longlink header from name.
521.977 - It consists of an extended tar header, with the length
521.978 - of the longname as size, followed by data blocks,
521.979 - which contain the longname as a null terminated string.
521.980 - """
521.981 - name += NUL
521.982 -
521.983 - tarinfo = self.__class__()
521.984 - tarinfo.name = "././@LongLink"
521.985 - tarinfo.type = type
521.986 - tarinfo.mode = 0
521.987 - tarinfo.size = len(name)
521.988 -
521.989 - # create extended header
521.990 - buf = tarinfo.tobuf()
521.991 - # create name blocks
521.992 - buf += name
521.993 - blocks, remainder = divmod(len(name), BLOCKSIZE)
521.994 - if remainder > 0:
521.995 - buf += (BLOCKSIZE - remainder) * NUL
521.996 - return buf
521.997 -
521.998 - def isreg(self):
521.999 - return self.type in REGULAR_TYPES
521.1000 - def isfile(self):
521.1001 - return self.isreg()
521.1002 - def isdir(self):
521.1003 - return self.type == DIRTYPE
521.1004 - def issym(self):
521.1005 - return self.type == SYMTYPE
521.1006 - def islnk(self):
521.1007 - return self.type == LNKTYPE
521.1008 - def ischr(self):
521.1009 - return self.type == CHRTYPE
521.1010 - def isblk(self):
521.1011 - return self.type == BLKTYPE
521.1012 - def isfifo(self):
521.1013 - return self.type == FIFOTYPE
521.1014 - def issparse(self):
521.1015 - return self.type == GNUTYPE_SPARSE
521.1016 - def isdev(self):
521.1017 - return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE)
521.1018 -# class TarInfo
521.1019 -
521.1020 -class TarFile(object):
521.1021 - """The TarFile Class provides an interface to tar archives.
521.1022 - """
521.1023 -
521.1024 - debug = 0 # May be set from 0 (no msgs) to 3 (all msgs)
521.1025 -
521.1026 - dereference = False # If true, add content of linked file to the
521.1027 - # tar file, else the link.
521.1028 -
521.1029 - ignore_zeros = False # If true, skips empty or invalid blocks and
521.1030 - # continues processing.
521.1031 -
521.1032 - errorlevel = 0 # If 0, fatal errors only appear in debug
521.1033 - # messages (if debug >= 0). If > 0, errors
521.1034 - # are passed to the caller as exceptions.
521.1035 -
521.1036 - posix = False # If True, generates POSIX.1-1990-compliant
521.1037 - # archives (no GNU extensions!)
521.1038 -
521.1039 - fileobject = ExFileObject
521.1040 -
521.1041 - def __init__(self, name=None, mode="r", fileobj=None):
521.1042 - """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
521.1043 - read from an existing archive, 'a' to append data to an existing
521.1044 - file or 'w' to create a new file overwriting an existing one. `mode'
521.1045 - defaults to 'r'.
521.1046 - If `fileobj' is given, it is used for reading or writing data. If it
521.1047 - can be determined, `mode' is overridden by `fileobj's mode.
521.1048 - `fileobj' is not closed, when TarFile is closed.
521.1049 - """
521.1050 - self.name = os.path.abspath(name)
521.1051 -
521.1052 - if len(mode) > 1 or mode not in "raw":
521.1053 - raise ValueError("mode must be 'r', 'a' or 'w'")
521.1054 - self._mode = mode
521.1055 - self.mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode]
521.1056 -
521.1057 - if not fileobj:
521.1058 - fileobj = file(self.name, self.mode)
521.1059 - self._extfileobj = False
521.1060 - else:
521.1061 - if self.name is None and hasattr(fileobj, "name"):
521.1062 - self.name = os.path.abspath(fileobj.name)
521.1063 - if hasattr(fileobj, "mode"):
521.1064 - self.mode = fileobj.mode
521.1065 - self._extfileobj = True
521.1066 - self.fileobj = fileobj
521.1067 -
521.1068 - # Init datastructures
521.1069 - self.closed = False
521.1070 - self.members = [] # list of members as TarInfo objects
521.1071 - self._loaded = False # flag if all members have been read
521.1072 - self.offset = 0L # current position in the archive file
521.1073 - self.inodes = {} # dictionary caching the inodes of
521.1074 - # archive members already added
521.1075 -
521.1076 - if self._mode == "r":
521.1077 - self.firstmember = None
521.1078 - self.firstmember = self.next()
521.1079 -
521.1080 - if self._mode == "a":
521.1081 - # Move to the end of the archive,
521.1082 - # before the first empty block.
521.1083 - self.firstmember = None
521.1084 - while True:
521.1085 - try:
521.1086 - tarinfo = self.next()
521.1087 - except ReadError:
521.1088 - self.fileobj.seek(0)
521.1089 - break
521.1090 - if tarinfo is None:
521.1091 - self.fileobj.seek(- BLOCKSIZE, 1)
521.1092 - break
521.1093 -
521.1094 - if self._mode in "aw":
521.1095 - self._loaded = True
521.1096 -
521.1097 - #--------------------------------------------------------------------------
521.1098 - # Below are the classmethods which act as alternate constructors to the
521.1099 - # TarFile class. The open() method is the only one that is needed for
521.1100 - # public use; it is the "super"-constructor and is able to select an
521.1101 - # adequate "sub"-constructor for a particular compression using the mapping
521.1102 - # from OPEN_METH.
521.1103 - #
521.1104 - # This concept allows one to subclass TarFile without losing the comfort of
521.1105 - # the super-constructor. A sub-constructor is registered and made available
521.1106 - # by adding it to the mapping in OPEN_METH.
521.1107 -
521.1108 - @classmethod
521.1109 - def open(cls, name=None, mode="r", fileobj=None, bufsize=20*512):
521.1110 - """Open a tar archive for reading, writing or appending. Return
521.1111 - an appropriate TarFile class.
521.1112 -
521.1113 - mode:
521.1114 - 'r' or 'r:*' open for reading with transparent compression
521.1115 - 'r:' open for reading exclusively uncompressed
521.1116 - 'r:gz' open for reading with gzip compression
521.1117 - 'r:bz2' open for reading with bzip2 compression
521.1118 - 'a' or 'a:' open for appending
521.1119 - 'w' or 'w:' open for writing without compression
521.1120 - 'w:gz' open for writing with gzip compression
521.1121 - 'w:bz2' open for writing with bzip2 compression
521.1122 -
521.1123 - 'r|*' open a stream of tar blocks with transparent compression
521.1124 - 'r|' open an uncompressed stream of tar blocks for reading
521.1125 - 'r|gz' open a gzip compressed stream of tar blocks
521.1126 - 'r|bz2' open a bzip2 compressed stream of tar blocks
521.1127 - 'w|' open an uncompressed stream for writing
521.1128 - 'w|gz' open a gzip compressed stream for writing
521.1129 - 'w|bz2' open a bzip2 compressed stream for writing
521.1130 - """
521.1131 -
521.1132 - if not name and not fileobj:
521.1133 - raise ValueError("nothing to open")
521.1134 -
521.1135 - if mode in ("r", "r:*"):
521.1136 - # Find out which *open() is appropriate for opening the file.
521.1137 - for comptype in cls.OPEN_METH:
521.1138 - func = getattr(cls, cls.OPEN_METH[comptype])
521.1139 - if fileobj is not None:
521.1140 - saved_pos = fileobj.tell()
521.1141 - try:
521.1142 - return func(name, "r", fileobj)
521.1143 - except (ReadError, CompressionError):
521.1144 - if fileobj is not None:
521.1145 - fileobj.seek(saved_pos)
521.1146 - continue
521.1147 - raise ReadError("file could not be opened successfully")
521.1148 -
521.1149 - elif ":" in mode:
521.1150 - filemode, comptype = mode.split(":", 1)
521.1151 - filemode = filemode or "r"
521.1152 - comptype = comptype or "tar"
521.1153 -
521.1154 - # Select the *open() function according to
521.1155 - # given compression.
521.1156 - if comptype in cls.OPEN_METH:
521.1157 - func = getattr(cls, cls.OPEN_METH[comptype])
521.1158 - else:
521.1159 - raise CompressionError("unknown compression type %r" % comptype)
521.1160 - return func(name, filemode, fileobj)
521.1161 -
521.1162 - elif "|" in mode:
521.1163 - filemode, comptype = mode.split("|", 1)
521.1164 - filemode = filemode or "r"
521.1165 - comptype = comptype or "tar"
521.1166 -
521.1167 - if filemode not in "rw":
521.1168 - raise ValueError("mode must be 'r' or 'w'")
521.1169 -
521.1170 - t = cls(name, filemode,
521.1171 - _Stream(name, filemode, comptype, fileobj, bufsize))
521.1172 - t._extfileobj = False
521.1173 - return t
521.1174 -
521.1175 - elif mode in "aw":
521.1176 - return cls.taropen(name, mode, fileobj)
521.1177 -
521.1178 - raise ValueError("undiscernible mode")
521.1179 -
521.1180 - @classmethod
521.1181 - def taropen(cls, name, mode="r", fileobj=None):
521.1182 - """Open uncompressed tar archive name for reading or writing.
521.1183 - """
521.1184 - if len(mode) > 1 or mode not in "raw":
521.1185 - raise ValueError("mode must be 'r', 'a' or 'w'")
521.1186 - return cls(name, mode, fileobj)
521.1187 -
521.1188 - @classmethod
521.1189 - def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9):
521.1190 - """Open gzip compressed tar archive name for reading or writing.
521.1191 - Appending is not allowed.
521.1192 - """
521.1193 - if len(mode) > 1 or mode not in "rw":
521.1194 - raise ValueError("mode must be 'r' or 'w'")
521.1195 -
521.1196 - try:
521.1197 - import gzip
521.1198 - gzip.GzipFile
521.1199 - except (ImportError, AttributeError):
521.1200 - raise CompressionError("gzip module is not available")
521.1201 -
521.1202 - if fileobj is None:
521.1203 - fileobj = file(name, mode + "b")
521.1204 -
521.1205 - try:
521.1206 - t = cls.taropen(name, mode,
521.1207 - gzip.GzipFile(name, mode, compresslevel, fileobj))
521.1208 - except IOError:
521.1209 - raise ReadError("not a gzip file")
521.1210 - t._extfileobj = False
521.1211 - return t
521.1212 -
521.1213 - @classmethod
521.1214 - def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9):
521.1215 - """Open bzip2 compressed tar archive name for reading or writing.
521.1216 - Appending is not allowed.
521.1217 - """
521.1218 - if len(mode) > 1 or mode not in "rw":
521.1219 - raise ValueError("mode must be 'r' or 'w'.")
521.1220 -
521.1221 - try:
521.1222 - import bz2
521.1223 - except ImportError:
521.1224 - raise CompressionError("bz2 module is not available")
521.1225 -
521.1226 - if fileobj is not None:
521.1227 - fileobj = _BZ2Proxy(fileobj, mode)
521.1228 - else:
521.1229 - fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel)
521.1230 -
521.1231 - try:
521.1232 - t = cls.taropen(name, mode, fileobj)
521.1233 - except IOError:
521.1234 - raise ReadError("not a bzip2 file")
521.1235 - t._extfileobj = False
521.1236 - return t
521.1237 -
521.1238 - # All *open() methods are registered here.
521.1239 - OPEN_METH = {
521.1240 - "tar": "taropen", # uncompressed tar
521.1241 - "gz": "gzopen", # gzip compressed tar
521.1242 - "bz2": "bz2open" # bzip2 compressed tar
521.1243 - }
521.1244 -
521.1245 - #--------------------------------------------------------------------------
521.1246 - # The public methods which TarFile provides:
521.1247 -
521.1248 - def close(self):
521.1249 - """Close the TarFile. In write-mode, two finishing zero blocks are
521.1250 - appended to the archive.
521.1251 - """
521.1252 - if self.closed:
521.1253 - return
521.1254 -
521.1255 - if self._mode in "aw":
521.1256 - self.fileobj.write(NUL * (BLOCKSIZE * 2))
521.1257 - self.offset += (BLOCKSIZE * 2)
521.1258 - # fill up the end with zero-blocks
521.1259 - # (like option -b20 for tar does)
521.1260 - blocks, remainder = divmod(self.offset, RECORDSIZE)
521.1261 - if remainder > 0:
521.1262 - self.fileobj.write(NUL * (RECORDSIZE - remainder))
521.1263 -
521.1264 - if not self._extfileobj:
521.1265 - self.fileobj.close()
521.1266 - self.closed = True
521.1267 -
521.1268 - def getmember(self, name):
521.1269 - """Return a TarInfo object for member `name'. If `name' can not be
521.1270 - found in the archive, KeyError is raised. If a member occurs more
521.1271 - than once in the archive, its last occurence is assumed to be the
521.1272 - most up-to-date version.
521.1273 - """
521.1274 - tarinfo = self._getmember(name)
521.1275 - if tarinfo is None:
521.1276 - raise KeyError("filename %r not found" % name)
521.1277 - return tarinfo
521.1278 -
521.1279 - def getmembers(self):
521.1280 - """Return the members of the archive as a list of TarInfo objects. The
521.1281 - list has the same order as the members in the archive.
521.1282 - """
521.1283 - self._check()
521.1284 - if not self._loaded: # if we want to obtain a list of
521.1285 - self._load() # all members, we first have to
521.1286 - # scan the whole archive.
521.1287 - return self.members
521.1288 -
521.1289 - def getnames(self):
521.1290 - """Return the members of the archive as a list of their names. It has
521.1291 - the same order as the list returned by getmembers().
521.1292 - """
521.1293 - return [tarinfo.name for tarinfo in self.getmembers()]
521.1294 -
521.1295 - def gettarinfo(self, name=None, arcname=None, fileobj=None):
521.1296 - """Create a TarInfo object for either the file `name' or the file
521.1297 - object `fileobj' (using os.fstat on its file descriptor). You can
521.1298 - modify some of the TarInfo's attributes before you add it using
521.1299 - addfile(). If given, `arcname' specifies an alternative name for the
521.1300 - file in the archive.
521.1301 - """
521.1302 - self._check("aw")
521.1303 -
521.1304 - # When fileobj is given, replace name by
521.1305 - # fileobj's real name.
521.1306 - if fileobj is not None:
521.1307 - name = fileobj.name
521.1308 -
521.1309 - # Building the name of the member in the archive.
521.1310 - # Backward slashes are converted to forward slashes,
521.1311 - # Absolute paths are turned to relative paths.
521.1312 - if arcname is None:
521.1313 - arcname = name
521.1314 - arcname = normpath(arcname)
521.1315 - drv, arcname = os.path.splitdrive(arcname)
521.1316 - while arcname[0:1] == "/":
521.1317 - arcname = arcname[1:]
521.1318 -
521.1319 - # Now, fill the TarInfo object with
521.1320 - # information specific for the file.
521.1321 - tarinfo = TarInfo()
521.1322 -
521.1323 - # Use os.stat or os.lstat, depending on platform
521.1324 - # and if symlinks shall be resolved.
521.1325 - if fileobj is None:
521.1326 - if hasattr(os, "lstat") and not self.dereference:
521.1327 - statres = os.lstat(name)
521.1328 - else:
521.1329 - statres = os.stat(name)
521.1330 - else:
521.1331 - statres = os.fstat(fileobj.fileno())
521.1332 - linkname = ""
521.1333 -
521.1334 - stmd = statres.st_mode
521.1335 - if stat.S_ISREG(stmd):
521.1336 - inode = (statres.st_ino, statres.st_dev)
521.1337 - if not self.dereference and \
521.1338 - statres.st_nlink > 1 and inode in self.inodes:
521.1339 - # Is it a hardlink to an already
521.1340 - # archived file?
521.1341 - type = LNKTYPE
521.1342 - linkname = self.inodes[inode]
521.1343 - else:
521.1344 - # The inode is added only if its valid.
521.1345 - # For win32 it is always 0.
521.1346 - type = REGTYPE
521.1347 - if inode[0]:
521.1348 - self.inodes[inode] = arcname
521.1349 - elif stat.S_ISDIR(stmd):
521.1350 - type = DIRTYPE
521.1351 - if arcname[-1:] != "/":
521.1352 - arcname += "/"
521.1353 - elif stat.S_ISFIFO(stmd):
521.1354 - type = FIFOTYPE
521.1355 - elif stat.S_ISLNK(stmd):
521.1356 - type = SYMTYPE
521.1357 - linkname = os.readlink(name)
521.1358 - elif stat.S_ISCHR(stmd):
521.1359 - type = CHRTYPE
521.1360 - elif stat.S_ISBLK(stmd):
521.1361 - type = BLKTYPE
521.1362 - else:
521.1363 - return None
521.1364 -
521.1365 - # Fill the TarInfo object with all
521.1366 - # information we can get.
521.1367 - tarinfo.name = arcname
521.1368 - tarinfo.mode = stmd
521.1369 - tarinfo.uid = statres.st_uid
521.1370 - tarinfo.gid = statres.st_gid
521.1371 - if stat.S_ISREG(stmd):
521.1372 - tarinfo.size = statres.st_size
521.1373 - else:
521.1374 - tarinfo.size = 0L
521.1375 - tarinfo.mtime = statres.st_mtime
521.1376 - tarinfo.type = type
521.1377 - tarinfo.linkname = linkname
521.1378 - if pwd:
521.1379 - try:
521.1380 - tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0]
521.1381 - except KeyError:
521.1382 - pass
521.1383 - if grp:
521.1384 - try:
521.1385 - tarinfo.gname = grp.getgrgid(tarinfo.gid)[0]
521.1386 - except KeyError:
521.1387 - pass
521.1388 -
521.1389 - if type in (CHRTYPE, BLKTYPE):
521.1390 - if hasattr(os, "major") and hasattr(os, "minor"):
521.1391 - tarinfo.devmajor = os.major(statres.st_rdev)
521.1392 - tarinfo.devminor = os.minor(statres.st_rdev)
521.1393 - return tarinfo
521.1394 -
521.1395 - def list(self, verbose=True):
521.1396 - """Print a table of contents to sys.stdout. If `verbose' is False, only
521.1397 - the names of the members are printed. If it is True, an `ls -l'-like
521.1398 - output is produced.
521.1399 - """
521.1400 - self._check()
521.1401 -
521.1402 - for tarinfo in self:
521.1403 - if verbose:
521.1404 - print filemode(tarinfo.mode),
521.1405 - print "%s/%s" % (tarinfo.uname or tarinfo.uid,
521.1406 - tarinfo.gname or tarinfo.gid),
521.1407 - if tarinfo.ischr() or tarinfo.isblk():
521.1408 - print "%10s" % ("%d,%d" \
521.1409 - % (tarinfo.devmajor, tarinfo.devminor)),
521.1410 - else:
521.1411 - print "%10d" % tarinfo.size,
521.1412 - print "%d-%02d-%02d %02d:%02d:%02d" \
521.1413 - % time.localtime(tarinfo.mtime)[:6],
521.1414 -
521.1415 - print tarinfo.name,
521.1416 -
521.1417 - if verbose:
521.1418 - if tarinfo.issym():
521.1419 - print "->", tarinfo.linkname,
521.1420 - if tarinfo.islnk():
521.1421 - print "link to", tarinfo.linkname,
521.1422 - print
521.1423 -
521.1424 - def add(self, name, arcname=None, recursive=True):
521.1425 - """Add the file `name' to the archive. `name' may be any type of file
521.1426 - (directory, fifo, symbolic link, etc.). If given, `arcname'
521.1427 - specifies an alternative name for the file in the archive.
521.1428 - Directories are added recursively by default. This can be avoided by
521.1429 - setting `recursive' to False.
521.1430 - """
521.1431 - self._check("aw")
521.1432 -
521.1433 - if arcname is None:
521.1434 - arcname = name
521.1435 -
521.1436 - # Skip if somebody tries to archive the archive...
521.1437 - if self.name is not None and os.path.abspath(name) == self.name:
521.1438 - self._dbg(2, "tarfile: Skipped %r" % name)
521.1439 - return
521.1440 -
521.1441 - # Special case: The user wants to add the current
521.1442 - # working directory.
521.1443 - if name == ".":
521.1444 - if recursive:
521.1445 - if arcname == ".":
521.1446 - arcname = ""
521.1447 - for f in os.listdir("."):
521.1448 - self.add(f, os.path.join(arcname, f))
521.1449 - return
521.1450 -
521.1451 - self._dbg(1, name)
521.1452 -
521.1453 - # Create a TarInfo object from the file.
521.1454 - tarinfo = self.gettarinfo(name, arcname)
521.1455 -
521.1456 - if tarinfo is None:
521.1457 - self._dbg(1, "tarfile: Unsupported type %r" % name)
521.1458 - return
521.1459 -
521.1460 - # Append the tar header and data to the archive.
521.1461 - if tarinfo.isreg():
521.1462 - f = file(name, "rb")
521.1463 - self.addfile(tarinfo, f)
521.1464 - f.close()
521.1465 -
521.1466 - elif tarinfo.isdir():
521.1467 - self.addfile(tarinfo)
521.1468 - if recursive:
521.1469 - for f in os.listdir(name):
521.1470 - self.add(os.path.join(name, f), os.path.join(arcname, f))
521.1471 -
521.1472 - else:
521.1473 - self.addfile(tarinfo)
521.1474 -
521.1475 - def addfile(self, tarinfo, fileobj=None):
521.1476 - """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
521.1477 - given, tarinfo.size bytes are read from it and added to the archive.
521.1478 - You can create TarInfo objects using gettarinfo().
521.1479 - On Windows platforms, `fileobj' should always be opened with mode
521.1480 - 'rb' to avoid irritation about the file size.
521.1481 - """
521.1482 - self._check("aw")
521.1483 -
521.1484 - tarinfo = copy.copy(tarinfo)
521.1485 -
521.1486 - buf = tarinfo.tobuf(self.posix)
521.1487 - self.fileobj.write(buf)
521.1488 - self.offset += len(buf)
521.1489 -
521.1490 - # If there's data to follow, append it.
521.1491 - if fileobj is not None:
521.1492 - copyfileobj(fileobj, self.fileobj, tarinfo.size)
521.1493 - blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)
521.1494 - if remainder > 0:
521.1495 - self.fileobj.write(NUL * (BLOCKSIZE - remainder))
521.1496 - blocks += 1
521.1497 - self.offset += blocks * BLOCKSIZE
521.1498 -
521.1499 - self.members.append(tarinfo)
521.1500 -
521.1501 - def extractall(self, path=".", members=None):
521.1502 - """Extract all members from the archive to the current working
521.1503 - directory and set owner, modification time and permissions on
521.1504 - directories afterwards. `path' specifies a different directory
521.1505 - to extract to. `members' is optional and must be a subset of the
521.1506 - list returned by getmembers().
521.1507 - """
521.1508 - directories = []
521.1509 -
521.1510 - if members is None:
521.1511 - members = self
521.1512 -
521.1513 - for tarinfo in members:
521.1514 - if tarinfo.isdir():
521.1515 - # Extract directory with a safe mode, so that
521.1516 - # all files below can be extracted as well.
521.1517 - try:
521.1518 - os.makedirs(os.path.join(path, tarinfo.name), 0777)
521.1519 - except EnvironmentError:
521.1520 - pass
521.1521 - directories.append(tarinfo)
521.1522 - else:
521.1523 - self.extract(tarinfo, path)
521.1524 -
521.1525 - # Reverse sort directories.
521.1526 - directories.sort(lambda a, b: cmp(a.name, b.name))
521.1527 - directories.reverse()
521.1528 -
521.1529 - # Set correct owner, mtime and filemode on directories.
521.1530 - for tarinfo in directories:
521.1531 - path = os.path.join(path, tarinfo.name)
521.1532 - try:
521.1533 - self.chown(tarinfo, path)
521.1534 - self.utime(tarinfo, path)
521.1535 - self.chmod(tarinfo, path)
521.1536 - except ExtractError, e:
521.1537 - if self.errorlevel > 1:
521.1538 - raise
521.1539 - else:
521.1540 - self._dbg(1, "tarfile: %s" % e)
521.1541 -
521.1542 - def extract(self, member, path=""):
521.1543 - """Extract a member from the archive to the current working directory,
521.1544 - using its full name. Its file information is extracted as accurately
521.1545 - as possible. `member' may be a filename or a TarInfo object. You can
521.1546 - specify a different directory using `path'.
521.1547 - """
521.1548 - self._check("r")
521.1549 -
521.1550 - if isinstance(member, TarInfo):
521.1551 - tarinfo = member
521.1552 - else:
521.1553 - tarinfo = self.getmember(member)
521.1554 -
521.1555 - # Prepare the link target for makelink().
521.1556 - if tarinfo.islnk():
521.1557 - tarinfo._link_target = os.path.join(path, tarinfo.linkname)
521.1558 -
521.1559 - try:
521.1560 - self._extract_member(tarinfo, os.path.join(path, tarinfo.name))
521.1561 - except EnvironmentError, e:
521.1562 - if self.errorlevel > 0:
521.1563 - raise
521.1564 - else:
521.1565 - if e.filename is None:
521.1566 - self._dbg(1, "tarfile: %s" % e.strerror)
521.1567 - else:
521.1568 - self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename))
521.1569 - except ExtractError, e:
521.1570 - if self.errorlevel > 1:
521.1571 - raise
521.1572 - else:
521.1573 - self._dbg(1, "tarfile: %s" % e)
521.1574 -
521.1575 - def extractfile(self, member):
521.1576 - """Extract a member from the archive as a file object. `member' may be
521.1577 - a filename or a TarInfo object. If `member' is a regular file, a
521.1578 - file-like object is returned. If `member' is a link, a file-like
521.1579 - object is constructed from the link's target. If `member' is none of
521.1580 - the above, None is returned.
521.1581 - The file-like object is read-only and provides the following
521.1582 - methods: read(), readline(), readlines(), seek() and tell()
521.1583 - """
521.1584 - self._check("r")
521.1585 -
521.1586 - if isinstance(member, TarInfo):
521.1587 - tarinfo = member
521.1588 - else:
521.1589 - tarinfo = self.getmember(member)
521.1590 -
521.1591 - if tarinfo.isreg():
521.1592 - return self.fileobject(self, tarinfo)
521.1593 -
521.1594 - elif tarinfo.type not in SUPPORTED_TYPES:
521.1595 - # If a member's type is unknown, it is treated as a
521.1596 - # regular file.
521.1597 - return self.fileobject(self, tarinfo)
521.1598 -
521.1599 - elif tarinfo.islnk() or tarinfo.issym():
521.1600 - if isinstance(self.fileobj, _Stream):
521.1601 - # A small but ugly workaround for the case that someone tries
521.1602 - # to extract a (sym)link as a file-object from a non-seekable
521.1603 - # stream of tar blocks.
521.1604 - raise StreamError("cannot extract (sym)link as file object")
521.1605 - else:
521.1606 - # A (sym)link's file object is its target's file object.
521.1607 - return self.extractfile(self._getmember(tarinfo.linkname,
521.1608 - tarinfo))
521.1609 - else:
521.1610 - # If there's no data associated with the member (directory, chrdev,
521.1611 - # blkdev, etc.), return None instead of a file object.
521.1612 - return None
521.1613 -
521.1614 - def _extract_member(self, tarinfo, targetpath):
521.1615 - """Extract the TarInfo object tarinfo to a physical
521.1616 - file called targetpath.
521.1617 - """
521.1618 - # Fetch the TarInfo object for the given name
521.1619 - # and build the destination pathname, replacing
521.1620 - # forward slashes to platform specific separators.
521.1621 - if targetpath[-1:] == "/":
521.1622 - targetpath = targetpath[:-1]
521.1623 - targetpath = os.path.normpath(targetpath)
521.1624 -
521.1625 - # Create all upper directories.
521.1626 - upperdirs = os.path.dirname(targetpath)
521.1627 - if upperdirs and not os.path.exists(upperdirs):
521.1628 - ti = TarInfo()
521.1629 - ti.name = upperdirs
521.1630 - ti.type = DIRTYPE
521.1631 - ti.mode = 0777
521.1632 - ti.mtime = tarinfo.mtime
521.1633 - ti.uid = tarinfo.uid
521.1634 - ti.gid = tarinfo.gid
521.1635 - ti.uname = tarinfo.uname
521.1636 - ti.gname = tarinfo.gname
521.1637 - try:
521.1638 - self._extract_member(ti, ti.name)
521.1639 - except:
521.1640 - pass
521.1641 -
521.1642 - if tarinfo.islnk() or tarinfo.issym():
521.1643 - self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
521.1644 - else:
521.1645 - self._dbg(1, tarinfo.name)
521.1646 -
521.1647 - if tarinfo.isreg():
521.1648 - self.makefile(tarinfo, targetpath)
521.1649 - elif tarinfo.isdir():
521.1650 - self.makedir(tarinfo, targetpath)
521.1651 - elif tarinfo.isfifo():
521.1652 - self.makefifo(tarinfo, targetpath)
521.1653 - elif tarinfo.ischr() or tarinfo.isblk():
521.1654 - self.makedev(tarinfo, targetpath)
521.1655 - elif tarinfo.islnk() or tarinfo.issym():
521.1656 - self.makelink(tarinfo, targetpath)
521.1657 - elif tarinfo.type not in SUPPORTED_TYPES:
521.1658 - self.makeunknown(tarinfo, targetpath)
521.1659 - else:
521.1660 - self.makefile(tarinfo, targetpath)
521.1661 -
521.1662 - self.chown(tarinfo, targetpath)
521.1663 - if not tarinfo.issym():
521.1664 - self.chmod(tarinfo, targetpath)
521.1665 - self.utime(tarinfo, targetpath)
521.1666 -
521.1667 - #--------------------------------------------------------------------------
521.1668 - # Below are the different file methods. They are called via
521.1669 - # _extract_member() when extract() is called. They can be replaced in a
521.1670 - # subclass to implement other functionality.
521.1671 -
521.1672 - def makedir(self, tarinfo, targetpath):
521.1673 - """Make a directory called targetpath.
521.1674 - """
521.1675 - try:
521.1676 - os.mkdir(targetpath)
521.1677 - except EnvironmentError, e:
521.1678 - if e.errno != errno.EEXIST:
521.1679 - raise
521.1680 -
521.1681 - def makefile(self, tarinfo, targetpath):
521.1682 - """Make a file called targetpath.
521.1683 - """
521.1684 - source = self.extractfile(tarinfo)
521.1685 - target = file(targetpath, "wb")
521.1686 - copyfileobj(source, target)
521.1687 - source.close()
521.1688 - target.close()
521.1689 -
521.1690 - def makeunknown(self, tarinfo, targetpath):
521.1691 - """Make a file from a TarInfo object with an unknown type
521.1692 - at targetpath.
521.1693 - """
521.1694 - self.makefile(tarinfo, targetpath)
521.1695 - self._dbg(1, "tarfile: Unknown file type %r, " \
521.1696 - "extracted as regular file." % tarinfo.type)
521.1697 -
521.1698 - def makefifo(self, tarinfo, targetpath):
521.1699 - """Make a fifo called targetpath.
521.1700 - """
521.1701 - if hasattr(os, "mkfifo"):
521.1702 - os.mkfifo(targetpath)
521.1703 - else:
521.1704 - raise ExtractError("fifo not supported by system")
521.1705 -
521.1706 - def makedev(self, tarinfo, targetpath):
521.1707 - """Make a character or block device called targetpath.
521.1708 - """
521.1709 - if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
521.1710 - raise ExtractError("special devices not supported by system")
521.1711 -
521.1712 - mode = tarinfo.mode
521.1713 - if tarinfo.isblk():
521.1714 - mode |= stat.S_IFBLK
521.1715 - else:
521.1716 - mode |= stat.S_IFCHR
521.1717 -
521.1718 - os.mknod(targetpath, mode,
521.1719 - os.makedev(tarinfo.devmajor, tarinfo.devminor))
521.1720 -
521.1721 - def makelink(self, tarinfo, targetpath):
521.1722 - """Make a (symbolic) link called targetpath. If it cannot be created
521.1723 - (platform limitation), we try to make a copy of the referenced file
521.1724 - instead of a link.
521.1725 - """
521.1726 - linkpath = tarinfo.linkname
521.1727 - try:
521.1728 - if tarinfo.issym():
521.1729 - os.symlink(linkpath, targetpath)
521.1730 - else:
521.1731 - # See extract().
521.1732 - os.link(tarinfo._link_target, targetpath)
521.1733 - except AttributeError:
521.1734 - if tarinfo.issym():
521.1735 - linkpath = os.path.join(os.path.dirname(tarinfo.name),
521.1736 - linkpath)
521.1737 - linkpath = normpath(linkpath)
521.1738 -
521.1739 - try:
521.1740 - self._extract_member(self.getmember(linkpath), targetpath)
521.1741 - except (EnvironmentError, KeyError), e:
521.1742 - linkpath = os.path.normpath(linkpath)
521.1743 - try:
521.1744 - shutil.copy2(linkpath, targetpath)
521.1745 - except EnvironmentError, e:
521.1746 - raise IOError("link could not be created")
521.1747 -
521.1748 - def chown(self, tarinfo, targetpath):
521.1749 - """Set owner of targetpath according to tarinfo.
521.1750 - """
521.1751 - if pwd and hasattr(os, "geteuid") and os.geteuid() == 0:
521.1752 - # We have to be root to do so.
521.1753 - try:
521.1754 - g = grp.getgrnam(tarinfo.gname)[2]
521.1755 - except KeyError:
521.1756 - try:
521.1757 - g = grp.getgrgid(tarinfo.gid)[2]
521.1758 - except KeyError:
521.1759 - g = os.getgid()
521.1760 - try:
521.1761 - u = pwd.getpwnam(tarinfo.uname)[2]
521.1762 - except KeyError:
521.1763 - try:
521.1764 - u = pwd.getpwuid(tarinfo.uid)[2]
521.1765 - except KeyError:
521.1766 - u = os.getuid()
521.1767 - try:
521.1768 - if tarinfo.issym() and hasattr(os, "lchown"):
521.1769 - os.lchown(targetpath, u, g)
521.1770 - else:
521.1771 - if sys.platform != "os2emx":
521.1772 - os.chown(targetpath, u, g)
521.1773 - except EnvironmentError, e:
521.1774 - raise ExtractError("could not change owner")
521.1775 -
521.1776 - def chmod(self, tarinfo, targetpath):
521.1777 - """Set file permissions of targetpath according to tarinfo.
521.1778 - """
521.1779 - if hasattr(os, 'chmod'):
521.1780 - try:
521.1781 - os.chmod(targetpath, tarinfo.mode)
521.1782 - except EnvironmentError, e:
521.1783 - raise ExtractError("could not change mode")
521.1784 -
521.1785 - def utime(self, tarinfo, targetpath):
521.1786 - """Set modification time of targetpath according to tarinfo.
521.1787 - """
521.1788 - if not hasattr(os, 'utime'):
521.1789 - return
521.1790 - if sys.platform == "win32" and tarinfo.isdir():
521.1791 - # According to msdn.microsoft.com, it is an error (EACCES)
521.1792 - # to use utime() on directories.
521.1793 - return
521.1794 - try:
521.1795 - os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
521.1796 - except EnvironmentError, e:
521.1797 - raise ExtractError("could not change modification time")
521.1798 -
521.1799 - #--------------------------------------------------------------------------
521.1800 - def next(self):
521.1801 - """Return the next member of the archive as a TarInfo object, when
521.1802 - TarFile is opened for reading. Return None if there is no more
521.1803 - available.
521.1804 - """
521.1805 - self._check("ra")
521.1806 - if self.firstmember is not None:
521.1807 - m = self.firstmember
521.1808 - self.firstmember = None
521.1809 - return m
521.1810 -
521.1811 - # Read the next block.
521.1812 - self.fileobj.seek(self.offset)
521.1813 - while True:
521.1814 - buf = self.fileobj.read(BLOCKSIZE)
521.1815 - if not buf:
521.1816 - return None
521.1817 -
521.1818 - try:
521.1819 - tarinfo = TarInfo.frombuf(buf)
521.1820 -
521.1821 - # Set the TarInfo object's offset to the current position of the
521.1822 - # TarFile and set self.offset to the position where the data blocks
521.1823 - # should begin.
521.1824 - tarinfo.offset = self.offset
521.1825 - self.offset += BLOCKSIZE
521.1826 -
521.1827 - tarinfo = self.proc_member(tarinfo)
521.1828 -
521.1829 - except ValueError, e:
521.1830 - if self.ignore_zeros:
521.1831 - self._dbg(2, "0x%X: empty or invalid block: %s" %
521.1832 - (self.offset, e))
521.1833 - self.offset += BLOCKSIZE
521.1834 - continue
521.1835 - else:
521.1836 - if self.offset == 0:
521.1837 - raise ReadError("empty, unreadable or compressed "
521.1838 - "file: %s" % e)
521.1839 - return None
521.1840 - break
521.1841 -
521.1842 - # Some old tar programs represent a directory as a regular
521.1843 - # file with a trailing slash.
521.1844 - if tarinfo.isreg() and tarinfo.name.endswith("/"):
521.1845 - tarinfo.type = DIRTYPE
521.1846 -
521.1847 - # Directory names should have a '/' at the end.
521.1848 - if tarinfo.isdir():
521.1849 - tarinfo.name += "/"
521.1850 -
521.1851 - self.members.append(tarinfo)
521.1852 - return tarinfo
521.1853 -
521.1854 - #--------------------------------------------------------------------------
521.1855 - # The following are methods that are called depending on the type of a
521.1856 - # member. The entry point is proc_member() which is called with a TarInfo
521.1857 - # object created from the header block from the current offset. The
521.1858 - # proc_member() method can be overridden in a subclass to add custom
521.1859 - # proc_*() methods. A proc_*() method MUST implement the following
521.1860 - # operations:
521.1861 - # 1. Set tarinfo.offset_data to the position where the data blocks begin,
521.1862 - # if there is data that follows.
521.1863 - # 2. Set self.offset to the position where the next member's header will
521.1864 - # begin.
521.1865 - # 3. Return tarinfo or another valid TarInfo object.
521.1866 - def proc_member(self, tarinfo):
521.1867 - """Choose the right processing method for tarinfo depending
521.1868 - on its type and call it.
521.1869 - """
521.1870 - if tarinfo.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
521.1871 - return self.proc_gnulong(tarinfo)
521.1872 - elif tarinfo.type == GNUTYPE_SPARSE:
521.1873 - return self.proc_sparse(tarinfo)
521.1874 - else:
521.1875 - return self.proc_builtin(tarinfo)
521.1876 -
521.1877 - def proc_builtin(self, tarinfo):
521.1878 - """Process a builtin type member or an unknown member
521.1879 - which will be treated as a regular file.
521.1880 - """
521.1881 - tarinfo.offset_data = self.offset
521.1882 - if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES:
521.1883 - # Skip the following data blocks.
521.1884 - self.offset += self._block(tarinfo.size)
521.1885 - return tarinfo
521.1886 -
521.1887 - def proc_gnulong(self, tarinfo):
521.1888 - """Process the blocks that hold a GNU longname
521.1889 - or longlink member.
521.1890 - """
521.1891 - buf = ""
521.1892 - count = tarinfo.size
521.1893 - while count > 0:
521.1894 - block = self.fileobj.read(BLOCKSIZE)
521.1895 - buf += block
521.1896 - self.offset += BLOCKSIZE
521.1897 - count -= BLOCKSIZE
521.1898 -
521.1899 - # Fetch the next header and process it.
521.1900 - b = self.fileobj.read(BLOCKSIZE)
521.1901 - t = TarInfo.frombuf(b)
521.1902 - t.offset = self.offset
521.1903 - self.offset += BLOCKSIZE
521.1904 - next = self.proc_member(t)
521.1905 -
521.1906 - # Patch the TarInfo object from the next header with
521.1907 - # the longname information.
521.1908 - next.offset = tarinfo.offset
521.1909 - if tarinfo.type == GNUTYPE_LONGNAME:
521.1910 - next.name = buf.rstrip(NUL)
521.1911 - elif tarinfo.type == GNUTYPE_LONGLINK:
521.1912 - next.linkname = buf.rstrip(NUL)
521.1913 -
521.1914 - return next
521.1915 -
521.1916 - def proc_sparse(self, tarinfo):
521.1917 - """Process a GNU sparse header plus extra headers.
521.1918 - """
521.1919 - buf = tarinfo.buf
521.1920 - sp = _ringbuffer()
521.1921 - pos = 386
521.1922 - lastpos = 0L
521.1923 - realpos = 0L
521.1924 - # There are 4 possible sparse structs in the
521.1925 - # first header.
521.1926 - for i in xrange(4):
521.1927 - try:
521.1928 - offset = nti(buf[pos:pos + 12])
521.1929 - numbytes = nti(buf[pos + 12:pos + 24])
521.1930 - except ValueError:
521.1931 - break
521.1932 - if offset > lastpos:
521.1933 - sp.append(_hole(lastpos, offset - lastpos))
521.1934 - sp.append(_data(offset, numbytes, realpos))
521.1935 - realpos += numbytes
521.1936 - lastpos = offset + numbytes
521.1937 - pos += 24
521.1938 -
521.1939 - isextended = ord(buf[482])
521.1940 - origsize = nti(buf[483:495])
521.1941 -
521.1942 - # If the isextended flag is given,
521.1943 - # there are extra headers to process.
521.1944 - while isextended == 1:
521.1945 - buf = self.fileobj.read(BLOCKSIZE)
521.1946 - self.offset += BLOCKSIZE
521.1947 - pos = 0
521.1948 - for i in xrange(21):
521.1949 - try:
521.1950 - offset = nti(buf[pos:pos + 12])
521.1951 - numbytes = nti(buf[pos + 12:pos + 24])
521.1952 - except ValueError:
521.1953 - break
521.1954 - if offset > lastpos:
521.1955 - sp.append(_hole(lastpos, offset - lastpos))
521.1956 - sp.append(_data(offset, numbytes, realpos))
521.1957 - realpos += numbytes
521.1958 - lastpos = offset + numbytes
521.1959 - pos += 24
521.1960 - isextended = ord(buf[504])
521.1961 -
521.1962 - if lastpos < origsize:
521.1963 - sp.append(_hole(lastpos, origsize - lastpos))
521.1964 -
521.1965 - tarinfo.sparse = sp
521.1966 -
521.1967 - tarinfo.offset_data = self.offset
521.1968 - self.offset += self._block(tarinfo.size)
521.1969 - tarinfo.size = origsize
521.1970 -
521.1971 - return tarinfo
521.1972 -
521.1973 - #--------------------------------------------------------------------------
521.1974 - # Little helper methods:
521.1975 -
521.1976 - def _block(self, count):
521.1977 - """Round up a byte count by BLOCKSIZE and return it,
521.1978 - e.g. _block(834) => 1024.
521.1979 - """
521.1980 - blocks, remainder = divmod(count, BLOCKSIZE)
521.1981 - if remainder:
521.1982 - blocks += 1
521.1983 - return blocks * BLOCKSIZE
521.1984 -
521.1985 - def _getmember(self, name, tarinfo=None):
521.1986 - """Find an archive member by name from bottom to top.
521.1987 - If tarinfo is given, it is used as the starting point.
521.1988 - """
521.1989 - # Ensure that all members have been loaded.
521.1990 - members = self.getmembers()
521.1991 -
521.1992 - if tarinfo is None:
521.1993 - end = len(members)
521.1994 - else:
521.1995 - end = members.index(tarinfo)
521.1996 -
521.1997 - for i in xrange(end - 1, -1, -1):
521.1998 - if name == members[i].name:
521.1999 - return members[i]
521.2000 -
521.2001 - def _load(self):
521.2002 - """Read through the entire archive file and look for readable
521.2003 - members.
521.2004 - """
521.2005 - while True:
521.2006 - tarinfo = self.next()
521.2007 - if tarinfo is None:
521.2008 - break
521.2009 - self._loaded = True
521.2010 -
521.2011 - def _check(self, mode=None):
521.2012 - """Check if TarFile is still open, and if the operation's mode
521.2013 - corresponds to TarFile's mode.
521.2014 - """
521.2015 - if self.closed:
521.2016 - raise IOError("%s is closed" % self.__class__.__name__)
521.2017 - if mode is not None and self._mode not in mode:
521.2018 - raise IOError("bad operation for mode %r" % self._mode)
521.2019 -
521.2020 - def __iter__(self):
521.2021 - """Provide an iterator object.
521.2022 - """
521.2023 - if self._loaded:
521.2024 - return iter(self.members)
521.2025 - else:
521.2026 - return TarIter(self)
521.2027 -
521.2028 - def _dbg(self, level, msg):
521.2029 - """Write debugging output to sys.stderr.
521.2030 - """
521.2031 - if level <= self.debug:
521.2032 - print >> sys.stderr, msg
521.2033 -# class TarFile
521.2034 -
521.2035 -class TarIter:
521.2036 - """Iterator Class.
521.2037 -
521.2038 - for tarinfo in TarFile(...):
521.2039 - suite...
521.2040 - """
521.2041 -
521.2042 - def __init__(self, tarfile):
521.2043 - """Construct a TarIter object.
521.2044 - """
521.2045 - self.tarfile = tarfile
521.2046 - self.index = 0
521.2047 - def __iter__(self):
521.2048 - """Return iterator object.
521.2049 - """
521.2050 - return self
521.2051 - def next(self):
521.2052 - """Return the next item using TarFile's next() method.
521.2053 - When all members have been read, set TarFile as _loaded.
521.2054 - """
521.2055 - # Fix for SF #1100429: Under rare circumstances it can
521.2056 - # happen that getmembers() is called during iteration,
521.2057 - # which will cause TarIter to stop prematurely.
521.2058 - if not self.tarfile._loaded:
521.2059 - tarinfo = self.tarfile.next()
521.2060 - if not tarinfo:
521.2061 - self.tarfile._loaded = True
521.2062 - raise StopIteration
521.2063 - else:
521.2064 - try:
521.2065 - tarinfo = self.tarfile.members[self.index]
521.2066 - except IndexError:
521.2067 - raise StopIteration
521.2068 - self.index += 1
521.2069 - return tarinfo
521.2070 -
521.2071 -# Helper classes for sparse file support
521.2072 -class _section:
521.2073 - """Base class for _data and _hole.
521.2074 - """
521.2075 - def __init__(self, offset, size):
521.2076 - self.offset = offset
521.2077 - self.size = size
521.2078 - def __contains__(self, offset):
521.2079 - return self.offset <= offset < self.offset + self.size
521.2080 -
521.2081 -class _data(_section):
521.2082 - """Represent a data section in a sparse file.
521.2083 - """
521.2084 - def __init__(self, offset, size, realpos):
521.2085 - _section.__init__(self, offset, size)
521.2086 - self.realpos = realpos
521.2087 -
521.2088 -class _hole(_section):
521.2089 - """Represent a hole section in a sparse file.
521.2090 - """
521.2091 - pass
521.2092 -
521.2093 -class _ringbuffer(list):
521.2094 - """Ringbuffer class which increases performance
521.2095 - over a regular list.
521.2096 - """
521.2097 - def __init__(self):
521.2098 - self.idx = 0
521.2099 - def find(self, offset):
521.2100 - idx = self.idx
521.2101 - while True:
521.2102 - item = self[idx]
521.2103 - if offset in item:
521.2104 - break
521.2105 - idx += 1
521.2106 - if idx == len(self):
521.2107 - idx = 0
521.2108 - if idx == self.idx:
521.2109 - # End of File
521.2110 - return None
521.2111 - self.idx = idx
521.2112 - return item
521.2113 -
521.2114 -#---------------------------------------------
521.2115 -# zipfile compatible TarFile class
521.2116 -#---------------------------------------------
521.2117 -TAR_PLAIN = 0 # zipfile.ZIP_STORED
521.2118 -TAR_GZIPPED = 8 # zipfile.ZIP_DEFLATED
521.2119 -class TarFileCompat:
521.2120 - """TarFile class compatible with standard module zipfile's
521.2121 - ZipFile class.
521.2122 - """
521.2123 - def __init__(self, file, mode="r", compression=TAR_PLAIN):
521.2124 - if compression == TAR_PLAIN:
521.2125 - self.tarfile = TarFile.taropen(file, mode)
521.2126 - elif compression == TAR_GZIPPED:
521.2127 - self.tarfile = TarFile.gzopen(file, mode)
521.2128 - else:
521.2129 - raise ValueError("unknown compression constant")
521.2130 - if mode[0:1] == "r":
521.2131 - members = self.tarfile.getmembers()
521.2132 - for m in members:
521.2133 - m.filename = m.name
521.2134 - m.file_size = m.size
521.2135 - m.date_time = time.gmtime(m.mtime)[:6]
521.2136 - def namelist(self):
521.2137 - return map(lambda m: m.name, self.infolist())
521.2138 - def infolist(self):
521.2139 - return filter(lambda m: m.type in REGULAR_TYPES,
521.2140 - self.tarfile.getmembers())
521.2141 - def printdir(self):
521.2142 - self.tarfile.list()
521.2143 - def testzip(self):
521.2144 - return
521.2145 - def getinfo(self, name):
521.2146 - return self.tarfile.getmember(name)
521.2147 - def read(self, name):
521.2148 - return self.tarfile.extractfile(self.tarfile.getmember(name)).read()
521.2149 - def write(self, filename, arcname=None, compress_type=None):
521.2150 - self.tarfile.add(filename, arcname)
521.2151 - def writestr(self, zinfo, bytes):
521.2152 - try:
521.2153 - from cStringIO import StringIO
521.2154 - except ImportError:
521.2155 - from StringIO import StringIO
521.2156 - import calendar
521.2157 - zinfo.name = zinfo.filename
521.2158 - zinfo.size = zinfo.file_size
521.2159 - zinfo.mtime = calendar.timegm(zinfo.date_time)
521.2160 - self.tarfile.addfile(zinfo, StringIO(bytes))
521.2161 - def close(self):
521.2162 - self.tarfile.close()
521.2163 -#class TarFileCompat
521.2164 -
521.2165 -#--------------------
521.2166 -# exported functions
521.2167 -#--------------------
521.2168 -def is_tarfile(name):
521.2169 - """Return True if name points to a tar archive that we
521.2170 - are able to handle, else return False.
521.2171 - """
521.2172 - try:
521.2173 - t = open(name)
521.2174 - t.close()
521.2175 - return True
521.2176 - except TarError:
521.2177 - return False
521.2178 -
521.2179 -open = TarFile.open
522.1 --- a/python.editor/test/unit/data/testfiles/tarfile.py.indexed Sun Jan 04 13:11:53 2015 -0600
522.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
522.3 @@ -1,486 +0,0 @@
522.4 -
522.5 -
522.6 -Document 0
522.7 -Searchable Keys:
522.8 - class : CompressionError
522.9 - class-ig : compressionerror
522.10 - extends : TarError
522.11 - in : tarfile
522.12 -
522.13 -Not Searchable Keys:
522.14 - clzattrs : ;|PRIVATE|;
522.15 -
522.16 -
522.17 -Document 1
522.18 -Searchable Keys:
522.19 - class : ExFileObject
522.20 - class-ig : exfileobject
522.21 - extends : object
522.22 - in : tarfile
522.23 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,tarfile,tarinfo;
522.24 - member : __iter__;F;|PRIVATE|;self;
522.25 - member : blocksize;D;|PRIVATE|;
522.26 - member : buffer;D;;
522.27 - member : close;F;|PRIVATE|;self;
522.28 - member : closed;D;;
522.29 - member : fileobj;D;;
522.30 - member : mode;D;;
522.31 - member : name;D;;
522.32 - member : position;D;;
522.33 - member : read;F;|PRIVATE|;self,size;
522.34 - member : readline;F;|PRIVATE|;self,size;
522.35 - member : readlines;F;|PRIVATE|;self;
522.36 - member : seek;F;|PRIVATE|;self,pos,whence;
522.37 - member : size;D;;
522.38 - member : tell;F;|PRIVATE|;self;
522.39 -
522.40 -Not Searchable Keys:
522.41 - clzattrs : ;|PRIVATE|;
522.42 -
522.43 -
522.44 -Document 2
522.45 -Searchable Keys:
522.46 - class : ExtractError
522.47 - class-ig : extracterror
522.48 - extends : TarError
522.49 - in : tarfile
522.50 -
522.51 -Not Searchable Keys:
522.52 - clzattrs : ;|PRIVATE|;
522.53 -
522.54 -
522.55 -Document 3
522.56 -Searchable Keys:
522.57 - class : ReadError
522.58 - class-ig : readerror
522.59 - extends : TarError
522.60 - in : tarfile
522.61 -
522.62 -Not Searchable Keys:
522.63 - clzattrs : ;|PRIVATE|;
522.64 -
522.65 -
522.66 -Document 4
522.67 -Searchable Keys:
522.68 - class : StreamError
522.69 - class-ig : streamerror
522.70 - extends : TarError
522.71 - in : tarfile
522.72 -
522.73 -Not Searchable Keys:
522.74 - clzattrs : ;|PRIVATE|;
522.75 -
522.76 -
522.77 -Document 5
522.78 -Searchable Keys:
522.79 - class : TarError
522.80 - class-ig : tarerror
522.81 - extends : Exception
522.82 - in : tarfile
522.83 -
522.84 -Not Searchable Keys:
522.85 -
522.86 -
522.87 -Document 6
522.88 -Searchable Keys:
522.89 - class : TarFile
522.90 - class-ig : tarfile
522.91 - extends : object
522.92 - in : tarfile
522.93 - member : OPEN_METH;D;;
522.94 - member : __init__;c;|CONSTRUCTOR|;self,name,mode,fileobj;
522.95 - member : __iter__;F;;self;
522.96 - member : _block;F;|PRIVATE|;self,count;
522.97 - member : _check;F;|PRIVATE|;self,mode;
522.98 - member : _dbg;F;|PRIVATE|;self,level,msg;
522.99 - member : _extfileobj;D;|PRIVATE|;
522.100 - member : _extract_member;F;|PRIVATE|;self,tarinfo,targetpath;
522.101 - member : _getmember;F;|PRIVATE|;self,name,tarinfo;
522.102 - member : _load;F;|PRIVATE|;self;
522.103 - member : _loaded;D;|PRIVATE|;
522.104 - member : _mode;D;|PRIVATE|;
522.105 - member : add;F;;self,name,arcname,recursive;
522.106 - member : addfile;F;;self,tarinfo,fileobj;
522.107 - member : bz2open;c;|CONSTRUCTOR|STATIC|;cls,name,mode,fileobj,compresslevel;
522.108 - member : chmod;F;;self,tarinfo,targetpath;
522.109 - member : chown;F;;self,tarinfo,targetpath;
522.110 - member : close;F;;self;
522.111 - member : closed;D;;
522.112 - member : debug;D;;
522.113 - member : dereference;D;;
522.114 - member : errorlevel;D;;
522.115 - member : extract;F;;self,member,path;
522.116 - member : extractall;F;;self,path,members;
522.117 - member : extractfile;F;;self,member;
522.118 - member : fileobj;D;;
522.119 - member : fileobject;D;;
522.120 - member : firstmember;D;;
522.121 - member : getmember;F;;self,name;
522.122 - member : getmembers;F;;self;
522.123 - member : getnames;F;;self;
522.124 - member : gettarinfo;F;;self,name,arcname,fileobj;
522.125 - member : gzopen;c;|CONSTRUCTOR|STATIC|;cls,name,mode,fileobj,compresslevel;
522.126 - member : ignore_zeros;D;;
522.127 - member : inodes;D;;
522.128 - member : list;F;;self,verbose;
522.129 - member : makedev;F;;self,tarinfo,targetpath;
522.130 - member : makedir;F;;self,tarinfo,targetpath;
522.131 - member : makefifo;F;;self,tarinfo,targetpath;
522.132 - member : makefile;F;;self,tarinfo,targetpath;
522.133 - member : makelink;F;;self,tarinfo,targetpath;
522.134 - member : makeunknown;F;;self,tarinfo,targetpath;
522.135 - member : members;D;;
522.136 - member : mode;D;;
522.137 - member : name;D;;
522.138 - member : next;F;;self;
522.139 - member : offset;D;;
522.140 - member : open;c;|CONSTRUCTOR|STATIC|;cls,name,mode,fileobj,bufsize;
522.141 - member : posix;D;;
522.142 - member : proc_builtin;F;;self,tarinfo;
522.143 - member : proc_gnulong;F;;self,tarinfo;
522.144 - member : proc_member;F;;self,tarinfo;
522.145 - member : proc_sparse;F;;self,tarinfo;
522.146 - member : taropen;c;|CONSTRUCTOR|STATIC|;cls,name,mode,fileobj;
522.147 - member : utime;F;;self,tarinfo,targetpath;
522.148 -
522.149 -Not Searchable Keys:
522.150 -
522.151 -
522.152 -Document 7
522.153 -Searchable Keys:
522.154 - class : TarFileCompat
522.155 - class-ig : tarfilecompat
522.156 - in : tarfile
522.157 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,file,mode,compression;
522.158 - member : close;F;|PRIVATE|;self;
522.159 - member : getinfo;F;|PRIVATE|;self,name;
522.160 - member : infolist;F;|PRIVATE|;self;
522.161 - member : namelist;F;|PRIVATE|;self;
522.162 - member : printdir;F;|PRIVATE|;self;
522.163 - member : read;F;|PRIVATE|;self,name;
522.164 - member : tarfile;D;;
522.165 - member : testzip;F;|PRIVATE|;self;
522.166 - member : write;F;|PRIVATE|;self,filename,arcname,compress_type;
522.167 - member : writestr;F;|PRIVATE|;self,zinfo,bytes;
522.168 -
522.169 -Not Searchable Keys:
522.170 - clzattrs : ;|PRIVATE|;
522.171 -
522.172 -
522.173 -Document 8
522.174 -Searchable Keys:
522.175 - class : TarInfo
522.176 - class-ig : tarinfo
522.177 - extends : object
522.178 - in : tarfile
522.179 - member : __init__;c;|CONSTRUCTOR|;self,name;
522.180 - member : __repr__;F;;self;
522.181 - member : _create_gnulong;F;|PRIVATE|;self,name,type;
522.182 - member : buf;D;;
522.183 - member : chksum;D;;
522.184 - member : devmajor;D;;
522.185 - member : devminor;D;;
522.186 - member : frombuf;c;|CONSTRUCTOR|STATIC|;cls,buf;
522.187 - member : gid;D;;
522.188 - member : gname;D;;
522.189 - member : isblk;F;;self;
522.190 - member : ischr;F;;self;
522.191 - member : isdev;F;;self;
522.192 - member : isdir;F;;self;
522.193 - member : isfifo;F;;self;
522.194 - member : isfile;F;;self;
522.195 - member : islnk;F;;self;
522.196 - member : isreg;F;;self;
522.197 - member : issparse;F;;self;
522.198 - member : issym;F;;self;
522.199 - member : linkname;D;;
522.200 - member : mode;D;;
522.201 - member : mtime;D;;
522.202 - member : name;D;;
522.203 - member : offset;D;;
522.204 - member : offset_data;D;;
522.205 - member : size;D;;
522.206 - member : tobuf;F;;self,posix;
522.207 - member : type;D;;
522.208 - member : uid;D;;
522.209 - member : uname;D;;
522.210 -
522.211 -Not Searchable Keys:
522.212 -
522.213 -
522.214 -Document 9
522.215 -Searchable Keys:
522.216 - class : TarIter
522.217 - class-ig : tariter
522.218 - in : tarfile
522.219 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,tarfile;
522.220 - member : __iter__;F;|PRIVATE|;self;
522.221 - member : index;D;;
522.222 - member : next;F;|PRIVATE|;self;
522.223 - member : tarfile;D;;
522.224 -
522.225 -Not Searchable Keys:
522.226 - clzattrs : ;|PRIVATE|;
522.227 -
522.228 -
522.229 -Document 10
522.230 -Searchable Keys:
522.231 - class : _BZ2Proxy
522.232 - class-ig : _bz2proxy
522.233 - extends : object
522.234 - in : tarfile
522.235 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,fileobj,mode;
522.236 - member : blocksize;D;|PRIVATE|;
522.237 - member : buf;D;;
522.238 - member : bz2obj;D;;
522.239 - member : close;F;|PRIVATE|;self;
522.240 - member : fileobj;D;;
522.241 - member : init;F;|PRIVATE|;self;
522.242 - member : mode;D;;
522.243 - member : pos;D;;
522.244 - member : read;F;|PRIVATE|;self,size;
522.245 - member : seek;F;|PRIVATE|;self,pos;
522.246 - member : tell;F;|PRIVATE|;self;
522.247 - member : write;F;|PRIVATE|;self,data;
522.248 -
522.249 -Not Searchable Keys:
522.250 - clzattrs : ;|PRIVATE|;
522.251 -
522.252 -
522.253 -Document 11
522.254 -Searchable Keys:
522.255 - class : _FileInFile
522.256 - class-ig : _fileinfile
522.257 - extends : object
522.258 - in : tarfile
522.259 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,fileobj,offset,size,sparse;
522.260 - member : fileobj;D;;
522.261 - member : offset;D;;
522.262 - member : position;D;;
522.263 - member : read;F;|PRIVATE|;self,size;
522.264 - member : readnormal;F;|PRIVATE|;self,size;
522.265 - member : readsparse;F;|PRIVATE|;self,size;
522.266 - member : readsparsesection;F;|PRIVATE|;self,size;
522.267 - member : seek;F;|PRIVATE|;self,position;
522.268 - member : size;D;;
522.269 - member : sparse;D;;
522.270 - member : tell;F;|PRIVATE|;self;
522.271 -
522.272 -Not Searchable Keys:
522.273 - clzattrs : ;|PRIVATE|;
522.274 -
522.275 -
522.276 -Document 12
522.277 -Searchable Keys:
522.278 - class : _LowLevelFile
522.279 - class-ig : _lowlevelfile
522.280 - in : tarfile
522.281 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,name,mode;
522.282 - member : close;F;|PRIVATE|;self;
522.283 - member : fd;D;;
522.284 - member : read;F;|PRIVATE|;self,size;
522.285 - member : write;F;|PRIVATE|;self,s;
522.286 -
522.287 -Not Searchable Keys:
522.288 - clzattrs : ;|PRIVATE|;
522.289 -
522.290 -
522.291 -Document 13
522.292 -Searchable Keys:
522.293 - class : _Stream
522.294 - class-ig : _stream
522.295 - in : tarfile
522.296 - member : __del__;F;|PRIVATE|;self;
522.297 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,name,mode,comptype,fileobj,bufsize;
522.298 - member : __read;F;|PRIVATE|;self,size;
522.299 - member : __write;F;|PRIVATE|;self,s;
522.300 - member : _extfileobj;D;|PRIVATE|;
522.301 - member : _init_read_gz;F;|PRIVATE|;self;
522.302 - member : _init_write_gz;F;|PRIVATE|;self;
522.303 - member : _read;F;|PRIVATE|;self,size;
522.304 - member : buf;D;;
522.305 - member : bufsize;D;;
522.306 - member : close;F;|PRIVATE|;self;
522.307 - member : closed;D;;
522.308 - member : cmp;D;;
522.309 - member : comptype;D;;
522.310 - member : crc;D;;
522.311 - member : dbuf;D;;
522.312 - member : fileobj;D;;
522.313 - member : mode;D;;
522.314 - member : name;D;;
522.315 - member : pos;D;;
522.316 - member : read;F;|PRIVATE|;self,size;
522.317 - member : seek;F;|PRIVATE|;self,pos;
522.318 - member : tell;F;|PRIVATE|;self;
522.319 - member : write;F;|PRIVATE|;self,s;
522.320 - member : zlib;D;;
522.321 -
522.322 -Not Searchable Keys:
522.323 - clzattrs : ;|PRIVATE|;
522.324 -
522.325 -
522.326 -Document 14
522.327 -Searchable Keys:
522.328 - class : _StreamProxy
522.329 - class-ig : _streamproxy
522.330 - extends : object
522.331 - in : tarfile
522.332 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,fileobj;
522.333 - member : buf;D;;
522.334 - member : close;F;|PRIVATE|;self;
522.335 - member : fileobj;D;;
522.336 - member : getcomptype;F;|PRIVATE|;self;
522.337 - member : read;D;;
522.338 - member : read;F;|PRIVATE|;self,size;
522.339 -
522.340 -Not Searchable Keys:
522.341 - clzattrs : ;|PRIVATE|;
522.342 -
522.343 -
522.344 -Document 15
522.345 -Searchable Keys:
522.346 - class : _data
522.347 - class-ig : _data
522.348 - extends : _section
522.349 - in : tarfile
522.350 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,offset,size,realpos;
522.351 - member : realpos;D;;
522.352 -
522.353 -Not Searchable Keys:
522.354 - clzattrs : ;|PRIVATE|;
522.355 -
522.356 -
522.357 -Document 16
522.358 -Searchable Keys:
522.359 - class : _hole
522.360 - class-ig : _hole
522.361 - extends : _section
522.362 - in : tarfile
522.363 -
522.364 -Not Searchable Keys:
522.365 - clzattrs : ;|PRIVATE|;
522.366 -
522.367 -
522.368 -Document 17
522.369 -Searchable Keys:
522.370 - class : _ringbuffer
522.371 - class-ig : _ringbuffer
522.372 - extends : list
522.373 - in : tarfile
522.374 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self;
522.375 - member : find;F;|PRIVATE|;self,offset;
522.376 - member : idx;D;;
522.377 -
522.378 -Not Searchable Keys:
522.379 - clzattrs : ;|PRIVATE|;
522.380 -
522.381 -
522.382 -Document 18
522.383 -Searchable Keys:
522.384 - class : _section
522.385 - class-ig : _section
522.386 - in : tarfile
522.387 - member : __contains__;F;|PRIVATE|;self,offset;
522.388 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,offset,size;
522.389 - member : offset;D;;
522.390 - member : size;D;;
522.391 -
522.392 -Not Searchable Keys:
522.393 - clzattrs : ;|PRIVATE|;
522.394 -
522.395 -
522.396 -Document 19
522.397 -Searchable Keys:
522.398 - item : AREGTYPE;D;|PRIVATE|;
522.399 - item : BLKTYPE;D;|PRIVATE|;
522.400 - item : BLOCKSIZE;D;|PRIVATE|;
522.401 - item : CHRTYPE;D;|PRIVATE|;
522.402 - item : CONTTYPE;D;|PRIVATE|;
522.403 - item : CompressionError;C;|PRIVATE|;
522.404 - item : DIRTYPE;D;|PRIVATE|;
522.405 - item : ExFileObject;C;|PRIVATE|;
522.406 - item : ExtractError;C;|PRIVATE|;
522.407 - item : FIFOTYPE;D;|PRIVATE|;
522.408 - item : GNUTYPE_LONGLINK;D;|PRIVATE|;
522.409 - item : GNUTYPE_LONGNAME;D;|PRIVATE|;
522.410 - item : GNUTYPE_SPARSE;D;|PRIVATE|;
522.411 - item : LENGTH_LINK;D;|PRIVATE|;
522.412 - item : LENGTH_NAME;D;|PRIVATE|;
522.413 - item : LENGTH_PREFIX;D;|PRIVATE|;
522.414 - item : LNKTYPE;D;|PRIVATE|;
522.415 - item : MAGIC;D;|PRIVATE|;
522.416 - item : MAXSIZE_MEMBER;D;|PRIVATE|;
522.417 - item : NUL;D;|PRIVATE|;
522.418 - item : RECORDSIZE;D;|PRIVATE|;
522.419 - item : REGTYPE;D;|PRIVATE|;
522.420 - item : REGULAR_TYPES;D;|PRIVATE|;
522.421 - item : ReadError;C;|PRIVATE|;
522.422 - item : SUPPORTED_TYPES;D;|PRIVATE|;
522.423 - item : SYMTYPE;D;|PRIVATE|;
522.424 - item : S_IFBLK;D;|PRIVATE|;
522.425 - item : S_IFCHR;D;|PRIVATE|;
522.426 - item : S_IFDIR;D;|PRIVATE|;
522.427 - item : S_IFIFO;D;|PRIVATE|;
522.428 - item : S_IFLNK;D;|PRIVATE|;
522.429 - item : S_IFREG;D;|PRIVATE|;
522.430 - item : StreamError;C;|PRIVATE|;
522.431 - item : TAR_GZIPPED;D;|PRIVATE|;
522.432 - item : TAR_PLAIN;D;|PRIVATE|;
522.433 - item : TGEXEC;D;|PRIVATE|;
522.434 - item : TGREAD;D;|PRIVATE|;
522.435 - item : TGWRITE;D;|PRIVATE|;
522.436 - item : TOEXEC;D;|PRIVATE|;
522.437 - item : TOREAD;D;|PRIVATE|;
522.438 - item : TOWRITE;D;|PRIVATE|;
522.439 - item : TSGID;D;|PRIVATE|;
522.440 - item : TSUID;D;|PRIVATE|;
522.441 - item : TSVTX;D;|PRIVATE|;
522.442 - item : TUEXEC;D;|PRIVATE|;
522.443 - item : TUREAD;D;|PRIVATE|;
522.444 - item : TUWRITE;D;|PRIVATE|;
522.445 - item : TarError;C;;
522.446 - item : TarFile;C;;
522.447 - item : TarFileCompat;C;|PRIVATE|;
522.448 - item : TarInfo;C;;
522.449 - item : TarIter;C;|PRIVATE|;
522.450 - item : VERSION;D;|PRIVATE|;
522.451 - item : _BZ2Proxy;C;|PRIVATE|;
522.452 - item : _FileInFile;C;|PRIVATE|;
522.453 - item : _LowLevelFile;C;|PRIVATE|;
522.454 - item : _Stream;C;|PRIVATE|;
522.455 - item : _StreamProxy;C;|PRIVATE|;
522.456 - item : __all__;D;;
522.457 - item : __author__;D;|PRIVATE|;
522.458 - item : __credits__;D;|PRIVATE|;
522.459 - item : __cvsid__;D;|PRIVATE|;
522.460 - item : __date__;D;|PRIVATE|;
522.461 - item : __version__;D;|PRIVATE|;
522.462 - item : _data;C;|PRIVATE|;
522.463 - item : _hole;C;|PRIVATE|;
522.464 - item : _ringbuffer;C;|PRIVATE|;
522.465 - item : _section;C;|PRIVATE|;
522.466 - item : calc_chksums;F;|PRIVATE|;buf;
522.467 - item : copy;I;|PRIVATE|;
522.468 - item : copyfileobj;F;|PRIVATE|;src,dst,length;
522.469 - item : errno;I;|PRIVATE|;
522.470 - item : filemode;F;|PRIVATE|;mode;
522.471 - item : filemode_table;D;|PRIVATE|;
522.472 - item : grp;I;|PRIVATE|;
522.473 - item : is_tarfile;F;;name;
522.474 - item : itn;F;|PRIVATE|;n,digits,posix;
522.475 - item : normpath;D;|PRIVATE|;
522.476 - item : nti;F;|PRIVATE|;s;
522.477 - item : open;D;|PRIVATE|;
522.478 - item : os;I;|PRIVATE|;
522.479 - item : pwd;I;|PRIVATE|;
522.480 - item : shutil;I;|PRIVATE|;
522.481 - item : stat;I;|PRIVATE|;
522.482 - item : stn;F;|PRIVATE|;s,length;
522.483 - item : struct;I;|PRIVATE|;
522.484 - item : sys;I;|PRIVATE|;
522.485 - item : time;I;|PRIVATE|;
522.486 - item : version;D;|PRIVATE|;
522.487 - module : tarfile
522.488 -
522.489 -Not Searchable Keys:
523.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py Sun Jan 04 13:11:53 2015 -0600
523.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
523.3 @@ -1,530 +0,0 @@
523.4 -from test_support import verify, TestFailed, check_syntax
523.5 -
523.6 -import warnings
523.7 -warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>")
523.8 -
523.9 -print "1. simple nesting"
523.10 -
523.11 -def make_adder(x):
523.12 - def adder(y):
523.13 - return x + y
523.14 - return adder
523.15 -
523.16 -inc = make_adder(1)
523.17 -plus10 = make_adder(10)
523.18 -
523.19 -verify(inc(1) == 2)
523.20 -verify(plus10(-2) == 8)
523.21 -
523.22 -print "2. extra nesting"
523.23 -
523.24 -def make_adder2(x):
523.25 - def extra(): # check freevars passing through non-use scopes
523.26 - def adder(y):
523.27 - return x + y
523.28 - return adder
523.29 - return extra()
523.30 -
523.31 -inc = make_adder2(1)
523.32 -plus10 = make_adder2(10)
523.33 -
523.34 -verify(inc(1) == 2)
523.35 -verify(plus10(-2) == 8)
523.36 -
523.37 -print "3. simple nesting + rebinding"
523.38 -
523.39 -def make_adder3(x):
523.40 - def adder(y):
523.41 - return x + y
523.42 - x = x + 1 # check tracking of assignment to x in defining scope
523.43 - return adder
523.44 -
523.45 -inc = make_adder3(0)
523.46 -plus10 = make_adder3(9)
523.47 -
523.48 -verify(inc(1) == 2)
523.49 -verify(plus10(-2) == 8)
523.50 -
523.51 -print "4. nesting with global but no free"
523.52 -
523.53 -def make_adder4(): # XXX add exta level of indirection
523.54 - def nest():
523.55 - def nest():
523.56 - def adder(y):
523.57 - return global_x + y # check that plain old globals work
523.58 - return adder
523.59 - return nest()
523.60 - return nest()
523.61 -
523.62 -global_x = 1
523.63 -adder = make_adder4()
523.64 -verify(adder(1) == 2)
523.65 -
523.66 -global_x = 10
523.67 -verify(adder(-2) == 8)
523.68 -
523.69 -print "5. nesting through class"
523.70 -
523.71 -def make_adder5(x):
523.72 - class Adder:
523.73 - def __call__(self, y):
523.74 - return x + y
523.75 - return Adder()
523.76 -
523.77 -inc = make_adder5(1)
523.78 -plus10 = make_adder5(10)
523.79 -
523.80 -verify(inc(1) == 2)
523.81 -verify(plus10(-2) == 8)
523.82 -
523.83 -print "6. nesting plus free ref to global"
523.84 -
523.85 -def make_adder6(x):
523.86 - global global_nest_x
523.87 - def adder(y):
523.88 - return global_nest_x + y
523.89 - global_nest_x = x
523.90 - return adder
523.91 -
523.92 -inc = make_adder6(1)
523.93 -plus10 = make_adder6(10)
523.94 -
523.95 -verify(inc(1) == 11) # there's only one global
523.96 -verify(plus10(-2) == 8)
523.97 -
523.98 -print "7. nearest enclosing scope"
523.99 -
523.100 -def f(x):
523.101 - def g(y):
523.102 - x = 42 # check that this masks binding in f()
523.103 - def h(z):
523.104 - return x + z
523.105 - return h
523.106 - return g(2)
523.107 -
523.108 -test_func = f(10)
523.109 -verify(test_func(5) == 47)
523.110 -
523.111 -print "8. mixed freevars and cellvars"
523.112 -
523.113 -def identity(x):
523.114 - return x
523.115 -
523.116 -def f(x, y, z):
523.117 - def g(a, b, c):
523.118 - a = a + x # 3
523.119 - def h():
523.120 - # z * (4 + 9)
523.121 - # 3 * 13
523.122 - return identity(z * (b + y))
523.123 - y = c + z # 9
523.124 - return h
523.125 - return g
523.126 -
523.127 -g = f(1, 2, 3)
523.128 -h = g(2, 4, 6)
523.129 -verify(h() == 39)
523.130 -
523.131 -print "9. free variable in method"
523.132 -
523.133 -def test():
523.134 - method_and_var = "var"
523.135 - class Test:
523.136 - def method_and_var(self):
523.137 - return "method"
523.138 - def test(self):
523.139 - return method_and_var
523.140 - def actual_global(self):
523.141 - return str("global")
523.142 - def str(self):
523.143 - return str(self)
523.144 - return Test()
523.145 -
523.146 -t = test()
523.147 -verify(t.test() == "var")
523.148 -verify(t.method_and_var() == "method")
523.149 -verify(t.actual_global() == "global")
523.150 -
523.151 -method_and_var = "var"
523.152 -class Test:
523.153 - # this class is not nested, so the rules are different
523.154 - def method_and_var(self):
523.155 - return "method"
523.156 - def test(self):
523.157 - return method_and_var
523.158 - def actual_global(self):
523.159 - return str("global")
523.160 - def str(self):
523.161 - return str(self)
523.162 -
523.163 -t = Test()
523.164 -verify(t.test() == "var")
523.165 -verify(t.method_and_var() == "method")
523.166 -verify(t.actual_global() == "global")
523.167 -
523.168 -print "10. recursion"
523.169 -
523.170 -def f(x):
523.171 - def fact(n):
523.172 - if n == 0:
523.173 - return 1
523.174 - else:
523.175 - return n * fact(n - 1)
523.176 - if x >= 0:
523.177 - return fact(x)
523.178 - else:
523.179 - raise ValueError, "x must be >= 0"
523.180 -
523.181 -verify(f(6) == 720)
523.182 -
523.183 -
523.184 -print "11. unoptimized namespaces"
523.185 -
523.186 -check_syntax("""\
523.187 -def unoptimized_clash1(strip):
523.188 - def f(s):
523.189 - from string import *
523.190 - return strip(s) # ambiguity: free or local
523.191 - return f
523.192 -""")
523.193 -
523.194 -check_syntax("""\
523.195 -def unoptimized_clash2():
523.196 - from string import *
523.197 - def f(s):
523.198 - return strip(s) # ambiguity: global or local
523.199 - return f
523.200 -""")
523.201 -
523.202 -check_syntax("""\
523.203 -def unoptimized_clash2():
523.204 - from string import *
523.205 - def g():
523.206 - def f(s):
523.207 - return strip(s) # ambiguity: global or local
523.208 - return f
523.209 -""")
523.210 -
523.211 -# XXX could allow this for exec with const argument, but what's the point
523.212 -check_syntax("""\
523.213 -def error(y):
523.214 - exec "a = 1"
523.215 - def f(x):
523.216 - return x + y
523.217 - return f
523.218 -""")
523.219 -
523.220 -check_syntax("""\
523.221 -def f(x):
523.222 - def g():
523.223 - return x
523.224 - del x # can't del name
523.225 -""")
523.226 -
523.227 -check_syntax("""\
523.228 -def f():
523.229 - def g():
523.230 - from string import *
523.231 - return strip # global or local?
523.232 -""")
523.233 -
523.234 -# and verify a few cases that should work
523.235 -
523.236 -exec """
523.237 -def noproblem1():
523.238 - from string import *
523.239 - f = lambda x:x
523.240 -
523.241 -def noproblem2():
523.242 - from string import *
523.243 - def f(x):
523.244 - return x + 1
523.245 -
523.246 -def noproblem3():
523.247 - from string import *
523.248 - def f(x):
523.249 - global y
523.250 - y = x
523.251 -"""
523.252 -
523.253 -print "12. lambdas"
523.254 -
523.255 -f1 = lambda x: lambda y: x + y
523.256 -inc = f1(1)
523.257 -plus10 = f1(10)
523.258 -verify(inc(1) == 2)
523.259 -verify(plus10(5) == 15)
523.260 -
523.261 -f2 = lambda x: (lambda : lambda y: x + y)()
523.262 -inc = f2(1)
523.263 -plus10 = f2(10)
523.264 -verify(inc(1) == 2)
523.265 -verify(plus10(5) == 15)
523.266 -
523.267 -f3 = lambda x: lambda y: global_x + y
523.268 -global_x = 1
523.269 -inc = f3(None)
523.270 -verify(inc(2) == 3)
523.271 -
523.272 -f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y)
523.273 -g = f8(1, 2, 3)
523.274 -h = g(2, 4, 6)
523.275 -verify(h() == 18)
523.276 -
523.277 -print "13. UnboundLocal"
523.278 -
523.279 -def errorInOuter():
523.280 - print y
523.281 - def inner():
523.282 - return y
523.283 - y = 1
523.284 -
523.285 -def errorInInner():
523.286 - def inner():
523.287 - return y
523.288 - inner()
523.289 - y = 1
523.290 -
523.291 -try:
523.292 - errorInOuter()
523.293 -except UnboundLocalError:
523.294 - pass
523.295 -else:
523.296 - raise TestFailed
523.297 -
523.298 -try:
523.299 - errorInInner()
523.300 -except NameError:
523.301 - pass
523.302 -else:
523.303 - raise TestFailed
523.304 -
523.305 -print "14. complex definitions"
523.306 -
523.307 -def makeReturner(*lst):
523.308 - def returner():
523.309 - return lst
523.310 - return returner
523.311 -
523.312 -verify(makeReturner(1,2,3)() == (1,2,3))
523.313 -
523.314 -def makeReturner2(**kwargs):
523.315 - def returner():
523.316 - return kwargs
523.317 - return returner
523.318 -
523.319 -verify(makeReturner2(a=11)()['a'] == 11)
523.320 -
523.321 -def makeAddPair((a, b)):
523.322 - def addPair((c, d)):
523.323 - return (a + c, b + d)
523.324 - return addPair
523.325 -
523.326 -verify(makeAddPair((1, 2))((100, 200)) == (101,202))
523.327 -
523.328 -print "15. scope of global statements"
523.329 -# Examples posted by Samuele Pedroni to python-dev on 3/1/2001
523.330 -
523.331 -# I
523.332 -x = 7
523.333 -def f():
523.334 - x = 1
523.335 - def g():
523.336 - global x
523.337 - def i():
523.338 - def h():
523.339 - return x
523.340 - return h()
523.341 - return i()
523.342 - return g()
523.343 -verify(f() == 7)
523.344 -verify(x == 7)
523.345 -
523.346 -# II
523.347 -x = 7
523.348 -def f():
523.349 - x = 1
523.350 - def g():
523.351 - x = 2
523.352 - def i():
523.353 - def h():
523.354 - return x
523.355 - return h()
523.356 - return i()
523.357 - return g()
523.358 -verify(f() == 2)
523.359 -verify(x == 7)
523.360 -
523.361 -# III
523.362 -x = 7
523.363 -def f():
523.364 - x = 1
523.365 - def g():
523.366 - global x
523.367 - x = 2
523.368 - def i():
523.369 - def h():
523.370 - return x
523.371 - return h()
523.372 - return i()
523.373 - return g()
523.374 -verify(f() == 2)
523.375 -verify(x == 2)
523.376 -
523.377 -# IV
523.378 -x = 7
523.379 -def f():
523.380 - x = 3
523.381 - def g():
523.382 - global x
523.383 - x = 2
523.384 - def i():
523.385 - def h():
523.386 - return x
523.387 - return h()
523.388 - return i()
523.389 - return g()
523.390 -verify(f() == 2)
523.391 -verify(x == 2)
523.392 -
523.393 -print "16. check leaks"
523.394 -
523.395 -class Foo:
523.396 - count = 0
523.397 -
523.398 - def __init__(self):
523.399 - Foo.count += 1
523.400 -
523.401 - def __del__(self):
523.402 - Foo.count -= 1
523.403 -
523.404 -def f1():
523.405 - x = Foo()
523.406 - def f2():
523.407 - return x
523.408 - f2()
523.409 -
523.410 -for i in range(100):
523.411 - f1()
523.412 -
523.413 -import os
523.414 -if os.name == 'java':
523.415 - from java.lang import System, Thread
523.416 - System.gc()
523.417 - Thread.sleep(100)
523.418 - System.gc()
523.419 -verify(Foo.count == 0)
523.420 -
523.421 -print "17. class and global"
523.422 -
523.423 -def test(x):
523.424 - class Foo:
523.425 - global x
523.426 - def __call__(self, y):
523.427 - return x + y
523.428 - return Foo()
523.429 -
523.430 -x = 0
523.431 -verify(test(6)(2) == 8)
523.432 -x = -1
523.433 -verify(test(3)(2) == 5)
523.434 -
523.435 -print "18. verify that locals() works"
523.436 -
523.437 -def f(x):
523.438 - def g(y):
523.439 - def h(z):
523.440 - return y + z
523.441 - w = x + y
523.442 - y += 3
523.443 - return locals()
523.444 - return g
523.445 -
523.446 -d = f(2)(4)
523.447 -verify(d.has_key('h'))
523.448 -del d['h']
523.449 -verify(d == {'x': 2, 'y': 7, 'w': 6})
523.450 -
523.451 -print "19. var is bound and free in class"
523.452 -
523.453 -def f(x):
523.454 - class C:
523.455 - def m(self):
523.456 - return x
523.457 - a = x
523.458 - return C
523.459 -
523.460 -inst = f(3)()
523.461 -verify(inst.a == inst.m())
523.462 -
523.463 -print "20. interaction with trace function"
523.464 -
523.465 -import sys
523.466 -def tracer(a,b,c):
523.467 - return tracer
523.468 -
523.469 -def adaptgetter(name, klass, getter):
523.470 - kind, des = getter
523.471 - if kind == 1: # AV happens when stepping from this line to next
523.472 - if des == "":
523.473 - des = "_%s__%s" % (klass.__name__, name)
523.474 - return lambda obj: getattr(obj, des)
523.475 -
523.476 -class TestClass:
523.477 - pass
523.478 -
523.479 -sys.settrace(tracer)
523.480 -adaptgetter("foo", TestClass, (1, ""))
523.481 -sys.settrace(None)
523.482 -
523.483 -try: sys.settrace()
523.484 -except TypeError: pass
523.485 -else: raise TestFailed, 'sys.settrace() did not raise TypeError'
523.486 -
523.487 -print "20. eval and exec with free variables"
523.488 -
523.489 -def f(x):
523.490 - return lambda: x + 1
523.491 -
523.492 -g = f(3)
523.493 -try:
523.494 - eval(g.func_code)
523.495 -except TypeError:
523.496 - pass
523.497 -else:
523.498 - print "eval() should have failed, because code contained free vars"
523.499 -
523.500 -try:
523.501 - exec g.func_code
523.502 -except TypeError:
523.503 - pass
523.504 -else:
523.505 - print "exec should have failed, because code contained free vars"
523.506 -
523.507 -print "21. list comprehension with local variables"
523.508 -
523.509 -try:
523.510 - print bad
523.511 -except NameError:
523.512 - pass
523.513 -else:
523.514 - print "bad should not be defined"
523.515 -
523.516 -def x():
523.517 - [bad for s in 'a b' for bad in s.split()]
523.518 -
523.519 -x()
523.520 -try:
523.521 - print bad
523.522 -except NameError:
523.523 - pass
523.524 -
523.525 -print "22. eval with free variables"
523.526 -
523.527 -def f(x):
523.528 - def g():
523.529 - x
523.530 - eval("x + 1")
523.531 - return g
523.532 -
523.533 -f(4)()
524.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.folds Sun Jan 04 13:11:53 2015 -0600
524.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
524.3 @@ -1,531 +0,0 @@
524.4 - from test_support import verify, TestFailed, check_syntax
524.5 -
524.6 - import warnings
524.7 - warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>")
524.8 -
524.9 - print "1. simple nesting"
524.10 -
524.11 -+ def make_adder(x):
524.12 -+ def adder(y):
524.13 -- return x + y
524.14 -| return adder
524.15 --
524.16 - inc = make_adder(1)
524.17 - plus10 = make_adder(10)
524.18 -
524.19 - verify(inc(1) == 2)
524.20 - verify(plus10(-2) == 8)
524.21 -
524.22 - print "2. extra nesting"
524.23 -
524.24 -+ def make_adder2(x):
524.25 -+ def extra(): # check freevars passing through non-use scopes
524.26 -+ def adder(y):
524.27 -- return x + y
524.28 -- return adder
524.29 -| return extra()
524.30 --
524.31 - inc = make_adder2(1)
524.32 - plus10 = make_adder2(10)
524.33 -
524.34 - verify(inc(1) == 2)
524.35 - verify(plus10(-2) == 8)
524.36 -
524.37 - print "3. simple nesting + rebinding"
524.38 -
524.39 -+ def make_adder3(x):
524.40 -+ def adder(y):
524.41 -- return x + y
524.42 -| x = x + 1 # check tracking of assignment to x in defining scope
524.43 -| return adder
524.44 --
524.45 - inc = make_adder3(0)
524.46 - plus10 = make_adder3(9)
524.47 -
524.48 - verify(inc(1) == 2)
524.49 - verify(plus10(-2) == 8)
524.50 -
524.51 - print "4. nesting with global but no free"
524.52 -
524.53 -+ def make_adder4(): # XXX add exta level of indirection
524.54 -+ def nest():
524.55 -+ def nest():
524.56 -+ def adder(y):
524.57 -- return global_x + y # check that plain old globals work
524.58 -- return adder
524.59 -- return nest()
524.60 -| return nest()
524.61 --
524.62 - global_x = 1
524.63 - adder = make_adder4()
524.64 - verify(adder(1) == 2)
524.65 -
524.66 - global_x = 10
524.67 - verify(adder(-2) == 8)
524.68 -
524.69 - print "5. nesting through class"
524.70 -
524.71 -+ def make_adder5(x):
524.72 -+ class Adder:
524.73 -+ def __call__(self, y):
524.74 -- return x + y
524.75 -| return Adder()
524.76 --
524.77 - inc = make_adder5(1)
524.78 - plus10 = make_adder5(10)
524.79 -
524.80 - verify(inc(1) == 2)
524.81 - verify(plus10(-2) == 8)
524.82 -
524.83 - print "6. nesting plus free ref to global"
524.84 -
524.85 -+ def make_adder6(x):
524.86 -| global global_nest_x
524.87 -+ def adder(y):
524.88 -- return global_nest_x + y
524.89 -| global_nest_x = x
524.90 -| return adder
524.91 --
524.92 - inc = make_adder6(1)
524.93 - plus10 = make_adder6(10)
524.94 -
524.95 - verify(inc(1) == 11) # there's only one global
524.96 - verify(plus10(-2) == 8)
524.97 -
524.98 - print "7. nearest enclosing scope"
524.99 -
524.100 -+ def f(x):
524.101 -+ def g(y):
524.102 -| x = 42 # check that this masks binding in f()
524.103 -+ def h(z):
524.104 -- return x + z
524.105 -- return h
524.106 -| return g(2)
524.107 --
524.108 - test_func = f(10)
524.109 - verify(test_func(5) == 47)
524.110 -
524.111 - print "8. mixed freevars and cellvars"
524.112 -
524.113 -+ def identity(x):
524.114 -| return x
524.115 --
524.116 -+ def f(x, y, z):
524.117 -+ def g(a, b, c):
524.118 -| a = a + x # 3
524.119 -+ def h():
524.120 -| # z * (4 + 9)
524.121 -| # 3 * 13
524.122 -- return identity(z * (b + y))
524.123 -| y = c + z # 9
524.124 -- return h
524.125 -| return g
524.126 --
524.127 - g = f(1, 2, 3)
524.128 - h = g(2, 4, 6)
524.129 - verify(h() == 39)
524.130 -
524.131 - print "9. free variable in method"
524.132 -
524.133 -+ def test():
524.134 -| method_and_var = "var"
524.135 -+ class Test:
524.136 -+ def method_and_var(self):
524.137 -- return "method"
524.138 -+ def test(self):
524.139 -- return method_and_var
524.140 -+ def actual_global(self):
524.141 -- return str("global")
524.142 -+ def str(self):
524.143 -- return str(self)
524.144 -| return Test()
524.145 --
524.146 - t = test()
524.147 - verify(t.test() == "var")
524.148 - verify(t.method_and_var() == "method")
524.149 - verify(t.actual_global() == "global")
524.150 -
524.151 - method_and_var = "var"
524.152 -+ class Test:
524.153 -| # this class is not nested, so the rules are different
524.154 -+ def method_and_var(self):
524.155 -- return "method"
524.156 -+ def test(self):
524.157 -- return method_and_var
524.158 -+ def actual_global(self):
524.159 -- return str("global")
524.160 -+ def str(self):
524.161 -| return str(self)
524.162 --
524.163 - t = Test()
524.164 - verify(t.test() == "var")
524.165 - verify(t.method_and_var() == "method")
524.166 - verify(t.actual_global() == "global")
524.167 -
524.168 - print "10. recursion"
524.169 -
524.170 -+ def f(x):
524.171 -+ def fact(n):
524.172 -| if n == 0:
524.173 -| return 1
524.174 -| else:
524.175 -- return n * fact(n - 1)
524.176 -| if x >= 0:
524.177 -| return fact(x)
524.178 -| else:
524.179 -| raise ValueError, "x must be >= 0"
524.180 --
524.181 - verify(f(6) == 720)
524.182 -
524.183 -
524.184 - print "11. unoptimized namespaces"
524.185 -
524.186 -+ check_syntax("""\
524.187 -| def unoptimized_clash1(strip):
524.188 -| def f(s):
524.189 -| from string import *
524.190 -| return strip(s) # ambiguity: free or local
524.191 -- return f
524.192 - """)
524.193 -
524.194 -+ check_syntax("""\
524.195 -| def unoptimized_clash2():
524.196 -| from string import *
524.197 -| def f(s):
524.198 -| return strip(s) # ambiguity: global or local
524.199 -- return f
524.200 - """)
524.201 -
524.202 -+ check_syntax("""\
524.203 -| def unoptimized_clash2():
524.204 -| from string import *
524.205 -| def g():
524.206 -| def f(s):
524.207 -| return strip(s) # ambiguity: global or local
524.208 -- return f
524.209 - """)
524.210 -
524.211 - # XXX could allow this for exec with const argument, but what's the point
524.212 -+ check_syntax("""\
524.213 -| def error(y):
524.214 -| exec "a = 1"
524.215 -| def f(x):
524.216 -| return x + y
524.217 -- return f
524.218 - """)
524.219 -
524.220 -+ check_syntax("""\
524.221 -| def f(x):
524.222 -| def g():
524.223 -| return x
524.224 -- del x # can't del name
524.225 - """)
524.226 -
524.227 -+ check_syntax("""\
524.228 -| def f():
524.229 -| def g():
524.230 -| from string import *
524.231 -- return strip # global or local?
524.232 - """)
524.233 -
524.234 - # and verify a few cases that should work
524.235 -
524.236 -+ exec """
524.237 -| def noproblem1():
524.238 -| from string import *
524.239 -| f = lambda x:x
524.240 -|
524.241 -| def noproblem2():
524.242 -| from string import *
524.243 -| def f(x):
524.244 -| return x + 1
524.245 -|
524.246 -| def noproblem3():
524.247 -| from string import *
524.248 -| def f(x):
524.249 -| global y
524.250 -| y = x
524.251 -- """
524.252 -
524.253 - print "12. lambdas"
524.254 -
524.255 - f1 = lambda x: lambda y: x + y
524.256 - inc = f1(1)
524.257 - plus10 = f1(10)
524.258 - verify(inc(1) == 2)
524.259 - verify(plus10(5) == 15)
524.260 -
524.261 - f2 = lambda x: (lambda : lambda y: x + y)()
524.262 - inc = f2(1)
524.263 - plus10 = f2(10)
524.264 - verify(inc(1) == 2)
524.265 - verify(plus10(5) == 15)
524.266 -
524.267 - f3 = lambda x: lambda y: global_x + y
524.268 - global_x = 1
524.269 - inc = f3(None)
524.270 - verify(inc(2) == 3)
524.271 -
524.272 - f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y)
524.273 - g = f8(1, 2, 3)
524.274 - h = g(2, 4, 6)
524.275 - verify(h() == 18)
524.276 -
524.277 - print "13. UnboundLocal"
524.278 -
524.279 -+ def errorInOuter():
524.280 -| print y
524.281 -+ def inner():
524.282 -- return y
524.283 -| y = 1
524.284 --
524.285 -+ def errorInInner():
524.286 -+ def inner():
524.287 -- return y
524.288 -| inner()
524.289 -| y = 1
524.290 --
524.291 - try:
524.292 - errorInOuter()
524.293 - except UnboundLocalError:
524.294 - pass
524.295 - else:
524.296 - raise TestFailed
524.297 -
524.298 - try:
524.299 - errorInInner()
524.300 - except NameError:
524.301 - pass
524.302 - else:
524.303 - raise TestFailed
524.304 -
524.305 - print "14. complex definitions"
524.306 -
524.307 -+ def makeReturner(*lst):
524.308 -+ def returner():
524.309 -- return lst
524.310 -| return returner
524.311 --
524.312 - verify(makeReturner(1,2,3)() == (1,2,3))
524.313 -
524.314 -+ def makeReturner2(**kwargs):
524.315 -+ def returner():
524.316 -- return kwargs
524.317 -| return returner
524.318 --
524.319 - verify(makeReturner2(a=11)()['a'] == 11)
524.320 -
524.321 -+ def makeAddPair((a, b)):
524.322 -+ def addPair((c, d)):
524.323 -- return (a + c, b + d)
524.324 -| return addPair
524.325 --
524.326 - verify(makeAddPair((1, 2))((100, 200)) == (101,202))
524.327 -
524.328 - print "15. scope of global statements"
524.329 - # Examples posted by Samuele Pedroni to python-dev on 3/1/2001
524.330 -
524.331 - # I
524.332 - x = 7
524.333 -+ def f():
524.334 -| x = 1
524.335 -+ def g():
524.336 -| global x
524.337 -+ def i():
524.338 -+ def h():
524.339 -- return x
524.340 -- return h()
524.341 -- return i()
524.342 -- return g()
524.343 - verify(f() == 7)
524.344 - verify(x == 7)
524.345 -
524.346 - # II
524.347 - x = 7
524.348 -+ def f():
524.349 -| x = 1
524.350 -+ def g():
524.351 -| x = 2
524.352 -+ def i():
524.353 -+ def h():
524.354 -- return x
524.355 -- return h()
524.356 -- return i()
524.357 -- return g()
524.358 - verify(f() == 2)
524.359 - verify(x == 7)
524.360 -
524.361 - # III
524.362 - x = 7
524.363 -+ def f():
524.364 -| x = 1
524.365 -+ def g():
524.366 -| global x
524.367 -| x = 2
524.368 -+ def i():
524.369 -+ def h():
524.370 -- return x
524.371 -- return h()
524.372 -- return i()
524.373 -- return g()
524.374 - verify(f() == 2)
524.375 - verify(x == 2)
524.376 -
524.377 - # IV
524.378 - x = 7
524.379 -+ def f():
524.380 -| x = 3
524.381 -+ def g():
524.382 -| global x
524.383 -| x = 2
524.384 -+ def i():
524.385 -+ def h():
524.386 -- return x
524.387 -- return h()
524.388 -- return i()
524.389 -- return g()
524.390 - verify(f() == 2)
524.391 - verify(x == 2)
524.392 -
524.393 - print "16. check leaks"
524.394 -
524.395 -+ class Foo:
524.396 -| count = 0
524.397 -|
524.398 -+ def __init__(self):
524.399 -| Foo.count += 1
524.400 --
524.401 -+ def __del__(self):
524.402 -| Foo.count -= 1
524.403 --
524.404 -+ def f1():
524.405 -| x = Foo()
524.406 -+ def f2():
524.407 -- return x
524.408 -| f2()
524.409 --
524.410 - for i in range(100):
524.411 - f1()
524.412 -
524.413 - import os
524.414 - if os.name == 'java':
524.415 - from java.lang import System, Thread
524.416 - System.gc()
524.417 - Thread.sleep(100)
524.418 - System.gc()
524.419 - verify(Foo.count == 0)
524.420 -
524.421 - print "17. class and global"
524.422 -
524.423 -+ def test(x):
524.424 -+ class Foo:
524.425 -| global x
524.426 -+ def __call__(self, y):
524.427 -- return x + y
524.428 -| return Foo()
524.429 --
524.430 - x = 0
524.431 - verify(test(6)(2) == 8)
524.432 - x = -1
524.433 - verify(test(3)(2) == 5)
524.434 -
524.435 - print "18. verify that locals() works"
524.436 -
524.437 -+ def f(x):
524.438 -+ def g(y):
524.439 -+ def h(z):
524.440 -- return y + z
524.441 -| w = x + y
524.442 -| y += 3
524.443 -- return locals()
524.444 -| return g
524.445 --
524.446 - d = f(2)(4)
524.447 - verify(d.has_key('h'))
524.448 - del d['h']
524.449 - verify(d == {'x': 2, 'y': 7, 'w': 6})
524.450 -
524.451 - print "19. var is bound and free in class"
524.452 -
524.453 -+ def f(x):
524.454 -+ class C:
524.455 -+ def m(self):
524.456 -- return x
524.457 -- a = x
524.458 -| return C
524.459 --
524.460 - inst = f(3)()
524.461 - verify(inst.a == inst.m())
524.462 -
524.463 - print "20. interaction with trace function"
524.464 -
524.465 - import sys
524.466 -+ def tracer(a,b,c):
524.467 -| return tracer
524.468 --
524.469 -+ def adaptgetter(name, klass, getter):
524.470 -| kind, des = getter
524.471 -| if kind == 1: # AV happens when stepping from this line to next
524.472 -| if des == "":
524.473 -| des = "_%s__%s" % (klass.__name__, name)
524.474 -| return lambda obj: getattr(obj, des)
524.475 --
524.476 -+ class TestClass:
524.477 -| pass
524.478 --
524.479 - sys.settrace(tracer)
524.480 - adaptgetter("foo", TestClass, (1, ""))
524.481 - sys.settrace(None)
524.482 -
524.483 - try: sys.settrace()
524.484 - except TypeError: pass
524.485 - else: raise TestFailed, 'sys.settrace() did not raise TypeError'
524.486 -
524.487 - print "20. eval and exec with free variables"
524.488 -
524.489 -+ def f(x):
524.490 -| return lambda: x + 1
524.491 --
524.492 - g = f(3)
524.493 - try:
524.494 - eval(g.func_code)
524.495 - except TypeError:
524.496 - pass
524.497 - else:
524.498 - print "eval() should have failed, because code contained free vars"
524.499 -
524.500 - try:
524.501 - exec g.func_code
524.502 - except TypeError:
524.503 - pass
524.504 - else:
524.505 - print "exec should have failed, because code contained free vars"
524.506 -
524.507 - print "21. list comprehension with local variables"
524.508 -
524.509 - try:
524.510 - print bad
524.511 - except NameError:
524.512 - pass
524.513 - else:
524.514 - print "bad should not be defined"
524.515 -
524.516 -+ def x():
524.517 -| [bad for s in 'a b' for bad in s.split()]
524.518 --
524.519 - x()
524.520 - try:
524.521 - print bad
524.522 - except NameError:
524.523 - pass
524.524 -
524.525 - print "22. eval with free variables"
524.526 -
524.527 -+ def f(x):
524.528 -+ def g():
524.529 -| x
524.530 -- eval("x + 1")
524.531 -| return g
524.532 --
524.533 - f(4)()
524.534 -
525.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.nameoffsets Sun Jan 04 13:11:53 2015 -0600
525.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
525.3 @@ -1,531 +0,0 @@
525.4 -
525.5 -from test_support import verify, TestFailed, check_syntax
525.6 -
525.7 -import warnings
525.8 -<Attribute><Name>warnings</Name></Attribute>.<Call>filterwarnings</Call>("ignore", r"import \*", <Name>SyntaxWarning</Name>, "<string>")
525.9 -
525.10 -print "1. simple nesting"
525.11 -
525.12 -def <FunctionDef>make_adder</FunctionDef>(<Name>x</Name>):
525.13 - def <FunctionDef>adder</FunctionDef>(<Name>y</Name>):
525.14 - return <Name>x</Name> + <Name>y</Name>
525.15 - return <Name>adder</Name>
525.16 -
525.17 -<Name>inc</Name> = <Call><Name>make_adder</Name></Call>(1)
525.18 -<Name>plus10</Name> = <Call><Name>make_adder</Name></Call>(10)
525.19 -
525.20 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 2)
525.21 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(-2) == 8)
525.22 -
525.23 -print "2. extra nesting"
525.24 -
525.25 -def <FunctionDef>make_adder2</FunctionDef>(<Name>x</Name>):
525.26 - def <FunctionDef>extra</FunctionDef>(): # check freevars passing through non-use scopes
525.27 - def <FunctionDef>adder</FunctionDef>(<Name>y</Name>):
525.28 - return <Name>x</Name> + <Name>y</Name>
525.29 - return <Name>adder</Name>
525.30 - return <Call><Name>extra</Name></Call>()
525.31 -
525.32 -<Name>inc</Name> = <Call><Name>make_adder2</Name></Call>(1)
525.33 -<Name>plus10</Name> = <Call><Name>make_adder2</Name></Call>(10)
525.34 -
525.35 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 2)
525.36 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(-2) == 8)
525.37 -
525.38 -print "3. simple nesting + rebinding"
525.39 -
525.40 -def <FunctionDef>make_adder3</FunctionDef>(<Name>x</Name>):
525.41 - def <FunctionDef>adder</FunctionDef>(<Name>y</Name>):
525.42 - return <Name>x</Name> + <Name>y</Name>
525.43 - <Name>x</Name> = <Name>x</Name> + 1 # check tracking of assignment to x in defining scope
525.44 - return <Name>adder</Name>
525.45 -
525.46 -<Name>inc</Name> = <Call><Name>make_adder3</Name></Call>(0)
525.47 -<Name>plus10</Name> = <Call><Name>make_adder3</Name></Call>(9)
525.48 -
525.49 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 2)
525.50 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(-2) == 8)
525.51 -
525.52 -print "4. nesting with global but no free"
525.53 -
525.54 -def <FunctionDef>make_adder4</FunctionDef>(): # XXX add exta level of indirection
525.55 - def <FunctionDef>nest</FunctionDef>():
525.56 - def <FunctionDef>nest</FunctionDef>():
525.57 - def <FunctionDef>adder</FunctionDef>(<Name>y</Name>):
525.58 - return <Name>global_x</Name> + <Name>y</Name> # check that plain old globals work
525.59 - return <Name>adder</Name>
525.60 - return <Call><Name>nest</Name></Call>()
525.61 - return <Call><Name>nest</Name></Call>()
525.62 -
525.63 -<Name>global_x</Name> = 1
525.64 -<Name>adder</Name> = <Call><Name>make_adder4</Name></Call>()
525.65 -<Call><Name>verify</Name></Call>(<Call><Name>adder</Name></Call>(1) == 2)
525.66 -
525.67 -<Name>global_x</Name> = 10
525.68 -<Call><Name>verify</Name></Call>(<Call><Name>adder</Name></Call>(-2) == 8)
525.69 -
525.70 -print "5. nesting through class"
525.71 -
525.72 -def <FunctionDef>make_adder5</FunctionDef>(<Name>x</Name>):
525.73 - class <ClassDef>Adder</ClassDef>:
525.74 - def <FunctionDef>__call__</FunctionDef>(<Name>self</Name>, <Name>y</Name>):
525.75 - return <Name>x</Name> + <Name>y</Name>
525.76 - return <Call><Name>Adder</Name></Call>()
525.77 -
525.78 -<Name>inc</Name> = <Call><Name>make_adder5</Name></Call>(1)
525.79 -<Name>plus10</Name> = <Call><Name>make_adder5</Name></Call>(10)
525.80 -
525.81 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 2)
525.82 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(-2) == 8)
525.83 -
525.84 -print "6. nesting plus free ref to global"
525.85 -
525.86 -def <FunctionDef>make_adder6</FunctionDef>(<Name>x</Name>):
525.87 - global global_nest_x
525.88 - def <FunctionDef>adder</FunctionDef>(<Name>y</Name>):
525.89 - return <Name>global_nest_x</Name> + <Name>y</Name>
525.90 - <Name>global_nest_x</Name> = <Name>x</Name>
525.91 - return <Name>adder</Name>
525.92 -
525.93 -<Name>inc</Name> = <Call><Name>make_adder6</Name></Call>(1)
525.94 -<Name>plus10</Name> = <Call><Name>make_adder6</Name></Call>(10)
525.95 -
525.96 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 11) # there's only one global
525.97 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(-2) == 8)
525.98 -
525.99 -print "7. nearest enclosing scope"
525.100 -
525.101 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>):
525.102 - def <FunctionDef>g</FunctionDef>(<Name>y</Name>):
525.103 - <Name>x</Name> = 42 # check that this masks binding in f()
525.104 - def <FunctionDef>h</FunctionDef>(<Name>z</Name>):
525.105 - return <Name>x</Name> + <Name>z</Name>
525.106 - return <Name>h</Name>
525.107 - return <Call><Name>g</Name></Call>(2)
525.108 -
525.109 -<Name>test_func</Name> = <Call><Name>f</Name></Call>(10)
525.110 -<Call><Name>verify</Name></Call>(<Call><Name>test_func</Name></Call>(5) == 47)
525.111 -
525.112 -print "8. mixed freevars and cellvars"
525.113 -
525.114 -def <FunctionDef>identity</FunctionDef>(<Name>x</Name>):
525.115 - return <Name>x</Name>
525.116 -
525.117 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>, <Name>y</Name>, <Name>z</Name>):
525.118 - def <FunctionDef>g</FunctionDef>(<Name>a</Name>, <Name>b</Name>, <Name>c</Name>):
525.119 - <Name>a</Name> = <Name>a</Name> + <Name>x</Name> # 3
525.120 - def <FunctionDef>h</FunctionDef>():
525.121 - # z * (4 + 9)
525.122 - # 3 * 13
525.123 - return <Call><Name>identity</Name></Call>(<Name>z</Name> * (<Name>b</Name> + <Name>y</Name>))
525.124 - <Name>y</Name> = <Name>c</Name> + <Name>z</Name> # 9
525.125 - return <Name>h</Name>
525.126 - return <Name>g</Name>
525.127 -
525.128 -<Name>g</Name> = <Call><Name>f</Name></Call>(1, 2, 3)
525.129 -<Name>h</Name> = <Call><Name>g</Name></Call>(2, 4, 6)
525.130 -<Call><Name>verify</Name></Call>(<Call><Name>h</Name></Call>() == 39)
525.131 -
525.132 -print "9. free variable in method"
525.133 -
525.134 -def <FunctionDef>test</FunctionDef>():
525.135 - <Name>method_and_var</Name> = "var"
525.136 - class <ClassDef>Test</ClassDef>:
525.137 - def <FunctionDef>method_and_var</FunctionDef>(<Name>self</Name>):
525.138 - return "method"
525.139 - def <FunctionDef>test</FunctionDef>(<Name>self</Name>):
525.140 - return <Name>method_and_var</Name>
525.141 - def <FunctionDef>actual_global</FunctionDef>(<Name>self</Name>):
525.142 - return <Call><Name>str</Name></Call>("global")
525.143 - def <FunctionDef>str</FunctionDef>(<Name>self</Name>):
525.144 - return <Call><Name>str</Name></Call>(<Name>self</Name>)
525.145 - return <Call><Name>Test</Name></Call>()
525.146 -
525.147 -<Name>t</Name> = <Call><Name>test</Name></Call>()
525.148 -<Call><Name>verify</Name></Call>(<Attribute><Name>t</Name></Attribute>.<Call>test</Call>() == "var")
525.149 -<Call><Name>verify</Name></Call>(<Attribute><Name>t</Name></Attribute>.<Call>method_and_var</Call>() == "method")
525.150 -<Call><Name>verify</Name></Call>(<Attribute><Name>t</Name></Attribute>.<Call>actual_global</Call>() == "global")
525.151 -
525.152 -<Name>method_and_var</Name> = "var"
525.153 -class <ClassDef>Test</ClassDef>:
525.154 - # this class is not nested, so the rules are different
525.155 - def <FunctionDef>method_and_var</FunctionDef>(<Name>self</Name>):
525.156 - return "method"
525.157 - def <FunctionDef>test</FunctionDef>(<Name>self</Name>):
525.158 - return <Name>method_and_var</Name>
525.159 - def <FunctionDef>actual_global</FunctionDef>(<Name>self</Name>):
525.160 - return <Call><Name>str</Name></Call>("global")
525.161 - def <FunctionDef>str</FunctionDef>(<Name>self</Name>):
525.162 - return <Call><Name>str</Name></Call>(<Name>self</Name>)
525.163 -
525.164 -<Name>t</Name> = <Call><Name>Test</Name></Call>()
525.165 -<Call><Name>verify</Name></Call>(<Attribute><Name>t</Name></Attribute>.<Call>test</Call>() == "var")
525.166 -<Call><Name>verify</Name></Call>(<Attribute><Name>t</Name></Attribute>.<Call>method_and_var</Call>() == "method")
525.167 -<Call><Name>verify</Name></Call>(<Attribute><Name>t</Name></Attribute>.<Call>actual_global</Call>() == "global")
525.168 -
525.169 -print "10. recursion"
525.170 -
525.171 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>):
525.172 - def <FunctionDef>fact</FunctionDef>(<Name>n</Name>):
525.173 - if <Name>n</Name> == 0:
525.174 - return 1
525.175 - else:
525.176 - return <Name>n</Name> * <Call><Name>fact</Name></Call>(<Name>n</Name> - 1)
525.177 - if <Name>x</Name> >= 0:
525.178 - return <Call><Name>fact</Name></Call>(<Name>x</Name>)
525.179 - else:
525.180 - raise <Name>ValueError</Name>, "x must be >= 0"
525.181 -
525.182 -<Call><Name>verify</Name></Call>(<Call><Name>f</Name></Call>(6) == 720)
525.183 -
525.184 -
525.185 -print "11. unoptimized namespaces"
525.186 -
525.187 -<Call><Name>check_syntax</Name></Call>("""\
525.188 -def unoptimized_clash1(strip):
525.189 - def f(s):
525.190 - from string import *
525.191 - return strip(s) # ambiguity: free or local
525.192 - return f
525.193 -""")
525.194 -
525.195 -<Call><Name>check_syntax</Name></Call>("""\
525.196 -def unoptimized_clash2():
525.197 - from string import *
525.198 - def f(s):
525.199 - return strip(s) # ambiguity: global or local
525.200 - return f
525.201 -""")
525.202 -
525.203 -<Call><Name>check_syntax</Name></Call>("""\
525.204 -def unoptimized_clash2():
525.205 - from string import *
525.206 - def g():
525.207 - def f(s):
525.208 - return strip(s) # ambiguity: global or local
525.209 - return f
525.210 -""")
525.211 -
525.212 -# XXX could allow this for exec with const argument, but what's the point
525.213 -<Call><Name>check_syntax</Name></Call>("""\
525.214 -def error(y):
525.215 - exec "a = 1"
525.216 - def f(x):
525.217 - return x + y
525.218 - return f
525.219 -""")
525.220 -
525.221 -<Call><Name>check_syntax</Name></Call>("""\
525.222 -def f(x):
525.223 - def g():
525.224 - return x
525.225 - del x # can't del name
525.226 -""")
525.227 -
525.228 -<Call><Name>check_syntax</Name></Call>("""\
525.229 -def f():
525.230 - def g():
525.231 - from string import *
525.232 - return strip # global or local?
525.233 -""")
525.234 -
525.235 -# and verify a few cases that should work
525.236 -
525.237 -exec """
525.238 -def noproblem1():
525.239 - from string import *
525.240 - f = lambda x:x
525.241 -
525.242 -def noproblem2():
525.243 - from string import *
525.244 - def f(x):
525.245 - return x + 1
525.246 -
525.247 -def noproblem3():
525.248 - from string import *
525.249 - def f(x):
525.250 - global y
525.251 - y = x
525.252 -"""
525.253 -
525.254 -print "12. lambdas"
525.255 -
525.256 -<Name>f1</Name> = lambda <Name>x</Name>: lambda <Name>y</Name>: <Name>x</Name> + <Name>y</Name>
525.257 -<Name>inc</Name> = <Call><Name>f1</Name></Call>(1)
525.258 -<Name>plus10</Name> = <Call><Name>f1</Name></Call>(10)
525.259 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 2)
525.260 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(5) == 15)
525.261 -
525.262 -<Name>f2</Name> = lambda <Name>x</Name>: (lambda : lambda <Name>y</Name>: <Name>x</Name> + <Name>y</Name>)()
525.263 -<Name>inc</Name> = <Call><Name>f2</Name></Call>(1)
525.264 -<Name>plus10</Name> = <Call><Name>f2</Name></Call>(10)
525.265 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 2)
525.266 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(5) == 15)
525.267 -
525.268 -<Name>f3</Name> = lambda <Name>x</Name>: lambda <Name>y</Name>: <Name>global_x</Name> + <Name>y</Name>
525.269 -<Name>global_x</Name> = 1
525.270 -<Name>inc</Name> = <Call><Name>f3</Name></Call>(<Name>None</Name>)
525.271 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(2) == 3)
525.272 -
525.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>)
525.274 -<Name>g</Name> = <Call><Name>f8</Name></Call>(1, 2, 3)
525.275 -<Name>h</Name> = <Call><Name>g</Name></Call>(2, 4, 6)
525.276 -<Call><Name>verify</Name></Call>(<Call><Name>h</Name></Call>() == 18)
525.277 -
525.278 -print "13. UnboundLocal"
525.279 -
525.280 -def <FunctionDef>errorInOuter</FunctionDef>():
525.281 - print <Name>y</Name>
525.282 - def <FunctionDef>inner</FunctionDef>():
525.283 - return <Name>y</Name>
525.284 - <Name>y</Name> = 1
525.285 -
525.286 -def <FunctionDef>errorInInner</FunctionDef>():
525.287 - def <FunctionDef>inner</FunctionDef>():
525.288 - return <Name>y</Name>
525.289 - <Call><Name>inner</Name></Call>()
525.290 - <Name>y</Name> = 1
525.291 -
525.292 -try:
525.293 - <Call><Name>errorInOuter</Name></Call>()
525.294 -except <Name>UnboundLocalError</Name>:
525.295 - pass
525.296 -else:
525.297 - raise <Name>TestFailed</Name>
525.298 -
525.299 -try:
525.300 - <Call><Name>errorInInner</Name></Call>()
525.301 -except <Name>NameError</Name>:
525.302 - pass
525.303 -else:
525.304 - raise <Name>TestFailed</Name>
525.305 -
525.306 -print "14. complex definitions"
525.307 -
525.308 -def <FunctionDef>makeReturner</FunctionDef>(*lst):
525.309 - def <FunctionDef>returner</FunctionDef>():
525.310 - return <Name>lst</Name>
525.311 - return <Name>returner</Name>
525.312 -
525.313 -<Call><Name>verify</Name></Call>(<Call><Call><Name>makeReturner</Name></Call></Call>(1,2,3)() == (1,2,3))
525.314 -
525.315 -def <FunctionDef>makeReturner2</FunctionDef>(**kwargs):
525.316 - def <FunctionDef>returner</FunctionDef>():
525.317 - return <Name>kwargs</Name>
525.318 - return <Name>returner</Name>
525.319 -
525.320 -<Call><Name>verify</Name></Call>(<Call><Name>makeReturner2</Name></Call>(a=11)<Call>()['a'] == 11</Call>)
525.321 -
525.322 -def <FunctionDef>makeAddPair</FunctionDef>((<Name>a</Name>, <Name>b</Name>)):
525.323 - def <FunctionDef>addPair</FunctionDef>((<Name>c</Name>, <Name>d</Name>)):
525.324 - return (<Name>a</Name> + <Name>c</Name>, <Name>b</Name> + <Name>d</Name>)
525.325 - return <Name>addPair</Name>
525.326 -
525.327 -<Call><Name>verify</Name></Call>(<Call><Call><Name>makeAddPair</Name></Call></Call>((1, 2))((100, 200)) == (101,202))
525.328 -
525.329 -print "15. scope of global statements"
525.330 -# Examples posted by Samuele Pedroni to python-dev on 3/1/2001
525.331 -
525.332 -# I
525.333 -<Name>x</Name> = 7
525.334 -def <FunctionDef>f</FunctionDef>():
525.335 - <Name>x</Name> = 1
525.336 - def <FunctionDef>g</FunctionDef>():
525.337 - global x
525.338 - def <FunctionDef>i</FunctionDef>():
525.339 - def <FunctionDef>h</FunctionDef>():
525.340 - return <Name>x</Name>
525.341 - return <Call><Name>h</Name></Call>()
525.342 - return <Call><Name>i</Name></Call>()
525.343 - return <Call><Name>g</Name></Call>()
525.344 -<Call><Name>verify</Name></Call>(<Call><Name>f</Name></Call>() == 7)
525.345 -<Call><Name>verify</Name></Call>(<Name>x</Name> == 7)
525.346 -
525.347 -# II
525.348 -<Name>x</Name> = 7
525.349 -def <FunctionDef>f</FunctionDef>():
525.350 - <Name>x</Name> = 1
525.351 - def <FunctionDef>g</FunctionDef>():
525.352 - <Name>x</Name> = 2
525.353 - def <FunctionDef>i</FunctionDef>():
525.354 - def <FunctionDef>h</FunctionDef>():
525.355 - return <Name>x</Name>
525.356 - return <Call><Name>h</Name></Call>()
525.357 - return <Call><Name>i</Name></Call>()
525.358 - return <Call><Name>g</Name></Call>()
525.359 -<Call><Name>verify</Name></Call>(<Call><Name>f</Name></Call>() == 2)
525.360 -<Call><Name>verify</Name></Call>(<Name>x</Name> == 7)
525.361 -
525.362 -# III
525.363 -<Name>x</Name> = 7
525.364 -def <FunctionDef>f</FunctionDef>():
525.365 - <Name>x</Name> = 1
525.366 - def <FunctionDef>g</FunctionDef>():
525.367 - global x
525.368 - <Name>x</Name> = 2
525.369 - def <FunctionDef>i</FunctionDef>():
525.370 - def <FunctionDef>h</FunctionDef>():
525.371 - return <Name>x</Name>
525.372 - return <Call><Name>h</Name></Call>()
525.373 - return <Call><Name>i</Name></Call>()
525.374 - return <Call><Name>g</Name></Call>()
525.375 -<Call><Name>verify</Name></Call>(<Call><Name>f</Name></Call>() == 2)
525.376 -<Call><Name>verify</Name></Call>(<Name>x</Name> == 2)
525.377 -
525.378 -# IV
525.379 -<Name>x</Name> = 7
525.380 -def <FunctionDef>f</FunctionDef>():
525.381 - <Name>x</Name> = 3
525.382 - def <FunctionDef>g</FunctionDef>():
525.383 - global x
525.384 - <Name>x</Name> = 2
525.385 - def <FunctionDef>i</FunctionDef>():
525.386 - def <FunctionDef>h</FunctionDef>():
525.387 - return <Name>x</Name>
525.388 - return <Call><Name>h</Name></Call>()
525.389 - return <Call><Name>i</Name></Call>()
525.390 - return <Call><Name>g</Name></Call>()
525.391 -<Call><Name>verify</Name></Call>(<Call><Name>f</Name></Call>() == 2)
525.392 -<Call><Name>verify</Name></Call>(<Name>x</Name> == 2)
525.393 -
525.394 -print "16. check leaks"
525.395 -
525.396 -class <ClassDef>Foo</ClassDef>:
525.397 - <Name>count</Name> = 0
525.398 -
525.399 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>):
525.400 - <Attribute><Name>Foo</Name></Attribute>.count += 1
525.401 -
525.402 - def <FunctionDef>__del__</FunctionDef>(<Name>self</Name>):
525.403 - <Attribute><Name>Foo</Name></Attribute>.count -= 1
525.404 -
525.405 -def <FunctionDef>f1</FunctionDef>():
525.406 - <Name>x</Name> = <Call><Name>Foo</Name></Call>()
525.407 - def <FunctionDef>f2</FunctionDef>():
525.408 - return <Name>x</Name>
525.409 - <Call><Name>f2</Name></Call>()
525.410 -
525.411 -for <Name>i</Name> in <Call><Name>range</Name></Call>(100):
525.412 - <Call><Name>f1</Name></Call>()
525.413 -
525.414 -import os
525.415 -if <Attribute><Name>os</Name></Attribute>.name == 'java':
525.416 - from java.lang import System, Thread
525.417 - <Attribute><Name>System</Name></Attribute>.<Call>gc</Call>()
525.418 - <Attribute><Name>Thread</Name></Attribute>.<Call>sleep</Call>(100)
525.419 - <Attribute><Name>System</Name></Attribute>.<Call>gc</Call>()
525.420 -<Call><Name>verify</Name></Call>(<Attribute><Name>Foo</Name></Attribute>.count == 0)
525.421 -
525.422 -print "17. class and global"
525.423 -
525.424 -def <FunctionDef>test</FunctionDef>(<Name>x</Name>):
525.425 - class <ClassDef>Foo</ClassDef>:
525.426 - global x
525.427 - def <FunctionDef>__call__</FunctionDef>(<Name>self</Name>, <Name>y</Name>):
525.428 - return <Name>x</Name> + <Name>y</Name>
525.429 - return <Call><Name>Foo</Name></Call>()
525.430 -
525.431 -<Name>x</Name> = 0
525.432 -<Call><Name>verify</Name></Call>(<Call><Call><Name>test</Name></Call></Call>(6)(2) == 8)
525.433 -<Name>x</Name> = -1
525.434 -<Call><Name>verify</Name></Call>(<Call><Call><Name>test</Name></Call></Call>(3)(2) == 5)
525.435 -
525.436 -print "18. verify that locals() works"
525.437 -
525.438 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>):
525.439 - def <FunctionDef>g</FunctionDef>(<Name>y</Name>):
525.440 - def <FunctionDef>h</FunctionDef>(<Name>z</Name>):
525.441 - return <Name>y</Name> + <Name>z</Name>
525.442 - <Name>w</Name> = <Name>x</Name> + <Name>y</Name>
525.443 - <Name>y</Name> += 3
525.444 - return <Call><Name>locals</Name></Call>()
525.445 - return <Name>g</Name>
525.446 -
525.447 -<Name>d</Name> = <Call><Call><Name>f</Name></Call></Call>(2)(4)
525.448 -<Call><Name>verify</Name></Call>(<Attribute><Name>d</Name></Attribute>.<Call>has_key</Call>('h'))
525.449 -del <Name>d</Name>['h']
525.450 -<Call><Name>verify</Name></Call>(<Name>d</Name> == {'x': 2, 'y': 7, 'w': 6})
525.451 -
525.452 -print "19. var is bound and free in class"
525.453 -
525.454 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>):
525.455 - class <ClassDef>C</ClassDef>:
525.456 - def <FunctionDef>m</FunctionDef>(<Name>self</Name>):
525.457 - return <Name>x</Name>
525.458 - <Name>a</Name> = <Name>x</Name>
525.459 - return <Name>C</Name>
525.460 -
525.461 -<Name>inst</Name> = <Call><Call><Name>f</Name></Call></Call>(3)()
525.462 -<Call><Name>verify</Name></Call>(<Attribute><Name>inst</Name></Attribute>.a == <Attribute><Name>inst</Name></Attribute>.<Call>m</Call>())
525.463 -
525.464 -print "20. interaction with trace function"
525.465 -
525.466 -import sys
525.467 -def <FunctionDef>tracer</FunctionDef>(<Name>a</Name>,<Name>b</Name>,<Name>c</Name>):
525.468 - return <Name>tracer</Name>
525.469 -
525.470 -def <FunctionDef>adaptgetter</FunctionDef>(<Name>name</Name>, <Name>klass</Name>, <Name>getter</Name>):
525.471 - <Name>kind</Name>, <Name>des</Name> = <Name>getter</Name>
525.472 - if <Name>kind</Name> == 1: # AV happens when stepping from this line to next
525.473 - if <Name>des</Name> == "":
525.474 - <Name>des</Name> = "_%s__%s" % (<Attribute><Name>klass</Name></Attribute>.__name__, <Name>name</Name>)
525.475 - return lambda <Name>obj</Name>: <Call><Name>getattr</Name></Call>(<Name>obj</Name>, <Name>des</Name>)
525.476 -
525.477 -class <ClassDef>TestClass</ClassDef>:
525.478 - pass
525.479 -
525.480 -<Attribute><Name>sys</Name></Attribute>.<Call>settrace</Call>(<Name>tracer</Name>)
525.481 -<Call><Name>adaptgetter</Name></Call>("foo", <Name>TestClass</Name>, (1, ""))
525.482 -<Attribute><Name>sys</Name></Attribute>.<Call>settrace</Call>(<Name>None</Name>)
525.483 -
525.484 -try: <Attribute><Name>sys</Name></Attribute>.<Call>settrace</Call>()
525.485 -except <Name>TypeError</Name>: pass
525.486 -else: raise <Name>TestFailed</Name>, 'sys.settrace() did not raise TypeError'
525.487 -
525.488 -print "20. eval and exec with free variables"
525.489 -
525.490 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>):
525.491 - return lambda: <Name>x</Name> + 1
525.492 -
525.493 -<Name>g</Name> = <Call><Name>f</Name></Call>(3)
525.494 -try:
525.495 - <Call><Name>eval</Name></Call>(<Attribute><Name>g</Name></Attribute>.func_code)
525.496 -except <Name>TypeError</Name>:
525.497 - pass
525.498 -else:
525.499 - print "eval() should have failed, because code contained free vars"
525.500 -
525.501 -try:
525.502 - exec <Attribute><Name>g</Name></Attribute>.func_code
525.503 -except <Name>TypeError</Name>:
525.504 - pass
525.505 -else:
525.506 - print "exec should have failed, because code contained free vars"
525.507 -
525.508 -print "21. list comprehension with local variables"
525.509 -
525.510 -try:
525.511 - print <Name>bad</Name>
525.512 -except <Name>NameError</Name>:
525.513 - pass
525.514 -else:
525.515 - print "bad should not be defined"
525.516 -
525.517 -def <FunctionDef>x</FunctionDef>():
525.518 - [<Name>bad</Name> for <Name>s</Name> in 'a b' for <Name>bad</Name> in <Attribute><Name>s</Name></Attribute>.<Call>split</Call>()]
525.519 -
525.520 -<Call><Name>x</Name></Call>()
525.521 -try:
525.522 - print <Name>bad</Name>
525.523 -except <Name>NameError</Name>:
525.524 - pass
525.525 -
525.526 -print "22. eval with free variables"
525.527 -
525.528 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>):
525.529 - def <FunctionDef>g</FunctionDef>():
525.530 - <Name>x</Name>
525.531 - <Call><Name>eval</Name></Call>("x + 1")
525.532 - return <Name>g</Name>
525.533 -
525.534 -<Call><Call><Name>f</Name></Call></Call>(4)()
526.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.offsets Sun Jan 04 13:11:53 2015 -0600
526.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
526.3 @@ -1,531 +0,0 @@
526.4 -
526.5 -<Module><ImportFrom>from test_support import verify, TestFailed, check_syntax</ImportFrom>
526.6 -
526.7 -<Import>import warnings</Import>
526.8 -<Expr><Call><Attribute><Name>warnings</Name>.filterwarnings</Attribute>(<Str>"ignore"</Str>, <Str>r"import \*"</Str>, <Name>SyntaxWarning</Name>, <Str>"<string>"</Str>)</Call></Expr>
526.9 -
526.10 -<Print>print <Str>"1. simple nesting"</Str></Print>
526.11 -
526.12 -<FunctionDef>def make_adder(<Name>x</Name>):
526.13 - <FunctionDef>def adder(<Name>y</Name>):
526.14 - <Return>return <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Return>
526.15 - </FunctionDef> <Return>return <Name>adder</Name></Return>
526.16 -
526.17 -</FunctionDef><Assign><Name>inc</Name> = <Call><Name>make_adder</Name>(<Num>1</Num>)</Call></Assign>
526.18 -<Assign><Name>plus10</Name> = <Call><Name>make_adder</Name>(<Num>10</Num>)</Call></Assign>
526.19 -
526.20 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
526.21 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>-2</Num>)</Call> == <Num>8</Num></Compare>)</Call></Expr>
526.22 -
526.23 -<Print>print <Str>"2. extra nesting"</Str></Print>
526.24 -
526.25 -<FunctionDef>def make_adder2(<Name>x</Name>):
526.26 - <FunctionDef>def extra(): # check freevars passing through non-use scopes
526.27 - <FunctionDef>def adder(<Name>y</Name>):
526.28 - <Return>return <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Return>
526.29 - </FunctionDef> <Return>return <Name>adder</Name></Return>
526.30 - </FunctionDef> <Return>return <Call><Name>extra</Name>()</Call></Return>
526.31 -
526.32 -</FunctionDef><Assign><Name>inc</Name> = <Call><Name>make_adder2</Name>(<Num>1</Num>)</Call></Assign>
526.33 -<Assign><Name>plus10</Name> = <Call><Name>make_adder2</Name>(<Num>10</Num>)</Call></Assign>
526.34 -
526.35 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
526.36 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>-2</Num>)</Call> == <Num>8</Num></Compare>)</Call></Expr>
526.37 -
526.38 -<Print>print <Str>"3. simple nesting + rebinding"</Str></Print>
526.39 -
526.40 -<FunctionDef>def make_adder3(<Name>x</Name>):
526.41 - <FunctionDef>def adder(<Name>y</Name>):
526.42 - <Return>return <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Return>
526.43 - </FunctionDef> <Assign><Name>x</Name> = <BinOp><Name>x</Name> + <Num>1</Num></BinOp></Assign> # check tracking of assignment to x in defining scope
526.44 - <Return>return <Name>adder</Name></Return>
526.45 -
526.46 -</FunctionDef><Assign><Name>inc</Name> = <Call><Name>make_adder3</Name>(<Num>0</Num>)</Call></Assign>
526.47 -<Assign><Name>plus10</Name> = <Call><Name>make_adder3</Name>(<Num>9</Num>)</Call></Assign>
526.48 -
526.49 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
526.50 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>-2</Num>)</Call> == <Num>8</Num></Compare>)</Call></Expr>
526.51 -
526.52 -<Print>print <Str>"4. nesting with global but no free"</Str></Print>
526.53 -
526.54 -<FunctionDef>def make_adder4(): # XXX add exta level of indirection
526.55 - <FunctionDef>def nest():
526.56 - <FunctionDef>def nest():
526.57 - <FunctionDef>def adder(<Name>y</Name>):
526.58 - <Return>return <BinOp><Name>global_x</Name> + <Name>y</Name></BinOp></Return> # check that plain old globals work
526.59 - </FunctionDef> <Return>return <Name>adder</Name></Return>
526.60 - </FunctionDef> <Return>return <Call><Name>nest</Name>()</Call></Return>
526.61 - </FunctionDef> <Return>return <Call><Name>nest</Name>()</Call></Return>
526.62 -
526.63 -</FunctionDef><Assign><Name>global_x</Name> = <Num>1</Num></Assign>
526.64 -<Assign><Name>adder</Name> = <Call><Name>make_adder4</Name>()</Call></Assign>
526.65 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>adder</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
526.66 -
526.67 -<Assign><Name>global_x</Name> = <Num>10</Num></Assign>
526.68 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>adder</Name>(<Num>-2</Num>)</Call> == <Num>8</Num></Compare>)</Call></Expr>
526.69 -
526.70 -<Print>print <Str>"5. nesting through class"</Str></Print>
526.71 -
526.72 -<FunctionDef>def make_adder5(<Name>x</Name>):
526.73 - <ClassDef>class Adder:
526.74 - <FunctionDef>def __call__(<Name>self</Name>, <Name>y</Name>):
526.75 - <Return>return <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Return>
526.76 - </FunctionDef></ClassDef> <Return>return <Call><Name>Adder</Name>()</Call></Return>
526.77 -
526.78 -</FunctionDef><Assign><Name>inc</Name> = <Call><Name>make_adder5</Name>(<Num>1</Num>)</Call></Assign>
526.79 -<Assign><Name>plus10</Name> = <Call><Name>make_adder5</Name>(<Num>10</Num>)</Call></Assign>
526.80 -
526.81 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
526.82 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>-2</Num>)</Call> == <Num>8</Num></Compare>)</Call></Expr>
526.83 -
526.84 -<Print>print <Str>"6. nesting plus free ref to global"</Str></Print>
526.85 -
526.86 -<FunctionDef>def make_adder6(<Name>x</Name>):
526.87 - <Global>global global_nest_x</Global>
526.88 - <FunctionDef>def adder(<Name>y</Name>):
526.89 - <Return>return <BinOp><Name>global_nest_x</Name> + <Name>y</Name></BinOp></Return>
526.90 - </FunctionDef> <Assign><Name>global_nest_x</Name> = <Name>x</Name></Assign>
526.91 - <Return>return <Name>adder</Name></Return>
526.92 -
526.93 -</FunctionDef><Assign><Name>inc</Name> = <Call><Name>make_adder6</Name>(<Num>1</Num>)</Call></Assign>
526.94 -<Assign><Name>plus10</Name> = <Call><Name>make_adder6</Name>(<Num>10</Num>)</Call></Assign>
526.95 -
526.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
526.97 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>-2</Num>)</Call> == <Num>8</Num></Compare>)</Call></Expr>
526.98 -
526.99 -<Print>print <Str>"7. nearest enclosing scope"</Str></Print>
526.100 -
526.101 -<FunctionDef>def f(<Name>x</Name>):
526.102 - <FunctionDef>def g(<Name>y</Name>):
526.103 - <Assign><Name>x</Name> = <Num>42</Num></Assign> # check that this masks binding in f()
526.104 - <FunctionDef>def h(<Name>z</Name>):
526.105 - <Return>return <BinOp><Name>x</Name> + <Name>z</Name></BinOp></Return>
526.106 - </FunctionDef> <Return>return <Name>h</Name></Return>
526.107 - </FunctionDef> <Return>return <Call><Name>g</Name>(<Num>2</Num>)</Call></Return>
526.108 -
526.109 -</FunctionDef><Assign><Name>test_func</Name> = <Call><Name>f</Name>(<Num>10</Num>)</Call></Assign>
526.110 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>test_func</Name>(<Num>5</Num>)</Call> == <Num>47</Num></Compare>)</Call></Expr>
526.111 -
526.112 -<Print>print <Str>"8. mixed freevars and cellvars"</Str></Print>
526.113 -
526.114 -<FunctionDef>def identity(<Name>x</Name>):
526.115 - <Return>return <Name>x</Name></Return>
526.116 -
526.117 -</FunctionDef><FunctionDef>def f(<Name>x</Name>, <Name>y</Name>, <Name>z</Name>):
526.118 - <FunctionDef>def g(<Name>a</Name>, <Name>b</Name>, <Name>c</Name>):
526.119 - <Assign><Name>a</Name> = <BinOp><Name>a</Name> + <Name>x</Name></BinOp></Assign> # 3
526.120 - <FunctionDef>def h():
526.121 - # z * (4 + 9)
526.122 - # 3 * 13
526.123 - <Return>return <Call><Name>identity</Name>(<BinOp><Name>z</Name> * <BinOp>(<Name>b</Name> + <Name>y</Name>)</BinOp></BinOp>)</Call></Return>
526.124 - </FunctionDef> <Assign><Name>y</Name> = <BinOp><Name>c</Name> + <Name>z</Name></BinOp></Assign> # 9
526.125 - <Return>return <Name>h</Name></Return>
526.126 - </FunctionDef> <Return>return <Name>g</Name></Return>
526.127 -
526.128 -</FunctionDef><Assign><Name>g</Name> = <Call><Name>f</Name>(<Num>1</Num>, <Num>2</Num>, <Num>3</Num>)</Call></Assign>
526.129 -<Assign><Name>h</Name> = <Call><Name>g</Name>(<Num>2</Num>, <Num>4</Num>, <Num>6</Num>)</Call></Assign>
526.130 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>h</Name>()</Call> == <Num>39</Num></Compare>)</Call></Expr>
526.131 -
526.132 -<Print>print <Str>"9. free variable in method"</Str></Print>
526.133 -
526.134 -<FunctionDef>def test():
526.135 - <Assign><Name>method_and_var</Name> = <Str>"var"</Str></Assign>
526.136 - <ClassDef>class Test:
526.137 - <FunctionDef>def method_and_var(<Name>self</Name>):
526.138 - <Return>return <Str>"method"</Str></Return>
526.139 - </FunctionDef> <FunctionDef>def test(<Name>self</Name>):
526.140 - <Return>return <Name>method_and_var</Name></Return>
526.141 - </FunctionDef> <FunctionDef>def actual_global(<Name>self</Name>):
526.142 - <Return>return <Call><Name>str</Name>(<Str>"global"</Str>)</Call></Return>
526.143 - </FunctionDef> <FunctionDef>def str(<Name>self</Name>):
526.144 - <Return>return <Call><Name>str</Name>(<Name>self</Name>)</Call></Return>
526.145 - </FunctionDef></ClassDef> <Return>return <Call><Name>Test</Name>()</Call></Return>
526.146 -
526.147 -</FunctionDef><Assign><Name>t</Name> = <Call><Name>test</Name>()</Call></Assign>
526.148 -<Expr><Call><Name>verify</Name>(<Compare><Call><Attribute><Name>t</Name>.test</Attribute>()</Call> == <Str>"var"</Str></Compare>)</Call></Expr>
526.149 -<Expr><Call><Name>verify</Name>(<Compare><Call><Attribute><Name>t</Name>.method_and_var</Attribute>()</Call> == <Str>"method"</Str></Compare>)</Call></Expr>
526.150 -<Expr><Call><Name>verify</Name>(<Compare><Call><Attribute><Name>t</Name>.actual_global</Attribute>()</Call> == <Str>"global"</Str></Compare>)</Call></Expr>
526.151 -
526.152 -<Assign><Name>method_and_var</Name> = <Str>"var"</Str></Assign>
526.153 -<ClassDef>class Test:
526.154 - # this class is not nested, so the rules are different
526.155 - <FunctionDef>def method_and_var(<Name>self</Name>):
526.156 - <Return>return <Str>"method"</Str></Return>
526.157 - </FunctionDef> <FunctionDef>def test(<Name>self</Name>):
526.158 - <Return>return <Name>method_and_var</Name></Return>
526.159 - </FunctionDef> <FunctionDef>def actual_global(<Name>self</Name>):
526.160 - <Return>return <Call><Name>str</Name>(<Str>"global"</Str>)</Call></Return>
526.161 - </FunctionDef> <FunctionDef>def str(<Name>self</Name>):
526.162 - <Return>return <Call><Name>str</Name>(<Name>self</Name>)</Call></Return>
526.163 -
526.164 -</FunctionDef></ClassDef><Assign><Name>t</Name> = <Call><Name>Test</Name>()</Call></Assign>
526.165 -<Expr><Call><Name>verify</Name>(<Compare><Call><Attribute><Name>t</Name>.test</Attribute>()</Call> == <Str>"var"</Str></Compare>)</Call></Expr>
526.166 -<Expr><Call><Name>verify</Name>(<Compare><Call><Attribute><Name>t</Name>.method_and_var</Attribute>()</Call> == <Str>"method"</Str></Compare>)</Call></Expr>
526.167 -<Expr><Call><Name>verify</Name>(<Compare><Call><Attribute><Name>t</Name>.actual_global</Attribute>()</Call> == <Str>"global"</Str></Compare>)</Call></Expr>
526.168 -
526.169 -<Print>print <Str>"10. recursion"</Str></Print>
526.170 -
526.171 -<FunctionDef>def f(<Name>x</Name>):
526.172 - <FunctionDef>def fact(<Name>n</Name>):
526.173 - <If>if <Compare><Name>n</Name> == <Num>0</Num></Compare>:
526.174 - <Return>return <Num>1</Num></Return>
526.175 - else:
526.176 - <Return>return <BinOp><Name>n</Name> * <Call><Name>fact</Name>(<BinOp><Name>n</Name> - <Num>1</Num></BinOp>)</Call></BinOp></Return>
526.177 - </If></FunctionDef> <If>if <Compare><Name>x</Name> >= <Num>0</Num></Compare>:
526.178 - <Return>return <Call><Name>fact</Name>(<Name>x</Name>)</Call></Return>
526.179 - else:
526.180 - <Raise>raise <Name>ValueError</Name>, <Str>"x must be >= 0"</Str></Raise>
526.181 -
526.182 -</If></FunctionDef><Expr><Call><Name>verify</Name>(<Compare><Call><Name>f</Name>(<Num>6</Num>)</Call> == <Num>720</Num></Compare>)</Call></Expr>
526.183 -
526.184 -
526.185 -<Print>print <Str>"11. unoptimized namespaces"</Str></Print>
526.186 -
526.187 -<Expr><Call><Name>check_syntax</Name>(<Str>"""\
526.188 -def unoptimized_clash1(strip):
526.189 - def f(s):
526.190 - from string import *
526.191 - return strip(s) # ambiguity: free or local
526.192 - return f
526.193 -"""</Str>)</Call></Expr>
526.194 -
526.195 -<Expr><Call><Name>check_syntax</Name>(<Str>"""\
526.196 -def unoptimized_clash2():
526.197 - from string import *
526.198 - def f(s):
526.199 - return strip(s) # ambiguity: global or local
526.200 - return f
526.201 -"""</Str>)</Call></Expr>
526.202 -
526.203 -<Expr><Call><Name>check_syntax</Name>(<Str>"""\
526.204 -def unoptimized_clash2():
526.205 - from string import *
526.206 - def g():
526.207 - def f(s):
526.208 - return strip(s) # ambiguity: global or local
526.209 - return f
526.210 -"""</Str>)</Call></Expr>
526.211 -
526.212 -# XXX could allow this for exec with const argument, but what's the point
526.213 -<Expr><Call><Name>check_syntax</Name>(<Str>"""\
526.214 -def error(y):
526.215 - exec "a = 1"
526.216 - def f(x):
526.217 - return x + y
526.218 - return f
526.219 -"""</Str>)</Call></Expr>
526.220 -
526.221 -<Expr><Call><Name>check_syntax</Name>(<Str>"""\
526.222 -def f(x):
526.223 - def g():
526.224 - return x
526.225 - del x # can't del name
526.226 -"""</Str>)</Call></Expr>
526.227 -
526.228 -<Expr><Call><Name>check_syntax</Name>(<Str>"""\
526.229 -def f():
526.230 - def g():
526.231 - from string import *
526.232 - return strip # global or local?
526.233 -"""</Str>)</Call></Expr>
526.234 -
526.235 -# and verify a few cases that should work
526.236 -
526.237 -<Exec>exec <Str>"""
526.238 -def noproblem1():
526.239 - from string import *
526.240 - f = lambda x:x
526.241 -
526.242 -def noproblem2():
526.243 - from string import *
526.244 - def f(x):
526.245 - return x + 1
526.246 -
526.247 -def noproblem3():
526.248 - from string import *
526.249 - def f(x):
526.250 - global y
526.251 - y = x
526.252 -"""</Str></Exec>
526.253 -
526.254 -<Print>print <Str>"12. lambdas"</Str></Print>
526.255 -
526.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>
526.257 -<Assign><Name>inc</Name> = <Call><Name>f1</Name>(<Num>1</Num>)</Call></Assign>
526.258 -<Assign><Name>plus10</Name> = <Call><Name>f1</Name>(<Num>10</Num>)</Call></Assign>
526.259 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
526.260 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>5</Num>)</Call> == <Num>15</Num></Compare>)</Call></Expr>
526.261 -
526.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>
526.263 -<Assign><Name>inc</Name> = <Call><Name>f2</Name>(<Num>1</Num>)</Call></Assign>
526.264 -<Assign><Name>plus10</Name> = <Call><Name>f2</Name>(<Num>10</Num>)</Call></Assign>
526.265 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
526.266 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>5</Num>)</Call> == <Num>15</Num></Compare>)</Call></Expr>
526.267 -
526.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>
526.269 -<Assign><Name>global_x</Name> = <Num>1</Num></Assign>
526.270 -<Assign><Name>inc</Name> = <Call><Name>f3</Name>(<Name>None</Name>)</Call></Assign>
526.271 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>2</Num>)</Call> == <Num>3</Num></Compare>)</Call></Expr>
526.272 -
526.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>
526.274 -<Assign><Name>g</Name> = <Call><Name>f8</Name>(<Num>1</Num>, <Num>2</Num>, <Num>3</Num>)</Call></Assign>
526.275 -<Assign><Name>h</Name> = <Call><Name>g</Name>(<Num>2</Num>, <Num>4</Num>, <Num>6</Num>)</Call></Assign>
526.276 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>h</Name>()</Call> == <Num>18</Num></Compare>)</Call></Expr>
526.277 -
526.278 -<Print>print <Str>"13. UnboundLocal"</Str></Print>
526.279 -
526.280 -<FunctionDef>def errorInOuter():
526.281 - <Print>print <Name>y</Name></Print>
526.282 - <FunctionDef>def inner():
526.283 - <Return>return <Name>y</Name></Return>
526.284 - </FunctionDef> <Assign><Name>y</Name> = <Num>1</Num></Assign>
526.285 -
526.286 -</FunctionDef><FunctionDef>def errorInInner():
526.287 - <FunctionDef>def inner():
526.288 - <Return>return <Name>y</Name></Return>
526.289 - </FunctionDef> <Expr><Call><Name>inner</Name>()</Call></Expr>
526.290 - <Assign><Name>y</Name> = <Num>1</Num></Assign>
526.291 -
526.292 -</FunctionDef><TryExcept>try:
526.293 - <Expr><Call><Name>errorInOuter</Name>()</Call></Expr>
526.294 -<ExceptHandler>except <Name>UnboundLocalError</Name>:
526.295 - <Pass>pass</Pass>
526.296 -</ExceptHandler>else:
526.297 - <Raise>raise <Name>TestFailed</Name></Raise>
526.298 -
526.299 -</TryExcept><TryExcept>try:
526.300 - <Expr><Call><Name>errorInInner</Name>()</Call></Expr>
526.301 -<ExceptHandler>except <Name>NameError</Name>:
526.302 - <Pass>pass</Pass>
526.303 -</ExceptHandler>else:
526.304 - <Raise>raise <Name>TestFailed</Name></Raise>
526.305 -
526.306 -</TryExcept><Print>print <Str>"14. complex definitions"</Str></Print>
526.307 -
526.308 -<FunctionDef>def makeReturner(*lst):
526.309 - <FunctionDef>def returner():
526.310 - <Return>return <Name>lst</Name></Return>
526.311 - </FunctionDef> <Return>return <Name>returner</Name></Return>
526.312 -
526.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>
526.314 -
526.315 -<FunctionDef>def makeReturner2(**kwargs):
526.316 - <FunctionDef>def returner():
526.317 - <Return>return <Name>kwargs</Name></Return>
526.318 - </FunctionDef> <Return>return <Name>returner</Name></Return>
526.319 -
526.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>
526.321 -
526.322 -<FunctionDef>def makeAddPair(<Tuple>(<Name>a</Name>, <Name>b</Name>)</Tuple>):
526.323 - <FunctionDef>def addPair(<Tuple>(<Name>c</Name>, <Name>d</Name>)</Tuple>):
526.324 - <Return>return <Tuple>(<BinOp><Name>a</Name> + <Name>c</Name></BinOp>, <BinOp><Name>b</Name> + <Name>d</Name></BinOp>)</Tuple></Return>
526.325 - </FunctionDef> <Return>return <Name>addPair</Name></Return>
526.326 -
526.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>
526.328 -
526.329 -<Print>print <Str>"15. scope of global statements"</Str></Print>
526.330 -# Examples posted by Samuele Pedroni to python-dev on 3/1/2001
526.331 -
526.332 -# I
526.333 -<Assign><Name>x</Name> = <Num>7</Num></Assign>
526.334 -<FunctionDef>def f():
526.335 - <Assign><Name>x</Name> = <Num>1</Num></Assign>
526.336 - <FunctionDef>def g():
526.337 - <Global>global x</Global>
526.338 - <FunctionDef>def i():
526.339 - <FunctionDef>def h():
526.340 - <Return>return <Name>x</Name></Return>
526.341 - </FunctionDef> <Return>return <Call><Name>h</Name>()</Call></Return>
526.342 - </FunctionDef> <Return>return <Call><Name>i</Name>()</Call></Return>
526.343 - </FunctionDef> <Return>return <Call><Name>g</Name>()</Call></Return>
526.344 -</FunctionDef><Expr><Call><Name>verify</Name>(<Compare><Call><Name>f</Name>()</Call> == <Num>7</Num></Compare>)</Call></Expr>
526.345 -<Expr><Call><Name>verify</Name>(<Compare><Name>x</Name> == <Num>7</Num></Compare>)</Call></Expr>
526.346 -
526.347 -# II
526.348 -<Assign><Name>x</Name> = <Num>7</Num></Assign>
526.349 -<FunctionDef>def f():
526.350 - <Assign><Name>x</Name> = <Num>1</Num></Assign>
526.351 - <FunctionDef>def g():
526.352 - <Assign><Name>x</Name> = <Num>2</Num></Assign>
526.353 - <FunctionDef>def i():
526.354 - <FunctionDef>def h():
526.355 - <Return>return <Name>x</Name></Return>
526.356 - </FunctionDef> <Return>return <Call><Name>h</Name>()</Call></Return>
526.357 - </FunctionDef> <Return>return <Call><Name>i</Name>()</Call></Return>
526.358 - </FunctionDef> <Return>return <Call><Name>g</Name>()</Call></Return>
526.359 -</FunctionDef><Expr><Call><Name>verify</Name>(<Compare><Call><Name>f</Name>()</Call> == <Num>2</Num></Compare>)</Call></Expr>
526.360 -<Expr><Call><Name>verify</Name>(<Compare><Name>x</Name> == <Num>7</Num></Compare>)</Call></Expr>
526.361 -
526.362 -# III
526.363 -<Assign><Name>x</Name> = <Num>7</Num></Assign>
526.364 -<FunctionDef>def f():
526.365 - <Assign><Name>x</Name> = <Num>1</Num></Assign>
526.366 - <FunctionDef>def g():
526.367 - <Global>global x</Global>
526.368 - <Assign><Name>x</Name> = <Num>2</Num></Assign>
526.369 - <FunctionDef>def i():
526.370 - <FunctionDef>def h():
526.371 - <Return>return <Name>x</Name></Return>
526.372 - </FunctionDef> <Return>return <Call><Name>h</Name>()</Call></Return>
526.373 - </FunctionDef> <Return>return <Call><Name>i</Name>()</Call></Return>
526.374 - </FunctionDef> <Return>return <Call><Name>g</Name>()</Call></Return>
526.375 -</FunctionDef><Expr><Call><Name>verify</Name>(<Compare><Call><Name>f</Name>()</Call> == <Num>2</Num></Compare>)</Call></Expr>
526.376 -<Expr><Call><Name>verify</Name>(<Compare><Name>x</Name> == <Num>2</Num></Compare>)</Call></Expr>
526.377 -
526.378 -# IV
526.379 -<Assign><Name>x</Name> = <Num>7</Num></Assign>
526.380 -<FunctionDef>def f():
526.381 - <Assign><Name>x</Name> = <Num>3</Num></Assign>
526.382 - <FunctionDef>def g():
526.383 - <Global>global x</Global>
526.384 - <Assign><Name>x</Name> = <Num>2</Num></Assign>
526.385 - <FunctionDef>def i():
526.386 - <FunctionDef>def h():
526.387 - <Return>return <Name>x</Name></Return>
526.388 - </FunctionDef> <Return>return <Call><Name>h</Name>()</Call></Return>
526.389 - </FunctionDef> <Return>return <Call><Name>i</Name>()</Call></Return>
526.390 - </FunctionDef> <Return>return <Call><Name>g</Name>()</Call></Return>
526.391 -</FunctionDef><Expr><Call><Name>verify</Name>(<Compare><Call><Name>f</Name>()</Call> == <Num>2</Num></Compare>)</Call></Expr>
526.392 -<Expr><Call><Name>verify</Name>(<Compare><Name>x</Name> == <Num>2</Num></Compare>)</Call></Expr>
526.393 -
526.394 -<Print>print <Str>"16. check leaks"</Str></Print>
526.395 -
526.396 -<ClassDef>class Foo:
526.397 - <Assign><Name>count</Name> = <Num>0</Num></Assign>
526.398 -
526.399 - <FunctionDef>def __init__(<Name>self</Name>):
526.400 - <AugAssign><Attribute><Name>Foo</Name>.count</Attribute> += <Num>1</Num></AugAssign>
526.401 -
526.402 - </FunctionDef> <FunctionDef>def __del__(<Name>self</Name>):
526.403 - <AugAssign><Attribute><Name>Foo</Name>.count</Attribute> -= <Num>1</Num></AugAssign>
526.404 -
526.405 -</FunctionDef></ClassDef><FunctionDef>def f1():
526.406 - <Assign><Name>x</Name> = <Call><Name>Foo</Name>()</Call></Assign>
526.407 - <FunctionDef>def f2():
526.408 - <Return>return <Name>x</Name></Return>
526.409 - </FunctionDef> <Expr><Call><Name>f2</Name>()</Call></Expr>
526.410 -
526.411 -</FunctionDef><For>for <Name>i</Name> in <Call><Name>range</Name>(<Num>100</Num>)</Call>:
526.412 - <Expr><Call><Name>f1</Name>()</Call></Expr>
526.413 -
526.414 -</For><Import>import os</Import>
526.415 -<If>if <Compare><Attribute><Name>os</Name>.name</Attribute> == <Str>'java'</Str></Compare>:
526.416 - <ImportFrom>from java.lang import System, Thread</ImportFrom>
526.417 - <Expr><Call><Attribute><Name>System</Name>.gc</Attribute>()</Call></Expr>
526.418 - <Expr><Call><Attribute><Name>Thread</Name>.sleep</Attribute>(<Num>100</Num>)</Call></Expr>
526.419 - <Expr><Call><Attribute><Name>System</Name>.gc</Attribute>()</Call></Expr>
526.420 -</If><Expr><Call><Name>verify</Name>(<Compare><Attribute><Name>Foo</Name>.count</Attribute> == <Num>0</Num></Compare>)</Call></Expr>
526.421 -
526.422 -<Print>print <Str>"17. class and global"</Str></Print>
526.423 -
526.424 -<FunctionDef>def test(<Name>x</Name>):
526.425 - <ClassDef>class Foo:
526.426 - <Global>global x</Global>
526.427 - <FunctionDef>def __call__(<Name>self</Name>, <Name>y</Name>):
526.428 - <Return>return <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Return>
526.429 - </FunctionDef></ClassDef> <Return>return <Call><Name>Foo</Name>()</Call></Return>
526.430 -
526.431 -</FunctionDef><Assign><Name>x</Name> = <Num>0</Num></Assign>
526.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>
526.433 -<Assign><Name>x</Name> = <Num>-1</Num></Assign>
526.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>
526.435 -
526.436 -<Print>print <Str>"18. verify that locals() works"</Str></Print>
526.437 -
526.438 -<FunctionDef>def f(<Name>x</Name>):
526.439 - <FunctionDef>def g(<Name>y</Name>):
526.440 - <FunctionDef>def h(<Name>z</Name>):
526.441 - <Return>return <BinOp><Name>y</Name> + <Name>z</Name></BinOp></Return>
526.442 - </FunctionDef> <Assign><Name>w</Name> = <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Assign>
526.443 - <AugAssign><Name>y</Name> += <Num>3</Num></AugAssign>
526.444 - <Return>return <Call><Name>locals</Name>()</Call></Return>
526.445 - </FunctionDef> <Return>return <Name>g</Name></Return>
526.446 -
526.447 -</FunctionDef><Assign><Name>d</Name> = <Call><Name>f</Name><Call>(<Num>2</Num>)</Call>(<Num>4</Num>)</Call></Assign>
526.448 -<Expr><Call><Name>verify</Name>(<Call><Attribute><Name>d</Name>.has_key</Attribute>(<Str>'h'</Str>)</Call>)</Call></Expr>
526.449 -<Delete>del <Subscript><Name>d</Name>[<Index><Str>'h'</Str></Index>]</Subscript></Delete>
526.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>
526.451 -
526.452 -<Print>print <Str>"19. var is bound and free in class"</Str></Print>
526.453 -
526.454 -<FunctionDef>def f(<Name>x</Name>):
526.455 - <ClassDef>class C:
526.456 - <FunctionDef>def m(<Name>self</Name>):
526.457 - <Return>return <Name>x</Name></Return>
526.458 - </FunctionDef> <Assign><Name>a</Name> = <Name>x</Name></Assign>
526.459 - </ClassDef> <Return>return <Name>C</Name></Return>
526.460 -
526.461 -</FunctionDef><Assign><Name>inst</Name> = <Call><Name>f</Name><Call>(<Num>3</Num>)</Call>()</Call></Assign>
526.462 -<Expr><Call><Name>verify</Name>(<Compare><Attribute><Name>inst</Name>.a</Attribute> == <Call><Attribute><Name>inst</Name>.m</Attribute>()</Call></Compare>)</Call></Expr>
526.463 -
526.464 -<Print>print <Str>"20. interaction with trace function"</Str></Print>
526.465 -
526.466 -<Import>import sys</Import>
526.467 -<FunctionDef>def tracer(<Name>a</Name>,<Name>b</Name>,<Name>c</Name>):
526.468 - <Return>return <Name>tracer</Name></Return>
526.469 -
526.470 -</FunctionDef><FunctionDef>def adaptgetter(<Name>name</Name>, <Name>klass</Name>, <Name>getter</Name>):
526.471 - <Assign><Tuple><Name>kind</Name>, <Name>des</Name></Tuple> = <Name>getter</Name></Assign>
526.472 - <If>if <Compare><Name>kind</Name> == <Num>1</Num></Compare>: # AV happens when stepping from this line to next
526.473 - <If>if <Compare><Name>des</Name> == <Str>""</Str></Compare>:
526.474 - <Assign><Name>des</Name> = <BinOp><Str>"_%s__%s"</Str> % <Tuple>(<Attribute><Name>klass</Name>.__name__</Attribute>, <Name>name</Name>)</Tuple></BinOp></Assign>
526.475 - </If> <Return>return <Lambda>lambda <Name>obj</Name>: <Call><Name>getattr</Name>(<Name>obj</Name>, <Name>des</Name>)</Call></Lambda></Return>
526.476 -
526.477 -</If></FunctionDef><ClassDef>class TestClass:
526.478 - <Pass>pass</Pass>
526.479 -
526.480 -</ClassDef><Expr><Call><Attribute><Name>sys</Name>.settrace</Attribute>(<Name>tracer</Name>)</Call></Expr>
526.481 -<Expr><Call><Name>adaptgetter</Name>(<Str>"foo"</Str>, <Name>TestClass</Name>, <Tuple>(<Num>1</Num>, <Str>""</Str>)</Tuple>)</Call></Expr>
526.482 -<Expr><Call><Attribute><Name>sys</Name>.settrace</Attribute>(<Name>None</Name>)</Call></Expr>
526.483 -
526.484 -<TryExcept>try: <Expr><Call><Attribute><Name>sys</Name>.settrace</Attribute>()</Call></Expr>
526.485 -<ExceptHandler>except <Name>TypeError</Name>: <Pass>pass</Pass>
526.486 -</ExceptHandler>else: <Raise>raise <Name>TestFailed</Name>, <Str>'sys.settrace() did not raise TypeError'</Str></Raise>
526.487 -
526.488 -</TryExcept><Print>print <Str>"20. eval and exec with free variables"</Str></Print>
526.489 -
526.490 -<FunctionDef>def f(<Name>x</Name>):
526.491 - <Return>return <Lambda>lambda: <BinOp><Name>x</Name> + <Num>1</Num></BinOp></Lambda></Return>
526.492 -
526.493 -</FunctionDef><Assign><Name>g</Name> = <Call><Name>f</Name>(<Num>3</Num>)</Call></Assign>
526.494 -<TryExcept>try:
526.495 - <Expr><Call><Name>eval</Name>(<Attribute><Name>g</Name>.func_code</Attribute>)</Call></Expr>
526.496 -<ExceptHandler>except <Name>TypeError</Name>:
526.497 - <Pass>pass</Pass>
526.498 -</ExceptHandler>else:
526.499 - <Print>print <Str>"eval() should have failed, because code contained free vars"</Str></Print>
526.500 -
526.501 -</TryExcept><TryExcept>try:
526.502 - <Exec>exec <Attribute><Name>g</Name>.func_code</Attribute></Exec>
526.503 -<ExceptHandler>except <Name>TypeError</Name>:
526.504 - <Pass>pass</Pass>
526.505 -</ExceptHandler>else:
526.506 - <Print>print <Str>"exec should have failed, because code contained free vars"</Str></Print>
526.507 -
526.508 -</TryExcept><Print>print <Str>"21. list comprehension with local variables"</Str></Print>
526.509 -
526.510 -<TryExcept>try:
526.511 - <Print>print <Name>bad</Name></Print>
526.512 -<ExceptHandler>except <Name>NameError</Name>:
526.513 - <Pass>pass</Pass>
526.514 -</ExceptHandler>else:
526.515 - <Print>print <Str>"bad should not be defined"</Str></Print>
526.516 -
526.517 -</TryExcept><FunctionDef>def x():
526.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>
526.519 -
526.520 -</FunctionDef><Expr><Call><Name>x</Name>()</Call></Expr>
526.521 -<TryExcept>try:
526.522 - <Print>print <Name>bad</Name></Print>
526.523 -<ExceptHandler>except <Name>NameError</Name>:
526.524 - <Pass>pass</Pass>
526.525 -
526.526 -</ExceptHandler></TryExcept><Print>print <Str>"22. eval with free variables"</Str></Print>
526.527 -
526.528 -<FunctionDef>def f(<Name>x</Name>):
526.529 - <FunctionDef>def g():
526.530 - <Expr><Name>x</Name></Expr>
526.531 - <Expr><Call><Name>eval</Name>(<Str>"x + 1"</Str>)</Call></Expr>
526.532 - </FunctionDef> <Return>return <Name>g</Name></Return>
526.533 -
526.534 -</FunctionDef><Expr><Call><Name>f</Name><Call>(<Num>4</Num>)</Call>()</Call></Expr></Module>
527.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.semantic Sun Jan 04 13:11:53 2015 -0600
527.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
527.3 @@ -1,530 +0,0 @@
527.4 -from test_support import verify, TestFailed, check_syntax
527.5 -
527.6 -import warnings
527.7 -warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>")
527.8 -
527.9 -print "1. simple nesting"
527.10 -
527.11 -def |>METHOD:make_adder<|(|>PARAMETER:x<|):
527.12 - def |>METHOD:adder<|(|>PARAMETER:y<|):
527.13 - return x + |>PARAMETER:y<|
527.14 - return adder
527.15 -
527.16 -inc = make_adder(1)
527.17 -plus10 = make_adder(10)
527.18 -
527.19 -verify(inc(1) == 2)
527.20 -verify(plus10(-2) == 8)
527.21 -
527.22 -print "2. extra nesting"
527.23 -
527.24 -def |>METHOD:make_adder2<|(|>PARAMETER:x<|):
527.25 - def |>METHOD:extra<|(): # check freevars passing through non-use scopes
527.26 - def |>METHOD:adder<|(|>PARAMETER:y<|):
527.27 - return x + |>PARAMETER:y<|
527.28 - return adder
527.29 - return extra()
527.30 -
527.31 -inc = make_adder2(1)
527.32 -plus10 = make_adder2(10)
527.33 -
527.34 -verify(inc(1) == 2)
527.35 -verify(plus10(-2) == 8)
527.36 -
527.37 -print "3. simple nesting + rebinding"
527.38 -
527.39 -def |>METHOD:make_adder3<|(|>PARAMETER:x<|):
527.40 - def |>METHOD:adder<|(|>PARAMETER:y<|):
527.41 - return x + |>PARAMETER:y<|
527.42 - |>PARAMETER:x<| = |>PARAMETER:x<| + 1 # check tracking of assignment to x in defining scope
527.43 - return adder
527.44 -
527.45 -inc = make_adder3(0)
527.46 -plus10 = make_adder3(9)
527.47 -
527.48 -verify(inc(1) == 2)
527.49 -verify(plus10(-2) == 8)
527.50 -
527.51 -print "4. nesting with global but no free"
527.52 -
527.53 -def |>METHOD:make_adder4<|(): # XXX add exta level of indirection
527.54 - def |>METHOD:nest<|():
527.55 - def |>METHOD:nest<|():
527.56 - def |>METHOD:adder<|(|>PARAMETER:y<|):
527.57 - return global_x + |>PARAMETER:y<| # check that plain old globals work
527.58 - return adder
527.59 - return nest()
527.60 - return nest()
527.61 -
527.62 -global_x = 1
527.63 -adder = make_adder4()
527.64 -verify(adder(1) == 2)
527.65 -
527.66 -global_x = 10
527.67 -verify(adder(-2) == 8)
527.68 -
527.69 -print "5. nesting through class"
527.70 -
527.71 -def |>METHOD:make_adder5<|(|>PARAMETER:x<|):
527.72 - class Adder:
527.73 - def |>METHOD:__call__<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER:y<|):
527.74 - return x + |>PARAMETER:y<|
527.75 - return Adder()
527.76 -
527.77 -inc = make_adder5(1)
527.78 -plus10 = make_adder5(10)
527.79 -
527.80 -verify(inc(1) == 2)
527.81 -verify(plus10(-2) == 8)
527.82 -
527.83 -print "6. nesting plus free ref to global"
527.84 -
527.85 -def |>METHOD:make_adder6<|(|>PARAMETER:x<|):
527.86 - global global_nest_x
527.87 - def |>METHOD:adder<|(|>PARAMETER:y<|):
527.88 - return global_nest_x + |>PARAMETER:y<|
527.89 - global_nest_x = |>PARAMETER:x<|
527.90 - return adder
527.91 -
527.92 -inc = make_adder6(1)
527.93 -plus10 = make_adder6(10)
527.94 -
527.95 -verify(inc(1) == 11) # there's only one global
527.96 -verify(plus10(-2) == 8)
527.97 -
527.98 -print "7. nearest enclosing scope"
527.99 -
527.100 -def |>METHOD:f<|(|>PARAMETER,UNUSED:x<|):
527.101 - def |>METHOD:g<|(|>PARAMETER,UNUSED:y<|):
527.102 - x = 42 # check that this masks binding in f()
527.103 - def |>METHOD:h<|(|>PARAMETER:z<|):
527.104 - return x + |>PARAMETER:z<|
527.105 - return h
527.106 - return g(2)
527.107 -
527.108 -test_func = f(10)
527.109 -verify(test_func(5) == 47)
527.110 -
527.111 -print "8. mixed freevars and cellvars"
527.112 -
527.113 -def |>METHOD:identity<|(|>PARAMETER:x<|):
527.114 - return |>PARAMETER:x<|
527.115 -
527.116 -def |>METHOD:f<|(|>PARAMETER:x<|, |>PARAMETER,UNUSED:y<|, |>PARAMETER:z<|):
527.117 - def |>METHOD:g<|(|>PARAMETER:a<|, |>PARAMETER:b<|, |>PARAMETER:c<|):
527.118 - |>PARAMETER:a<| = |>PARAMETER:a<| + x # 3
527.119 - def |>METHOD:h<|():
527.120 - # z * (4 + 9)
527.121 - # 3 * 13
527.122 - return identity(z * (b + y))
527.123 - |>UNUSED:y<| = |>PARAMETER:c<| + z # 9
527.124 - return h
527.125 - return g
527.126 -
527.127 -g = f(1, 2, 3)
527.128 -h = g(2, 4, 6)
527.129 -verify(h() == 39)
527.130 -
527.131 -print "9. free variable in method"
527.132 -
527.133 -def |>METHOD:test<|():
527.134 - method_and_var = "var"
527.135 - class Test:
527.136 - def |>METHOD:method_and_var<|(|>PARAMETER,UNUSED:self<|):
527.137 - return "method"
527.138 - def |>METHOD:test<|(|>PARAMETER,UNUSED:self<|):
527.139 - return method_and_var
527.140 - def |>METHOD:actual_global<|(|>PARAMETER,UNUSED:self<|):
527.141 - return str("global")
527.142 - def |>METHOD:str<|(|>PARAMETER:self<|):
527.143 - return str(|>PARAMETER:self<|)
527.144 - return Test()
527.145 -
527.146 -t = test()
527.147 -verify(t.test() == "var")
527.148 -verify(t.method_and_var() == "method")
527.149 -verify(t.actual_global() == "global")
527.150 -
527.151 -method_and_var = "var"
527.152 -class Test:
527.153 - # this class is not nested, so the rules are different
527.154 - def |>METHOD:method_and_var<|(|>PARAMETER,UNUSED:self<|):
527.155 - return "method"
527.156 - def |>METHOD:test<|(|>PARAMETER,UNUSED:self<|):
527.157 - return method_and_var
527.158 - def |>METHOD:actual_global<|(|>PARAMETER,UNUSED:self<|):
527.159 - return str("global")
527.160 - def |>METHOD:str<|(|>PARAMETER:self<|):
527.161 - return str(|>PARAMETER:self<|)
527.162 -
527.163 -t = Test()
527.164 -verify(t.test() == "var")
527.165 -verify(t.method_and_var() == "method")
527.166 -verify(t.actual_global() == "global")
527.167 -
527.168 -print "10. recursion"
527.169 -
527.170 -def |>METHOD:f<|(|>PARAMETER:x<|):
527.171 - def |>METHOD:fact<|(|>PARAMETER:n<|):
527.172 - if |>PARAMETER:n<| == 0:
527.173 - return 1
527.174 - else:
527.175 - return |>PARAMETER:n<| * fact(|>PARAMETER:n<| - 1)
527.176 - if |>PARAMETER:x<| >= 0:
527.177 - return fact(|>PARAMETER:x<|)
527.178 - else:
527.179 - raise ValueError, "x must be >= 0"
527.180 -
527.181 -verify(f(6) == 720)
527.182 -
527.183 -
527.184 -print "11. unoptimized namespaces"
527.185 -
527.186 -check_syntax("""\
527.187 -def unoptimized_clash1(strip):
527.188 - def f(s):
527.189 - from string import *
527.190 - return strip(s) # ambiguity: free or local
527.191 - return f
527.192 -""")
527.193 -
527.194 -check_syntax("""\
527.195 -def unoptimized_clash2():
527.196 - from string import *
527.197 - def f(s):
527.198 - return strip(s) # ambiguity: global or local
527.199 - return f
527.200 -""")
527.201 -
527.202 -check_syntax("""\
527.203 -def unoptimized_clash2():
527.204 - from string import *
527.205 - def g():
527.206 - def f(s):
527.207 - return strip(s) # ambiguity: global or local
527.208 - return f
527.209 -""")
527.210 -
527.211 -# XXX could allow this for exec with const argument, but what's the point
527.212 -check_syntax("""\
527.213 -def error(y):
527.214 - exec "a = 1"
527.215 - def f(x):
527.216 - return x + y
527.217 - return f
527.218 -""")
527.219 -
527.220 -check_syntax("""\
527.221 -def f(x):
527.222 - def g():
527.223 - return x
527.224 - del x # can't del name
527.225 -""")
527.226 -
527.227 -check_syntax("""\
527.228 -def f():
527.229 - def g():
527.230 - from string import *
527.231 - return strip # global or local?
527.232 -""")
527.233 -
527.234 -# and verify a few cases that should work
527.235 -
527.236 -exec """
527.237 -def noproblem1():
527.238 - from string import *
527.239 - f = lambda x:x
527.240 -
527.241 -def noproblem2():
527.242 - from string import *
527.243 - def f(x):
527.244 - return x + 1
527.245 -
527.246 -def noproblem3():
527.247 - from string import *
527.248 - def f(x):
527.249 - global y
527.250 - y = x
527.251 -"""
527.252 -
527.253 -print "12. lambdas"
527.254 -
527.255 -f1 = lambda x: lambda y: x + y
527.256 -inc = f1(1)
527.257 -plus10 = f1(10)
527.258 -verify(inc(1) == 2)
527.259 -verify(plus10(5) == 15)
527.260 -
527.261 -f2 = lambda x: (lambda : lambda y: x + y)()
527.262 -inc = f2(1)
527.263 -plus10 = f2(10)
527.264 -verify(inc(1) == 2)
527.265 -verify(plus10(5) == 15)
527.266 -
527.267 -f3 = lambda x: lambda y: global_x + y
527.268 -global_x = 1
527.269 -inc = f3(None)
527.270 -verify(inc(2) == 3)
527.271 -
527.272 -f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y)
527.273 -g = f8(1, 2, 3)
527.274 -h = g(2, 4, 6)
527.275 -verify(h() == 18)
527.276 -
527.277 -print "13. UnboundLocal"
527.278 -
527.279 -def |>METHOD:errorInOuter<|():
527.280 - print y
527.281 - def |>METHOD:inner<|():
527.282 - return y
527.283 - y = 1
527.284 -
527.285 -def |>METHOD:errorInInner<|():
527.286 - def |>METHOD:inner<|():
527.287 - return y
527.288 - inner()
527.289 - |>UNUSED:y<| = 1
527.290 -
527.291 -try:
527.292 - errorInOuter()
527.293 -except UnboundLocalError:
527.294 - pass
527.295 -else:
527.296 - raise TestFailed
527.297 -
527.298 -try:
527.299 - errorInInner()
527.300 -except NameError:
527.301 - pass
527.302 -else:
527.303 - raise TestFailed
527.304 -
527.305 -print "14. complex definitions"
527.306 -
527.307 -def |>METHOD:makeReturner<|(*lst):
527.308 - def |>METHOD:returner<|():
527.309 - return lst
527.310 - return returner
527.311 -
527.312 -verify(makeReturner(1,2,3)() == (1,2,3))
527.313 -
527.314 -def |>METHOD:makeReturner2<|(**kwargs):
527.315 - def |>METHOD:returner<|():
527.316 - return kwargs
527.317 - return returner
527.318 -
527.319 -verify(makeReturner2(a=11)()['a'] == 11)
527.320 -
527.321 -def |>METHOD:makeAddPair<|((|>PARAMETER:a<|, |>PARAMETER:b<|)):
527.322 - def |>METHOD:addPair<|((|>PARAMETER:c<|, |>PARAMETER:d<|)):
527.323 - return (a + |>PARAMETER:c<|, b + |>PARAMETER:d<|)
527.324 - return addPair
527.325 -
527.326 -verify(makeAddPair((1, 2))((100, 200)) == (101,202))
527.327 -
527.328 -print "15. scope of global statements"
527.329 -# Examples posted by Samuele Pedroni to python-dev on 3/1/2001
527.330 -
527.331 -# I
527.332 -x = 7
527.333 -def |>METHOD:f<|():
527.334 - |>UNUSED:x<| = 1
527.335 - def |>METHOD:g<|():
527.336 - global x
527.337 - def |>METHOD:i<|():
527.338 - def |>METHOD:h<|():
527.339 - return x
527.340 - return h()
527.341 - return i()
527.342 - return g()
527.343 -verify(f() == 7)
527.344 -verify(x == 7)
527.345 -
527.346 -# II
527.347 -x = 7
527.348 -def |>METHOD:f<|():
527.349 - |>UNUSED:x<| = 1
527.350 - def |>METHOD:g<|():
527.351 - x = 2
527.352 - def |>METHOD:i<|():
527.353 - def |>METHOD:h<|():
527.354 - return x
527.355 - return h()
527.356 - return i()
527.357 - return g()
527.358 -verify(f() == 2)
527.359 -verify(x == 7)
527.360 -
527.361 -# III
527.362 -x = 7
527.363 -def |>METHOD:f<|():
527.364 - |>UNUSED:x<| = 1
527.365 - def |>METHOD:g<|():
527.366 - global x
527.367 - x = 2
527.368 - def |>METHOD:i<|():
527.369 - def |>METHOD:h<|():
527.370 - return x
527.371 - return h()
527.372 - return i()
527.373 - return g()
527.374 -verify(f() == 2)
527.375 -verify(x == 2)
527.376 -
527.377 -# IV
527.378 -x = 7
527.379 -def |>METHOD:f<|():
527.380 - |>UNUSED:x<| = 3
527.381 - def |>METHOD:g<|():
527.382 - global x
527.383 - x = 2
527.384 - def |>METHOD:i<|():
527.385 - def |>METHOD:h<|():
527.386 - return x
527.387 - return h()
527.388 - return i()
527.389 - return g()
527.390 -verify(f() == 2)
527.391 -verify(x == 2)
527.392 -
527.393 -print "16. check leaks"
527.394 -
527.395 -class Foo:
527.396 - count = 0
527.397 -
527.398 - def |>METHOD:__init__<|(|>PARAMETER,UNUSED:self<|):
527.399 - Foo.count += 1
527.400 -
527.401 - def |>METHOD:__del__<|(|>PARAMETER,UNUSED:self<|):
527.402 - Foo.count -= 1
527.403 -
527.404 -def |>METHOD:f1<|():
527.405 - x = Foo()
527.406 - def |>METHOD:f2<|():
527.407 - return x
527.408 - f2()
527.409 -
527.410 -for i in range(100):
527.411 - f1()
527.412 -
527.413 -import os
527.414 -if os.name == 'java':
527.415 - from java.lang import System, Thread
527.416 - System.gc()
527.417 - Thread.sleep(100)
527.418 - System.gc()
527.419 -verify(Foo.count == 0)
527.420 -
527.421 -print "17. class and global"
527.422 -
527.423 -def |>METHOD:test<|(|>PARAMETER:x<|):
527.424 - class Foo:
527.425 - global x
527.426 - def |>METHOD:__call__<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER:y<|):
527.427 - return x + |>PARAMETER:y<|
527.428 - return Foo()
527.429 -
527.430 -x = 0
527.431 -verify(test(6)(2) == 8)
527.432 -x = -1
527.433 -verify(test(3)(2) == 5)
527.434 -
527.435 -print "18. verify that locals() works"
527.436 -
527.437 -def |>METHOD:f<|(|>PARAMETER:x<|):
527.438 - def |>METHOD:g<|(|>PARAMETER:y<|):
527.439 - def |>METHOD:h<|(|>PARAMETER:z<|):
527.440 - return y + |>PARAMETER:z<|
527.441 - |>UNUSED:w<| = x + |>PARAMETER:y<|
527.442 - |>PARAMETER:y<| += 3
527.443 - return locals()
527.444 - return g
527.445 -
527.446 -d = f(2)(4)
527.447 -verify(d.has_key('h'))
527.448 -del d['h']
527.449 -verify(d == {'x': 2, 'y': 7, 'w': 6})
527.450 -
527.451 -print "19. var is bound and free in class"
527.452 -
527.453 -def |>METHOD:f<|(|>PARAMETER:x<|):
527.454 - class C:
527.455 - def |>METHOD:m<|(|>PARAMETER,UNUSED:self<|):
527.456 - return x
527.457 - a = x
527.458 - return C
527.459 -
527.460 -inst = f(3)()
527.461 -verify(inst.a == inst.m())
527.462 -
527.463 -print "20. interaction with trace function"
527.464 -
527.465 -import sys
527.466 -def |>METHOD:tracer<|(|>PARAMETER,UNUSED:a<|,|>PARAMETER,UNUSED:b<|,|>PARAMETER,UNUSED:c<|):
527.467 - return tracer
527.468 -
527.469 -def |>METHOD:adaptgetter<|(|>PARAMETER:name<|, |>PARAMETER:klass<|, |>PARAMETER:getter<|):
527.470 - kind, des = |>PARAMETER:getter<|
527.471 - if kind == 1: # AV happens when stepping from this line to next
527.472 - if des == "":
527.473 - des = "_%s__%s" % (|>PARAMETER:klass<|.__name__, |>PARAMETER:name<|)
527.474 - return lambda obj: getattr(obj, des)
527.475 -
527.476 -class TestClass:
527.477 - pass
527.478 -
527.479 -sys.settrace(tracer)
527.480 -adaptgetter("foo", TestClass, (1, ""))
527.481 -sys.settrace(None)
527.482 -
527.483 -try: sys.settrace()
527.484 -except TypeError: pass
527.485 -else: raise TestFailed, 'sys.settrace() did not raise TypeError'
527.486 -
527.487 -print "20. eval and exec with free variables"
527.488 -
527.489 -def |>METHOD:f<|(|>PARAMETER:x<|):
527.490 - return lambda: |>PARAMETER:x<| + 1
527.491 -
527.492 -g = f(3)
527.493 -try:
527.494 - eval(g.func_code)
527.495 -except TypeError:
527.496 - pass
527.497 -else:
527.498 - print "eval() should have failed, because code contained free vars"
527.499 -
527.500 -try:
527.501 - exec g.func_code
527.502 -except TypeError:
527.503 - pass
527.504 -else:
527.505 - print "exec should have failed, because code contained free vars"
527.506 -
527.507 -print "21. list comprehension with local variables"
527.508 -
527.509 -try:
527.510 - print bad
527.511 -except NameError:
527.512 - pass
527.513 -else:
527.514 - print "bad should not be defined"
527.515 -
527.516 -def |>METHOD:x<|():
527.517 - [bad for s in 'a b' for bad in s.split()]
527.518 -
527.519 -x()
527.520 -try:
527.521 - print bad
527.522 -except NameError:
527.523 - pass
527.524 -
527.525 -print "22. eval with free variables"
527.526 -
527.527 -def |>METHOD:f<|(|>PARAMETER:x<|):
527.528 - def |>METHOD:g<|():
527.529 - x
527.530 - eval("x + 1")
527.531 - return g
527.532 -
527.533 -f(4)()
528.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.structure Sun Jan 04 13:11:53 2015 -0600
528.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
528.3 @@ -1,83 +0,0 @@
528.4 -make_adder:METHOD:[]:ESCAPED{make_adder}(PARAMETERS{ESCAPED{x}}):
528.5 - adder:METHOD:[]:ESCAPED{adder}(PARAMETERS{ESCAPED{y}}):
528.6 -make_adder2:METHOD:[]:ESCAPED{make_adder2}(PARAMETERS{ESCAPED{x}}):
528.7 - extra:METHOD:[]:ESCAPED{extra}:
528.8 - adder:METHOD:[]:ESCAPED{adder}(PARAMETERS{ESCAPED{y}}):
528.9 -make_adder3:METHOD:[]:ESCAPED{make_adder3}(PARAMETERS{ESCAPED{x}}):
528.10 - adder:METHOD:[]:ESCAPED{adder}(PARAMETERS{ESCAPED{y}}):
528.11 -make_adder4:METHOD:[]:ESCAPED{make_adder4}:
528.12 - nest:METHOD:[]:ESCAPED{nest}:
528.13 - nest:METHOD:[]:ESCAPED{nest}:
528.14 - adder:METHOD:[]:ESCAPED{adder}(PARAMETERS{ESCAPED{y}}):
528.15 -make_adder5:METHOD:[]:ESCAPED{make_adder5}(PARAMETERS{ESCAPED{x}}):
528.16 - Adder:CLASS:[]:ESCAPED{Adder}:
528.17 - __call__:METHOD:[]:ESCAPED{__call__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{y}}):
528.18 -make_adder6:METHOD:[]:ESCAPED{make_adder6}(PARAMETERS{ESCAPED{x}}):
528.19 - adder:METHOD:[]:ESCAPED{adder}(PARAMETERS{ESCAPED{y}}):
528.20 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}}):
528.21 - g:METHOD:[]:ESCAPED{g}(PARAMETERS{ESCAPED{y}}):
528.22 - h:METHOD:[]:ESCAPED{h}(PARAMETERS{ESCAPED{z}}):
528.23 -identity:METHOD:[]:ESCAPED{identity}(PARAMETERS{ESCAPED{x}}):
528.24 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}ESCAPED{,}ESCAPED{y}ESCAPED{,}ESCAPED{z}}):
528.25 - g:METHOD:[]:ESCAPED{g}(PARAMETERS{ESCAPED{a}ESCAPED{,}ESCAPED{b}ESCAPED{,}ESCAPED{c}}):
528.26 - h:METHOD:[]:ESCAPED{h}:
528.27 -test:METHOD:[]:ESCAPED{test}:
528.28 - Test:CLASS:[]:ESCAPED{Test}:
528.29 - actual_global:METHOD:[]:ESCAPED{actual_global}(PARAMETERS{ESCAPED{self}}):
528.30 - method_and_var:METHOD:[]:ESCAPED{method_and_var}(PARAMETERS{ESCAPED{self}}):
528.31 - str:METHOD:[]:ESCAPED{str}(PARAMETERS{ESCAPED{self}}):
528.32 - test:METHOD:[]:ESCAPED{test}(PARAMETERS{ESCAPED{self}}):
528.33 -Test:CLASS:[]:ESCAPED{Test}:
528.34 - actual_global:METHOD:[]:ESCAPED{actual_global}(PARAMETERS{ESCAPED{self}}):
528.35 - method_and_var:METHOD:[]:ESCAPED{method_and_var}(PARAMETERS{ESCAPED{self}}):
528.36 - str:METHOD:[]:ESCAPED{str}(PARAMETERS{ESCAPED{self}}):
528.37 - test:METHOD:[]:ESCAPED{test}(PARAMETERS{ESCAPED{self}}):
528.38 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}}):
528.39 - fact:METHOD:[]:ESCAPED{fact}(PARAMETERS{ESCAPED{n}}):
528.40 -errorInOuter:METHOD:[]:ESCAPED{errorInOuter}:
528.41 - inner:METHOD:[]:ESCAPED{inner}:
528.42 -errorInInner:METHOD:[]:ESCAPED{errorInInner}:
528.43 - inner:METHOD:[]:ESCAPED{inner}:
528.44 -makeReturner:METHOD:[]:ESCAPED{makeReturner}(PARAMETERS{ESCAPED{lst}}):
528.45 - returner:METHOD:[]:ESCAPED{returner}:
528.46 -makeReturner2:METHOD:[]:ESCAPED{makeReturner2}(PARAMETERS{ESCAPED{kwargs}}):
528.47 - returner:METHOD:[]:ESCAPED{returner}:
528.48 -makeAddPair:METHOD:[]:ESCAPED{makeAddPair}:
528.49 - addPair:METHOD:[]:ESCAPED{addPair}:
528.50 -f:METHOD:[]:ESCAPED{f}:
528.51 - g:METHOD:[]:ESCAPED{g}:
528.52 - i:METHOD:[]:ESCAPED{i}:
528.53 - h:METHOD:[]:ESCAPED{h}:
528.54 -f:METHOD:[]:ESCAPED{f}:
528.55 - g:METHOD:[]:ESCAPED{g}:
528.56 - i:METHOD:[]:ESCAPED{i}:
528.57 - h:METHOD:[]:ESCAPED{h}:
528.58 -f:METHOD:[]:ESCAPED{f}:
528.59 - g:METHOD:[]:ESCAPED{g}:
528.60 - i:METHOD:[]:ESCAPED{i}:
528.61 - h:METHOD:[]:ESCAPED{h}:
528.62 -f:METHOD:[]:ESCAPED{f}:
528.63 - g:METHOD:[]:ESCAPED{g}:
528.64 - i:METHOD:[]:ESCAPED{i}:
528.65 - h:METHOD:[]:ESCAPED{h}:
528.66 -Foo:CLASS:[]:ESCAPED{Foo}:
528.67 - __del__:METHOD:[]:ESCAPED{__del__}(PARAMETERS{ESCAPED{self}}):
528.68 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}}):
528.69 -f1:METHOD:[]:ESCAPED{f1}:
528.70 - f2:METHOD:[]:ESCAPED{f2}:
528.71 -test:METHOD:[]:ESCAPED{test}(PARAMETERS{ESCAPED{x}}):
528.72 - Foo:CLASS:[]:ESCAPED{Foo}:
528.73 - __call__:METHOD:[]:ESCAPED{__call__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{y}}):
528.74 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}}):
528.75 - g:METHOD:[]:ESCAPED{g}(PARAMETERS{ESCAPED{y}}):
528.76 - h:METHOD:[]:ESCAPED{h}(PARAMETERS{ESCAPED{z}}):
528.77 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}}):
528.78 - C:CLASS:[]:ESCAPED{C}:
528.79 - m:METHOD:[]:ESCAPED{m}(PARAMETERS{ESCAPED{self}}):
528.80 -tracer:METHOD:[]:ESCAPED{tracer}(PARAMETERS{ESCAPED{a}ESCAPED{,}ESCAPED{b}ESCAPED{,}ESCAPED{c}}):
528.81 -adaptgetter:METHOD:[]:ESCAPED{adaptgetter}(PARAMETERS{ESCAPED{name}ESCAPED{,}ESCAPED{klass}ESCAPED{,}ESCAPED{getter}}):
528.82 -TestClass:CLASS:[]:ESCAPED{TestClass}:
528.83 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}}):
528.84 -x:METHOD:[]:ESCAPED{x}:
528.85 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}}):
528.86 - g:METHOD:[]:ESCAPED{g}:
529.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.testHint6.hints Sun Jan 04 13:11:53 2015 -0600
529.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
529.3 @@ -1,36 +0,0 @@
529.4 -def errorInOuter():
529.5 - ------------
529.6 -HINT:Name "errorInOuter" is not a valid function name according to your code style (lowercase_with_underscores)
529.7 -FIX:Ignore name violations for "errorInOuter"
529.8 -FIX:Change preferred function name style to mixedCase
529.9 -FIX:Turn off function name style checks
529.10 -def errorInInner():
529.11 - ------------
529.12 -HINT:Name "errorInInner" is not a valid function name according to your code style (lowercase_with_underscores)
529.13 -FIX:Ignore name violations for "errorInInner"
529.14 -FIX:Change preferred function name style to mixedCase
529.15 -FIX:Turn off function name style checks
529.16 -def makeReturner(*lst):
529.17 - ------------
529.18 -HINT:Name "makeReturner" is not a valid function name according to your code style (lowercase_with_underscores)
529.19 -FIX:Ignore name violations for "makeReturner"
529.20 -FIX:Change preferred function name style to mixedCase
529.21 -FIX:Turn off function name style checks
529.22 -def makeReturner2(**kwargs):
529.23 - -------------
529.24 -HINT:Name "makeReturner2" is not a valid function name according to your code style (lowercase_with_underscores)
529.25 -FIX:Ignore name violations for "makeReturner2"
529.26 -FIX:Change preferred function name style to mixedCase
529.27 -FIX:Turn off function name style checks
529.28 -def makeAddPair((a, b)):
529.29 - -----------
529.30 -HINT:Name "makeAddPair" is not a valid function name according to your code style (lowercase_with_underscores)
529.31 -FIX:Ignore name violations for "makeAddPair"
529.32 -FIX:Change preferred function name style to mixedCase
529.33 -FIX:Turn off function name style checks
529.34 - def addPair((c, d)):
529.35 - -------
529.36 -HINT:Name "addPair" is not a valid function name according to your code style (lowercase_with_underscores)
529.37 -FIX:Ignore name violations for "addPair"
529.38 -FIX:Change preferred function name style to mixedCase
529.39 -FIX:Turn off function name style checks
530.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.testNoStringCompletion.completion Sun Jan 04 13:11:53 2015 -0600
530.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
530.3 @@ -1,3 +0,0 @@
530.4 -Code completion result for source line:
530.5 -warnings.filterwarnings("ignore", r"i|mport \*", SyntaxWarning, "<string>")
530.6 -(QueryType=COMPLETION, NameKind=PREFIX)
531.1 --- a/python.editor/test/unit/data/testfiles/tokenize.py Sun Jan 04 13:11:53 2015 -0600
531.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
531.3 @@ -1,345 +0,0 @@
531.4 -"""Tokenization help for Python programs.
531.5 -
531.6 -generate_tokens(readline) is a generator that breaks a stream of
531.7 -text into Python tokens. It accepts a readline-like method which is called
531.8 -repeatedly to get the next line of input (or "" for EOF). It generates
531.9 -5-tuples with these members:
531.10 -
531.11 - the token type (see token.py)
531.12 - the token (a string)
531.13 - the starting (row, column) indices of the token (a 2-tuple of ints)
531.14 - the ending (row, column) indices of the token (a 2-tuple of ints)
531.15 - the original line (string)
531.16 -
531.17 -It is designed to match the working of the Python tokenizer exactly, except
531.18 -that it produces COMMENT tokens for comments and gives type OP for all
531.19 -operators
531.20 -
531.21 -Older entry points
531.22 - tokenize_loop(readline, tokeneater)
531.23 - tokenize(readline, tokeneater=printtoken)
531.24 -are the same, except instead of generating tokens, tokeneater is a callback
531.25 -function to which the 5 fields described above are passed as 5 arguments,
531.26 -each time a new token is found."""
531.27 -
531.28 -__author__ = 'Ka-Ping Yee <ping@lfw.org>'
531.29 -__credits__ = \
531.30 - 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro'
531.31 -
531.32 -import string, re
531.33 -from token import *
531.34 -
531.35 -import token
531.36 -__all__ = [x for x in dir(token) if x[0] != '_'] + ["COMMENT", "tokenize",
531.37 - "generate_tokens", "NL", "untokenize"]
531.38 -del x
531.39 -del token
531.40 -
531.41 -COMMENT = N_TOKENS
531.42 -tok_name[COMMENT] = 'COMMENT'
531.43 -NL = N_TOKENS + 1
531.44 -tok_name[NL] = 'NL'
531.45 -N_TOKENS += 2
531.46 -
531.47 -def group(*choices): return '(' + '|'.join(choices) + ')'
531.48 -def any(*choices): return group(*choices) + '*'
531.49 -def maybe(*choices): return group(*choices) + '?'
531.50 -
531.51 -Whitespace = r'[ \f\t]*'
531.52 -Comment = r'#[^\r\n]*'
531.53 -Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
531.54 -Name = r'[a-zA-Z_]\w*'
531.55 -
531.56 -Hexnumber = r'0[xX][\da-fA-F]*[lL]?'
531.57 -Octnumber = r'0[0-7]*[lL]?'
531.58 -Decnumber = r'[1-9]\d*[lL]?'
531.59 -Intnumber = group(Hexnumber, Octnumber, Decnumber)
531.60 -Exponent = r'[eE][-+]?\d+'
531.61 -Pointfloat = group(r'\d+\.\d*', r'\.\d+') + maybe(Exponent)
531.62 -Expfloat = r'\d+' + Exponent
531.63 -Floatnumber = group(Pointfloat, Expfloat)
531.64 -Imagnumber = group(r'\d+[jJ]', Floatnumber + r'[jJ]')
531.65 -Number = group(Imagnumber, Floatnumber, Intnumber)
531.66 -
531.67 -# Tail end of ' string.
531.68 -Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
531.69 -# Tail end of " string.
531.70 -Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
531.71 -# Tail end of ''' string.
531.72 -Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
531.73 -# Tail end of """ string.
531.74 -Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
531.75 -Triple = group("[uU]?[rR]?'''", '[uU]?[rR]?"""')
531.76 -# Single-line ' or " string.
531.77 -String = group(r"[uU]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
531.78 - r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
531.79 -
531.80 -# Because of leftmost-then-longest match semantics, be sure to put the
531.81 -# longest operators first (e.g., if = came before ==, == would get
531.82 -# recognized as two instances of =).
531.83 -Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=",
531.84 - r"//=?",
531.85 - r"[+\-*/%&|^=<>]=?",
531.86 - r"~")
531.87 -
531.88 -Bracket = '[][(){}]'
531.89 -Special = group(r'\r?\n', r'[:;.,`@]')
531.90 -Funny = group(Operator, Bracket, Special)
531.91 -
531.92 -PlainToken = group(Number, Funny, String, Name)
531.93 -Token = Ignore + PlainToken
531.94 -
531.95 -# First (or only) line of ' or " string.
531.96 -ContStr = group(r"[uU]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
531.97 - group("'", r'\\\r?\n'),
531.98 - r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
531.99 - group('"', r'\\\r?\n'))
531.100 -PseudoExtras = group(r'\\\r?\n', Comment, Triple)
531.101 -PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
531.102 -
531.103 -tokenprog, pseudoprog, single3prog, double3prog = map(
531.104 - re.compile, (Token, PseudoToken, Single3, Double3))
531.105 -endprogs = {"'": re.compile(Single), '"': re.compile(Double),
531.106 - "'''": single3prog, '"""': double3prog,
531.107 - "r'''": single3prog, 'r"""': double3prog,
531.108 - "u'''": single3prog, 'u"""': double3prog,
531.109 - "ur'''": single3prog, 'ur"""': double3prog,
531.110 - "R'''": single3prog, 'R"""': double3prog,
531.111 - "U'''": single3prog, 'U"""': double3prog,
531.112 - "uR'''": single3prog, 'uR"""': double3prog,
531.113 - "Ur'''": single3prog, 'Ur"""': double3prog,
531.114 - "UR'''": single3prog, 'UR"""': double3prog,
531.115 - 'r': None, 'R': None, 'u': None, 'U': None}
531.116 -
531.117 -triple_quoted = {}
531.118 -for t in ("'''", '"""',
531.119 - "r'''", 'r"""', "R'''", 'R"""',
531.120 - "u'''", 'u"""', "U'''", 'U"""',
531.121 - "ur'''", 'ur"""', "Ur'''", 'Ur"""',
531.122 - "uR'''", 'uR"""', "UR'''", 'UR"""'):
531.123 - triple_quoted[t] = t
531.124 -single_quoted = {}
531.125 -for t in ("'", '"',
531.126 - "r'", 'r"', "R'", 'R"',
531.127 - "u'", 'u"', "U'", 'U"',
531.128 - "ur'", 'ur"', "Ur'", 'Ur"',
531.129 - "uR'", 'uR"', "UR'", 'UR"' ):
531.130 - single_quoted[t] = t
531.131 -
531.132 -tabsize = 8
531.133 -
531.134 -class TokenError(Exception): pass
531.135 -
531.136 -class StopTokenizing(Exception): pass
531.137 -
531.138 -def printtoken(type, token, (srow, scol), (erow, ecol), line): # for testing
531.139 - print "%d,%d-%d,%d:\t%s\t%s" % \
531.140 - (srow, scol, erow, ecol, tok_name[type], repr(token))
531.141 -
531.142 -def tokenize(readline, tokeneater=printtoken):
531.143 - """
531.144 - The tokenize() function accepts two parameters: one representing the
531.145 - input stream, and one providing an output mechanism for tokenize().
531.146 -
531.147 - The first parameter, readline, must be a callable object which provides
531.148 - the same interface as the readline() method of built-in file objects.
531.149 - Each call to the function should return one line of input as a string.
531.150 -
531.151 - The second parameter, tokeneater, must also be a callable object. It is
531.152 - called once for each token, with five arguments, corresponding to the
531.153 - tuples generated by generate_tokens().
531.154 - """
531.155 - try:
531.156 - tokenize_loop(readline, tokeneater)
531.157 - except StopTokenizing:
531.158 - pass
531.159 -
531.160 -# backwards compatible interface
531.161 -def tokenize_loop(readline, tokeneater):
531.162 - for token_info in generate_tokens(readline):
531.163 - tokeneater(*token_info)
531.164 -
531.165 -
531.166 -def untokenize(iterable):
531.167 - """Transform tokens back into Python source code.
531.168 -
531.169 - Each element returned by the iterable must be a token sequence
531.170 - with at least two elements, a token number and token value.
531.171 -
531.172 - Round-trip invariant:
531.173 - # Output text will tokenize the back to the input
531.174 - t1 = [tok[:2] for tok in generate_tokens(f.readline)]
531.175 - newcode = untokenize(t1)
531.176 - readline = iter(newcode.splitlines(1)).next
531.177 - t2 = [tok[:2] for tokin generate_tokens(readline)]
531.178 - assert t1 == t2
531.179 - """
531.180 -
531.181 - startline = False
531.182 - indents = []
531.183 - toks = []
531.184 - toks_append = toks.append
531.185 - for tok in iterable:
531.186 - toknum, tokval = tok[:2]
531.187 -
531.188 - if toknum in (NAME, NUMBER):
531.189 - tokval += ' '
531.190 -
531.191 - if toknum == INDENT:
531.192 - indents.append(tokval)
531.193 - continue
531.194 - elif toknum == DEDENT:
531.195 - indents.pop()
531.196 - continue
531.197 - elif toknum in (NEWLINE, COMMENT, NL):
531.198 - startline = True
531.199 - elif startline and indents:
531.200 - toks_append(indents[-1])
531.201 - startline = False
531.202 - toks_append(tokval)
531.203 - return ''.join(toks)
531.204 -
531.205 -
531.206 -def generate_tokens(readline):
531.207 - """
531.208 - The generate_tokens() generator requires one argment, readline, which
531.209 - must be a callable object which provides the same interface as the
531.210 - readline() method of built-in file objects. Each call to the function
531.211 - should return one line of input as a string. Alternately, readline
531.212 - can be a callable function terminating with StopIteration:
531.213 - readline = open(myfile).next # Example of alternate readline
531.214 -
531.215 - The generator produces 5-tuples with these members: the token type; the
531.216 - token string; a 2-tuple (srow, scol) of ints specifying the row and
531.217 - column where the token begins in the source; a 2-tuple (erow, ecol) of
531.218 - ints specifying the row and column where the token ends in the source;
531.219 - and the line on which the token was found. The line passed is the
531.220 - logical line; continuation lines are included.
531.221 - """
531.222 - lnum = parenlev = continued = 0
531.223 - namechars, numchars = string.ascii_letters + '_', '0123456789'
531.224 - contstr, needcont = '', 0
531.225 - contline = None
531.226 - indents = [0]
531.227 -
531.228 - while 1: # loop over lines in stream
531.229 - try:
531.230 - line = readline()
531.231 - except StopIteration:
531.232 - line = ''
531.233 - lnum = lnum + 1
531.234 - pos, max = 0, len(line)
531.235 -
531.236 - if contstr: # continued string
531.237 - if not line:
531.238 - raise TokenError, ("EOF in multi-line string", strstart)
531.239 - endmatch = endprog.match(line)
531.240 - if endmatch:
531.241 - pos = end = endmatch.end(0)
531.242 - yield (STRING, contstr + line[:end],
531.243 - strstart, (lnum, end), contline + line)
531.244 - contstr, needcont = '', 0
531.245 - contline = None
531.246 - elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
531.247 - yield (ERRORTOKEN, contstr + line,
531.248 - strstart, (lnum, len(line)), contline)
531.249 - contstr = ''
531.250 - contline = None
531.251 - continue
531.252 - else:
531.253 - contstr = contstr + line
531.254 - contline = contline + line
531.255 - continue
531.256 -
531.257 - elif parenlev == 0 and not continued: # new statement
531.258 - if not line: break
531.259 - column = 0
531.260 - while pos < max: # measure leading whitespace
531.261 - if line[pos] == ' ': column = column + 1
531.262 - elif line[pos] == '\t': column = (column/tabsize + 1)*tabsize
531.263 - elif line[pos] == '\f': column = 0
531.264 - else: break
531.265 - pos = pos + 1
531.266 - if pos == max: break
531.267 -
531.268 - if line[pos] in '#\r\n': # skip comments or blank lines
531.269 - yield ((NL, COMMENT)[line[pos] == '#'], line[pos:],
531.270 - (lnum, pos), (lnum, len(line)), line)
531.271 - continue
531.272 -
531.273 - if column > indents[-1]: # count indents or dedents
531.274 - indents.append(column)
531.275 - yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
531.276 - while column < indents[-1]:
531.277 - if column not in indents:
531.278 - raise IndentationError(
531.279 - "unindent does not match any outer indentation level",
531.280 - ("<tokenize>", lnum, pos, line))
531.281 - indents = indents[:-1]
531.282 - yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
531.283 -
531.284 - else: # continued statement
531.285 - if not line:
531.286 - raise TokenError, ("EOF in multi-line statement", (lnum, 0))
531.287 - continued = 0
531.288 -
531.289 - while pos < max:
531.290 - pseudomatch = pseudoprog.match(line, pos)
531.291 - if pseudomatch: # scan for tokens
531.292 - start, end = pseudomatch.span(1)
531.293 - spos, epos, pos = (lnum, start), (lnum, end), end
531.294 - token, initial = line[start:end], line[start]
531.295 -
531.296 - if initial in numchars or \
531.297 - (initial == '.' and token != '.'): # ordinary number
531.298 - yield (NUMBER, token, spos, epos, line)
531.299 - elif initial in '\r\n':
531.300 - yield (parenlev > 0 and NL or NEWLINE,
531.301 - token, spos, epos, line)
531.302 - elif initial == '#':
531.303 - yield (COMMENT, token, spos, epos, line)
531.304 - elif token in triple_quoted:
531.305 - endprog = endprogs[token]
531.306 - endmatch = endprog.match(line, pos)
531.307 - if endmatch: # all on one line
531.308 - pos = endmatch.end(0)
531.309 - token = line[start:pos]
531.310 - yield (STRING, token, spos, (lnum, pos), line)
531.311 - else:
531.312 - strstart = (lnum, start) # multiple lines
531.313 - contstr = line[start:]
531.314 - contline = line
531.315 - break
531.316 - elif initial in single_quoted or \
531.317 - token[:2] in single_quoted or \
531.318 - token[:3] in single_quoted:
531.319 - if token[-1] == '\n': # continued string
531.320 - strstart = (lnum, start)
531.321 - endprog = (endprogs[initial] or endprogs[token[1]] or
531.322 - endprogs[token[2]])
531.323 - contstr, needcont = line[start:], 1
531.324 - contline = line
531.325 - break
531.326 - else: # ordinary string
531.327 - yield (STRING, token, spos, epos, line)
531.328 - elif initial in namechars: # ordinary name
531.329 - yield (NAME, token, spos, epos, line)
531.330 - elif initial == '\\': # continued stmt
531.331 - continued = 1
531.332 - else:
531.333 - if initial in '([{': parenlev = parenlev + 1
531.334 - elif initial in ')]}': parenlev = parenlev - 1
531.335 - yield (OP, token, spos, epos, line)
531.336 - else:
531.337 - yield (ERRORTOKEN, line[pos],
531.338 - (lnum, pos), (lnum, pos+1), line)
531.339 - pos = pos + 1
531.340 -
531.341 - for indent in indents[1:]: # pop remaining indent levels
531.342 - yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
531.343 - yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
531.344 -
531.345 -if __name__ == '__main__': # testing
531.346 - import sys
531.347 - if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline)
531.348 - else: tokenize(sys.stdin.readline)
532.1 --- a/python.editor/test/unit/data/testfiles/tokenize.py.scopes Sun Jan 04 13:11:53 2015 -0600
532.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
532.3 @@ -1,190 +0,0 @@
532.4 -=============================================
532.5 -<file-top>: Module : OffsetRange[0,13553>
532.6 -* [bound][imported][data][node=ImportFrom]
532.7 -Bracket [bound][data][read][node=Name]
532.8 -COMMENT [bound][data][read][node=Name]
532.9 -Comment [bound][data][read][node=Name]
532.10 -ContStr [bound][data][read][node=Name]
532.11 -Decnumber [bound][data][read][node=Name]
532.12 -Double [bound][data][read][node=Name]
532.13 -Double3 [bound][data][read][node=Name]
532.14 -Exception [read][UNRESOLVED][node=Name]
532.15 -Expfloat [bound][data][read][node=Name]
532.16 -Exponent [bound][data][read][node=Name]
532.17 -Floatnumber [bound][data][read][node=Name]
532.18 -Funny [bound][data][read][node=Name]
532.19 -Hexnumber [bound][data][read][node=Name]
532.20 -Ignore [bound][data][read][node=Name]
532.21 -Imagnumber [bound][data][read][node=Name]
532.22 -Intnumber [bound][data][read][node=Name]
532.23 -NL [bound][data][read][node=Name]
532.24 -N_TOKENS [bound][data][read][node=Name]
532.25 -Name [bound][data][read][node=Name]
532.26 -None [read][UNRESOLVED][node=Name]
532.27 -Number [bound][data][read][node=Name]
532.28 -Octnumber [bound][data][read][node=Name]
532.29 -Operator [bound][data][read][node=Name]
532.30 -PlainToken [bound][data][read][node=Name]
532.31 -Pointfloat [bound][data][read][node=Name]
532.32 -PseudoExtras [bound][data][read][node=Name]
532.33 -PseudoToken [bound][data][read][node=Name]
532.34 -Single [bound][data][read][node=Name]
532.35 -Single3 [bound][data][read][node=Name]
532.36 -Special [bound][data][read][node=Name]
532.37 -StopTokenizing [bound][class][def][read][node=ClassDef]
532.38 -String [bound][data][read][node=Name]
532.39 -Token [bound][data][read][node=Name]
532.40 -TokenError [bound][class][def][read][node=ClassDef]
532.41 -Triple [bound][data][read][node=Name]
532.42 -Whitespace [bound][data][read][node=Name]
532.43 -_[33_11] [bound][private][data][node=ListComp]
532.44 -__all__ [bound][data][node=Name]
532.45 -__author__ [bound][data][node=Name]
532.46 -__credits__ [bound][data][node=Name]
532.47 -__name__ [read][UNRESOLVED][node=Name]
532.48 -any [bound][function][def][read][called][node=FunctionDef]
532.49 -dir [read][called][UNRESOLVED][node=Name]
532.50 -double3prog [bound][data][read][node=Name]
532.51 -endprogs [bound][data][read][node=Name]
532.52 -generate_tokens [bound][function][def][node=FunctionDef]
532.53 -group [bound][function][def][read][called][node=FunctionDef]
532.54 -len [read][called][UNRESOLVED][node=Name]
532.55 -map [read][called][UNRESOLVED][node=Name]
532.56 -maybe [bound][function][def][read][called][node=FunctionDef]
532.57 -open [read][called][UNRESOLVED][node=Name]
532.58 -printtoken [bound][function][def][read][node=FunctionDef]
532.59 -pseudoprog [bound][data][read][node=Name]
532.60 -re [bound][imported][data][read][node=Import]
532.61 -single3prog [bound][data][read][node=Name]
532.62 -single_quoted [bound][data][read][node=Name]
532.63 -string [bound][imported][data][read][node=Import]
532.64 -sys [bound][imported][data][read][node=Import]
532.65 -t [bound][data][read][node=Name]
532.66 -tabsize [bound][data][read][node=Name]
532.67 -tok_name [read][UNRESOLVED][node=Name]
532.68 -token [bound][imported][data][read][node=Import]
532.69 -tokenize [bound][function][def][read][called][node=FunctionDef]
532.70 -tokenize_loop [bound][function][def][node=FunctionDef]
532.71 -tokenprog [bound][data][node=Name]
532.72 -triple_quoted [bound][data][read][node=Name]
532.73 -untokenize [bound][function][def][node=FunctionDef]
532.74 -x [bound][data][read][node=Name]
532.75 -
532.76 - =============================================
532.77 - group: FunctionDef : OffsetRange[1394,1452>
532.78 - choices [bound][param][data][read][node=arguments]
532.79 -
532.80 - =============================================
532.81 - any: FunctionDef : OffsetRange[1452,1500>
532.82 - choices [bound][param][data][read][node=arguments]
532.83 - group [free][read][called][node=Name]
532.84 -
532.85 - =============================================
532.86 - maybe: FunctionDef : OffsetRange[1500,1551>
532.87 - choices [bound][param][data][read][node=arguments]
532.88 - group [free][read][called][node=Name]
532.89 -
532.90 - =============================================
532.91 - class TokenError: ClassDef : OffsetRange[4630,4665>
532.92 -
532.93 - =============================================
532.94 - class StopTokenizing: ClassDef : OffsetRange[4665,4704>
532.95 -
532.96 - =============================================
532.97 - printtoken: FunctionDef : OffsetRange[4704,4881>
532.98 - (erow, ecol) [bound][param][data][read][node=Tuple]
532.99 - (srow, scol) [bound][param][data][read][node=Tuple]
532.100 - ecol [bound][from-param][data][read][node=Name]
532.101 - erow [bound][from-param][data][read][node=Name]
532.102 - line [bound][param][data][unused][node=Name]
532.103 - repr [free][read][called][node=Name]
532.104 - scol [bound][from-param][data][read][node=Name]
532.105 - srow [bound][from-param][data][read][node=Name]
532.106 - tok_name [free][read][node=Name]
532.107 - token [bound][param][data][read][node=Name]
532.108 - type [bound][param][data][read][node=Name]
532.109 -
532.110 - =============================================
532.111 - tokenize: FunctionDef : OffsetRange[4881,5636>
532.112 - StopTokenizing [free][read][node=Name]
532.113 - readline [bound][param][data][read][node=Name]
532.114 - tokeneater [bound][param][data][read][node=Name]
532.115 - tokenize_loop [free][read][called][node=Name]
532.116 -
532.117 - =============================================
532.118 - tokenize_loop: FunctionDef : OffsetRange[5636,5760>
532.119 - generate_tokens [free][read][called][node=Name]
532.120 - readline [bound][param][data][read][node=Name]
532.121 - token_info [bound][data][read][node=Name]
532.122 - tokeneater [bound][param][data][read][called][node=Name]
532.123 -
532.124 - =============================================
532.125 - untokenize: FunctionDef : OffsetRange[5760,6899>
532.126 - COMMENT [free][read][node=Name]
532.127 - DEDENT [free][read][node=Name]
532.128 - False [free][read][node=Name]
532.129 - INDENT [free][read][node=Name]
532.130 - NAME [free][read][node=Name]
532.131 - NEWLINE [free][read][node=Name]
532.132 - NL [free][read][node=Name]
532.133 - NUMBER [free][read][node=Name]
532.134 - True [free][read][node=Name]
532.135 - indents [bound][data][read][node=Name]
532.136 - iterable [bound][param][data][read][node=Name]
532.137 - startline [bound][data][read][node=Name]
532.138 - tok [bound][data][read][node=Name]
532.139 - toknum [bound][data][read][node=Name]
532.140 - toks [bound][data][read][node=Name]
532.141 - toks_append [bound][data][read][called][node=Name]
532.142 - tokval [bound][data][read][node=Name]
532.143 -
532.144 - =============================================
532.145 - generate_tokens: FunctionDef : OffsetRange[6899,13380>
532.146 - COMMENT [free][read][node=Name]
532.147 - DEDENT [free][read][node=Name]
532.148 - ENDMARKER [free][read][node=Name]
532.149 - ERRORTOKEN [free][read][node=Name]
532.150 - INDENT [free][read][node=Name]
532.151 - IndentationError [free][read][called][node=Name]
532.152 - NAME [free][read][node=Name]
532.153 - NEWLINE [free][read][node=Name]
532.154 - NL [free][read][node=Name]
532.155 - NUMBER [free][read][node=Name]
532.156 - None [free][read][node=Name]
532.157 - OP [free][read][node=Name]
532.158 - STRING [free][read][node=Name]
532.159 - StopIteration [free][read][node=Name]
532.160 - TokenError [free][read][node=Name]
532.161 - column [bound][data][read][node=Name]
532.162 - continued [bound][data][read][node=Name]
532.163 - contline [bound][data][read][node=Name]
532.164 - contstr [bound][data][read][node=Name]
532.165 - end [bound][data][read][node=Name]
532.166 - endmatch [bound][data][read][node=Name]
532.167 - endprog [bound][data][read][node=Name]
532.168 - endprogs [free][read][node=Name]
532.169 - epos [bound][data][read][node=Name]
532.170 - indent [bound][data][unused][node=Name]
532.171 - indents [bound][data][read][node=Name]
532.172 - initial [bound][data][read][node=Name]
532.173 - len [free][read][called][node=Name]
532.174 - line [bound][data][read][node=Name]
532.175 - lnum [bound][data][read][node=Name]
532.176 - max [bound][data][read][node=Name]
532.177 - namechars [bound][data][read][node=Name]
532.178 - needcont [bound][data][read][node=Name]
532.179 - numchars [bound][data][read][node=Name]
532.180 - parenlev [bound][data][read][node=Name]
532.181 - pos [bound][data][read][node=Name]
532.182 - pseudomatch [bound][data][read][node=Name]
532.183 - pseudoprog [free][read][node=Name]
532.184 - readline [bound][param][data][read][called][node=Name]
532.185 - single_quoted [free][read][node=Name]
532.186 - spos [bound][data][read][node=Name]
532.187 - start [bound][data][read][node=Name]
532.188 - string [free][read][node=Name]
532.189 - strstart [bound][data][read][node=Name]
532.190 - tabsize [free][read][node=Name]
532.191 - token [bound][data][read][node=Name]
532.192 - triple_quoted [free][read][node=Name]
532.193 -
533.1 --- a/python.editor/test/unit/data/testfiles/toppkg/__init__.py Sun Jan 04 13:11:53 2015 -0600
533.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
533.3 @@ -1,33 +0,0 @@
533.4 -"""distutils.command
533.5 -
533.6 -Package containing implementation of all the standard Distutils
533.7 -commands."""
533.8 -
533.9 -# This module should be kept compatible with Python 2.1.
533.10 -
533.11 -__revision__ = "$Id: __init__.py 37828 2004-11-10 22:23:15Z loewis $"
533.12 -
533.13 -__all__ = ['build',
533.14 - 'build_py',
533.15 - 'build_ext',
533.16 - 'build_clib',
533.17 - 'build_scripts',
533.18 - 'clean',
533.19 - 'install',
533.20 - 'install_lib',
533.21 - 'install_headers',
533.22 - 'install_scripts',
533.23 - 'install_data',
533.24 - 'sdist',
533.25 - 'register',
533.26 - 'bdist',
533.27 - 'bdist_dumb',
533.28 - 'bdist_rpm',
533.29 - 'bdist_wininst',
533.30 - # These two are reserved for future use:
533.31 - #'bdist_sdux',
533.32 - #'bdist_pkgtool',
533.33 - # Note:
533.34 - # bdist_packager is not included because it only provides
533.35 - # an abstract base class
533.36 - ]
534.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/__init__.py Sun Jan 04 13:11:53 2015 -0600
534.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
534.3 @@ -1,33 +0,0 @@
534.4 -"""distutils.command
534.5 -
534.6 -Package containing implementation of all the standard Distutils
534.7 -commands."""
534.8 -
534.9 -# This module should be kept compatible with Python 2.1.
534.10 -
534.11 -__revision__ = "$Id: __init__.py 37828 2004-11-10 22:23:15Z loewis $"
534.12 -
534.13 -__all__ = ['build',
534.14 - 'build_py',
534.15 - 'build_ext',
534.16 - 'build_clib',
534.17 - 'build_scripts',
534.18 - 'clean',
534.19 - 'install',
534.20 - 'install_lib',
534.21 - 'install_headers',
534.22 - 'install_scripts',
534.23 - 'install_data',
534.24 - 'sdist',
534.25 - 'register',
534.26 - 'bdist',
534.27 - 'bdist_dumb',
534.28 - 'bdist_rpm',
534.29 - 'bdist_wininst',
534.30 - # These two are reserved for future use:
534.31 - #'bdist_sdux',
534.32 - #'bdist_pkgtool',
534.33 - # Note:
534.34 - # bdist_packager is not included because it only provides
534.35 - # an abstract base class
534.36 - ]
535.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/lowpkg/__init__.py Sun Jan 04 13:11:53 2015 -0600
535.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
535.3 @@ -1,33 +0,0 @@
535.4 -"""distutils.command
535.5 -
535.6 -Package containing implementation of all the standard Distutils
535.7 -commands."""
535.8 -
535.9 -# This module should be kept compatible with Python 2.1.
535.10 -
535.11 -__revision__ = "$Id: __init__.py 37828 2004-11-10 22:23:15Z loewis $"
535.12 -
535.13 -__all__ = ['build',
535.14 - 'build_py',
535.15 - 'build_ext',
535.16 - 'build_clib',
535.17 - 'build_scripts',
535.18 - 'clean',
535.19 - 'install',
535.20 - 'install_lib',
535.21 - 'install_headers',
535.22 - 'install_scripts',
535.23 - 'install_data',
535.24 - 'sdist',
535.25 - 'register',
535.26 - 'bdist',
535.27 - 'bdist_dumb',
535.28 - 'bdist_rpm',
535.29 - 'bdist_wininst',
535.30 - # These two are reserved for future use:
535.31 - #'bdist_sdux',
535.32 - #'bdist_pkgtool',
535.33 - # Note:
535.34 - # bdist_packager is not included because it only provides
535.35 - # an abstract base class
535.36 - ]
536.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/lowpkg/imports.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 -from .moduleY import spam
536.5 -from .moduleY import spam as ham
536.6 -from . import moduleY
536.7 -from ..subpackage1 import moduleY
536.8 -from ..subpackage2.moduleZ import eggs
536.9 -from ..moduleA import foo
536.10 -from ...package import bar
536.11 -from ...sys import path
536.12 -
537.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/lowpkg/imports.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
537.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
537.3 @@ -1,9 +0,0 @@
537.4 -from toppkg.medpkg.lowpkg.moduleY import spam
537.5 -from .moduleY import spam as ham
537.6 -from . import moduleY
537.7 -from ..subpackage1 import moduleY
537.8 -from ..subpackage2.moduleZ import eggs
537.9 -from ..moduleA import foo
537.10 -from ...package import bar
537.11 -from ...sys import path
537.12 -
538.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/lowpkg/imports.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
538.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
538.3 @@ -1,9 +0,0 @@
538.4 -from .moduleY import spam
538.5 -from .moduleY import spam as ham
538.6 -from . import moduleY
538.7 -from toppkg.medpkg.subpackage1 import moduleY
538.8 -from ..subpackage2.moduleZ import eggs
538.9 -from ..moduleA import foo
538.10 -from ...package import bar
538.11 -from ...sys import path
538.12 -
539.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/lowpkg/imports.py.testFix3.fixed Sun Jan 04 13:11:53 2015 -0600
539.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
539.3 @@ -1,9 +0,0 @@
539.4 -from .moduleY import spam
539.5 -from .moduleY import spam as ham
539.6 -from . import moduleY
539.7 -from ..subpackage1 import moduleY
539.8 -from ..subpackage2.moduleZ import eggs
539.9 -from ..moduleA import foo
539.10 -from toppkg.package import bar
539.11 -from ...sys import path
539.12 -
540.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/lowpkg/imports.py.testHint1.hints Sun Jan 04 13:11:53 2015 -0600
540.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
540.3 @@ -1,32 +0,0 @@
540.4 -from .moduleY import spam
540.5 --------------------------
540.6 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
540.7 -FIX:Replace with absolute import
540.8 -from .moduleY import spam as ham
540.9 ---------------------------------
540.10 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
540.11 -FIX:Replace with absolute import
540.12 -from . import moduleY
540.13 ----------------------
540.14 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
540.15 -FIX:Replace with absolute import
540.16 -from ..subpackage1 import moduleY
540.17 ----------------------------------
540.18 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
540.19 -FIX:Replace with absolute import
540.20 -from ..subpackage2.moduleZ import eggs
540.21 ---------------------------------------
540.22 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
540.23 -FIX:Replace with absolute import
540.24 -from ..moduleA import foo
540.25 --------------------------
540.26 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
540.27 -FIX:Replace with absolute import
540.28 -from ...package import bar
540.29 ---------------------------
540.30 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
540.31 -FIX:Replace with absolute import
540.32 -from ...sys import path
540.33 ------------------------
540.34 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
540.35 -FIX:Replace with absolute import
541.1 --- a/python.editor/test/unit/data/testfiles/tuples.py Sun Jan 04 13:11:53 2015 -0600
541.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
541.3 @@ -1,15 +0,0 @@
541.4 -def foo():
541.5 - for x, y in None:
541.6 - print y
541.7 - for z in None:
541.8 - pass
541.9 - (a, b) = None
541.10 - c = None
541.11 - print b
541.12 - for dirpath, dirnames, filenames in os.walk(src): # dirnames unused
541.13 - for i, (name, path) in enumerate(result): # i unused
541.14 - pass
541.15 - aliases, entry = cmdutil.findcmd(command, table) # aliases unused
541.16 - for rev, node, fnode in self._hgtagsnodes(): # rev & node unused
541.17 - pass
541.18 -
542.1 --- a/python.editor/test/unit/data/testfiles/tuples.py.testUnusedHints7.hints Sun Jan 04 13:11:53 2015 -0600
542.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
542.3 @@ -1,31 +0,0 @@
542.4 - for x, y in None:
542.5 - -
542.6 -HINT:Unused Variable x
542.7 - for z in None:
542.8 - -
542.9 -HINT:Unused Variable z
542.10 - (a, b) = None
542.11 - -
542.12 -HINT:Unused Variable a
542.13 - c = None
542.14 - -
542.15 -HINT:Unused Variable c
542.16 - for dirpath, dirnames, filenames in os.walk(src): # dirnames unused
542.17 - ---------
542.18 -HINT:Unused Variable dirnames
542.19 -HINT:Unused Variable dirpath
542.20 -HINT:Unused Variable filenames
542.21 - for i, (name, path) in enumerate(result): # i unused
542.22 - ----
542.23 -HINT:Unused Variable i
542.24 -HINT:Unused Variable name
542.25 -HINT:Unused Variable path
542.26 - aliases, entry = cmdutil.findcmd(command, table) # aliases unused
542.27 - -----
542.28 -HINT:Unused Variable aliases
542.29 -HINT:Unused Variable entry
542.30 - for rev, node, fnode in self._hgtagsnodes(): # rev & node unused
542.31 - -----
542.32 -HINT:Unused Variable fnode
542.33 -HINT:Unused Variable node
542.34 -HINT:Unused Variable rev
543.1 --- a/python.editor/test/unit/data/testfiles/tuples.py.testUnusedHints8.hints Sun Jan 04 13:11:53 2015 -0600
543.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
543.3 @@ -1,6 +0,0 @@
543.4 - for z in None:
543.5 - -
543.6 -HINT:Unused Variable z
543.7 - c = None
543.8 - -
543.9 -HINT:Unused Variable c
544.1 --- a/python.editor/test/unit/data/testfiles/types.py Sun Jan 04 13:11:53 2015 -0600
544.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
544.3 @@ -1,25 +0,0 @@
544.4 -x = y = SomeOtherClass()
544.5 -z = y
544.6 -w = 5
544.7 -yz = "foo"
544.8 -someObject = SomeClass().foo();
544.9 -
544.10 -# Type variables
544.11 -# @type defined1: int
544.12 -#defined1.x()
544.13 -
544.14 -#FIRST_CARET_POS
544.15 -
544.16 -# Redefine
544.17 -# @type defined1: str
544.18 -#defined1.y()
544.19 -
544.20 -x = Other()
544.21 -y = 5
544.22 -z = "str"
544.23 -
544.24 -# Type assertions
544.25 -assert isinstanceof(s, basestring)
544.26 -s.i
544.27 -
544.28 -#SECOND_CARET_POS
545.1 --- a/python.editor/test/unit/data/testfiles/typevars.py Sun Jan 04 13:11:53 2015 -0600
545.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
545.3 @@ -1,9 +0,0 @@
545.4 -# Tests for Python type assertions
545.5 -
545.6 -# @type xy str
545.7 -xy.s1
545.8 -zs.t
545.9 -# @type xy int
545.10 -xy.s2
545.11 -
545.12 -
546.1 --- a/python.editor/test/unit/data/testfiles/typevars.py.testMarks11.occurrences Sun Jan 04 13:11:53 2015 -0600
546.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
546.3 @@ -1,4 +0,0 @@
546.4 -# @type ^|>MARK_OCCURRENCES:xy<| str
546.5 -|>MARK_OCCURRENCES:xy<|.s1
546.6 -# @type |>MARK_OCCURRENCES:xy<| int
546.7 -|>MARK_OCCURRENCES:xy<|.s2
547.1 --- a/python.editor/test/unit/data/testfiles/typevars.py.testRename7.rename Sun Jan 04 13:11:53 2015 -0600
547.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
547.3 @@ -1,4 +0,0 @@
547.4 -3: # @type |>xy<| str
547.5 -4: |>xy<|.s1
547.6 -6: # @type |>xy<| int
547.7 -7: |>xy<|.s2
548.1 --- a/python.editor/test/unit/data/testfiles/typevars.py.testRename8.rename Sun Jan 04 13:11:53 2015 -0600
548.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
548.3 @@ -1,4 +0,0 @@
548.4 -3: # @type |>xy<| str
548.5 -4: |>xy<|.s1
548.6 -6: # @type |>xy<| int
548.7 -7: |>xy<|.s2
549.1 --- a/python.editor/test/unit/data/testfiles/unittest.py Sun Jan 04 13:11:53 2015 -0600
549.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
549.3 @@ -1,816 +0,0 @@
549.4 -#!/usr/bin/env python
549.5 -'''
549.6 -Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
549.7 -Smalltalk testing framework.
549.8 -
549.9 -This module contains the core framework classes that form the basis of
549.10 -specific test cases and suites (TestCase, TestSuite etc.), and also a
549.11 -text-based utility class for running the tests and reporting the results
549.12 - (TextTestRunner).
549.13 -
549.14 -Simple usage:
549.15 -
549.16 - import unittest
549.17 -
549.18 - class IntegerArithmenticTestCase(unittest.TestCase):
549.19 - def testAdd(self): ## test method names begin 'test*'
549.20 - self.assertEquals((1 + 2), 3)
549.21 - self.assertEquals(0 + 1, 1)
549.22 - def testMultiply(self):
549.23 - self.assertEquals((0 * 10), 0)
549.24 - self.assertEquals((5 * 8), 40)
549.25 -
549.26 - if __name__ == '__main__':
549.27 - unittest.main()
549.28 -
549.29 -Further information is available in the bundled documentation, and from
549.30 -
549.31 - http://pyunit.sourceforge.net/
549.32 -
549.33 -Copyright (c) 1999-2003 Steve Purcell
549.34 -This module is free software, and you may redistribute it and/or modify
549.35 -it under the same terms as Python itself, so long as this copyright message
549.36 -and disclaimer are retained in their original form.
549.37 -
549.38 -IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
549.39 -SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
549.40 -THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
549.41 -DAMAGE.
549.42 -
549.43 -THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
549.44 -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
549.45 -PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
549.46 -AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
549.47 -SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
549.48 -'''
549.49 -
549.50 -__author__ = "Steve Purcell"
549.51 -__email__ = "stephen_purcell at yahoo dot com"
549.52 -__version__ = "#Revision: 1.63 $"[11:-2]
549.53 -
549.54 -import time
549.55 -import sys
549.56 -import traceback
549.57 -import os
549.58 -import types
549.59 -
549.60 -##############################################################################
549.61 -# Exported classes and functions
549.62 -##############################################################################
549.63 -__all__ = ['TestResult', 'TestCase', 'TestSuite', 'TextTestRunner',
549.64 - 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader']
549.65 -
549.66 -# Expose obsolete functions for backwards compatibility
549.67 -__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
549.68 -
549.69 -
549.70 -##############################################################################
549.71 -# Backward compatibility
549.72 -##############################################################################
549.73 -if sys.version_info[:2] < (2, 2):
549.74 - False, True = 0, 1
549.75 - def isinstance(obj, clsinfo):
549.76 - import __builtin__
549.77 - if type(clsinfo) in (tuple, list):
549.78 - for cls in clsinfo:
549.79 - if cls is type: cls = types.ClassType
549.80 - if __builtin__.isinstance(obj, cls):
549.81 - return 1
549.82 - return 0
549.83 - else: return __builtin__.isinstance(obj, clsinfo)
549.84 -
549.85 -
549.86 -##############################################################################
549.87 -# Test framework core
549.88 -##############################################################################
549.89 -
549.90 -# All classes defined herein are 'new-style' classes, allowing use of 'super()'
549.91 -__metaclass__ = type
549.92 -
549.93 -def _strclass(cls):
549.94 - return "%s.%s" % (cls.__module__, cls.__name__)
549.95 -
549.96 -__unittest = 1
549.97 -
549.98 -class TestResult:
549.99 - """Holder for test result information.
549.100 -
549.101 - Test results are automatically managed by the TestCase and TestSuite
549.102 - classes, and do not need to be explicitly manipulated by writers of tests.
549.103 -
549.104 - Each instance holds the total number of tests run, and collections of
549.105 - failures and errors that occurred among those test runs. The collections
549.106 - contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
549.107 - formatted traceback of the error that occurred.
549.108 - """
549.109 - def __init__(self):
549.110 - self.failures = []
549.111 - self.errors = []
549.112 - self.testsRun = 0
549.113 - self.shouldStop = 0
549.114 -
549.115 - def startTest(self, test):
549.116 - "Called when the given test is about to be run"
549.117 - self.testsRun = self.testsRun + 1
549.118 -
549.119 - def stopTest(self, test):
549.120 - "Called when the given test has been run"
549.121 - pass
549.122 -
549.123 - def addError(self, test, err):
549.124 - """Called when an error has occurred. 'err' is a tuple of values as
549.125 - returned by sys.exc_info().
549.126 - """
549.127 - self.errors.append((test, self._exc_info_to_string(err, test)))
549.128 -
549.129 - def addFailure(self, test, err):
549.130 - """Called when an error has occurred. 'err' is a tuple of values as
549.131 - returned by sys.exc_info()."""
549.132 - self.failures.append((test, self._exc_info_to_string(err, test)))
549.133 -
549.134 - def addSuccess(self, test):
549.135 - "Called when a test has completed successfully"
549.136 - pass
549.137 -
549.138 - def wasSuccessful(self):
549.139 - "Tells whether or not this result was a success"
549.140 - return len(self.failures) == len(self.errors) == 0
549.141 -
549.142 - def stop(self):
549.143 - "Indicates that the tests should be aborted"
549.144 - self.shouldStop = True
549.145 -
549.146 - def _exc_info_to_string(self, err, test):
549.147 - """Converts a sys.exc_info()-style tuple of values into a string."""
549.148 - exctype, value, tb = err
549.149 - # Skip test runner traceback levels
549.150 - while tb and self._is_relevant_tb_level(tb):
549.151 - tb = tb.tb_next
549.152 - if exctype is test.failureException:
549.153 - # Skip assert*() traceback levels
549.154 - length = self._count_relevant_tb_levels(tb)
549.155 - return ''.join(traceback.format_exception(exctype, value, tb, length))
549.156 - return ''.join(traceback.format_exception(exctype, value, tb))
549.157 -
549.158 - def _is_relevant_tb_level(self, tb):
549.159 - return tb.tb_frame.f_globals.has_key('__unittest')
549.160 -
549.161 - def _count_relevant_tb_levels(self, tb):
549.162 - length = 0
549.163 - while tb and not self._is_relevant_tb_level(tb):
549.164 - length += 1
549.165 - tb = tb.tb_next
549.166 - return length
549.167 -
549.168 - def __repr__(self):
549.169 - return "<%s run=%i errors=%i failures=%i>" % \
549.170 - (_strclass(self.__class__), self.testsRun, len(self.errors),
549.171 - len(self.failures))
549.172 -
549.173 -class TestCase:
549.174 - """A class whose instances are single test cases.
549.175 -
549.176 - By default, the test code itself should be placed in a method named
549.177 - 'runTest'.
549.178 -
549.179 - If the fixture may be used for many test cases, create as
549.180 - many test methods as are needed. When instantiating such a TestCase
549.181 - subclass, specify in the constructor arguments the name of the test method
549.182 - that the instance is to execute.
549.183 -
549.184 - Test authors should subclass TestCase for their own tests. Construction
549.185 - and deconstruction of the test's environment ('fixture') can be
549.186 - implemented by overriding the 'setUp' and 'tearDown' methods respectively.
549.187 -
549.188 - If it is necessary to override the __init__ method, the base class
549.189 - __init__ method must always be called. It is important that subclasses
549.190 - should not change the signature of their __init__ method, since instances
549.191 - of the classes are instantiated automatically by parts of the framework
549.192 - in order to be run.
549.193 - """
549.194 -
549.195 - # This attribute determines which exception will be raised when
549.196 - # the instance's assertion methods fail; test methods raising this
549.197 - # exception will be deemed to have 'failed' rather than 'errored'
549.198 -
549.199 - failureException = AssertionError
549.200 -
549.201 - def __init__(self, methodName='runTest'):
549.202 - """Create an instance of the class that will use the named test
549.203 - method when executed. Raises a ValueError if the instance does
549.204 - not have a method with the specified name.
549.205 - """
549.206 - try:
549.207 - self._testMethodName = methodName
549.208 - testMethod = getattr(self, methodName)
549.209 - self._testMethodDoc = testMethod.__doc__
549.210 - except AttributeError:
549.211 - raise ValueError, "no such test method in %s: %s" % \
549.212 - (self.__class__, methodName)
549.213 -
549.214 - def setUp(self):
549.215 - "Hook method for setting up the test fixture before exercising it."
549.216 - pass
549.217 -
549.218 - def tearDown(self):
549.219 - "Hook method for deconstructing the test fixture after testing it."
549.220 - pass
549.221 -
549.222 - def countTestCases(self):
549.223 - return 1
549.224 -
549.225 - def defaultTestResult(self):
549.226 - return TestResult()
549.227 -
549.228 - def shortDescription(self):
549.229 - """Returns a one-line description of the test, or None if no
549.230 - description has been provided.
549.231 -
549.232 - The default implementation of this method returns the first line of
549.233 - the specified test method's docstring.
549.234 - """
549.235 - doc = self._testMethodDoc
549.236 - return doc and doc.split("\n")[0].strip() or None
549.237 -
549.238 - def id(self):
549.239 - return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
549.240 -
549.241 - def __str__(self):
549.242 - return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
549.243 -
549.244 - def __repr__(self):
549.245 - return "<%s testMethod=%s>" % \
549.246 - (_strclass(self.__class__), self._testMethodName)
549.247 -
549.248 - def run(self, result=None):
549.249 - if result is None: result = self.defaultTestResult()
549.250 - result.startTest(self)
549.251 - testMethod = getattr(self, self._testMethodName)
549.252 - try:
549.253 - try:
549.254 - self.setUp()
549.255 - except KeyboardInterrupt:
549.256 - raise
549.257 - except:
549.258 - result.addError(self, self._exc_info())
549.259 - return
549.260 -
549.261 - ok = False
549.262 - try:
549.263 - testMethod()
549.264 - ok = True
549.265 - except self.failureException:
549.266 - result.addFailure(self, self._exc_info())
549.267 - except KeyboardInterrupt:
549.268 - raise
549.269 - except:
549.270 - result.addError(self, self._exc_info())
549.271 -
549.272 - try:
549.273 - self.tearDown()
549.274 - except KeyboardInterrupt:
549.275 - raise
549.276 - except:
549.277 - result.addError(self, self._exc_info())
549.278 - ok = False
549.279 - if ok: result.addSuccess(self)
549.280 - finally:
549.281 - result.stopTest(self)
549.282 -
549.283 - def __call__(self, *args, **kwds):
549.284 - return self.run(*args, **kwds)
549.285 -
549.286 - def debug(self):
549.287 - """Run the test without collecting errors in a TestResult"""
549.288 - self.setUp()
549.289 - getattr(self, self._testMethodName)()
549.290 - self.tearDown()
549.291 -
549.292 - def _exc_info(self):
549.293 - """Return a version of sys.exc_info() with the traceback frame
549.294 - minimised; usually the top level of the traceback frame is not
549.295 - needed.
549.296 - """
549.297 - exctype, excvalue, tb = sys.exc_info()
549.298 - if sys.platform[:4] == 'java': ## tracebacks look different in Jython
549.299 - return (exctype, excvalue, tb)
549.300 - return (exctype, excvalue, tb)
549.301 -
549.302 - def fail(self, msg=None):
549.303 - """Fail immediately, with the given message."""
549.304 - raise self.failureException, msg
549.305 -
549.306 - def failIf(self, expr, msg=None):
549.307 - "Fail the test if the expression is true."
549.308 - if expr: raise self.failureException, msg
549.309 -
549.310 - def failUnless(self, expr, msg=None):
549.311 - """Fail the test unless the expression is true."""
549.312 - if not expr: raise self.failureException, msg
549.313 -
549.314 - def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
549.315 - """Fail unless an exception of class excClass is thrown
549.316 - by callableObj when invoked with arguments args and keyword
549.317 - arguments kwargs. If a different type of exception is
549.318 - thrown, it will not be caught, and the test case will be
549.319 - deemed to have suffered an error, exactly as for an
549.320 - unexpected exception.
549.321 - """
549.322 - try:
549.323 - callableObj(*args, **kwargs)
549.324 - except excClass:
549.325 - return
549.326 - else:
549.327 - if hasattr(excClass,'__name__'): excName = excClass.__name__
549.328 - else: excName = str(excClass)
549.329 - raise self.failureException, "%s not raised" % excName
549.330 -
549.331 - def failUnlessEqual(self, first, second, msg=None):
549.332 - """Fail if the two objects are unequal as determined by the '=='
549.333 - operator.
549.334 - """
549.335 - if not first == second:
549.336 - raise self.failureException, \
549.337 - (msg or '%r != %r' % (first, second))
549.338 -
549.339 - def failIfEqual(self, first, second, msg=None):
549.340 - """Fail if the two objects are equal as determined by the '=='
549.341 - operator.
549.342 - """
549.343 - if first == second:
549.344 - raise self.failureException, \
549.345 - (msg or '%r == %r' % (first, second))
549.346 -
549.347 - def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
549.348 - """Fail if the two objects are unequal as determined by their
549.349 - difference rounded to the given number of decimal places
549.350 - (default 7) and comparing to zero.
549.351 -
549.352 - Note that decimal places (from zero) are usually not the same
549.353 - as significant digits (measured from the most signficant digit).
549.354 - """
549.355 - if round(second-first, places) != 0:
549.356 - raise self.failureException, \
549.357 - (msg or '%r != %r within %r places' % (first, second, places))
549.358 -
549.359 - def failIfAlmostEqual(self, first, second, places=7, msg=None):
549.360 - """Fail if the two objects are equal as determined by their
549.361 - difference rounded to the given number of decimal places
549.362 - (default 7) and comparing to zero.
549.363 -
549.364 - Note that decimal places (from zero) are usually not the same
549.365 - as significant digits (measured from the most signficant digit).
549.366 - """
549.367 - if round(second-first, places) == 0:
549.368 - raise self.failureException, \
549.369 - (msg or '%r == %r within %r places' % (first, second, places))
549.370 -
549.371 - # Synonyms for assertion methods
549.372 -
549.373 - assertEqual = assertEquals = failUnlessEqual
549.374 -
549.375 - assertNotEqual = assertNotEquals = failIfEqual
549.376 -
549.377 - assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
549.378 -
549.379 - assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
549.380 -
549.381 - assertRaises = failUnlessRaises
549.382 -
549.383 - assert_ = assertTrue = failUnless
549.384 -
549.385 - assertFalse = failIf
549.386 -
549.387 -
549.388 -
549.389 -class TestSuite:
549.390 - """A test suite is a composite test consisting of a number of TestCases.
549.391 -
549.392 - For use, create an instance of TestSuite, then add test case instances.
549.393 - When all tests have been added, the suite can be passed to a test
549.394 - runner, such as TextTestRunner. It will run the individual test cases
549.395 - in the order in which they were added, aggregating the results. When
549.396 - subclassing, do not forget to call the base class constructor.
549.397 - """
549.398 - def __init__(self, tests=()):
549.399 - self._tests = []
549.400 - self.addTests(tests)
549.401 -
549.402 - def __repr__(self):
549.403 - return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
549.404 -
549.405 - __str__ = __repr__
549.406 -
549.407 - def __iter__(self):
549.408 - return iter(self._tests)
549.409 -
549.410 - def countTestCases(self):
549.411 - cases = 0
549.412 - for test in self._tests:
549.413 - cases += test.countTestCases()
549.414 - return cases
549.415 -
549.416 - def addTest(self, test):
549.417 - # sanity checks
549.418 - if not callable(test):
549.419 - raise TypeError("the test to add must be callable")
549.420 - if (isinstance(test, (type, types.ClassType)) and
549.421 - issubclass(test, (TestCase, TestSuite))):
549.422 - raise TypeError("TestCases and TestSuites must be instantiated "
549.423 - "before passing them to addTest()")
549.424 - self._tests.append(test)
549.425 -
549.426 - def addTests(self, tests):
549.427 - if isinstance(tests, basestring):
549.428 - raise TypeError("tests must be an iterable of tests, not a string")
549.429 - for test in tests:
549.430 - self.addTest(test)
549.431 -
549.432 - def run(self, result):
549.433 - for test in self._tests:
549.434 - if result.shouldStop:
549.435 - break
549.436 - test(result)
549.437 - return result
549.438 -
549.439 - def __call__(self, *args, **kwds):
549.440 - return self.run(*args, **kwds)
549.441 -
549.442 - def debug(self):
549.443 - """Run the tests without collecting errors in a TestResult"""
549.444 - for test in self._tests: test.debug()
549.445 -
549.446 -
549.447 -class FunctionTestCase(TestCase):
549.448 - """A test case that wraps a test function.
549.449 -
549.450 - This is useful for slipping pre-existing test functions into the
549.451 - PyUnit framework. Optionally, set-up and tidy-up functions can be
549.452 - supplied. As with TestCase, the tidy-up ('tearDown') function will
549.453 - always be called if the set-up ('setUp') function ran successfully.
549.454 - """
549.455 -
549.456 - def __init__(self, testFunc, setUp=None, tearDown=None,
549.457 - description=None):
549.458 - TestCase.__init__(self)
549.459 - self.__setUpFunc = setUp
549.460 - self.__tearDownFunc = tearDown
549.461 - self.__testFunc = testFunc
549.462 - self.__description = description
549.463 -
549.464 - def setUp(self):
549.465 - if self.__setUpFunc is not None:
549.466 - self.__setUpFunc()
549.467 -
549.468 - def tearDown(self):
549.469 - if self.__tearDownFunc is not None:
549.470 - self.__tearDownFunc()
549.471 -
549.472 - def runTest(self):
549.473 - self.__testFunc()
549.474 -
549.475 - def id(self):
549.476 - return self.__testFunc.__name__
549.477 -
549.478 - def __str__(self):
549.479 - return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
549.480 -
549.481 - def __repr__(self):
549.482 - return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
549.483 -
549.484 - def shortDescription(self):
549.485 - if self.__description is not None: return self.__description
549.486 - doc = self.__testFunc.__doc__
549.487 - return doc and doc.split("\n")[0].strip() or None
549.488 -
549.489 -
549.490 -
549.491 -##############################################################################
549.492 -# Locating and loading tests
549.493 -##############################################################################
549.494 -
549.495 -class TestLoader:
549.496 - """This class is responsible for loading tests according to various
549.497 - criteria and returning them wrapped in a Test
549.498 - """
549.499 - testMethodPrefix = 'test'
549.500 - sortTestMethodsUsing = cmp
549.501 - suiteClass = TestSuite
549.502 -
549.503 - def loadTestsFromTestCase(self, testCaseClass):
549.504 - """Return a suite of all tests cases contained in testCaseClass"""
549.505 - if issubclass(testCaseClass, TestSuite):
549.506 - raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?")
549.507 - testCaseNames = self.getTestCaseNames(testCaseClass)
549.508 - if not testCaseNames and hasattr(testCaseClass, 'runTest'):
549.509 - testCaseNames = ['runTest']
549.510 - return self.suiteClass(map(testCaseClass, testCaseNames))
549.511 -
549.512 - def loadTestsFromModule(self, module):
549.513 - """Return a suite of all tests cases contained in the given module"""
549.514 - tests = []
549.515 - for name in dir(module):
549.516 - obj = getattr(module, name)
549.517 - if (isinstance(obj, (type, types.ClassType)) and
549.518 - issubclass(obj, TestCase)):
549.519 - tests.append(self.loadTestsFromTestCase(obj))
549.520 - return self.suiteClass(tests)
549.521 -
549.522 - def loadTestsFromName(self, name, module=None):
549.523 - """Return a suite of all tests cases given a string specifier.
549.524 -
549.525 - The name may resolve either to a module, a test case class, a
549.526 - test method within a test case class, or a callable object which
549.527 - returns a TestCase or TestSuite instance.
549.528 -
549.529 - The method optionally resolves the names relative to a given module.
549.530 - """
549.531 - parts = name.split('.')
549.532 - if module is None:
549.533 - parts_copy = parts[:]
549.534 - while parts_copy:
549.535 - try:
549.536 - module = __import__('.'.join(parts_copy))
549.537 - break
549.538 - except ImportError:
549.539 - del parts_copy[-1]
549.540 - if not parts_copy: raise
549.541 - parts = parts[1:]
549.542 - obj = module
549.543 - for part in parts:
549.544 - parent, obj = obj, getattr(obj, part)
549.545 -
549.546 - if type(obj) == types.ModuleType:
549.547 - return self.loadTestsFromModule(obj)
549.548 - elif (isinstance(obj, (type, types.ClassType)) and
549.549 - issubclass(obj, TestCase)):
549.550 - return self.loadTestsFromTestCase(obj)
549.551 - elif type(obj) == types.UnboundMethodType:
549.552 - return parent(obj.__name__)
549.553 - elif isinstance(obj, TestSuite):
549.554 - return obj
549.555 - elif callable(obj):
549.556 - test = obj()
549.557 - if not isinstance(test, (TestCase, TestSuite)):
549.558 - raise ValueError, \
549.559 - "calling %s returned %s, not a test" % (obj,test)
549.560 - return test
549.561 - else:
549.562 - raise ValueError, "don't know how to make test from: %s" % obj
549.563 -
549.564 - def loadTestsFromNames(self, names, module=None):
549.565 - """Return a suite of all tests cases found using the given sequence
549.566 - of string specifiers. See 'loadTestsFromName()'.
549.567 - """
549.568 - suites = [self.loadTestsFromName(name, module) for name in names]
549.569 - return self.suiteClass(suites)
549.570 -
549.571 - def getTestCaseNames(self, testCaseClass):
549.572 - """Return a sorted sequence of method names found within testCaseClass
549.573 - """
549.574 - def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
549.575 - return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname))
549.576 - testFnNames = filter(isTestMethod, dir(testCaseClass))
549.577 - for baseclass in testCaseClass.__bases__:
549.578 - for testFnName in self.getTestCaseNames(baseclass):
549.579 - if testFnName not in testFnNames: # handle overridden methods
549.580 - testFnNames.append(testFnName)
549.581 - if self.sortTestMethodsUsing:
549.582 - testFnNames.sort(self.sortTestMethodsUsing)
549.583 - return testFnNames
549.584 -
549.585 -
549.586 -
549.587 -defaultTestLoader = TestLoader()
549.588 -
549.589 -
549.590 -##############################################################################
549.591 -# Patches for old functions: these functions should be considered obsolete
549.592 -##############################################################################
549.593 -
549.594 -def _makeLoader(prefix, sortUsing, suiteClass=None):
549.595 - loader = TestLoader()
549.596 - loader.sortTestMethodsUsing = sortUsing
549.597 - loader.testMethodPrefix = prefix
549.598 - if suiteClass: loader.suiteClass = suiteClass
549.599 - return loader
549.600 -
549.601 -def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
549.602 - return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
549.603 -
549.604 -def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
549.605 - return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
549.606 -
549.607 -def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
549.608 - return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
549.609 -
549.610 -
549.611 -##############################################################################
549.612 -# Text UI
549.613 -##############################################################################
549.614 -
549.615 -class _WritelnDecorator:
549.616 - """Used to decorate file-like objects with a handy 'writeln' method"""
549.617 - def __init__(self,stream):
549.618 - self.stream = stream
549.619 -
549.620 - def __getattr__(self, attr):
549.621 - return getattr(self.stream,attr)
549.622 -
549.623 - def writeln(self, arg=None):
549.624 - if arg: self.write(arg)
549.625 - self.write('\n') # text-mode streams translate to \r\n if needed
549.626 -
549.627 -
549.628 -class _TextTestResult(TestResult):
549.629 - """A test result class that can print formatted text results to a stream.
549.630 -
549.631 - Used by TextTestRunner.
549.632 - """
549.633 - separator1 = '=' * 70
549.634 - separator2 = '-' * 70
549.635 -
549.636 - def __init__(self, stream, descriptions, verbosity):
549.637 - TestResult.__init__(self)
549.638 - self.stream = stream
549.639 - self.showAll = verbosity > 1
549.640 - self.dots = verbosity == 1
549.641 - self.descriptions = descriptions
549.642 -
549.643 - def getDescription(self, test):
549.644 - if self.descriptions:
549.645 - return test.shortDescription() or str(test)
549.646 - else:
549.647 - return str(test)
549.648 -
549.649 - def startTest(self, test):
549.650 - TestResult.startTest(self, test)
549.651 - if self.showAll:
549.652 - self.stream.write(self.getDescription(test))
549.653 - self.stream.write(" ... ")
549.654 -
549.655 - def addSuccess(self, test):
549.656 - TestResult.addSuccess(self, test)
549.657 - if self.showAll:
549.658 - self.stream.writeln("ok")
549.659 - elif self.dots:
549.660 - self.stream.write('.')
549.661 -
549.662 - def addError(self, test, err):
549.663 - TestResult.addError(self, test, err)
549.664 - if self.showAll:
549.665 - self.stream.writeln("ERROR")
549.666 - elif self.dots:
549.667 - self.stream.write('E')
549.668 -
549.669 - def addFailure(self, test, err):
549.670 - TestResult.addFailure(self, test, err)
549.671 - if self.showAll:
549.672 - self.stream.writeln("FAIL")
549.673 - elif self.dots:
549.674 - self.stream.write('F')
549.675 -
549.676 - def printErrors(self):
549.677 - if self.dots or self.showAll:
549.678 - self.stream.writeln()
549.679 - self.printErrorList('ERROR', self.errors)
549.680 - self.printErrorList('FAIL', self.failures)
549.681 -
549.682 - def printErrorList(self, flavour, errors):
549.683 - for test, err in errors:
549.684 - self.stream.writeln(self.separator1)
549.685 - self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
549.686 - self.stream.writeln(self.separator2)
549.687 - self.stream.writeln("%s" % err)
549.688 -
549.689 -
549.690 -class TextTestRunner:
549.691 - """A test runner class that displays results in textual form.
549.692 -
549.693 - It prints out the names of tests as they are run, errors as they
549.694 - occur, and a summary of the results at the end of the test run.
549.695 - """
549.696 - def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
549.697 - self.stream = _WritelnDecorator(stream)
549.698 - self.descriptions = descriptions
549.699 - self.verbosity = verbosity
549.700 -
549.701 - def _makeResult(self):
549.702 - return _TextTestResult(self.stream, self.descriptions, self.verbosity)
549.703 -
549.704 - def run(self, test):
549.705 - "Run the given test case or test suite."
549.706 - result = self._makeResult()
549.707 - startTime = time.time()
549.708 - test(result)
549.709 - stopTime = time.time()
549.710 - timeTaken = stopTime - startTime
549.711 - result.printErrors()
549.712 - self.stream.writeln(result.separator2)
549.713 - run = result.testsRun
549.714 - self.stream.writeln("Ran %d test%s in %.3fs" %
549.715 - (run, run != 1 and "s" or "", timeTaken))
549.716 - self.stream.writeln()
549.717 - if not result.wasSuccessful():
549.718 - self.stream.write("FAILED (")
549.719 - failed, errored = map(len, (result.failures, result.errors))
549.720 - if failed:
549.721 - self.stream.write("failures=%d" % failed)
549.722 - if errored:
549.723 - if failed: self.stream.write(", ")
549.724 - self.stream.write("errors=%d" % errored)
549.725 - self.stream.writeln(")")
549.726 - else:
549.727 - self.stream.writeln("OK")
549.728 - return result
549.729 -
549.730 -
549.731 -
549.732 -##############################################################################
549.733 -# Facilities for running tests from the command line
549.734 -##############################################################################
549.735 -
549.736 -class TestProgram:
549.737 - """A command-line program that runs a set of tests; this is primarily
549.738 - for making test modules conveniently executable.
549.739 - """
549.740 - USAGE = """\
549.741 -Usage: %(progName)s [options] [test] [...]
549.742 -
549.743 -Options:
549.744 - -h, --help Show this message
549.745 - -v, --verbose Verbose output
549.746 - -q, --quiet Minimal output
549.747 -
549.748 -Examples:
549.749 - %(progName)s - run default set of tests
549.750 - %(progName)s MyTestSuite - run suite 'MyTestSuite'
549.751 - %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
549.752 - %(progName)s MyTestCase - run all 'test*' test methods
549.753 - in MyTestCase
549.754 -"""
549.755 - def __init__(self, module='__main__', defaultTest=None,
549.756 - argv=None, testRunner=None, testLoader=defaultTestLoader):
549.757 - if type(module) == type(''):
549.758 - self.module = __import__(module)
549.759 - for part in module.split('.')[1:]:
549.760 - self.module = getattr(self.module, part)
549.761 - else:
549.762 - self.module = module
549.763 - if argv is None:
549.764 - argv = sys.argv
549.765 - self.verbosity = 1
549.766 - self.defaultTest = defaultTest
549.767 - self.testRunner = testRunner
549.768 - self.testLoader = testLoader
549.769 - self.progName = os.path.basename(argv[0])
549.770 - self.parseArgs(argv)
549.771 - self.runTests()
549.772 -
549.773 - def usageExit(self, msg=None):
549.774 - if msg: print msg
549.775 - print self.USAGE % self.__dict__
549.776 - sys.exit(2)
549.777 -
549.778 - def parseArgs(self, argv):
549.779 - import getopt
549.780 - try:
549.781 - options, args = getopt.getopt(argv[1:], 'hHvq',
549.782 - ['help','verbose','quiet'])
549.783 - for opt, value in options:
549.784 - if opt in ('-h','-H','--help'):
549.785 - self.usageExit()
549.786 - if opt in ('-q','--quiet'):
549.787 - self.verbosity = 0
549.788 - if opt in ('-v','--verbose'):
549.789 - self.verbosity = 2
549.790 - if len(args) == 0 and self.defaultTest is None:
549.791 - self.test = self.testLoader.loadTestsFromModule(self.module)
549.792 - return
549.793 - if len(args) > 0:
549.794 - self.testNames = args
549.795 - else:
549.796 - self.testNames = (self.defaultTest,)
549.797 - self.createTests()
549.798 - except getopt.error, msg:
549.799 - self.usageExit(msg)
549.800 -
549.801 - def createTests(self):
549.802 - self.test = self.testLoader.loadTestsFromNames(self.testNames,
549.803 - self.module)
549.804 -
549.805 - def runTests(self):
549.806 - if self.testRunner is None:
549.807 - self.testRunner = TextTestRunner(verbosity=self.verbosity)
549.808 - result = self.testRunner.run(self.test)
549.809 - sys.exit(not result.wasSuccessful())
549.810 -
549.811 -main = TestProgram
549.812 -
549.813 -
549.814 -##############################################################################
549.815 -# Executing this module from the command line
549.816 -##############################################################################
549.817 -
549.818 -if __name__ == "__main__":
549.819 - main(module=None)
550.1 --- a/python.editor/test/unit/data/testfiles/unittest.py.indexed Sun Jan 04 13:11:53 2015 -0600
550.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
550.3 @@ -1,267 +0,0 @@
550.4 -
550.5 -
550.6 -Document 0
550.7 -Searchable Keys:
550.8 - class : FunctionTestCase
550.9 - class-ig : functiontestcase
550.10 - extends : TestCase
550.11 - in : unittest
550.12 - member : __description;D;|PRIVATE|;
550.13 - member : __init__;c;|CONSTRUCTOR|;self,testFunc,setUp,tearDown,description;
550.14 - member : __repr__;F;;self;
550.15 - member : __setUpFunc;D;|PRIVATE|;
550.16 - member : __str__;F;;self;
550.17 - member : __tearDownFunc;D;|PRIVATE|;
550.18 - member : __testFunc;D;|PRIVATE|;
550.19 - member : id;F;;self;
550.20 - member : runTest;F;;self;
550.21 - member : setUp;F;;self;
550.22 - member : shortDescription;F;;self;
550.23 - member : tearDown;F;;self;
550.24 -
550.25 -Not Searchable Keys:
550.26 -
550.27 -
550.28 -Document 1
550.29 -Searchable Keys:
550.30 - class : TestCase
550.31 - class-ig : testcase
550.32 - in : unittest
550.33 - member : __call__;F;;self,args,kwds;
550.34 - member : __init__;c;|CONSTRUCTOR|;self,methodName;
550.35 - member : __repr__;F;;self;
550.36 - member : __str__;F;;self;
550.37 - member : _exc_info;F;|PRIVATE|;self;
550.38 - member : _testMethodDoc;D;|PRIVATE|;
550.39 - member : _testMethodName;D;|PRIVATE|;
550.40 - member : assertAlmostEqual;F;;self,first,second,places,msg;
550.41 - member : assertAlmostEquals;F;;self,first,second,places,msg;
550.42 - member : assertEqual;F;;self,first,second,msg;
550.43 - member : assertEquals;F;;self,first,second,msg;
550.44 - member : assertFalse;F;;self,expr,msg;
550.45 - member : assertNotAlmostEqual;F;;self,first,second,places,msg;
550.46 - member : assertNotAlmostEquals;F;;self,first,second,places,msg;
550.47 - member : assertNotEqual;F;;self,first,second,msg;
550.48 - member : assertNotEquals;F;;self,first,second,msg;
550.49 - member : assertRaises;F;;self,excClass,callableObj,args,kwargs;
550.50 - member : assertTrue;F;;self,expr,msg;
550.51 - member : assert_;F;;self,expr,msg;
550.52 - member : countTestCases;F;;self;
550.53 - member : debug;F;;self;
550.54 - member : defaultTestResult;F;;self;
550.55 - member : fail;F;;self,msg;
550.56 - member : failIf;F;;self,expr,msg;
550.57 - member : failIfAlmostEqual;F;;self,first,second,places,msg;
550.58 - member : failIfEqual;F;;self,first,second,msg;
550.59 - member : failUnless;F;;self,expr,msg;
550.60 - member : failUnlessAlmostEqual;F;;self,first,second,places,msg;
550.61 - member : failUnlessEqual;F;;self,first,second,msg;
550.62 - member : failUnlessRaises;F;;self,excClass,callableObj,args,kwargs;
550.63 - member : failureException;D;;
550.64 - member : id;F;;self;
550.65 - member : run;F;;self,result;
550.66 - member : setUp;F;;self;
550.67 - member : shortDescription;F;;self;
550.68 - member : tearDown;F;;self;
550.69 -
550.70 -Not Searchable Keys:
550.71 -
550.72 -
550.73 -Document 2
550.74 -Searchable Keys:
550.75 - class : TestLoader
550.76 - class-ig : testloader
550.77 - in : unittest
550.78 - member : getTestCaseNames;F;;self,testCaseClass;
550.79 - member : loadTestsFromModule;F;;self,module;
550.80 - member : loadTestsFromName;F;;self,name,module;
550.81 - member : loadTestsFromNames;F;;self,names,module;
550.82 - member : loadTestsFromTestCase;F;;self,testCaseClass;
550.83 - member : sortTestMethodsUsing;D;;
550.84 - member : suiteClass;D;;
550.85 - member : testMethodPrefix;D;;
550.86 -
550.87 -Not Searchable Keys:
550.88 -
550.89 -
550.90 -Document 3
550.91 -Searchable Keys:
550.92 - class : TestProgram
550.93 - class-ig : testprogram
550.94 - in : unittest
550.95 - member : USAGE;D;|PRIVATE|;
550.96 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,module,defaultTest,argv,testRunner,testLoader;
550.97 - member : createTests;F;|PRIVATE|;self;
550.98 - member : defaultTest;D;;
550.99 - member : module;D;;
550.100 - member : parseArgs;F;|PRIVATE|;self,argv;
550.101 - member : progName;D;;
550.102 - member : runTests;F;|PRIVATE|;self;
550.103 - member : test;D;;
550.104 - member : testLoader;D;;
550.105 - member : testNames;D;;
550.106 - member : testRunner;D;;
550.107 - member : usageExit;F;|PRIVATE|;self,msg;
550.108 - member : verbosity;D;;
550.109 -
550.110 -Not Searchable Keys:
550.111 - clzattrs : ;|PRIVATE|;
550.112 -
550.113 -
550.114 -Document 4
550.115 -Searchable Keys:
550.116 - class : TestResult
550.117 - class-ig : testresult
550.118 - in : unittest
550.119 - member : __init__;c;|CONSTRUCTOR|;self;
550.120 - member : __repr__;F;;self;
550.121 - member : _count_relevant_tb_levels;F;|PRIVATE|;self,tb;
550.122 - member : _exc_info_to_string;F;|PRIVATE|;self,err,test;
550.123 - member : _is_relevant_tb_level;F;|PRIVATE|;self,tb;
550.124 - member : addError;F;;self,test,err;
550.125 - member : addFailure;F;;self,test,err;
550.126 - member : addSuccess;F;;self,test;
550.127 - member : errors;D;;
550.128 - member : failures;D;;
550.129 - member : shouldStop;D;;
550.130 - member : startTest;F;;self,test;
550.131 - member : stop;F;;self;
550.132 - member : stopTest;F;;self,test;
550.133 - member : testsRun;D;;
550.134 - member : wasSuccessful;F;;self;
550.135 -
550.136 -Not Searchable Keys:
550.137 -
550.138 -
550.139 -Document 5
550.140 -Searchable Keys:
550.141 - class : TestSuite
550.142 - class-ig : testsuite
550.143 - in : unittest
550.144 - member : __call__;F;;self,args,kwds;
550.145 - member : __init__;c;|CONSTRUCTOR|;self,tests;
550.146 - member : __iter__;F;;self;
550.147 - member : __repr__;F;;self;
550.148 - member : __str__;F;;self;
550.149 - member : _tests;D;|PRIVATE|;
550.150 - member : addTest;F;;self,test;
550.151 - member : addTests;F;;self,tests;
550.152 - member : countTestCases;F;;self;
550.153 - member : debug;F;;self;
550.154 - member : run;F;;self,result;
550.155 -
550.156 -Not Searchable Keys:
550.157 -
550.158 -
550.159 -Document 6
550.160 -Searchable Keys:
550.161 - class : TextTestRunner
550.162 - class-ig : texttestrunner
550.163 - in : unittest
550.164 - member : __init__;c;|CONSTRUCTOR|;self,stream,descriptions,verbosity;
550.165 - member : _makeResult;F;|PRIVATE|;self;
550.166 - member : descriptions;D;;
550.167 - member : run;F;;self,test;
550.168 - member : stream;D;;
550.169 - member : verbosity;D;;
550.170 -
550.171 -Not Searchable Keys:
550.172 -
550.173 -
550.174 -Document 7
550.175 -Searchable Keys:
550.176 - class : _TextTestResult
550.177 - class-ig : _texttestresult
550.178 - extends : TestResult
550.179 - in : unittest
550.180 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,stream,descriptions,verbosity;
550.181 - member : addError;F;|PRIVATE|;self,test,err;
550.182 - member : addFailure;F;|PRIVATE|;self,test,err;
550.183 - member : addSuccess;F;|PRIVATE|;self,test;
550.184 - member : descriptions;D;;
550.185 - member : dots;D;;
550.186 - member : getDescription;F;|PRIVATE|;self,test;
550.187 - member : printErrorList;F;|PRIVATE|;self,flavour,errors;
550.188 - member : printErrors;F;|PRIVATE|;self;
550.189 - member : separator1;D;|PRIVATE|;
550.190 - member : separator2;D;|PRIVATE|;
550.191 - member : showAll;D;;
550.192 - member : startTest;F;|PRIVATE|;self,test;
550.193 - member : stream;D;;
550.194 -
550.195 -Not Searchable Keys:
550.196 - clzattrs : ;|PRIVATE|;
550.197 -
550.198 -
550.199 -Document 8
550.200 -Searchable Keys:
550.201 - class : _WritelnDecorator
550.202 - class-ig : _writelndecorator
550.203 - in : unittest
550.204 - member : __getattr__;F;|PRIVATE|;self,attr;
550.205 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,stream;
550.206 - member : stream;D;;
550.207 - member : writeln;F;|PRIVATE|;self,arg;
550.208 -
550.209 -Not Searchable Keys:
550.210 - clzattrs : ;|PRIVATE|;
550.211 -
550.212 -
550.213 -Document 9
550.214 -Searchable Keys:
550.215 - class : main
550.216 - class-ig : main
550.217 - in : unittest
550.218 - member : USAGE;D;|PRIVATE|;
550.219 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,module,defaultTest,argv,testRunner,testLoader;
550.220 - member : createTests;F;|PRIVATE|;self;
550.221 - member : defaultTest;D;;
550.222 - member : module;D;;
550.223 - member : parseArgs;F;|PRIVATE|;self,argv;
550.224 - member : progName;D;;
550.225 - member : runTests;F;|PRIVATE|;self;
550.226 - member : test;D;;
550.227 - member : testLoader;D;;
550.228 - member : testNames;D;;
550.229 - member : testRunner;D;;
550.230 - member : usageExit;F;|PRIVATE|;self,msg;
550.231 - member : verbosity;D;;
550.232 -
550.233 -Not Searchable Keys:
550.234 -
550.235 -
550.236 -Document 10
550.237 -Searchable Keys:
550.238 - item : False;D;|PRIVATE|;
550.239 - item : FunctionTestCase;C;;
550.240 - item : TestCase;C;;
550.241 - item : TestLoader;C;;
550.242 - item : TestProgram;C;|PRIVATE|;
550.243 - item : TestResult;C;;
550.244 - item : TestSuite;C;;
550.245 - item : TextTestRunner;C;;
550.246 - item : True;D;|PRIVATE|;
550.247 - item : _TextTestResult;C;|PRIVATE|;
550.248 - item : _WritelnDecorator;C;|PRIVATE|;
550.249 - item : __all__;D;;
550.250 - item : __author__;D;|PRIVATE|;
550.251 - item : __email__;D;|PRIVATE|;
550.252 - item : __metaclass__;D;|PRIVATE|;
550.253 - item : __unittest;D;|PRIVATE|;
550.254 - item : __version__;D;|PRIVATE|;
550.255 - item : _makeLoader;F;|PRIVATE|;prefix,sortUsing,suiteClass;
550.256 - item : _strclass;F;|PRIVATE|;cls;
550.257 - item : defaultTestLoader;D;;
550.258 - item : findTestCases;F;;module,prefix,sortUsing,suiteClass;
550.259 - item : getTestCaseNames;F;;testCaseClass,prefix,sortUsing;
550.260 - item : isinstance;F;|PRIVATE|;obj,clsinfo;
550.261 - item : main;C;;
550.262 - item : makeSuite;F;;testCaseClass,prefix,sortUsing,suiteClass;
550.263 - item : os;I;|PRIVATE|;
550.264 - item : sys;I;|PRIVATE|;
550.265 - item : time;I;|PRIVATE|;
550.266 - item : traceback;I;|PRIVATE|;
550.267 - item : types;I;|PRIVATE|;
550.268 - module : unittest
550.269 -
550.270 -Not Searchable Keys:
551.1 --- a/python.editor/test/unit/data/testfiles/unittest.py.scopes Sun Jan 04 13:11:53 2015 -0600
551.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
551.3 @@ -1,969 +0,0 @@
551.4 -=============================================
551.5 -<file-top>: Module : OffsetRange[22,29392>
551.6 -False [bound][private][data][read][node=Name]
551.7 -FunctionTestCase [bound][class][def][node=ClassDef]
551.8 -None [private][read][UNRESOLVED][node=Name]
551.9 -TestCase [bound][class][def][read][node=ClassDef]
551.10 -TestLoader [bound][class][def][read][called][node=ClassDef]
551.11 -TestProgram [bound][private][class][def][read][node=ClassDef]
551.12 -TestResult [bound][class][def][read][called][node=ClassDef]
551.13 -TestSuite [bound][class][def][read][node=ClassDef]
551.14 -TextTestRunner [bound][class][def][read][called][node=ClassDef]
551.15 -True [bound][private][data][read][node=Name]
551.16 -_TextTestResult [bound][private][class][def][read][called][node=ClassDef]
551.17 -_WritelnDecorator [bound][private][class][def][read][called][node=ClassDef]
551.18 -__all__ [bound][data][read][node=Name]
551.19 -__author__ [bound][private][data][node=Name]
551.20 -__email__ [bound][private][data][node=Name]
551.21 -__metaclass__ [bound][private][data][node=Name]
551.22 -__name__ [private][read][UNRESOLVED][node=Name]
551.23 -__unittest [bound][private][data][node=Name]
551.24 -__version__ [bound][private][data][node=Name]
551.25 -_makeLoader [bound][private][function][def][read][called][node=FunctionDef]
551.26 -_strclass [bound][private][function][def][read][called][node=FunctionDef]
551.27 -cmp [private][read][UNRESOLVED][node=Name]
551.28 -defaultTestLoader [bound][data][read][node=Name]
551.29 -findTestCases [bound][function][def][node=FunctionDef]
551.30 -getTestCaseNames [bound][function][def][node=FunctionDef]
551.31 -isinstance [bound][private][function][def][read][called][node=FunctionDef]
551.32 -main [bound][class][read][alias][called][node=ClassDef]
551.33 -makeSuite [bound][function][def][node=FunctionDef]
551.34 -os [bound][imported][private][data][read][node=Import]
551.35 -sys [bound][imported][private][data][read][node=Import]
551.36 -time [bound][imported][private][data][read][node=Import]
551.37 -traceback [bound][imported][private][data][read][node=Import]
551.38 -type [private][read][UNRESOLVED][node=Name]
551.39 -types [bound][imported][private][data][read][node=Import]
551.40 -
551.41 - =============================================
551.42 - isinstance: FunctionDef : OffsetRange[2570,3180>
551.43 - __builtin__ [bound][imported][private][data][read][node=Import]
551.44 - cls [bound][private][data][read][node=Name]
551.45 - clsinfo [bound][param][private][data][read][node=Name]
551.46 - list [free][private][read][node=Name]
551.47 - obj [bound][param][private][data][read][node=Name]
551.48 - tuple [free][private][read][node=Name]
551.49 - type [free][private][read][called][node=Name]
551.50 - types [free][private][read][node=Name]
551.51 -
551.52 - =============================================
551.53 - _strclass: FunctionDef : OffsetRange[3202,3275>
551.54 - cls [bound][param][private][data][read][node=Name]
551.55 -
551.56 - =============================================
551.57 - class TestResult: ClassDef : OffsetRange[3291,6032>
551.58 - __init__ [bound][function][def][node=FunctionDef]
551.59 - __repr__ [bound][function][def][node=FunctionDef]
551.60 - _count_relevant_tb_levels [bound][private][function][def][node=FunctionDef]
551.61 - _exc_info_to_string [bound][private][function][def][node=FunctionDef]
551.62 - _is_relevant_tb_level [bound][private][function][def][node=FunctionDef]
551.63 - addError [bound][function][def][node=FunctionDef]
551.64 - addFailure [bound][function][def][node=FunctionDef]
551.65 - addSuccess [bound][function][def][node=FunctionDef]
551.66 - startTest [bound][function][def][node=FunctionDef]
551.67 - stop [bound][function][def][node=FunctionDef]
551.68 - stopTest [bound][function][def][node=FunctionDef]
551.69 - wasSuccessful [bound][function][def][node=FunctionDef]
551.70 - ------ Attributes ---------------------------------------
551.71 - errors : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.72 - failures : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.73 - shouldStop : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.74 - testsRun : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.75 -
551.76 - =============================================
551.77 - __init__: FunctionDef : OffsetRange[3797,3927>
551.78 - self [bound][param][data][read][node=Name]
551.79 -
551.80 - =============================================
551.81 - startTest: FunctionDef : OffsetRange[3928,4057>
551.82 - self [bound][param][data][read][node=Name]
551.83 - test [bound][param][data][unused][node=Name]
551.84 - ------ Attributes ---------------------------------------
551.85 - testsRun : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.86 -
551.87 - =============================================
551.88 - stopTest: FunctionDef : OffsetRange[4058,4151>
551.89 - self [bound][param][data][unused][node=Name]
551.90 - test [bound][param][data][unused][node=Name]
551.91 -
551.92 - =============================================
551.93 - addError: FunctionDef : OffsetRange[4152,4383>
551.94 - err [bound][param][data][read][node=Name]
551.95 - self [bound][param][data][read][node=Name]
551.96 - test [bound][param][data][read][node=Name]
551.97 - ------ Attributes ---------------------------------------
551.98 - _exc_info_to_string : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
551.99 - errors : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.100 -
551.101 - =============================================
551.102 - addFailure: FunctionDef : OffsetRange[4384,4610>
551.103 - err [bound][param][data][read][node=Name]
551.104 - self [bound][param][data][read][node=Name]
551.105 - test [bound][param][data][read][node=Name]
551.106 - ------ Attributes ---------------------------------------
551.107 - _exc_info_to_string : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
551.108 - failures : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.109 -
551.110 - =============================================
551.111 - addSuccess: FunctionDef : OffsetRange[4611,4712>
551.112 - self [bound][param][data][unused][node=Name]
551.113 - test [bound][param][data][unused][node=Name]
551.114 -
551.115 - =============================================
551.116 - wasSuccessful: FunctionDef : OffsetRange[4713,4858>
551.117 - len [free][read][called][node=Name]
551.118 - self [bound][param][data][read][node=Name]
551.119 - ------ Attributes ---------------------------------------
551.120 - errors : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.121 - failures : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.122 -
551.123 - =============================================
551.124 - stop: FunctionDef : OffsetRange[4859,4963>
551.125 - True [free][read][node=Name]
551.126 - self [bound][param][data][read][node=Name]
551.127 -
551.128 - =============================================
551.129 - _exc_info_to_string: FunctionDef : OffsetRange[4964,5546>
551.130 - err [bound][param][data][read][node=Name]
551.131 - exctype [bound][data][read][node=Name]
551.132 - length [bound][data][read][node=Name]
551.133 - self [bound][param][data][read][node=Name]
551.134 - tb [bound][data][read][node=Name]
551.135 - test [bound][param][data][read][node=Name]
551.136 - traceback [free][read][node=Name]
551.137 - value [bound][data][read][node=Name]
551.138 - ------ Attributes ---------------------------------------
551.139 - _count_relevant_tb_levels : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
551.140 - _is_relevant_tb_level : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
551.141 -
551.142 - =============================================
551.143 - _is_relevant_tb_level: FunctionDef : OffsetRange[5547,5647>
551.144 - self [bound][param][data][unused][node=Name]
551.145 - tb [bound][param][data][read][node=Name]
551.146 -
551.147 - =============================================
551.148 - _count_relevant_tb_levels: FunctionDef : OffsetRange[5648,5843>
551.149 - length [bound][data][read][node=Name]
551.150 - self [bound][param][data][read][node=Name]
551.151 - tb [bound][param][data][read][node=Name]
551.152 - ------ Attributes ---------------------------------------
551.153 - _is_relevant_tb_level : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
551.154 -
551.155 - =============================================
551.156 - __repr__: FunctionDef : OffsetRange[5844,6032>
551.157 - _strclass [free][read][called][node=Name]
551.158 - len [free][read][called][node=Name]
551.159 - self [bound][param][data][read][node=Name]
551.160 - ------ Attributes ---------------------------------------
551.161 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.162 - errors : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.163 - failures : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.164 - testsRun : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.165 -
551.166 - =============================================
551.167 - class TestCase: ClassDef : OffsetRange[6032,13849>
551.168 - AssertionError [free][read][node=Name]
551.169 - None [free][read][node=Name]
551.170 - __call__ [bound][function][def][node=FunctionDef]
551.171 - __init__ [bound][function][def][node=FunctionDef]
551.172 - __repr__ [bound][function][def][node=FunctionDef]
551.173 - __str__ [bound][function][def][node=FunctionDef]
551.174 - _exc_info [bound][private][function][def][node=FunctionDef]
551.175 - assertAlmostEqual [bound][function][alias][node=FunctionDef]
551.176 - assertAlmostEquals [bound][function][alias][node=FunctionDef]
551.177 - assertEqual [bound][function][alias][node=FunctionDef]
551.178 - assertEquals [bound][function][alias][node=FunctionDef]
551.179 - assertFalse [bound][function][alias][node=FunctionDef]
551.180 - assertNotAlmostEqual [bound][function][alias][node=FunctionDef]
551.181 - assertNotAlmostEquals [bound][function][alias][node=FunctionDef]
551.182 - assertNotEqual [bound][function][alias][node=FunctionDef]
551.183 - assertNotEquals [bound][function][alias][node=FunctionDef]
551.184 - assertRaises [bound][function][alias][node=FunctionDef]
551.185 - assertTrue [bound][function][alias][node=FunctionDef]
551.186 - assert_ [bound][function][alias][node=FunctionDef]
551.187 - countTestCases [bound][function][def][node=FunctionDef]
551.188 - debug [bound][function][def][node=FunctionDef]
551.189 - defaultTestResult [bound][function][def][node=FunctionDef]
551.190 - fail [bound][function][def][node=FunctionDef]
551.191 - failIf [bound][function][def][read][node=FunctionDef]
551.192 - failIfAlmostEqual [bound][function][def][read][node=FunctionDef]
551.193 - failIfEqual [bound][function][def][read][node=FunctionDef]
551.194 - failUnless [bound][function][def][read][node=FunctionDef]
551.195 - failUnlessAlmostEqual [bound][function][def][read][node=FunctionDef]
551.196 - failUnlessEqual [bound][function][def][read][node=FunctionDef]
551.197 - failUnlessRaises [bound][function][def][read][node=FunctionDef]
551.198 - failureException [bound][data][node=Name]
551.199 - id [bound][function][def][node=FunctionDef]
551.200 - run [bound][function][def][node=FunctionDef]
551.201 - setUp [bound][function][def][node=FunctionDef]
551.202 - shortDescription [bound][function][def][node=FunctionDef]
551.203 - tearDown [bound][function][def][node=FunctionDef]
551.204 - ------ Attributes ---------------------------------------
551.205 - _testMethodDoc : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.206 - _testMethodName : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.207 -
551.208 - =============================================
551.209 - __init__: FunctionDef : OffsetRange[7252,7817>
551.210 - AttributeError [free][read][node=Name]
551.211 - ValueError [free][read][node=Name]
551.212 - getattr [free][read][called][node=Name]
551.213 - methodName [bound][param][data][read][node=Name]
551.214 - self [bound][param][data][read][node=Name]
551.215 - testMethod [bound][data][read][node=Name]
551.216 - ------ Attributes ---------------------------------------
551.217 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.218 -
551.219 - =============================================
551.220 - setUp: FunctionDef : OffsetRange[7818,7928>
551.221 - self [bound][param][data][unused][node=Name]
551.222 -
551.223 - =============================================
551.224 - tearDown: FunctionDef : OffsetRange[7929,8042>
551.225 - self [bound][param][data][unused][node=Name]
551.226 -
551.227 - =============================================
551.228 - countTestCases: FunctionDef : OffsetRange[8043,8090>
551.229 - self [bound][param][data][unused][node=Name]
551.230 -
551.231 - =============================================
551.232 - defaultTestResult: FunctionDef : OffsetRange[8091,8152>
551.233 - TestResult [free][read][called][node=Name]
551.234 - self [bound][param][data][unused][node=Name]
551.235 -
551.236 - =============================================
551.237 - shortDescription: FunctionDef : OffsetRange[8153,8521>
551.238 - None [free][read][node=Name]
551.239 - doc [bound][data][read][node=Name]
551.240 - self [bound][param][data][read][node=Name]
551.241 - ------ Attributes ---------------------------------------
551.242 - _testMethodDoc : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.243 -
551.244 - =============================================
551.245 - id: FunctionDef : OffsetRange[8522,8615>
551.246 - _strclass [free][read][called][node=Name]
551.247 - self [bound][param][data][read][node=Name]
551.248 - ------ Attributes ---------------------------------------
551.249 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.250 - _testMethodName : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.251 -
551.252 - =============================================
551.253 - __str__: FunctionDef : OffsetRange[8616,8716>
551.254 - _strclass [free][read][called][node=Name]
551.255 - self [bound][param][data][read][node=Name]
551.256 - ------ Attributes ---------------------------------------
551.257 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.258 - _testMethodName : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.259 -
551.260 - =============================================
551.261 - __repr__: FunctionDef : OffsetRange[8717,8846>
551.262 - _strclass [free][read][called][node=Name]
551.263 - self [bound][param][data][read][node=Name]
551.264 - ------ Attributes ---------------------------------------
551.265 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.266 - _testMethodName : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.267 -
551.268 - =============================================
551.269 - run: FunctionDef : OffsetRange[8847,9885>
551.270 - False [free][read][node=Name]
551.271 - KeyboardInterrupt [free][read][node=Name]
551.272 - None [free][read][node=Name]
551.273 - True [free][read][node=Name]
551.274 - getattr [free][read][called][node=Name]
551.275 - ok [bound][data][read][node=Name]
551.276 - result [bound][param][data][read][node=Name]
551.277 - self [bound][param][data][read][node=Name]
551.278 - testMethod [bound][data][read][called][node=Name]
551.279 - ------ Attributes ---------------------------------------
551.280 - _exc_info : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
551.281 - _testMethodName : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.282 - defaultTestResult : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.283 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.284 - setUp : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.285 - tearDown : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.286 -
551.287 - =============================================
551.288 - __call__: FunctionDef : OffsetRange[9886,9964>
551.289 - args [bound][param][data][read][node=arguments]
551.290 - kwds [bound][param][data][read][node=arguments]
551.291 - self [bound][param][data][read][node=Name]
551.292 - ------ Attributes ---------------------------------------
551.293 - run : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.294 -
551.295 - =============================================
551.296 - debug: FunctionDef : OffsetRange[9965,10146>
551.297 - getattr [free][read][called][node=Name]
551.298 - self [bound][param][data][read][node=Name]
551.299 - ------ Attributes ---------------------------------------
551.300 - _testMethodName : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.301 - setUp : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.302 - tearDown : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.303 -
551.304 - =============================================
551.305 - _exc_info: FunctionDef : OffsetRange[10147,10555>
551.306 - exctype [bound][data][read][node=Name]
551.307 - excvalue [bound][data][read][node=Name]
551.308 - self [bound][param][data][unused][node=Name]
551.309 - sys [free][read][node=Name]
551.310 - tb [bound][data][read][node=Name]
551.311 -
551.312 - =============================================
551.313 - fail: FunctionDef : OffsetRange[10556,10683>
551.314 - msg [bound][param][data][read][node=Name]
551.315 - self [bound][param][data][read][node=Name]
551.316 - ------ Attributes ---------------------------------------
551.317 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.318 -
551.319 - =============================================
551.320 - failIf: FunctionDef : OffsetRange[10684,10823>
551.321 - expr [bound][param][data][read][node=Name]
551.322 - msg [bound][param][data][read][node=Name]
551.323 - self [bound][param][data][read][node=Name]
551.324 - ------ Attributes ---------------------------------------
551.325 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.326 -
551.327 - =============================================
551.328 - failUnless: FunctionDef : OffsetRange[10824,10979>
551.329 - expr [bound][param][data][read][node=Name]
551.330 - msg [bound][param][data][read][node=Name]
551.331 - self [bound][param][data][read][node=Name]
551.332 - ------ Attributes ---------------------------------------
551.333 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.334 -
551.335 - =============================================
551.336 - failUnlessRaises: FunctionDef : OffsetRange[10980,11722>
551.337 - args [bound][param][data][read][node=arguments]
551.338 - callableObj [bound][param][data][read][called][node=Name]
551.339 - excClass [bound][param][data][read][node=Name]
551.340 - excName [bound][data][read][node=Name]
551.341 - hasattr [free][read][called][node=Name]
551.342 - kwargs [bound][param][data][read][node=arguments]
551.343 - self [bound][param][data][read][node=Name]
551.344 - str [free][read][called][node=Name]
551.345 - ------ Attributes ---------------------------------------
551.346 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.347 -
551.348 - =============================================
551.349 - failUnlessEqual: FunctionDef : OffsetRange[11723,12016>
551.350 - first [bound][param][data][read][node=Name]
551.351 - msg [bound][param][data][read][node=Name]
551.352 - second [bound][param][data][read][node=Name]
551.353 - self [bound][param][data][read][node=Name]
551.354 - ------ Attributes ---------------------------------------
551.355 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.356 -
551.357 - =============================================
551.358 - failIfEqual: FunctionDef : OffsetRange[12017,12300>
551.359 - first [bound][param][data][read][node=Name]
551.360 - msg [bound][param][data][read][node=Name]
551.361 - second [bound][param][data][read][node=Name]
551.362 - self [bound][param][data][read][node=Name]
551.363 - ------ Attributes ---------------------------------------
551.364 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.365 -
551.366 - =============================================
551.367 - failUnlessAlmostEqual: FunctionDef : OffsetRange[12301,12888>
551.368 - first [bound][param][data][read][node=Name]
551.369 - msg [bound][param][data][read][node=Name]
551.370 - places [bound][param][data][read][node=Name]
551.371 - round [free][read][called][node=Name]
551.372 - second [bound][param][data][read][node=Name]
551.373 - self [bound][param][data][read][node=Name]
551.374 - ------ Attributes ---------------------------------------
551.375 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.376 -
551.377 - =============================================
551.378 - failIfAlmostEqual: FunctionDef : OffsetRange[12889,13508>
551.379 - first [bound][param][data][read][node=Name]
551.380 - msg [bound][param][data][read][node=Name]
551.381 - places [bound][param][data][read][node=Name]
551.382 - round [free][read][called][node=Name]
551.383 - second [bound][param][data][read][node=Name]
551.384 - self [bound][param][data][read][node=Name]
551.385 - ------ Attributes ---------------------------------------
551.386 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.387 -
551.388 - =============================================
551.389 - class TestSuite: ClassDef : OffsetRange[13849,15757>
551.390 - __call__ [bound][function][def][node=FunctionDef]
551.391 - __init__ [bound][function][def][node=FunctionDef]
551.392 - __iter__ [bound][function][def][node=FunctionDef]
551.393 - __repr__ [bound][function][def][read][node=FunctionDef]
551.394 - __str__ [bound][function][alias][node=FunctionDef]
551.395 - addTest [bound][function][def][node=FunctionDef]
551.396 - addTests [bound][function][def][node=FunctionDef]
551.397 - countTestCases [bound][function][def][node=FunctionDef]
551.398 - debug [bound][function][def][node=FunctionDef]
551.399 - run [bound][function][def][node=FunctionDef]
551.400 - ------ Attributes ---------------------------------------
551.401 - _tests : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.402 -
551.403 - =============================================
551.404 - __init__: FunctionDef : OffsetRange[14316,14404>
551.405 - self [bound][param][data][read][node=Name]
551.406 - tests [bound][param][data][read][node=Name]
551.407 - ------ Attributes ---------------------------------------
551.408 - addTests : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.409 -
551.410 - =============================================
551.411 - __repr__: FunctionDef : OffsetRange[14405,14503>
551.412 - _strclass [free][read][called][node=Name]
551.413 - self [bound][param][data][read][node=Name]
551.414 - ------ Attributes ---------------------------------------
551.415 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.416 - _tests : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.417 -
551.418 - =============================================
551.419 - __iter__: FunctionDef : OffsetRange[14528,14585>
551.420 - iter [free][read][called][node=Name]
551.421 - self [bound][param][data][read][node=Name]
551.422 - ------ Attributes ---------------------------------------
551.423 - _tests : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.424 -
551.425 - =============================================
551.426 - countTestCases: FunctionDef : OffsetRange[14586,14731>
551.427 - cases [bound][data][read][node=Name]
551.428 - self [bound][param][data][read][node=Name]
551.429 - test [bound][data][read][node=Name]
551.430 - ------ Attributes ---------------------------------------
551.431 - _tests : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.432 -
551.433 - =============================================
551.434 - addTest: FunctionDef : OffsetRange[14732,15166>
551.435 - TestCase [free][read][node=Name]
551.436 - TestSuite [free][read][node=Name]
551.437 - TypeError [free][read][called][node=Name]
551.438 - callable [free][read][called][node=Name]
551.439 - isinstance [free][read][called][node=Name]
551.440 - issubclass [free][read][called][node=Name]
551.441 - self [bound][param][data][read][node=Name]
551.442 - test [bound][param][data][read][node=Name]
551.443 - type [free][read][node=Name]
551.444 - types [free][read][node=Name]
551.445 - ------ Attributes ---------------------------------------
551.446 - _tests : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.447 -
551.448 - =============================================
551.449 - addTests: FunctionDef : OffsetRange[15167,15378>
551.450 - TypeError [free][read][called][node=Name]
551.451 - basestring [free][read][node=Name]
551.452 - isinstance [free][read][called][node=Name]
551.453 - self [bound][param][data][read][node=Name]
551.454 - test [bound][data][read][node=Name]
551.455 - tests [bound][param][data][read][node=Name]
551.456 - ------ Attributes ---------------------------------------
551.457 - addTest : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.458 -
551.459 - =============================================
551.460 - run: FunctionDef : OffsetRange[15379,15542>
551.461 - result [bound][param][data][read][node=Name]
551.462 - self [bound][param][data][read][node=Name]
551.463 - test [bound][data][read][called][node=Name]
551.464 - ------ Attributes ---------------------------------------
551.465 - _tests : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.466 -
551.467 - =============================================
551.468 - __call__: FunctionDef : OffsetRange[15543,15621>
551.469 - args [bound][param][data][read][node=arguments]
551.470 - kwds [bound][param][data][read][node=arguments]
551.471 - self [bound][param][data][read][node=Name]
551.472 - ------ Attributes ---------------------------------------
551.473 - run : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.474 -
551.475 - =============================================
551.476 - debug: FunctionDef : OffsetRange[15622,15757>
551.477 - self [bound][param][data][read][node=Name]
551.478 - test [bound][data][read][node=Name]
551.479 - ------ Attributes ---------------------------------------
551.480 - _tests : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.481 -
551.482 - =============================================
551.483 - class FunctionTestCase: ClassDef : OffsetRange[15757,17312>
551.484 - None [free][read][node=Name]
551.485 - __init__ [bound][function][def][node=FunctionDef]
551.486 - __repr__ [bound][function][def][node=FunctionDef]
551.487 - __str__ [bound][function][def][node=FunctionDef]
551.488 - id [bound][function][def][node=FunctionDef]
551.489 - runTest [bound][function][def][node=FunctionDef]
551.490 - setUp [bound][function][def][node=FunctionDef]
551.491 - shortDescription [bound][function][def][node=FunctionDef]
551.492 - tearDown [bound][function][def][node=FunctionDef]
551.493 - ------ Attributes ---------------------------------------
551.494 - __description : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.495 - __setUpFunc : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.496 - __tearDownFunc : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.497 - __testFunc : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.498 -
551.499 - =============================================
551.500 - __init__: FunctionDef : OffsetRange[16134,16410>
551.501 - TestCase [free][read][node=Name]
551.502 - description [bound][param][data][read][node=Name]
551.503 - self [bound][param][data][read][node=Name]
551.504 - setUp [bound][param][data][read][node=Name]
551.505 - tearDown [bound][param][data][read][node=Name]
551.506 - testFunc [bound][param][data][read][node=Name]
551.507 - ------ Attributes ---------------------------------------
551.508 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.509 -
551.510 - =============================================
551.511 - setUp: FunctionDef : OffsetRange[16411,16504>
551.512 - None [free][read][node=Name]
551.513 - self [bound][param][data][read][node=Name]
551.514 - ------ Attributes ---------------------------------------
551.515 - __setUpFunc : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
551.516 -
551.517 - =============================================
551.518 - tearDown: FunctionDef : OffsetRange[16505,16607>
551.519 - None [free][read][node=Name]
551.520 - self [bound][param][data][read][node=Name]
551.521 - ------ Attributes ---------------------------------------
551.522 - __tearDownFunc : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
551.523 -
551.524 - =============================================
551.525 - runTest: FunctionDef : OffsetRange[16608,16657>
551.526 - self [bound][param][data][read][node=Name]
551.527 - ------ Attributes ---------------------------------------
551.528 - __testFunc : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
551.529 -
551.530 - =============================================
551.531 - id: FunctionDef : OffsetRange[16658,16716>
551.532 - self [bound][param][data][read][node=Name]
551.533 - ------ Attributes ---------------------------------------
551.534 - __testFunc : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.535 -
551.536 - =============================================
551.537 - __str__: FunctionDef : OffsetRange[16717,16821>
551.538 - _strclass [free][read][called][node=Name]
551.539 - self [bound][param][data][read][node=Name]
551.540 - ------ Attributes ---------------------------------------
551.541 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.542 - __testFunc : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.543 -
551.544 - =============================================
551.545 - __repr__: FunctionDef : OffsetRange[16822,16927>
551.546 - _strclass [free][read][called][node=Name]
551.547 - self [bound][param][data][read][node=Name]
551.548 - ------ Attributes ---------------------------------------
551.549 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.550 - __testFunc : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.551 -
551.552 - =============================================
551.553 - shortDescription: FunctionDef : OffsetRange[16928,17312>
551.554 - None [free][read][node=Name]
551.555 - doc [bound][data][read][node=Name]
551.556 - self [bound][param][data][read][node=Name]
551.557 - ------ Attributes ---------------------------------------
551.558 - __description : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.559 - __testFunc : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
551.560 -
551.561 - =============================================
551.562 - class TestLoader: ClassDef : OffsetRange[17312,21193>
551.563 - None [free][read][node=Name]
551.564 - TestSuite [free][read][node=Name]
551.565 - cmp [free][read][node=Name]
551.566 - getTestCaseNames [bound][function][def][node=FunctionDef]
551.567 - loadTestsFromModule [bound][function][def][node=FunctionDef]
551.568 - loadTestsFromName [bound][function][def][node=FunctionDef]
551.569 - loadTestsFromNames [bound][function][def][node=FunctionDef]
551.570 - loadTestsFromTestCase [bound][function][def][node=FunctionDef]
551.571 - sortTestMethodsUsing [bound][data][node=Name]
551.572 - suiteClass [bound][data][node=Name]
551.573 - testMethodPrefix [bound][data][node=Name]
551.574 -
551.575 - =============================================
551.576 - loadTestsFromTestCase: FunctionDef : OffsetRange[17553,18085>
551.577 - TestSuite [free][read][node=Name]
551.578 - TypeError [free][read][called][node=Name]
551.579 - hasattr [free][read][called][node=Name]
551.580 - issubclass [free][read][called][node=Name]
551.581 - map [free][read][called][node=Name]
551.582 - self [bound][param][data][read][node=Name]
551.583 - testCaseClass [bound][param][data][read][node=Name]
551.584 - testCaseNames [bound][data][read][node=Name]
551.585 - ------ Attributes ---------------------------------------
551.586 - getTestCaseNames : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.587 - suiteClass : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.588 -
551.589 - =============================================
551.590 - loadTestsFromModule: FunctionDef : OffsetRange[18086,18504>
551.591 - TestCase [free][read][node=Name]
551.592 - dir [free][read][called][node=Name]
551.593 - getattr [free][read][called][node=Name]
551.594 - isinstance [free][read][called][node=Name]
551.595 - issubclass [free][read][called][node=Name]
551.596 - module [bound][param][data][read][node=Name]
551.597 - name [bound][data][read][node=Name]
551.598 - obj [bound][data][read][node=Name]
551.599 - self [bound][param][data][read][node=Name]
551.600 - tests [bound][data][read][node=Name]
551.601 - type [free][read][node=Name]
551.602 - types [free][read][node=Name]
551.603 - ------ Attributes ---------------------------------------
551.604 - loadTestsFromTestCase : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.605 - suiteClass : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.606 -
551.607 - =============================================
551.608 - loadTestsFromName: FunctionDef : OffsetRange[18505,20125>
551.609 - ImportError [free][read][node=Name]
551.610 - None [free][read][node=Name]
551.611 - TestCase [free][read][node=Name]
551.612 - TestSuite [free][read][node=Name]
551.613 - ValueError [free][read][node=Name]
551.614 - __import__ [free][read][called][node=Name]
551.615 - callable [free][read][called][node=Name]
551.616 - getattr [free][read][called][node=Name]
551.617 - isinstance [free][read][called][node=Name]
551.618 - issubclass [free][read][called][node=Name]
551.619 - module [bound][param][data][read][node=Name]
551.620 - name [bound][param][data][read][node=Name]
551.621 - obj [bound][data][read][called][node=Name]
551.622 - parent [bound][data][read][called][node=Name]
551.623 - part [bound][data][read][node=Name]
551.624 - parts [bound][data][read][node=Name]
551.625 - parts_copy [bound][data][read][node=Name]
551.626 - self [bound][param][data][read][node=Name]
551.627 - test [bound][data][read][node=Name]
551.628 - type [free][read][called][node=Name]
551.629 - types [free][read][node=Name]
551.630 - ------ Attributes ---------------------------------------
551.631 - loadTestsFromModule : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.632 - loadTestsFromTestCase : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.633 -
551.634 - =============================================
551.635 - loadTestsFromNames: FunctionDef : OffsetRange[20126,20438>
551.636 - _[565_18] [bound][private][data][unused][node=ListComp]
551.637 - module [bound][param][data][read][node=Name]
551.638 - name [bound][data][read][node=Name]
551.639 - names [bound][param][data][read][node=Name]
551.640 - self [bound][param][data][read][node=Name]
551.641 - suites [bound][data][read][node=Name]
551.642 - ------ Attributes ---------------------------------------
551.643 - loadTestsFromName : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.644 - suiteClass : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.645 -
551.646 - =============================================
551.647 - getTestCaseNames: FunctionDef : OffsetRange[20439,21193>
551.648 - baseclass [bound][data][read][node=Name]
551.649 - callable [free][node=null]
551.650 - dir [free][read][called][node=Name]
551.651 - filter [free][read][called][node=Name]
551.652 - getattr [free][node=null]
551.653 - isTestMethod [bound][function][def][read][node=FunctionDef]
551.654 - self [bound][param][data][read][node=Name]
551.655 - testCaseClass [bound][param][data][read][node=Name]
551.656 - testFnName [bound][data][read][node=Name]
551.657 - testFnNames [bound][data][read][node=Name]
551.658 - ---------------------------------------------
551.659 - inner_free: {callable=PRESENT, getattr=PRESENT}
551.660 - ------ Attributes ---------------------------------------
551.661 - getTestCaseNames : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.662 - sortTestMethodsUsing : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.663 - testMethodPrefix : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.664 -
551.665 - =============================================
551.666 - isTestMethod: FunctionDef : OffsetRange[20581,20769>
551.667 - attrname [bound][param][data][read][node=Name]
551.668 - callable [free][read][called][node=Name]
551.669 - getattr [free][read][called][node=Name]
551.670 - prefix [bound][param][data][read][node=Name]
551.671 - testCaseClass [bound][param][data][read][node=Name]
551.672 -
551.673 - =============================================
551.674 - _makeLoader: FunctionDef : OffsetRange[21462,21691>
551.675 - TestLoader [free][private][read][called][node=Name]
551.676 - loader [bound][private][data][read][node=Name]
551.677 - prefix [bound][param][private][data][read][node=Name]
551.678 - sortUsing [bound][param][private][data][read][node=Name]
551.679 - suiteClass [bound][param][private][data][read][node=Name]
551.680 -
551.681 - =============================================
551.682 - getTestCaseNames: FunctionDef : OffsetRange[21691,21826>
551.683 - _makeLoader [free][read][called][node=Name]
551.684 - prefix [bound][param][data][read][node=Name]
551.685 - sortUsing [bound][param][data][read][node=Name]
551.686 - testCaseClass [bound][param][data][read][node=Name]
551.687 -
551.688 - =============================================
551.689 - makeSuite: FunctionDef : OffsetRange[21826,22000>
551.690 - _makeLoader [free][read][called][node=Name]
551.691 - prefix [bound][param][data][read][node=Name]
551.692 - sortUsing [bound][param][data][read][node=Name]
551.693 - suiteClass [bound][param][data][read][node=Name]
551.694 - testCaseClass [bound][param][data][read][node=Name]
551.695 -
551.696 - =============================================
551.697 - findTestCases: FunctionDef : OffsetRange[22000,22332>
551.698 - _makeLoader [free][read][called][node=Name]
551.699 - module [bound][param][data][read][node=Name]
551.700 - prefix [bound][param][data][read][node=Name]
551.701 - sortUsing [bound][param][data][read][node=Name]
551.702 - suiteClass [bound][param][data][read][node=Name]
551.703 -
551.704 - =============================================
551.705 - class _WritelnDecorator: ClassDef : OffsetRange[22332,22708>
551.706 - None [free][private][read][node=Name]
551.707 - __getattr__ [bound][private][function][def][node=FunctionDef]
551.708 - __init__ [bound][private][function][def][node=FunctionDef]
551.709 - writeln [bound][private][function][def][node=FunctionDef]
551.710 - ------ Attributes ---------------------------------------
551.711 - stream : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.712 -
551.713 - =============================================
551.714 - __init__: FunctionDef : OffsetRange[22436,22496>
551.715 - self [bound][param][private][data][read][node=Name]
551.716 - stream [bound][param][private][data][read][node=Name]
551.717 -
551.718 - =============================================
551.719 - __getattr__: FunctionDef : OffsetRange[22497,22571>
551.720 - attr [bound][param][private][data][read][node=Name]
551.721 - getattr [free][private][read][called][node=Name]
551.722 - self [bound][param][private][data][read][node=Name]
551.723 - ------ Attributes ---------------------------------------
551.724 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.725 -
551.726 - =============================================
551.727 - writeln: FunctionDef : OffsetRange[22572,22708>
551.728 - arg [bound][param][private][data][read][node=Name]
551.729 - self [bound][param][private][data][read][node=Name]
551.730 - ------ Attributes ---------------------------------------
551.731 - write : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.732 -
551.733 - =============================================
551.734 - class _TextTestResult: ClassDef : OffsetRange[22708,24622>
551.735 - __init__ [bound][private][function][def][node=FunctionDef]
551.736 - addError [bound][private][function][def][node=FunctionDef]
551.737 - addFailure [bound][private][function][def][node=FunctionDef]
551.738 - addSuccess [bound][private][function][def][node=FunctionDef]
551.739 - getDescription [bound][private][function][def][node=FunctionDef]
551.740 - printErrorList [bound][private][function][def][node=FunctionDef]
551.741 - printErrors [bound][private][function][def][node=FunctionDef]
551.742 - separator1 [bound][private][data][node=Name]
551.743 - separator2 [bound][private][data][node=Name]
551.744 - startTest [bound][private][function][def][node=FunctionDef]
551.745 - ------ Attributes ---------------------------------------
551.746 - descriptions : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.747 - dots : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.748 - showAll : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.749 - stream : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.750 -
551.751 - =============================================
551.752 - __init__: FunctionDef : OffsetRange[22915,23148>
551.753 - TestResult [free][private][read][node=Name]
551.754 - descriptions [bound][param][private][data][read][node=Name]
551.755 - self [bound][param][private][data][read][node=Name]
551.756 - stream [bound][param][private][data][read][node=Name]
551.757 - verbosity [bound][param][private][data][read][node=Name]
551.758 - ------ Attributes ---------------------------------------
551.759 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.760 -
551.761 - =============================================
551.762 - getDescription: FunctionDef : OffsetRange[23149,23314>
551.763 - self [bound][param][private][data][read][node=Name]
551.764 - str [free][private][read][called][node=Name]
551.765 - test [bound][param][private][data][read][node=Name]
551.766 - ------ Attributes ---------------------------------------
551.767 - descriptions : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.768 -
551.769 - =============================================
551.770 - startTest: FunctionDef : OffsetRange[23315,23508>
551.771 - TestResult [free][private][read][node=Name]
551.772 - self [bound][param][private][data][read][node=Name]
551.773 - test [bound][param][private][data][read][node=Name]
551.774 - ------ Attributes ---------------------------------------
551.775 - getDescription : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.776 - showAll : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.777 - startTest : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.778 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.779 -
551.780 - =============================================
551.781 - addSuccess: FunctionDef : OffsetRange[23509,23705>
551.782 - TestResult [free][private][read][node=Name]
551.783 - self [bound][param][private][data][read][node=Name]
551.784 - test [bound][param][private][data][read][node=Name]
551.785 - ------ Attributes ---------------------------------------
551.786 - addSuccess : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.787 - dots : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.788 - showAll : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.789 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.790 -
551.791 - =============================================
551.792 - addError: FunctionDef : OffsetRange[23706,23911>
551.793 - TestResult [free][private][read][node=Name]
551.794 - err [bound][param][private][data][read][node=Name]
551.795 - self [bound][param][private][data][read][node=Name]
551.796 - test [bound][param][private][data][read][node=Name]
551.797 - ------ Attributes ---------------------------------------
551.798 - addError : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.799 - dots : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.800 - showAll : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.801 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.802 -
551.803 - =============================================
551.804 - addFailure: FunctionDef : OffsetRange[23912,24120>
551.805 - TestResult [free][private][read][node=Name]
551.806 - err [bound][param][private][data][read][node=Name]
551.807 - self [bound][param][private][data][read][node=Name]
551.808 - test [bound][param][private][data][read][node=Name]
551.809 - ------ Attributes ---------------------------------------
551.810 - addFailure : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.811 - dots : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.812 - showAll : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.813 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.814 -
551.815 - =============================================
551.816 - printErrors: FunctionDef : OffsetRange[24121,24321>
551.817 - self [bound][param][private][data][read][node=Name]
551.818 - ------ Attributes ---------------------------------------
551.819 - dots : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.820 - errors : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.821 - failures : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.822 - printErrorList : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.823 - showAll : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.824 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.825 -
551.826 - =============================================
551.827 - printErrorList: FunctionDef : OffsetRange[24322,24622>
551.828 - err [bound][private][data][read][node=Name]
551.829 - errors [bound][param][private][data][read][node=Name]
551.830 - flavour [bound][param][private][data][read][node=Name]
551.831 - self [bound][param][private][data][read][node=Name]
551.832 - test [bound][private][data][read][node=Name]
551.833 - ------ Attributes ---------------------------------------
551.834 - getDescription : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.835 - separator1 : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.836 - separator2 : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.837 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.838 -
551.839 - =============================================
551.840 - class TextTestRunner: ClassDef : OffsetRange[24622,26349>
551.841 - __init__ [bound][function][def][node=FunctionDef]
551.842 - _makeResult [bound][private][function][def][node=FunctionDef]
551.843 - run [bound][function][def][node=FunctionDef]
551.844 - sys [free][read][node=Name]
551.845 - ------ Attributes ---------------------------------------
551.846 - descriptions : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.847 - stream : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.848 - verbosity : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.849 -
551.850 - =============================================
551.851 - __init__: FunctionDef : OffsetRange[24860,25056>
551.852 - _WritelnDecorator [free][read][called][node=Name]
551.853 - descriptions [bound][param][data][read][node=Name]
551.854 - self [bound][param][data][read][node=Name]
551.855 - stream [bound][param][data][read][node=Name]
551.856 - verbosity [bound][param][data][read][node=Name]
551.857 -
551.858 - =============================================
551.859 - _makeResult: FunctionDef : OffsetRange[25057,25163>
551.860 - _TextTestResult [free][read][called][node=Name]
551.861 - self [bound][param][data][read][node=Name]
551.862 - ------ Attributes ---------------------------------------
551.863 - descriptions : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.864 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.865 - verbosity : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.866 -
551.867 - =============================================
551.868 - run: FunctionDef : OffsetRange[25164,26349>
551.869 - errored [bound][data][read][node=Name]
551.870 - failed [bound][data][read][node=Name]
551.871 - len [free][read][node=Name]
551.872 - map [free][read][called][node=Name]
551.873 - result [bound][data][read][node=Name]
551.874 - run [bound][data][read][node=Name]
551.875 - self [bound][param][data][read][node=Name]
551.876 - startTime [bound][data][read][node=Name]
551.877 - stopTime [bound][data][read][node=Name]
551.878 - test [bound][param][data][read][called][node=Name]
551.879 - time [free][read][node=Name]
551.880 - timeTaken [bound][data][read][node=Name]
551.881 - ------ Attributes ---------------------------------------
551.882 - _makeResult : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
551.883 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.884 -
551.885 - =============================================
551.886 - class TestProgram: ClassDef : OffsetRange[26349,29118>
551.887 - None [free][private][read][node=Name]
551.888 - USAGE [bound][private][data][node=Name]
551.889 - __init__ [bound][private][function][def][node=FunctionDef]
551.890 - createTests [bound][private][function][def][node=FunctionDef]
551.891 - defaultTestLoader [free][private][read][node=Name]
551.892 - parseArgs [bound][private][function][def][node=FunctionDef]
551.893 - runTests [bound][private][function][def][node=FunctionDef]
551.894 - usageExit [bound][private][function][def][node=FunctionDef]
551.895 - ------ Attributes ---------------------------------------
551.896 - defaultTest : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.897 - module : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.898 - progName : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.899 - test : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
551.900 - testLoader : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.901 - testNames : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
551.902 - testRunner : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.903 - verbosity : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
551.904 -
551.905 - =============================================
551.906 - __init__: FunctionDef : OffsetRange[27056,27721>
551.907 - None [free][private][read][node=Name]
551.908 - __import__ [free][private][read][called][node=Name]
551.909 - argv [bound][param][private][data][read][node=Name]
551.910 - defaultTest [bound][param][private][data][read][node=Name]
551.911 - getattr [free][private][read][called][node=Name]
551.912 - module [bound][param][private][data][read][node=Name]
551.913 - os [free][private][read][node=Name]
551.914 - part [bound][private][data][read][node=Name]
551.915 - self [bound][param][private][data][read][node=Name]
551.916 - sys [free][private][read][node=Name]
551.917 - testLoader [bound][param][private][data][read][node=Name]
551.918 - testRunner [bound][param][private][data][read][node=Name]
551.919 - type [free][private][read][called][node=Name]
551.920 - ------ Attributes ---------------------------------------
551.921 - module : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.922 - parseArgs : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.923 - runTests : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.924 -
551.925 - =============================================
551.926 - usageExit: FunctionDef : OffsetRange[27722,27844>
551.927 - msg [bound][param][private][data][read][node=Name]
551.928 - self [bound][param][private][data][read][node=Name]
551.929 - sys [free][private][read][node=Name]
551.930 - ------ Attributes ---------------------------------------
551.931 - USAGE : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.932 - __dict__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.933 -
551.934 - =============================================
551.935 - parseArgs: FunctionDef : OffsetRange[27845,28729>
551.936 - None [free][private][read][node=Name]
551.937 - args [bound][private][data][read][node=Name]
551.938 - argv [bound][param][private][data][read][node=Name]
551.939 - getopt [bound][imported][private][data][read][node=Import]
551.940 - len [free][private][read][called][node=Name]
551.941 - msg [bound][private][data][read][node=Name]
551.942 - opt [bound][private][data][read][node=Name]
551.943 - options [bound][private][data][read][node=Name]
551.944 - self [bound][param][private][data][read][node=Name]
551.945 - value [bound][private][data][unused][node=Name]
551.946 - ------ Attributes ---------------------------------------
551.947 - createTests : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.948 - defaultTest : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.949 - module : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.950 - testLoader : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.951 - usageExit : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
551.952 -
551.953 - =============================================
551.954 - createTests: FunctionDef : OffsetRange[28730,28896>
551.955 - self [bound][param][private][data][read][node=Name]
551.956 - ------ Attributes ---------------------------------------
551.957 - module : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.958 - testLoader : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.959 - testNames : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.960 -
551.961 - =============================================
551.962 - runTests: FunctionDef : OffsetRange[28897,29118>
551.963 - None [free][private][read][node=Name]
551.964 - TextTestRunner [free][private][read][called][node=Name]
551.965 - result [bound][private][data][read][node=Name]
551.966 - self [bound][param][private][data][read][node=Name]
551.967 - sys [free][private][read][node=Name]
551.968 - ------ Attributes ---------------------------------------
551.969 - test : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.970 - testRunner : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.971 - verbosity : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
551.972 -
552.1 --- a/python.editor/test/unit/data/testfiles/unresolved.py Sun Jan 04 13:11:53 2015 -0600
552.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
552.3 @@ -1,12 +0,0 @@
552.4 -import binascii
552.5 -
552.6 -print "Whatever"
552.7 -putenv("hehe", "hoho")
552.8 -sys.displayhook("value")
552.9 -zip = ZipFile()
552.10 -
552.11 -def foo(x=None):
552.12 - pass
552.13 -
552.14 -binascii.a2b_hex("0xff")
552.15 -
553.1 --- a/python.editor/test/unit/data/testfiles/unresolved.py.scopes Sun Jan 04 13:11:53 2015 -0600
553.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
553.3 @@ -1,14 +0,0 @@
553.4 -=============================================
553.5 -<file-top>: Module : OffsetRange[0,150>
553.6 -None [read][UNRESOLVED][node=Name]
553.7 -ZipFile [read][called][UNRESOLVED][node=Name]
553.8 -binascii [bound][imported][data][read][node=Import]
553.9 -foo [bound][function][def][node=FunctionDef]
553.10 -putenv [read][called][UNRESOLVED][node=Name]
553.11 -sys [read][UNRESOLVED][node=Name]
553.12 -zip [bound][data][node=Name]
553.13 -
553.14 - =============================================
553.15 - foo: FunctionDef : OffsetRange[99,126>
553.16 - x [bound][param][data][unused][node=Name]
553.17 -
554.1 --- a/python.editor/test/unit/data/testfiles/unresolved.py.testUnresolvedHints.hints Sun Jan 04 13:11:53 2015 -0600
554.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
554.3 @@ -1,12 +0,0 @@
554.4 -putenv("hehe", "hoho")
554.5 -------
554.6 -HINT:Undefined name "putenv"
554.7 -FIX:Import os: putenv(key,value)
554.8 -sys.displayhook("value")
554.9 ----
554.10 -HINT:Undefined name "sys"
554.11 -FIX:Import sys
554.12 -zip = ZipFile()
554.13 - -------
554.14 -HINT:Undefined name "ZipFile"
554.15 -FIX:Import zipfile: ZipFile
555.1 --- a/python.editor/test/unit/data/testfiles/unresolved2.py Sun Jan 04 13:11:53 2015 -0600
555.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
555.3 @@ -1,3 +0,0 @@
555.4 -from zipfile import *
555.5 -ZipFile
555.6 -
556.1 --- a/python.editor/test/unit/data/testfiles/unresolved3.py Sun Jan 04 13:11:53 2015 -0600
556.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
556.3 @@ -1,5 +0,0 @@
556.4 -if __name__ == "__main__":
556.5 - print "Hello"
556.6 -print __doc__
556.7 -print __builtins__
556.8 -
557.1 --- a/python.editor/test/unit/data/testfiles/unresolved4.py Sun Jan 04 13:11:53 2015 -0600
557.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
557.3 @@ -1,10 +0,0 @@
557.4 -if (true):
557.5 - pass
557.6 -if (false):
557.7 - pass
557.8 -x = 0
557.9 -if (x == null):
557.10 - pass
557.11 -if (x == nil):
557.12 - pass
557.13 -
558.1 --- a/python.editor/test/unit/data/testfiles/unresolved4.py.testUnresolvedHints4.hints Sun Jan 04 13:11:53 2015 -0600
558.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
558.3 @@ -1,12 +0,0 @@
558.4 -if (true):
558.5 - ------
558.6 -HINT:Undefined name "true" - did you mean "True" ?
558.7 -if (false):
558.8 - -------
558.9 -HINT:Undefined name "false" - did you mean "False" ?
558.10 -if (x == null):
558.11 - ----
558.12 -HINT:Undefined name "null" - did you mean "None" ?
558.13 -if (x == nil):
558.14 - ---
558.15 -HINT:Undefined name "nil" - did you mean "None" ?
559.1 --- a/python.editor/test/unit/data/testfiles/unresolved5.py Sun Jan 04 13:11:53 2015 -0600
559.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
559.3 @@ -1,2 +0,0 @@
559.4 -from sys import *
559.5 -exc_info()
560.1 --- a/python.editor/test/unit/data/testfiles/unresolved6.py Sun Jan 04 13:11:53 2015 -0600
560.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
560.3 @@ -1,9 +0,0 @@
560.4 -def toplevel():
560.5 - if false:
560.6 - raise ValuError("toplevel")
560.7 -
560.8 -class WikiPage():
560.9 - def get(self, page_name):
560.10 - if true:
560.11 - raise ValuError("get")
560.12 -
561.1 --- a/python.editor/test/unit/data/testfiles/unresolved6.py.testUnresolvedHints6.hints Sun Jan 04 13:11:53 2015 -0600
561.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
561.3 @@ -1,12 +0,0 @@
561.4 - if false:
561.5 - -----
561.6 -HINT:Undefined name "false" - did you mean "False" ?
561.7 - raise ValuError("toplevel")
561.8 - ---------
561.9 -HINT:Undefined name "ValuError"
561.10 - if true:
561.11 - ----
561.12 -HINT:Undefined name "true" - did you mean "True" ?
561.13 - raise ValuError("get")
561.14 - ---------
561.15 -HINT:Undefined name "ValuError"
562.1 --- a/python.editor/test/unit/data/testfiles/unresolvedattributes.py Sun Jan 04 13:11:53 2015 -0600
562.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
562.3 @@ -1,7 +0,0 @@
562.4 -class TestUnresolved :
562.5 - def __init__(self) :
562.6 - self.defined = "defined"
562.7 -
562.8 - def useAttr(self):
562.9 - print self.defined # OK
562.10 - print self.undefined # KO
562.11 \ No newline at end of file
563.1 --- a/python.editor/test/unit/data/testfiles/unresolvedattributes.py.testUnresolvedAttribute.hints Sun Jan 04 13:11:53 2015 -0600
563.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
563.3 @@ -1,3 +0,0 @@
563.4 - print self.undefined # KO
563.5 - --------------
563.6 -HINT:Undefined attribute "self.undefined"
564.1 --- a/python.editor/test/unit/data/testfiles/unresolvedparents.py Sun Jan 04 13:11:53 2015 -0600
564.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
564.3 @@ -1,31 +0,0 @@
564.4 -from socket import SocketType
564.5 -import bdb
564.6 -
564.7 -class GoodParent :
564.8 - """ simply a good top parent"""
564.9 - pass
564.10 -
564.11 -class GoodChild( GoodParent ):
564.12 - """ good inherit """
564.13 - pass
564.14 -
564.15 -class BadChild( BadParent ):
564.16 - """inherit from inexisting parent"""
564.17 - pass
564.18 -
564.19 -class GoodImportedFrom( SocketType ):
564.20 - """ inherit from a from imported class"""
564.21 - pass
564.22 -
564.23 -class GoodImported( bdb.Bdb ):
564.24 - """ inherit from an imported public module """
564.25 - pass
564.26 -
564.27 -class BadImported( undefined.Undefined ):
564.28 - """ inherit from bad module bad class """
564.29 - pass
564.30 -
564.31 -
564.32 -class BadImported2( pdb.Pdb ): # import missing
564.33 - """ inherit from non imported module """
564.34 - pass
564.35 \ No newline at end of file
565.1 --- a/python.editor/test/unit/data/testfiles/unresolvedparents.py.testUnresolvedParent.hints Sun Jan 04 13:11:53 2015 -0600
565.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
565.3 @@ -1,9 +0,0 @@
565.4 -class BadChild( BadParent ):
565.5 - ---------
565.6 -HINT:Inheriting from undefined parent class "BadParent"
565.7 -class BadImported( undefined.Undefined ):
565.8 - -------------------
565.9 -HINT:Inheriting from undefined parent class "undefined.Undefined"
565.10 -class BadImported2( pdb.Pdb ): # import missing
565.11 - -------
565.12 -HINT:Inheriting from undefined parent class "pdb.Pdb"
566.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py Sun Jan 04 13:11:53 2015 -0600
566.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
566.3 @@ -1,22 +0,0 @@
566.4 -"""
566.5 -Test
566.6 -"""
566.7 -import math as _math
566.8 -import time as _time
566.9 -import sys
566.10 -import urimport
566.11 -import extract1b
566.12 -from foo import Sym1, Sym2
566.13 -from bar import Sym3
566.14 -from bar import Sym4
566.15 -from foo import Sym5, Sym6
566.16 -from foo import Sym7, Sym8
566.17 -
566.18 -
566.19 -sys.excepthook()
566.20 -_time.isused()
566.21 -Sym2()
566.22 -Sym3()
566.23 -Sym5()
566.24 -Sym6()
566.25 -
567.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py.scopes Sun Jan 04 13:11:53 2015 -0600
567.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
567.3 @@ -1,16 +0,0 @@
567.4 -=============================================
567.5 -<file-top>: Module : OffsetRange[0,283>
567.6 -Sym1 [bound][imported][data][node=ImportFrom]
567.7 -Sym2 [bound][imported][data][read][called][node=ImportFrom]
567.8 -Sym3 [bound][imported][data][read][called][node=ImportFrom]
567.9 -Sym4 [bound][imported][data][node=ImportFrom]
567.10 -Sym5 [bound][imported][data][read][called][node=ImportFrom]
567.11 -Sym6 [bound][imported][data][read][called][node=ImportFrom]
567.12 -Sym7 [bound][imported][data][node=ImportFrom]
567.13 -Sym8 [bound][imported][data][node=ImportFrom]
567.14 -_math [bound][imported][private][data][node=Import]
567.15 -_time [bound][imported][private][data][read][node=Import]
567.16 -extract1b [bound][imported][data][node=Import]
567.17 -sys [bound][imported][data][read][node=Import]
567.18 -urimport [bound][imported][data][node=Import]
567.19 -
568.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
568.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
568.3 @@ -1,21 +0,0 @@
568.4 -"""
568.5 -Test
568.6 -"""
568.7 -import math as _math
568.8 -import time as _time
568.9 -import sys
568.10 -import extract1b
568.11 -from foo import Sym1, Sym2
568.12 -from bar import Sym3
568.13 -from bar import Sym4
568.14 -from foo import Sym5, Sym6
568.15 -from foo import Sym7, Sym8
568.16 -
568.17 -
568.18 -sys.excepthook()
568.19 -_time.isused()
568.20 -Sym2()
568.21 -Sym3()
568.22 -Sym5()
568.23 -Sym6()
568.24 -
569.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
569.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
569.3 @@ -1,17 +0,0 @@
569.4 -"""
569.5 -Test
569.6 -"""
569.7 -import time as _time
569.8 -import sys
569.9 -from foo import Sym2
569.10 -from bar import Sym3
569.11 -from foo import Sym5, Sym6
569.12 -
569.13 -
569.14 -sys.excepthook()
569.15 -_time.isused()
569.16 -Sym2()
569.17 -Sym3()
569.18 -Sym5()
569.19 -Sym6()
569.20 -
570.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py.testFix3.fixed Sun Jan 04 13:11:53 2015 -0600
570.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
570.3 @@ -1,26 +0,0 @@
570.4 -"""
570.5 -Test
570.6 -"""
570.7 -import math as _math
570.8 -import sys
570.9 -import time as _time
570.10 -
570.11 -from bar import Sym3
570.12 -from bar import Sym4
570.13 -import extract1b
570.14 -from foo import Sym1
570.15 -from foo import Sym2
570.16 -from foo import Sym5
570.17 -from foo import Sym6
570.18 -from foo import Sym7
570.19 -from foo import Sym8
570.20 -import urimport
570.21 -
570.22 -
570.23 -sys.excepthook()
570.24 -_time.isused()
570.25 -Sym2()
570.26 -Sym3()
570.27 -Sym5()
570.28 -Sym6()
570.29 -
571.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py.testFix4.fixed Sun Jan 04 13:11:53 2015 -0600
571.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
571.3 @@ -1,22 +0,0 @@
571.4 -"""
571.5 -Test
571.6 -"""
571.7 -import math as _math
571.8 -import time as _time
571.9 -import sys
571.10 -import urimport
571.11 -import extract1b
571.12 -from foo import Sym2
571.13 -from bar import Sym3
571.14 -from bar import Sym4
571.15 -from foo import Sym5, Sym6
571.16 -from foo import Sym7, Sym8
571.17 -
571.18 -
571.19 -sys.excepthook()
571.20 -_time.isused()
571.21 -Sym2()
571.22 -Sym3()
571.23 -Sym5()
571.24 -Sym6()
571.25 -
572.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py.testHints.hints Sun Jan 04 13:11:53 2015 -0600
572.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
572.3 @@ -1,36 +0,0 @@
572.4 -import math as _math
572.5 ---------------------
572.6 -HINT:Unused Import
572.7 -FIX:Remove Unused Import
572.8 -FIX:Remove All Unused Imports
572.9 -FIX:Clean up and Organize Imports
572.10 -import urimport
572.11 ----------------
572.12 -HINT:Unused Import
572.13 -FIX:Remove Unused Import
572.14 -FIX:Remove All Unused Imports
572.15 -FIX:Clean up and Organize Imports
572.16 -import extract1b
572.17 -----------------
572.18 -HINT:Unused Import
572.19 -FIX:Remove Unused Import
572.20 -FIX:Remove All Unused Imports
572.21 -FIX:Clean up and Organize Imports
572.22 -from foo import Sym1, Sym2
572.23 ---------------------------
572.24 -HINT:Some symbols are unused ([Sym1])
572.25 -FIX:Remove [Sym1] from import
572.26 -FIX:Remove All Unused Imports
572.27 -FIX:Clean up and Organize Imports
572.28 -from bar import Sym4
572.29 ---------------------
572.30 -HINT:Unused Import
572.31 -FIX:Remove Unused Import
572.32 -FIX:Remove All Unused Imports
572.33 -FIX:Clean up and Organize Imports
572.34 -from foo import Sym7, Sym8
572.35 ---------------------------
572.36 -HINT:Unused Import
572.37 -FIX:Remove Unused Import
572.38 -FIX:Remove All Unused Imports
572.39 -FIX:Clean up and Organize Imports
573.1 --- a/python.editor/test/unit/data/testfiles/unusedimports2.py Sun Jan 04 13:11:53 2015 -0600
573.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
573.3 @@ -1,11 +0,0 @@
573.4 -"""
573.5 -Test
573.6 -"""
573.7 -import math as _math
573.8 -import time as _time
573.9 -import sys, os, four
573.10 -import urimport
573.11 -import extract1b
573.12 -
573.13 -sys.foo()
573.14 -
574.1 --- a/python.editor/test/unit/data/testfiles/unusedimports2.py.testFix5.fixed Sun Jan 04 13:11:53 2015 -0600
574.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
574.3 @@ -1,11 +0,0 @@
574.4 -"""
574.5 -Test
574.6 -"""
574.7 -import math as _math
574.8 -import time as _time
574.9 -import sys,
574.10 -import urimport
574.11 -import extract1b
574.12 -
574.13 -sys.foo()
574.14 -
575.1 --- a/python.editor/test/unit/data/testfiles/unusedimports3.py Sun Jan 04 13:11:53 2015 -0600
575.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
575.3 @@ -1,3 +0,0 @@
575.4 -import operator
575.5 -abs()
575.6 -
576.1 --- a/python.editor/test/unit/data/testfiles/unusedimports3.py.testNoHints2.hints Sun Jan 04 13:11:53 2015 -0600
576.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
576.3 @@ -1,6 +0,0 @@
576.4 -import operator
576.5 ----------------
576.6 -HINT:Unused Import
576.7 -FIX:Remove Unused Import
576.8 -FIX:Remove All Unused Imports
576.9 -FIX:Clean up and Organize Imports
577.1 --- a/python.editor/test/unit/data/testfiles/zipfile.py Sun Jan 04 13:11:53 2015 -0600
577.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
577.3 @@ -1,900 +0,0 @@
577.4 -"""
577.5 -Read and write ZIP files.
577.6 -"""
577.7 -import struct, os, time, sys
577.8 -import binascii, cStringIO
577.9 -
577.10 -try:
577.11 - import zlib # We may need its compression method
577.12 -except ImportError:
577.13 - zlib = None
577.14 -
577.15 -__all__ = ["BadZipfile", "error", "ZIP_STORED", "ZIP_DEFLATED", "is_zipfile",
577.16 - "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile" ]
577.17 -
577.18 -class BadZipfile(Exception):
577.19 - pass
577.20 -
577.21 -
577.22 -class LargeZipFile(Exception):
577.23 - """
577.24 - Raised when writing a zipfile, the zipfile requires ZIP64 extensions
577.25 - and those extensions are disabled.
577.26 - """
577.27 -
577.28 -error = BadZipfile # The exception raised by this module
577.29 -
577.30 -ZIP64_LIMIT= (1 << 31) - 1
577.31 -
577.32 -# constants for Zip file compression methods
577.33 -ZIP_STORED = 0
577.34 -ZIP_DEFLATED = 8
577.35 -# Other ZIP compression methods not supported
577.36 -
577.37 -# Here are some struct module formats for reading headers
577.38 -structEndArchive = "<4s4H2LH" # 9 items, end of archive, 22 bytes
577.39 -stringEndArchive = "PK\005\006" # magic number for end of archive record
577.40 -structCentralDir = "<4s4B4HlLL5HLL"# 19 items, central directory, 46 bytes
577.41 -stringCentralDir = "PK\001\002" # magic number for central directory
577.42 -structFileHeader = "<4s2B4HlLL2H" # 12 items, file header record, 30 bytes
577.43 -stringFileHeader = "PK\003\004" # magic number for file header
577.44 -structEndArchive64Locator = "<4slql" # 4 items, locate Zip64 header, 20 bytes
577.45 -stringEndArchive64Locator = "PK\x06\x07" # magic token for locator header
577.46 -structEndArchive64 = "<4sqhhllqqqq" # 10 items, end of archive (Zip64), 56 bytes
577.47 -stringEndArchive64 = "PK\x06\x06" # magic token for Zip64 header
577.48 -
577.49 -
577.50 -# indexes of entries in the central directory structure
577.51 -_CD_SIGNATURE = 0
577.52 -_CD_CREATE_VERSION = 1
577.53 -_CD_CREATE_SYSTEM = 2
577.54 -_CD_EXTRACT_VERSION = 3
577.55 -_CD_EXTRACT_SYSTEM = 4 # is this meaningful?
577.56 -_CD_FLAG_BITS = 5
577.57 -_CD_COMPRESS_TYPE = 6
577.58 -_CD_TIME = 7
577.59 -_CD_DATE = 8
577.60 -_CD_CRC = 9
577.61 -_CD_COMPRESSED_SIZE = 10
577.62 -_CD_UNCOMPRESSED_SIZE = 11
577.63 -_CD_FILENAME_LENGTH = 12
577.64 -_CD_EXTRA_FIELD_LENGTH = 13
577.65 -_CD_COMMENT_LENGTH = 14
577.66 -_CD_DISK_NUMBER_START = 15
577.67 -_CD_INTERNAL_FILE_ATTRIBUTES = 16
577.68 -_CD_EXTERNAL_FILE_ATTRIBUTES = 17
577.69 -_CD_LOCAL_HEADER_OFFSET = 18
577.70 -
577.71 -# indexes of entries in the local file header structure
577.72 -_FH_SIGNATURE = 0
577.73 -_FH_EXTRACT_VERSION = 1
577.74 -_FH_EXTRACT_SYSTEM = 2 # is this meaningful?
577.75 -_FH_GENERAL_PURPOSE_FLAG_BITS = 3
577.76 -_FH_COMPRESSION_METHOD = 4
577.77 -_FH_LAST_MOD_TIME = 5
577.78 -_FH_LAST_MOD_DATE = 6
577.79 -_FH_CRC = 7
577.80 -_FH_COMPRESSED_SIZE = 8
577.81 -_FH_UNCOMPRESSED_SIZE = 9
577.82 -_FH_FILENAME_LENGTH = 10
577.83 -_FH_EXTRA_FIELD_LENGTH = 11
577.84 -
577.85 -def is_zipfile(filename):
577.86 - """Quickly see if file is a ZIP file by checking the magic number."""
577.87 - try:
577.88 - fpin = open(filename, "rb")
577.89 - endrec = _EndRecData(fpin)
577.90 - fpin.close()
577.91 - if endrec:
577.92 - return True # file has correct magic number
577.93 - except IOError:
577.94 - pass
577.95 - return False
577.96 -
577.97 -def _EndRecData64(fpin, offset, endrec):
577.98 - """
577.99 - Read the ZIP64 end-of-archive records and use that to update endrec
577.100 - """
577.101 - locatorSize = struct.calcsize(structEndArchive64Locator)
577.102 - fpin.seek(offset - locatorSize, 2)
577.103 - data = fpin.read(locatorSize)
577.104 - sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data)
577.105 - if sig != stringEndArchive64Locator:
577.106 - return endrec
577.107 -
577.108 - if diskno != 0 or disks != 1:
577.109 - raise BadZipfile("zipfiles that span multiple disks are not supported")
577.110 -
577.111 - # Assume no 'zip64 extensible data'
577.112 - endArchiveSize = struct.calcsize(structEndArchive64)
577.113 - fpin.seek(offset - locatorSize - endArchiveSize, 2)
577.114 - data = fpin.read(endArchiveSize)
577.115 - sig, sz, create_version, read_version, disk_num, disk_dir, \
577.116 - dircount, dircount2, dirsize, diroffset = \
577.117 - struct.unpack(structEndArchive64, data)
577.118 - if sig != stringEndArchive64:
577.119 - return endrec
577.120 -
577.121 - # Update the original endrec using data from the ZIP64 record
577.122 - endrec[1] = disk_num
577.123 - endrec[2] = disk_dir
577.124 - endrec[3] = dircount
577.125 - endrec[4] = dircount2
577.126 - endrec[5] = dirsize
577.127 - endrec[6] = diroffset
577.128 - return endrec
577.129 -
577.130 -
577.131 -def _EndRecData(fpin):
577.132 - """Return data from the "End of Central Directory" record, or None.
577.133 -
577.134 - The data is a list of the nine items in the ZIP "End of central dir"
577.135 - record followed by a tenth item, the file seek offset of this record."""
577.136 - fpin.seek(-22, 2) # Assume no archive comment.
577.137 - filesize = fpin.tell() + 22 # Get file size
577.138 - data = fpin.read()
577.139 - if data[0:4] == stringEndArchive and data[-2:] == "\000\000":
577.140 - endrec = struct.unpack(structEndArchive, data)
577.141 - endrec = list(endrec)
577.142 - endrec.append("") # Append the archive comment
577.143 - endrec.append(filesize - 22) # Append the record start offset
577.144 - if endrec[-4] == -1 or endrec[-4] == 0xffffffff:
577.145 - return _EndRecData64(fpin, -22, endrec)
577.146 - return endrec
577.147 - # Search the last END_BLOCK bytes of the file for the record signature.
577.148 - # The comment is appended to the ZIP file and has a 16 bit length.
577.149 - # So the comment may be up to 64K long. We limit the search for the
577.150 - # signature to a few Kbytes at the end of the file for efficiency.
577.151 - # also, the signature must not appear in the comment.
577.152 - END_BLOCK = min(filesize, 1024 * 4)
577.153 - fpin.seek(filesize - END_BLOCK, 0)
577.154 - data = fpin.read()
577.155 - start = data.rfind(stringEndArchive)
577.156 - if start >= 0: # Correct signature string was found
577.157 - endrec = struct.unpack(structEndArchive, data[start:start+22])
577.158 - endrec = list(endrec)
577.159 - comment = data[start+22:]
577.160 - if endrec[7] == len(comment): # Comment length checks out
577.161 - # Append the archive comment and start offset
577.162 - endrec.append(comment)
577.163 - endrec.append(filesize - END_BLOCK + start)
577.164 - if endrec[-4] == -1 or endrec[-4] == 0xffffffff:
577.165 - return _EndRecData64(fpin, - END_BLOCK + start, endrec)
577.166 - return endrec
577.167 - return # Error, return None
577.168 -
577.169 -
577.170 -class ZipInfo (object):
577.171 - """Class with attributes describing each file in the ZIP archive."""
577.172 -
577.173 - __slots__ = (
577.174 - 'orig_filename',
577.175 - 'filename',
577.176 - 'date_time',
577.177 - 'compress_type',
577.178 - 'comment',
577.179 - 'extra',
577.180 - 'create_system',
577.181 - 'create_version',
577.182 - 'extract_version',
577.183 - 'reserved',
577.184 - 'flag_bits',
577.185 - 'volume',
577.186 - 'internal_attr',
577.187 - 'external_attr',
577.188 - 'header_offset',
577.189 - 'CRC',
577.190 - 'compress_size',
577.191 - 'file_size',
577.192 - )
577.193 -
577.194 - def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)):
577.195 - self.orig_filename = filename # Original file name in archive
577.196 -
577.197 - # Terminate the file name at the first null byte. Null bytes in file
577.198 - # names are used as tricks by viruses in archives.
577.199 - null_byte = filename.find(chr(0))
577.200 - if null_byte >= 0:
577.201 - filename = filename[0:null_byte]
577.202 - # This is used to ensure paths in generated ZIP files always use
577.203 - # forward slashes as the directory separator, as required by the
577.204 - # ZIP format specification.
577.205 - if os.sep != "/" and os.sep in filename:
577.206 - filename = filename.replace(os.sep, "/")
577.207 -
577.208 - self.filename = filename # Normalized file name
577.209 - self.date_time = date_time # year, month, day, hour, min, sec
577.210 - # Standard values:
577.211 - self.compress_type = ZIP_STORED # Type of compression for the file
577.212 - self.comment = "" # Comment for each file
577.213 - self.extra = "" # ZIP extra data
577.214 - if sys.platform == 'win32':
577.215 - self.create_system = 0 # System which created ZIP archive
577.216 - else:
577.217 - # Assume everything else is unix-y
577.218 - self.create_system = 3 # System which created ZIP archive
577.219 - self.create_version = 20 # Version which created ZIP archive
577.220 - self.extract_version = 20 # Version needed to extract archive
577.221 - self.reserved = 0 # Must be zero
577.222 - self.flag_bits = 0 # ZIP flag bits
577.223 - self.volume = 0 # Volume number of file header
577.224 - self.internal_attr = 0 # Internal attributes
577.225 - self.external_attr = 0 # External file attributes
577.226 - # Other attributes are set by class ZipFile:
577.227 - # header_offset Byte offset to the file header
577.228 - # CRC CRC-32 of the uncompressed file
577.229 - # compress_size Size of the compressed file
577.230 - # file_size Size of the uncompressed file
577.231 -
577.232 - def FileHeader(self):
577.233 - """Return the per-file header as a string."""
577.234 - dt = self.date_time
577.235 - dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
577.236 - dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
577.237 - if self.flag_bits & 0x08:
577.238 - # Set these to zero because we write them after the file data
577.239 - CRC = compress_size = file_size = 0
577.240 - else:
577.241 - CRC = self.CRC
577.242 - compress_size = self.compress_size
577.243 - file_size = self.file_size
577.244 -
577.245 - extra = self.extra
577.246 -
577.247 - if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT:
577.248 - # File is larger than what fits into a 4 byte integer,
577.249 - # fall back to the ZIP64 extension
577.250 - fmt = '<hhqq'
577.251 - extra = extra + struct.pack(fmt,
577.252 - 1, struct.calcsize(fmt)-4, file_size, compress_size)
577.253 - file_size = 0xffffffff # -1
577.254 - compress_size = 0xffffffff # -1
577.255 - self.extract_version = max(45, self.extract_version)
577.256 - self.create_version = max(45, self.extract_version)
577.257 -
577.258 - header = struct.pack(structFileHeader, stringFileHeader,
577.259 - self.extract_version, self.reserved, self.flag_bits,
577.260 - self.compress_type, dostime, dosdate, CRC,
577.261 - compress_size, file_size,
577.262 - len(self.filename), len(extra))
577.263 - return header + self.filename + extra
577.264 -
577.265 - def _decodeExtra(self):
577.266 - # Try to decode the extra field.
577.267 - extra = self.extra
577.268 - unpack = struct.unpack
577.269 - while extra:
577.270 - tp, ln = unpack('<hh', extra[:4])
577.271 - if tp == 1:
577.272 - if ln >= 24:
577.273 - counts = unpack('<qqq', extra[4:28])
577.274 - elif ln == 16:
577.275 - counts = unpack('<qq', extra[4:20])
577.276 - elif ln == 8:
577.277 - counts = unpack('<q', extra[4:12])
577.278 - elif ln == 0:
577.279 - counts = ()
577.280 - else:
577.281 - raise RuntimeError, "Corrupt extra field %s"%(ln,)
577.282 -
577.283 - idx = 0
577.284 -
577.285 - # ZIP64 extension (large files and/or large archives)
577.286 - if self.file_size == -1 or self.file_size == 0xFFFFFFFFL:
577.287 - self.file_size = counts[idx]
577.288 - idx += 1
577.289 -
577.290 - if self.compress_size == -1 or self.compress_size == 0xFFFFFFFFL:
577.291 - self.compress_size = counts[idx]
577.292 - idx += 1
577.293 -
577.294 - if self.header_offset == -1 or self.header_offset == 0xffffffffL:
577.295 - old = self.header_offset
577.296 - self.header_offset = counts[idx]
577.297 - idx+=1
577.298 -
577.299 - extra = extra[ln+4:]
577.300 -
577.301 -
577.302 -class ZipFile:
577.303 - """ Class with methods to open, read, write, close, list zip files.
577.304 -
577.305 - z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True)
577.306 -
577.307 - file: Either the path to the file, or a file-like object.
577.308 - If it is a path, the file will be opened and closed by ZipFile.
577.309 - mode: The mode can be either read "r", write "w" or append "a".
577.310 - compression: ZIP_STORED (no compression) or ZIP_DEFLATED (requires zlib).
577.311 - allowZip64: if True ZipFile will create files with ZIP64 extensions when
577.312 - needed, otherwise it will raise an exception when this would
577.313 - be necessary.
577.314 -
577.315 - """
577.316 -
577.317 - fp = None # Set here since __del__ checks it
577.318 -
577.319 - def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=False):
577.320 - """Open the ZIP file with mode read "r", write "w" or append "a"."""
577.321 - self._allowZip64 = allowZip64
577.322 - self._didModify = False
577.323 - if compression == ZIP_STORED:
577.324 - pass
577.325 - elif compression == ZIP_DEFLATED:
577.326 - if not zlib:
577.327 - raise RuntimeError,\
577.328 - "Compression requires the (missing) zlib module"
577.329 - else:
577.330 - raise RuntimeError, "That compression method is not supported"
577.331 - self.debug = 0 # Level of printing: 0 through 3
577.332 - self.NameToInfo = {} # Find file info given name
577.333 - self.filelist = [] # List of ZipInfo instances for archive
577.334 - self.compression = compression # Method of compression
577.335 - self.mode = key = mode.replace('b', '')[0]
577.336 -
577.337 - # Check if we were passed a file-like object
577.338 - if isinstance(file, basestring):
577.339 - self._filePassed = 0
577.340 - self.filename = file
577.341 - modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'}
577.342 - self.fp = open(file, modeDict[mode])
577.343 - else:
577.344 - self._filePassed = 1
577.345 - self.fp = file
577.346 - self.filename = getattr(file, 'name', None)
577.347 -
577.348 - if key == 'r':
577.349 - self._GetContents()
577.350 - elif key == 'w':
577.351 - pass
577.352 - elif key == 'a':
577.353 - try: # See if file is a zip file
577.354 - self._RealGetContents()
577.355 - # seek to start of directory and overwrite
577.356 - self.fp.seek(self.start_dir, 0)
577.357 - except BadZipfile: # file is not a zip file, just append
577.358 - self.fp.seek(0, 2)
577.359 - else:
577.360 - if not self._filePassed:
577.361 - self.fp.close()
577.362 - self.fp = None
577.363 - raise RuntimeError, 'Mode must be "r", "w" or "a"'
577.364 -
577.365 - def _GetContents(self):
577.366 - """Read the directory, making sure we close the file if the format
577.367 - is bad."""
577.368 - try:
577.369 - self._RealGetContents()
577.370 - except BadZipfile:
577.371 - if not self._filePassed:
577.372 - self.fp.close()
577.373 - self.fp = None
577.374 - raise
577.375 -
577.376 - def _RealGetContents(self):
577.377 - """Read in the table of contents for the ZIP file."""
577.378 - fp = self.fp
577.379 - endrec = _EndRecData(fp)
577.380 - if not endrec:
577.381 - raise BadZipfile, "File is not a zip file"
577.382 - if self.debug > 1:
577.383 - print endrec
577.384 - size_cd = endrec[5] # bytes in central directory
577.385 - offset_cd = endrec[6] # offset of central directory
577.386 - self.comment = endrec[8] # archive comment
577.387 - # endrec[9] is the offset of the "End of Central Dir" record
577.388 - if endrec[9] > ZIP64_LIMIT:
577.389 - x = endrec[9] - size_cd - 56 - 20
577.390 - else:
577.391 - x = endrec[9] - size_cd
577.392 - # "concat" is zero, unless zip was concatenated to another file
577.393 - concat = x - offset_cd
577.394 - if self.debug > 2:
577.395 - print "given, inferred, offset", offset_cd, x, concat
577.396 - # self.start_dir: Position of start of central directory
577.397 - self.start_dir = offset_cd + concat
577.398 - fp.seek(self.start_dir, 0)
577.399 - data = fp.read(size_cd)
577.400 - fp = cStringIO.StringIO(data)
577.401 - total = 0
577.402 - while total < size_cd:
577.403 - centdir = fp.read(46)
577.404 - total = total + 46
577.405 - if centdir[0:4] != stringCentralDir:
577.406 - raise BadZipfile, "Bad magic number for central directory"
577.407 - centdir = struct.unpack(structCentralDir, centdir)
577.408 - if self.debug > 2:
577.409 - print centdir
577.410 - filename = fp.read(centdir[_CD_FILENAME_LENGTH])
577.411 - # Create ZipInfo instance to store file information
577.412 - x = ZipInfo(filename)
577.413 - x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])
577.414 - x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])
577.415 - total = (total + centdir[_CD_FILENAME_LENGTH]
577.416 - + centdir[_CD_EXTRA_FIELD_LENGTH]
577.417 - + centdir[_CD_COMMENT_LENGTH])
577.418 - x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET]
577.419 - (x.create_version, x.create_system, x.extract_version, x.reserved,
577.420 - x.flag_bits, x.compress_type, t, d,
577.421 - x.CRC, x.compress_size, x.file_size) = centdir[1:12]
577.422 - x.volume, x.internal_attr, x.external_attr = centdir[15:18]
577.423 - # Convert date/time code to (year, month, day, hour, min, sec)
577.424 - x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F,
577.425 - t>>11, (t>>5)&0x3F, (t&0x1F) * 2 )
577.426 -
577.427 - x._decodeExtra()
577.428 - x.header_offset = x.header_offset + concat
577.429 - self.filelist.append(x)
577.430 - self.NameToInfo[x.filename] = x
577.431 - if self.debug > 2:
577.432 - print "total", total
577.433 -
577.434 -
577.435 - def namelist(self):
577.436 - """Return a list of file names in the archive."""
577.437 - l = []
577.438 - for data in self.filelist:
577.439 - l.append(data.filename)
577.440 - return l
577.441 -
577.442 - def infolist(self):
577.443 - """Return a list of class ZipInfo instances for files in the
577.444 - archive."""
577.445 - return self.filelist
577.446 -
577.447 - def printdir(self):
577.448 - """Print a table of contents for the zip file."""
577.449 - print "%-46s %19s %12s" % ("File Name", "Modified ", "Size")
577.450 - for zinfo in self.filelist:
577.451 - date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6]
577.452 - print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size)
577.453 -
577.454 - def testzip(self):
577.455 - """Read all the files and check the CRC."""
577.456 - for zinfo in self.filelist:
577.457 - try:
577.458 - self.read(zinfo.filename) # Check CRC-32
577.459 - except BadZipfile:
577.460 - return zinfo.filename
577.461 -
577.462 -
577.463 - def getinfo(self, name):
577.464 - """Return the instance of ZipInfo given 'name'."""
577.465 - return self.NameToInfo[name]
577.466 -
577.467 - def read(self, name):
577.468 - """Return file bytes (as a string) for name."""
577.469 - if self.mode not in ("r", "a"):
577.470 - raise RuntimeError, 'read() requires mode "r" or "a"'
577.471 - if not self.fp:
577.472 - raise RuntimeError, \
577.473 - "Attempt to read ZIP archive that was already closed"
577.474 - zinfo = self.getinfo(name)
577.475 - filepos = self.fp.tell()
577.476 -
577.477 - self.fp.seek(zinfo.header_offset, 0)
577.478 -
577.479 - # Skip the file header:
577.480 - fheader = self.fp.read(30)
577.481 - if fheader[0:4] != stringFileHeader:
577.482 - raise BadZipfile, "Bad magic number for file header"
577.483 -
577.484 - fheader = struct.unpack(structFileHeader, fheader)
577.485 - fname = self.fp.read(fheader[_FH_FILENAME_LENGTH])
577.486 - if fheader[_FH_EXTRA_FIELD_LENGTH]:
577.487 - self.fp.read(fheader[_FH_EXTRA_FIELD_LENGTH])
577.488 -
577.489 - if fname != zinfo.orig_filename:
577.490 - raise BadZipfile, \
577.491 - 'File name in directory "%s" and header "%s" differ.' % (
577.492 - zinfo.orig_filename, fname)
577.493 -
577.494 - bytes = self.fp.read(zinfo.compress_size)
577.495 - self.fp.seek(filepos, 0)
577.496 - if zinfo.compress_type == ZIP_STORED:
577.497 - pass
577.498 - elif zinfo.compress_type == ZIP_DEFLATED:
577.499 - if not zlib:
577.500 - raise RuntimeError, \
577.501 - "De-compression requires the (missing) zlib module"
577.502 - # zlib compress/decompress code by Jeremy Hylton of CNRI
577.503 - dc = zlib.decompressobj(-15)
577.504 - bytes = dc.decompress(bytes)
577.505 - # need to feed in unused pad byte so that zlib won't choke
577.506 - ex = dc.decompress('Z') + dc.flush()
577.507 - if ex:
577.508 - bytes = bytes + ex
577.509 - else:
577.510 - raise BadZipfile, \
577.511 - "Unsupported compression method %d for file %s" % \
577.512 - (zinfo.compress_type, name)
577.513 - crc = binascii.crc32(bytes)
577.514 - if crc != zinfo.CRC:
577.515 - raise BadZipfile, "Bad CRC-32 for file %s" % name
577.516 - return bytes
577.517 -
577.518 - def _writecheck(self, zinfo):
577.519 - """Check for errors before writing a file to the archive."""
577.520 - if zinfo.filename in self.NameToInfo:
577.521 - if self.debug: # Warning for duplicate names
577.522 - print "Duplicate name:", zinfo.filename
577.523 - if self.mode not in ("w", "a"):
577.524 - raise RuntimeError, 'write() requires mode "w" or "a"'
577.525 - if not self.fp:
577.526 - raise RuntimeError, \
577.527 - "Attempt to write ZIP archive that was already closed"
577.528 - if zinfo.compress_type == ZIP_DEFLATED and not zlib:
577.529 - raise RuntimeError, \
577.530 - "Compression requires the (missing) zlib module"
577.531 - if zinfo.compress_type not in (ZIP_STORED, ZIP_DEFLATED):
577.532 - raise RuntimeError, \
577.533 - "That compression method is not supported"
577.534 - if zinfo.file_size > ZIP64_LIMIT:
577.535 - if not self._allowZip64:
577.536 - raise LargeZipFile("Filesize would require ZIP64 extensions")
577.537 - if zinfo.header_offset > ZIP64_LIMIT:
577.538 - if not self._allowZip64:
577.539 - raise LargeZipFile("Zipfile size would require ZIP64 extensions")
577.540 -
577.541 - def write(self, filename, arcname=None, compress_type=None):
577.542 - """Put the bytes from filename into the archive under the name
577.543 - arcname."""
577.544 - st = os.stat(filename)
577.545 - mtime = time.localtime(st.st_mtime)
577.546 - date_time = mtime[0:6]
577.547 - # Create ZipInfo instance to store file information
577.548 - if arcname is None:
577.549 - arcname = filename
577.550 - arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
577.551 - while arcname[0] in (os.sep, os.altsep):
577.552 - arcname = arcname[1:]
577.553 - zinfo = ZipInfo(arcname, date_time)
577.554 - zinfo.external_attr = (st[0] & 0xFFFF) << 16L # Unix attributes
577.555 - if compress_type is None:
577.556 - zinfo.compress_type = self.compression
577.557 - else:
577.558 - zinfo.compress_type = compress_type
577.559 -
577.560 - zinfo.file_size = st.st_size
577.561 - zinfo.flag_bits = 0x00
577.562 - zinfo.header_offset = self.fp.tell() # Start of header bytes
577.563 -
577.564 - self._writecheck(zinfo)
577.565 - self._didModify = True
577.566 - fp = open(filename, "rb")
577.567 - # Must overwrite CRC and sizes with correct data later
577.568 - zinfo.CRC = CRC = 0
577.569 - zinfo.compress_size = compress_size = 0
577.570 - zinfo.file_size = file_size = 0
577.571 - self.fp.write(zinfo.FileHeader())
577.572 - if zinfo.compress_type == ZIP_DEFLATED:
577.573 - cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
577.574 - zlib.DEFLATED, -15)
577.575 - else:
577.576 - cmpr = None
577.577 - while 1:
577.578 - buf = fp.read(1024 * 8)
577.579 - if not buf:
577.580 - break
577.581 - file_size = file_size + len(buf)
577.582 - CRC = binascii.crc32(buf, CRC)
577.583 - if cmpr:
577.584 - buf = cmpr.compress(buf)
577.585 - compress_size = compress_size + len(buf)
577.586 - self.fp.write(buf)
577.587 - fp.close()
577.588 - if cmpr:
577.589 - buf = cmpr.flush()
577.590 - compress_size = compress_size + len(buf)
577.591 - self.fp.write(buf)
577.592 - zinfo.compress_size = compress_size
577.593 - else:
577.594 - zinfo.compress_size = file_size
577.595 - zinfo.CRC = CRC
577.596 - zinfo.file_size = file_size
577.597 - # Seek backwards and write CRC and file sizes
577.598 - position = self.fp.tell() # Preserve current position in file
577.599 - self.fp.seek(zinfo.header_offset + 14, 0)
577.600 - self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size,
577.601 - zinfo.file_size))
577.602 - self.fp.seek(position, 0)
577.603 - self.filelist.append(zinfo)
577.604 - self.NameToInfo[zinfo.filename] = zinfo
577.605 -
577.606 - def writestr(self, zinfo_or_arcname, bytes):
577.607 - """Write a file into the archive. The contents is the string
577.608 - 'bytes'. 'zinfo_or_arcname' is either a ZipInfo instance or
577.609 - the name of the file in the archive."""
577.610 - if not isinstance(zinfo_or_arcname, ZipInfo):
577.611 - zinfo = ZipInfo(filename=zinfo_or_arcname,
577.612 - date_time=time.localtime(time.time())[:6])
577.613 - zinfo.compress_type = self.compression
577.614 - else:
577.615 - zinfo = zinfo_or_arcname
577.616 - zinfo.file_size = len(bytes) # Uncompressed size
577.617 - zinfo.header_offset = self.fp.tell() # Start of header bytes
577.618 - self._writecheck(zinfo)
577.619 - self._didModify = True
577.620 - zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum
577.621 - if zinfo.compress_type == ZIP_DEFLATED:
577.622 - co = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
577.623 - zlib.DEFLATED, -15)
577.624 - bytes = co.compress(bytes) + co.flush()
577.625 - zinfo.compress_size = len(bytes) # Compressed size
577.626 - else:
577.627 - zinfo.compress_size = zinfo.file_size
577.628 - zinfo.header_offset = self.fp.tell() # Start of header bytes
577.629 - self.fp.write(zinfo.FileHeader())
577.630 - self.fp.write(bytes)
577.631 - self.fp.flush()
577.632 - if zinfo.flag_bits & 0x08:
577.633 - # Write CRC and file sizes after the file data
577.634 - self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size,
577.635 - zinfo.file_size))
577.636 - self.filelist.append(zinfo)
577.637 - self.NameToInfo[zinfo.filename] = zinfo
577.638 -
577.639 - def __del__(self):
577.640 - """Call the "close()" method in case the user forgot."""
577.641 - self.close()
577.642 -
577.643 - def close(self):
577.644 - """Close the file, and for mode "w" and "a" write the ending
577.645 - records."""
577.646 - if self.fp is None:
577.647 - return
577.648 -
577.649 - if self.mode in ("w", "a") and self._didModify: # write ending records
577.650 - count = 0
577.651 - pos1 = self.fp.tell()
577.652 - for zinfo in self.filelist: # write central directory
577.653 - count = count + 1
577.654 - dt = zinfo.date_time
577.655 - dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
577.656 - dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
577.657 - extra = []
577.658 - if zinfo.file_size > ZIP64_LIMIT \
577.659 - or zinfo.compress_size > ZIP64_LIMIT:
577.660 - extra.append(zinfo.file_size)
577.661 - extra.append(zinfo.compress_size)
577.662 - file_size = 0xffffffff #-1
577.663 - compress_size = 0xffffffff #-1
577.664 - else:
577.665 - file_size = zinfo.file_size
577.666 - compress_size = zinfo.compress_size
577.667 -
577.668 - if zinfo.header_offset > ZIP64_LIMIT:
577.669 - extra.append(zinfo.header_offset)
577.670 - header_offset = -1 # struct "l" format: 32 one bits
577.671 - else:
577.672 - header_offset = zinfo.header_offset
577.673 -
577.674 - extra_data = zinfo.extra
577.675 - if extra:
577.676 - # Append a ZIP64 field to the extra's
577.677 - extra_data = struct.pack(
577.678 - '<hh' + 'q'*len(extra),
577.679 - 1, 8*len(extra), *extra) + extra_data
577.680 -
577.681 - extract_version = max(45, zinfo.extract_version)
577.682 - create_version = max(45, zinfo.create_version)
577.683 - else:
577.684 - extract_version = zinfo.extract_version
577.685 - create_version = zinfo.create_version
577.686 -
577.687 - centdir = struct.pack(structCentralDir,
577.688 - stringCentralDir, create_version,
577.689 - zinfo.create_system, extract_version, zinfo.reserved,
577.690 - zinfo.flag_bits, zinfo.compress_type, dostime, dosdate,
577.691 - zinfo.CRC, compress_size, file_size,
577.692 - len(zinfo.filename), len(extra_data), len(zinfo.comment),
577.693 - 0, zinfo.internal_attr, zinfo.external_attr,
577.694 - header_offset)
577.695 - self.fp.write(centdir)
577.696 - self.fp.write(zinfo.filename)
577.697 - self.fp.write(extra_data)
577.698 - self.fp.write(zinfo.comment)
577.699 -
577.700 - pos2 = self.fp.tell()
577.701 - # Write end-of-zip-archive record
577.702 - if pos1 > ZIP64_LIMIT:
577.703 - # Need to write the ZIP64 end-of-archive records
577.704 - zip64endrec = struct.pack(
577.705 - structEndArchive64, stringEndArchive64,
577.706 - 44, 45, 45, 0, 0, count, count, pos2 - pos1, pos1)
577.707 - self.fp.write(zip64endrec)
577.708 -
577.709 - zip64locrec = struct.pack(
577.710 - structEndArchive64Locator,
577.711 - stringEndArchive64Locator, 0, pos2, 1)
577.712 - self.fp.write(zip64locrec)
577.713 -
577.714 - # XXX Why is `pos3` computed next? It's never referenced.
577.715 - pos3 = self.fp.tell()
577.716 - endrec = struct.pack(structEndArchive, stringEndArchive,
577.717 - 0, 0, count, count, pos2 - pos1, -1, 0)
577.718 - self.fp.write(endrec)
577.719 -
577.720 - else:
577.721 - endrec = struct.pack(structEndArchive, stringEndArchive,
577.722 - 0, 0, count, count, pos2 - pos1, pos1, 0)
577.723 - self.fp.write(endrec)
577.724 - self.fp.flush()
577.725 - if not self._filePassed:
577.726 - self.fp.close()
577.727 - self.fp = None
577.728 -
577.729 -
577.730 -class PyZipFile(ZipFile):
577.731 - """Class to create ZIP archives with Python library files and packages."""
577.732 -
577.733 - def writepy(self, pathname, basename = ""):
577.734 - """Add all files from "pathname" to the ZIP archive.
577.735 -
577.736 - If pathname is a package directory, search the directory and
577.737 - all package subdirectories recursively for all *.py and enter
577.738 - the modules into the archive. If pathname is a plain
577.739 - directory, listdir *.py and enter all modules. Else, pathname
577.740 - must be a Python *.py file and the module will be put into the
577.741 - archive. Added modules are always module.pyo or module.pyc.
577.742 - This method will compile the module.py into module.pyc if
577.743 - necessary.
577.744 - """
577.745 - dir, name = os.path.split(pathname)
577.746 - if os.path.isdir(pathname):
577.747 - initname = os.path.join(pathname, "__init__.py")
577.748 - if os.path.isfile(initname):
577.749 - # This is a package directory, add it
577.750 - if basename:
577.751 - basename = "%s/%s" % (basename, name)
577.752 - else:
577.753 - basename = name
577.754 - if self.debug:
577.755 - print "Adding package in", pathname, "as", basename
577.756 - fname, arcname = self._get_codename(initname[0:-3], basename)
577.757 - if self.debug:
577.758 - print "Adding", arcname
577.759 - self.write(fname, arcname)
577.760 - dirlist = os.listdir(pathname)
577.761 - dirlist.remove("__init__.py")
577.762 - # Add all *.py files and package subdirectories
577.763 - for filename in dirlist:
577.764 - path = os.path.join(pathname, filename)
577.765 - root, ext = os.path.splitext(filename)
577.766 - if os.path.isdir(path):
577.767 - if os.path.isfile(os.path.join(path, "__init__.py")):
577.768 - # This is a package directory, add it
577.769 - self.writepy(path, basename) # Recursive call
577.770 - elif ext == ".py":
577.771 - fname, arcname = self._get_codename(path[0:-3],
577.772 - basename)
577.773 - if self.debug:
577.774 - print "Adding", arcname
577.775 - self.write(fname, arcname)
577.776 - else:
577.777 - # This is NOT a package directory, add its files at top level
577.778 - if self.debug:
577.779 - print "Adding files from directory", pathname
577.780 - for filename in os.listdir(pathname):
577.781 - path = os.path.join(pathname, filename)
577.782 - root, ext = os.path.splitext(filename)
577.783 - if ext == ".py":
577.784 - fname, arcname = self._get_codename(path[0:-3],
577.785 - basename)
577.786 - if self.debug:
577.787 - print "Adding", arcname
577.788 - self.write(fname, arcname)
577.789 - else:
577.790 - if pathname[-3:] != ".py":
577.791 - raise RuntimeError, \
577.792 - 'Files added with writepy() must end with ".py"'
577.793 - fname, arcname = self._get_codename(pathname[0:-3], basename)
577.794 - if self.debug:
577.795 - print "Adding file", arcname
577.796 - self.write(fname, arcname)
577.797 -
577.798 - def _get_codename(self, pathname, basename):
577.799 - """Return (filename, archivename) for the path.
577.800 -
577.801 - Given a module name path, return the correct file path and
577.802 - archive name, compiling if necessary. For example, given
577.803 - /python/lib/string, return (/python/lib/string.pyc, string).
577.804 - """
577.805 - file_py = pathname + ".py"
577.806 - file_pyc = pathname + ".pyc"
577.807 - file_pyo = pathname + ".pyo"
577.808 - if os.path.isfile(file_pyo) and \
577.809 - os.stat(file_pyo).st_mtime >= os.stat(file_py).st_mtime:
577.810 - fname = file_pyo # Use .pyo file
577.811 - elif not os.path.isfile(file_pyc) or \
577.812 - os.stat(file_pyc).st_mtime < os.stat(file_py).st_mtime:
577.813 - import py_compile
577.814 - if self.debug:
577.815 - print "Compiling", file_py
577.816 - try:
577.817 - py_compile.compile(file_py, file_pyc, None, True)
577.818 - except py_compile.PyCompileError,err:
577.819 - print err.msg
577.820 - fname = file_pyc
577.821 - else:
577.822 - fname = file_pyc
577.823 - archivename = os.path.split(fname)[1]
577.824 - if basename:
577.825 - archivename = "%s/%s" % (basename, archivename)
577.826 - return (fname, archivename)
577.827 -
577.828 -
577.829 -def main(args = None):
577.830 - import textwrap
577.831 - USAGE=textwrap.dedent("""\
577.832 - Usage:
577.833 - zipfile.py -l zipfile.zip # Show listing of a zipfile
577.834 - zipfile.py -t zipfile.zip # Test if a zipfile is valid
577.835 - zipfile.py -e zipfile.zip target # Extract zipfile into target dir
577.836 - zipfile.py -c zipfile.zip src ... # Create zipfile from sources
577.837 - """)
577.838 - if args is None:
577.839 - args = sys.argv[1:]
577.840 -
577.841 - if not args or args[0] not in ('-l', '-c', '-e', '-t'):
577.842 - print USAGE
577.843 - sys.exit(1)
577.844 -
577.845 - if args[0] == '-l':
577.846 - if len(args) != 2:
577.847 - print USAGE
577.848 - sys.exit(1)
577.849 - zf = ZipFile(args[1], 'r')
577.850 - zf.printdir()
577.851 - zf.close()
577.852 -
577.853 - elif args[0] == '-t':
577.854 - if len(args) != 2:
577.855 - print USAGE
577.856 - sys.exit(1)
577.857 - zf = ZipFile(args[1], 'r')
577.858 - zf.testzip()
577.859 - print "Done testing"
577.860 -
577.861 - elif args[0] == '-e':
577.862 - if len(args) != 3:
577.863 - print USAGE
577.864 - sys.exit(1)
577.865 -
577.866 - zf = ZipFile(args[1], 'r')
577.867 - out = args[2]
577.868 - for path in zf.namelist():
577.869 - if path.startswith('./'):
577.870 - tgt = os.path.join(out, path[2:])
577.871 - else:
577.872 - tgt = os.path.join(out, path)
577.873 -
577.874 - tgtdir = os.path.dirname(tgt)
577.875 - if not os.path.exists(tgtdir):
577.876 - os.makedirs(tgtdir)
577.877 - fp = open(tgt, 'wb')
577.878 - fp.write(zf.read(path))
577.879 - fp.close()
577.880 - zf.close()
577.881 -
577.882 - elif args[0] == '-c':
577.883 - if len(args) < 3:
577.884 - print USAGE
577.885 - sys.exit(1)
577.886 -
577.887 - def addToZip(zf, path, zippath):
577.888 - if os.path.isfile(path):
577.889 - zf.write(path, zippath, ZIP_DEFLATED)
577.890 - elif os.path.isdir(path):
577.891 - for nm in os.listdir(path):
577.892 - addToZip(zf,
577.893 - os.path.join(path, nm), os.path.join(zippath, nm))
577.894 - # else: ignore
577.895 -
577.896 - zf = ZipFile(args[1], 'w', allowZip64=True)
577.897 - for src in args[2:]:
577.898 - addToZip(zf, src, os.path.basename(src))
577.899 -
577.900 - zf.close()
577.901 -
577.902 -if __name__ == "__main__":
577.903 - main()
578.1 --- a/python.editor/test/unit/data/testfiles/zipfile.py.indexed Sun Jan 04 13:11:53 2015 -0600
578.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
578.3 @@ -1,178 +0,0 @@
578.4 -
578.5 -
578.6 -Document 0
578.7 -Searchable Keys:
578.8 - class : BadZipfile
578.9 - class-ig : badzipfile
578.10 - extends : Exception
578.11 - in : zipfile
578.12 -
578.13 -Not Searchable Keys:
578.14 -
578.15 -
578.16 -Document 1
578.17 -Searchable Keys:
578.18 - class : LargeZipFile
578.19 - class-ig : largezipfile
578.20 - extends : Exception
578.21 - in : zipfile
578.22 -
578.23 -Not Searchable Keys:
578.24 -
578.25 -
578.26 -Document 2
578.27 -Searchable Keys:
578.28 - class : PyZipFile
578.29 - class-ig : pyzipfile
578.30 - extends : ZipFile
578.31 - in : zipfile
578.32 - member : _get_codename;F;|PRIVATE|;self,pathname,basename;
578.33 - member : writepy;F;;self,pathname,basename;
578.34 -
578.35 -Not Searchable Keys:
578.36 -
578.37 -
578.38 -Document 3
578.39 -Searchable Keys:
578.40 - class : ZipFile
578.41 - class-ig : zipfile
578.42 - in : zipfile
578.43 - member : NameToInfo;D;;
578.44 - member : _GetContents;F;|PRIVATE|;self;
578.45 - member : _RealGetContents;F;|PRIVATE|;self;
578.46 - member : __del__;F;;self;
578.47 - member : __init__;c;|CONSTRUCTOR|;self,file,mode,compression,allowZip64;
578.48 - member : _allowZip64;D;|PRIVATE|;
578.49 - member : _didModify;D;|PRIVATE|;
578.50 - member : _filePassed;D;|PRIVATE|;
578.51 - member : _writecheck;F;|PRIVATE|;self,zinfo;
578.52 - member : close;F;;self;
578.53 - member : comment;D;;
578.54 - member : compression;D;;
578.55 - member : debug;D;;
578.56 - member : filelist;D;;
578.57 - member : filename;D;;
578.58 - member : fp;D;;
578.59 - member : fp;D;;
578.60 - member : getinfo;F;;self,name;
578.61 - member : infolist;F;;self;
578.62 - member : mode;D;;
578.63 - member : namelist;F;;self;
578.64 - member : printdir;F;;self;
578.65 - member : read;F;;self,name;
578.66 - member : start_dir;D;;
578.67 - member : testzip;F;;self;
578.68 - member : write;F;;self,filename,arcname,compress_type;
578.69 - member : writestr;F;;self,zinfo_or_arcname,bytes;
578.70 -
578.71 -Not Searchable Keys:
578.72 -
578.73 -
578.74 -Document 4
578.75 -Searchable Keys:
578.76 - class : ZipInfo
578.77 - class-ig : zipinfo
578.78 - extends : object
578.79 - in : zipfile
578.80 - member : FileHeader;F;;self;
578.81 - member : __init__;c;|CONSTRUCTOR|;self,filename,date_time;
578.82 - member : __slots__;D;;
578.83 - member : _decodeExtra;F;|PRIVATE|;self;
578.84 - member : comment;D;;
578.85 - member : compress_size;D;;
578.86 - member : compress_type;D;;
578.87 - member : create_system;D;;
578.88 - member : create_version;D;;
578.89 - member : date_time;D;;
578.90 - member : external_attr;D;;
578.91 - member : extra;D;;
578.92 - member : extract_version;D;;
578.93 - member : file_size;D;;
578.94 - member : filename;D;;
578.95 - member : flag_bits;D;;
578.96 - member : header_offset;D;;
578.97 - member : internal_attr;D;;
578.98 - member : orig_filename;D;;
578.99 - member : reserved;D;;
578.100 - member : volume;D;;
578.101 -
578.102 -Not Searchable Keys:
578.103 -
578.104 -
578.105 -Document 5
578.106 -Searchable Keys:
578.107 - class : error
578.108 - class-ig : error
578.109 - extends : Exception
578.110 - in : zipfile
578.111 -
578.112 -Not Searchable Keys:
578.113 -
578.114 -
578.115 -Document 6
578.116 -Searchable Keys:
578.117 - item : BadZipfile;C;;
578.118 - item : LargeZipFile;C;;
578.119 - item : PyZipFile;C;;
578.120 - item : ZIP64_LIMIT;D;|PRIVATE|;
578.121 - item : ZIP_DEFLATED;D;;
578.122 - item : ZIP_STORED;D;;
578.123 - item : ZipFile;C;;
578.124 - item : ZipInfo;C;;
578.125 - item : _CD_COMMENT_LENGTH;D;|PRIVATE|;
578.126 - item : _CD_COMPRESSED_SIZE;D;|PRIVATE|;
578.127 - item : _CD_COMPRESS_TYPE;D;|PRIVATE|;
578.128 - item : _CD_CRC;D;|PRIVATE|;
578.129 - item : _CD_CREATE_SYSTEM;D;|PRIVATE|;
578.130 - item : _CD_CREATE_VERSION;D;|PRIVATE|;
578.131 - item : _CD_DATE;D;|PRIVATE|;
578.132 - item : _CD_DISK_NUMBER_START;D;|PRIVATE|;
578.133 - item : _CD_EXTERNAL_FILE_ATTRIBUTES;D;|PRIVATE|;
578.134 - item : _CD_EXTRACT_SYSTEM;D;|PRIVATE|;
578.135 - item : _CD_EXTRACT_VERSION;D;|PRIVATE|;
578.136 - item : _CD_EXTRA_FIELD_LENGTH;D;|PRIVATE|;
578.137 - item : _CD_FILENAME_LENGTH;D;|PRIVATE|;
578.138 - item : _CD_FLAG_BITS;D;|PRIVATE|;
578.139 - item : _CD_INTERNAL_FILE_ATTRIBUTES;D;|PRIVATE|;
578.140 - item : _CD_LOCAL_HEADER_OFFSET;D;|PRIVATE|;
578.141 - item : _CD_SIGNATURE;D;|PRIVATE|;
578.142 - item : _CD_TIME;D;|PRIVATE|;
578.143 - item : _CD_UNCOMPRESSED_SIZE;D;|PRIVATE|;
578.144 - item : _EndRecData64;F;|PRIVATE|;fpin,offset,endrec;
578.145 - item : _EndRecData;F;|PRIVATE|;fpin;
578.146 - item : _FH_COMPRESSED_SIZE;D;|PRIVATE|;
578.147 - item : _FH_COMPRESSION_METHOD;D;|PRIVATE|;
578.148 - item : _FH_CRC;D;|PRIVATE|;
578.149 - item : _FH_EXTRACT_SYSTEM;D;|PRIVATE|;
578.150 - item : _FH_EXTRACT_VERSION;D;|PRIVATE|;
578.151 - item : _FH_EXTRA_FIELD_LENGTH;D;|PRIVATE|;
578.152 - item : _FH_FILENAME_LENGTH;D;|PRIVATE|;
578.153 - item : _FH_GENERAL_PURPOSE_FLAG_BITS;D;|PRIVATE|;
578.154 - item : _FH_LAST_MOD_DATE;D;|PRIVATE|;
578.155 - item : _FH_LAST_MOD_TIME;D;|PRIVATE|;
578.156 - item : _FH_SIGNATURE;D;|PRIVATE|;
578.157 - item : _FH_UNCOMPRESSED_SIZE;D;|PRIVATE|;
578.158 - item : __all__;D;;
578.159 - item : binascii;I;|PRIVATE|;
578.160 - item : cStringIO;I;|PRIVATE|;
578.161 - item : error;C;;
578.162 - item : is_zipfile;F;;filename;
578.163 - item : main;F;|PRIVATE|;args;
578.164 - item : os;I;|PRIVATE|;
578.165 - item : stringCentralDir;D;|PRIVATE|;
578.166 - item : stringEndArchive64;D;|PRIVATE|;
578.167 - item : stringEndArchive64Locator;D;|PRIVATE|;
578.168 - item : stringEndArchive;D;|PRIVATE|;
578.169 - item : stringFileHeader;D;|PRIVATE|;
578.170 - item : struct;I;|PRIVATE|;
578.171 - item : structCentralDir;D;|PRIVATE|;
578.172 - item : structEndArchive64;D;|PRIVATE|;
578.173 - item : structEndArchive64Locator;D;|PRIVATE|;
578.174 - item : structEndArchive;D;|PRIVATE|;
578.175 - item : structFileHeader;D;|PRIVATE|;
578.176 - item : sys;I;|PRIVATE|;
578.177 - item : time;I;|PRIVATE|;
578.178 - item : zlib;I;|PRIVATE|;
578.179 - module : zipfile
578.180 -
578.181 -Not Searchable Keys:
579.1 --- a/python.editor/test/unit/data/testfiles/zipfile.py.scopes Sun Jan 04 13:11:53 2015 -0600
579.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
579.3 @@ -1,592 +0,0 @@
579.4 -=============================================
579.5 -<file-top>: Module : OffsetRange[0,35620>
579.6 -BadZipfile [bound][class][def][read][called][node=ClassDef]
579.7 -Exception [private][read][UNRESOLVED][node=Name]
579.8 -ImportError [private][read][UNRESOLVED][node=Name]
579.9 -LargeZipFile [bound][class][def][read][called][node=ClassDef]
579.10 -None [private][read][UNRESOLVED][node=Name]
579.11 -PyZipFile [bound][class][def][node=ClassDef]
579.12 -ZIP64_LIMIT [bound][private][data][read][node=Name]
579.13 -ZIP_DEFLATED [bound][data][read][node=Name]
579.14 -ZIP_STORED [bound][data][read][node=Name]
579.15 -ZipFile [bound][class][def][read][called][node=ClassDef]
579.16 -ZipInfo [bound][class][def][read][called][node=ClassDef]
579.17 -_CD_COMMENT_LENGTH [bound][private][data][read][node=Name]
579.18 -_CD_COMPRESSED_SIZE [bound][private][data][node=Name]
579.19 -_CD_COMPRESS_TYPE [bound][private][data][node=Name]
579.20 -_CD_CRC [bound][private][data][node=Name]
579.21 -_CD_CREATE_SYSTEM [bound][private][data][node=Name]
579.22 -_CD_CREATE_VERSION [bound][private][data][node=Name]
579.23 -_CD_DATE [bound][private][data][node=Name]
579.24 -_CD_DISK_NUMBER_START [bound][private][data][node=Name]
579.25 -_CD_EXTERNAL_FILE_ATTRIBUTES [bound][private][data][node=Name]
579.26 -_CD_EXTRACT_SYSTEM [bound][private][data][node=Name]
579.27 -_CD_EXTRACT_VERSION [bound][private][data][node=Name]
579.28 -_CD_EXTRA_FIELD_LENGTH [bound][private][data][read][node=Name]
579.29 -_CD_FILENAME_LENGTH [bound][private][data][read][node=Name]
579.30 -_CD_FLAG_BITS [bound][private][data][node=Name]
579.31 -_CD_INTERNAL_FILE_ATTRIBUTES [bound][private][data][node=Name]
579.32 -_CD_LOCAL_HEADER_OFFSET [bound][private][data][read][node=Name]
579.33 -_CD_SIGNATURE [bound][private][data][node=Name]
579.34 -_CD_TIME [bound][private][data][node=Name]
579.35 -_CD_UNCOMPRESSED_SIZE [bound][private][data][node=Name]
579.36 -_EndRecData [bound][private][function][def][read][called][node=FunctionDef]
579.37 -_EndRecData64 [bound][private][function][def][read][called][node=FunctionDef]
579.38 -_FH_COMPRESSED_SIZE [bound][private][data][node=Name]
579.39 -_FH_COMPRESSION_METHOD [bound][private][data][node=Name]
579.40 -_FH_CRC [bound][private][data][node=Name]
579.41 -_FH_EXTRACT_SYSTEM [bound][private][data][node=Name]
579.42 -_FH_EXTRACT_VERSION [bound][private][data][node=Name]
579.43 -_FH_EXTRA_FIELD_LENGTH [bound][private][data][read][node=Name]
579.44 -_FH_FILENAME_LENGTH [bound][private][data][read][node=Name]
579.45 -_FH_GENERAL_PURPOSE_FLAG_BITS [bound][private][data][node=Name]
579.46 -_FH_LAST_MOD_DATE [bound][private][data][node=Name]
579.47 -_FH_LAST_MOD_TIME [bound][private][data][node=Name]
579.48 -_FH_SIGNATURE [bound][private][data][node=Name]
579.49 -_FH_UNCOMPRESSED_SIZE [bound][private][data][node=Name]
579.50 -__all__ [bound][data][node=Name]
579.51 -__name__ [private][read][UNRESOLVED][node=Name]
579.52 -binascii [bound][imported][private][data][read][node=Import]
579.53 -cStringIO [bound][imported][private][data][read][node=Import]
579.54 -error [bound][class][alias][node=ClassDef]
579.55 -is_zipfile [bound][function][def][node=FunctionDef]
579.56 -main [bound][private][function][def][read][called][node=FunctionDef]
579.57 -object [private][read][UNRESOLVED][node=Name]
579.58 -os [bound][imported][private][data][read][node=Import]
579.59 -stringCentralDir [bound][private][data][read][node=Name]
579.60 -stringEndArchive [bound][private][data][read][node=Name]
579.61 -stringEndArchive64 [bound][private][data][read][node=Name]
579.62 -stringEndArchive64Locator [bound][private][data][read][node=Name]
579.63 -stringFileHeader [bound][private][data][read][node=Name]
579.64 -struct [bound][imported][private][data][read][node=Import]
579.65 -structCentralDir [bound][private][data][read][node=Name]
579.66 -structEndArchive [bound][private][data][read][node=Name]
579.67 -structEndArchive64 [bound][private][data][read][node=Name]
579.68 -structEndArchive64Locator [bound][private][data][read][node=Name]
579.69 -structFileHeader [bound][private][data][read][node=Name]
579.70 -sys [bound][imported][private][data][read][node=Import]
579.71 -time [bound][imported][private][data][read][node=Import]
579.72 -zlib [bound][imported][private][data][read][node=Import]
579.73 -
579.74 - =============================================
579.75 - class BadZipfile: ClassDef : OffsetRange[328,368>
579.76 -
579.77 - =============================================
579.78 - class LargeZipFile: ClassDef : OffsetRange[368,528>
579.79 -
579.80 - =============================================
579.81 - is_zipfile: FunctionDef : OffsetRange[2451,2794>
579.82 - False [free][read][node=Name]
579.83 - IOError [free][read][node=Name]
579.84 - True [free][read][node=Name]
579.85 - _EndRecData [free][read][called][node=Name]
579.86 - endrec [bound][data][read][node=Name]
579.87 - filename [bound][param][data][read][node=Name]
579.88 - fpin [bound][data][read][node=Name]
579.89 - open [free][read][called][node=Name]
579.90 -
579.91 - =============================================
579.92 - _EndRecData64: FunctionDef : OffsetRange[2794,3973>
579.93 - BadZipfile [free][private][read][called][node=Name]
579.94 - create_version [bound][private][data][unused][node=Name]
579.95 - data [bound][private][data][read][node=Name]
579.96 - dircount [bound][private][data][read][node=Name]
579.97 - dircount2 [bound][private][data][read][node=Name]
579.98 - diroffset [bound][private][data][read][node=Name]
579.99 - dirsize [bound][private][data][read][node=Name]
579.100 - disk_dir [bound][private][data][read][node=Name]
579.101 - disk_num [bound][private][data][read][node=Name]
579.102 - diskno [bound][private][data][read][node=Name]
579.103 - disks [bound][private][data][read][node=Name]
579.104 - endArchiveSize [bound][private][data][read][node=Name]
579.105 - endrec [bound][param][private][data][read][node=Name]
579.106 - fpin [bound][param][private][data][read][node=Name]
579.107 - locatorSize [bound][private][data][read][node=Name]
579.108 - offset [bound][param][private][data][read][node=Name]
579.109 - read_version [bound][private][data][unused][node=Name]
579.110 - reloff [bound][private][data][unused][node=Name]
579.111 - sig [bound][private][data][read][node=Name]
579.112 - stringEndArchive64 [free][private][read][node=Name]
579.113 - stringEndArchive64Locator [free][private][read][node=Name]
579.114 - struct [free][private][read][node=Name]
579.115 - structEndArchive64 [free][private][read][node=Name]
579.116 - structEndArchive64Locator [free][private][read][node=Name]
579.117 - sz [bound][private][data][unused][node=Name]
579.118 -
579.119 - =============================================
579.120 - _EndRecData: FunctionDef : OffsetRange[3973,5887>
579.121 - END_BLOCK [bound][private][data][read][node=Name]
579.122 - _EndRecData64 [free][private][read][called][node=Name]
579.123 - comment [bound][private][data][read][node=Name]
579.124 - data [bound][private][data][read][node=Name]
579.125 - endrec [bound][private][data][read][node=Name]
579.126 - filesize [bound][private][data][read][node=Name]
579.127 - fpin [bound][param][private][data][read][node=Name]
579.128 - len [free][private][read][called][node=Name]
579.129 - list [free][private][read][called][node=Name]
579.130 - min [free][private][read][called][node=Name]
579.131 - start [bound][private][data][read][node=Name]
579.132 - stringEndArchive [free][private][read][node=Name]
579.133 - struct [free][private][read][node=Name]
579.134 - structEndArchive [free][private][read][node=Name]
579.135 -
579.136 - =============================================
579.137 - class ZipInfo: ClassDef : OffsetRange[5887,11246>
579.138 - FileHeader [bound][function][def][node=FunctionDef]
579.139 - __init__ [bound][function][def][node=FunctionDef]
579.140 - __slots__ [bound][data][node=Name]
579.141 - _decodeExtra [bound][private][function][def][node=FunctionDef]
579.142 - ------ Attributes ---------------------------------------
579.143 - comment : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.144 - compress_size : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
579.145 - compress_type : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.146 - create_system : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.147 - create_version : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.148 - date_time : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.149 - external_attr : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.150 - extra : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.151 - extract_version : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.152 - file_size : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
579.153 - filename : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.154 - flag_bits : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.155 - header_offset : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
579.156 - internal_attr : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.157 - orig_filename : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.158 - reserved : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.159 - volume : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.160 -
579.161 - =============================================
579.162 - __init__: FunctionDef : OffsetRange[6490,8551>
579.163 - ZIP_STORED [free][read][node=Name]
579.164 - chr [free][read][called][node=Name]
579.165 - date_time [bound][param][data][read][node=Name]
579.166 - filename [bound][param][data][read][node=Name]
579.167 - null_byte [bound][data][read][node=Name]
579.168 - os [free][read][node=Name]
579.169 - self [bound][param][data][read][node=Name]
579.170 - sys [free][read][node=Name]
579.171 -
579.172 - =============================================
579.173 - FileHeader: FunctionDef : OffsetRange[8552,9961>
579.174 - CRC [bound][data][read][node=Name]
579.175 - ZIP64_LIMIT [free][read][node=Name]
579.176 - compress_size [bound][data][read][node=Name]
579.177 - dosdate [bound][data][read][node=Name]
579.178 - dostime [bound][data][read][node=Name]
579.179 - dt [bound][data][read][node=Name]
579.180 - extra [bound][data][read][node=Name]
579.181 - file_size [bound][data][read][node=Name]
579.182 - fmt [bound][data][read][node=Name]
579.183 - header [bound][data][read][node=Name]
579.184 - len [free][read][called][node=Name]
579.185 - max [free][read][called][node=Name]
579.186 - self [bound][param][data][read][node=Name]
579.187 - stringFileHeader [free][read][node=Name]
579.188 - struct [free][read][node=Name]
579.189 - structFileHeader [free][read][node=Name]
579.190 - ------ Attributes ---------------------------------------
579.191 - CRC : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.192 - compress_size : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.193 - compress_type : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.194 - date_time : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.195 - extra : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.196 - extract_version : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.197 - file_size : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.198 - filename : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.199 - flag_bits : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.200 - reserved : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.201 -
579.202 - =============================================
579.203 - _decodeExtra: FunctionDef : OffsetRange[9962,11246>
579.204 - RuntimeError [free][read][node=Name]
579.205 - counts [bound][data][read][node=Name]
579.206 - extra [bound][data][read][node=Name]
579.207 - idx [bound][data][read][node=Name]
579.208 - ln [bound][data][read][node=Name]
579.209 - old [bound][data][unused][node=Name]
579.210 - self [bound][param][data][read][node=Name]
579.211 - struct [free][read][node=Name]
579.212 - tp [bound][data][read][node=Name]
579.213 - unpack [bound][data][read][called][node=Name]
579.214 - ------ Attributes ---------------------------------------
579.215 - compress_size : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.216 - extra : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.217 - file_size : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.218 - header_offset : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.219 -
579.220 - =============================================
579.221 - class ZipFile: ClassDef : OffsetRange[11246,28949>
579.222 - False [free][read][node=Name]
579.223 - None [free][read][node=Name]
579.224 - ZIP_STORED [free][read][node=Name]
579.225 - _GetContents [bound][private][function][def][node=FunctionDef]
579.226 - _RealGetContents [bound][private][function][def][node=FunctionDef]
579.227 - __del__ [bound][function][def][node=FunctionDef]
579.228 - __init__ [bound][function][def][node=FunctionDef]
579.229 - _writecheck [bound][private][function][def][node=FunctionDef]
579.230 - close [bound][function][def][node=FunctionDef]
579.231 - fp [bound][data][node=Name]
579.232 - getinfo [bound][function][def][node=FunctionDef]
579.233 - infolist [bound][function][def][node=FunctionDef]
579.234 - namelist [bound][function][def][node=FunctionDef]
579.235 - printdir [bound][function][def][node=FunctionDef]
579.236 - read [bound][function][def][node=FunctionDef]
579.237 - testzip [bound][function][def][node=FunctionDef]
579.238 - write [bound][function][def][node=FunctionDef]
579.239 - writestr [bound][function][def][node=FunctionDef]
579.240 - ------ Attributes ---------------------------------------
579.241 - NameToInfo : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.242 - _allowZip64 : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.243 - _didModify : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.244 - _filePassed : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.245 - comment : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
579.246 - compression : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.247 - debug : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.248 - filelist : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.249 - filename : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.250 - fp : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.251 - mode : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
579.252 - start_dir : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
579.253 -
579.254 - =============================================
579.255 - __init__: FunctionDef : OffsetRange[11956,13836>
579.256 - BadZipfile [free][read][node=Name]
579.257 - False [free][read][node=Name]
579.258 - None [free][read][node=Name]
579.259 - RuntimeError [free][read][node=Name]
579.260 - ZIP_DEFLATED [free][read][node=Name]
579.261 - ZIP_STORED [free][read][node=Name]
579.262 - allowZip64 [bound][param][data][read][node=Name]
579.263 - basestring [free][read][node=Name]
579.264 - compression [bound][param][data][read][node=Name]
579.265 - file [bound][param][data][read][node=Name]
579.266 - getattr [free][read][called][node=Name]
579.267 - isinstance [free][read][called][node=Name]
579.268 - key [bound][data][read][node=Name]
579.269 - mode [bound][param][data][read][node=Name]
579.270 - modeDict [bound][data][read][node=Name]
579.271 - open [free][read][called][node=Name]
579.272 - self [bound][param][data][read][node=Name]
579.273 - zlib [free][read][node=Name]
579.274 - ------ Attributes ---------------------------------------
579.275 - _GetContents : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
579.276 - _RealGetContents : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
579.277 - _filePassed : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
579.278 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.279 - start_dir : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.280 -
579.281 - =============================================
579.282 - _GetContents: FunctionDef : OffsetRange[13837,14153>
579.283 - BadZipfile [free][read][node=Name]
579.284 - None [free][read][node=Name]
579.285 - self [bound][param][data][read][node=Name]
579.286 - ------ Attributes ---------------------------------------
579.287 - _RealGetContents : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
579.288 - _filePassed : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
579.289 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.290 -
579.291 - =============================================
579.292 - _RealGetContents: FunctionDef : OffsetRange[14154,16820>
579.293 - BadZipfile [free][read][node=Name]
579.294 - ZIP64_LIMIT [free][read][node=Name]
579.295 - ZipInfo [free][read][called][node=Name]
579.296 - _CD_COMMENT_LENGTH [free][read][node=Name]
579.297 - _CD_EXTRA_FIELD_LENGTH [free][read][node=Name]
579.298 - _CD_FILENAME_LENGTH [free][read][node=Name]
579.299 - _CD_LOCAL_HEADER_OFFSET [free][read][node=Name]
579.300 - _EndRecData [free][read][called][node=Name]
579.301 - cStringIO [free][read][node=Name]
579.302 - centdir [bound][data][read][node=Name]
579.303 - concat [bound][data][read][node=Name]
579.304 - d [bound][data][read][node=Name]
579.305 - data [bound][data][read][node=Name]
579.306 - endrec [bound][data][read][node=Name]
579.307 - filename [bound][data][read][node=Name]
579.308 - fp [bound][data][read][node=Name]
579.309 - offset_cd [bound][data][read][node=Name]
579.310 - self [bound][param][data][read][node=Name]
579.311 - size_cd [bound][data][read][node=Name]
579.312 - stringCentralDir [free][read][node=Name]
579.313 - struct [free][read][node=Name]
579.314 - structCentralDir [free][read][node=Name]
579.315 - t [bound][data][read][node=Name]
579.316 - total [bound][data][read][node=Name]
579.317 - x [bound][data][read][node=Name]
579.318 - ------ Attributes ---------------------------------------
579.319 - NameToInfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.320 - debug : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.321 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.322 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.323 - start_dir : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.324 -
579.325 - =============================================
579.326 - namelist: FunctionDef : OffsetRange[16821,17006>
579.327 - data [bound][data][read][node=Name]
579.328 - l [bound][data][read][node=Name]
579.329 - self [bound][param][data][read][node=Name]
579.330 - ------ Attributes ---------------------------------------
579.331 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.332 -
579.333 - =============================================
579.334 - infolist: FunctionDef : OffsetRange[17007,17149>
579.335 - self [bound][param][data][read][node=Name]
579.336 - ------ Attributes ---------------------------------------
579.337 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.338 -
579.339 - =============================================
579.340 - printdir: FunctionDef : OffsetRange[17150,17487>
579.341 - date [bound][data][read][node=Name]
579.342 - self [bound][param][data][read][node=Name]
579.343 - zinfo [bound][data][read][node=Name]
579.344 - ------ Attributes ---------------------------------------
579.345 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.346 -
579.347 - =============================================
579.348 - testzip: FunctionDef : OffsetRange[17488,17749>
579.349 - BadZipfile [free][read][node=Name]
579.350 - self [bound][param][data][read][node=Name]
579.351 - zinfo [bound][data][read][node=Name]
579.352 - ------ Attributes ---------------------------------------
579.353 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.354 - read : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
579.355 -
579.356 - =============================================
579.357 - getinfo: FunctionDef : OffsetRange[17750,17875>
579.358 - name [bound][param][data][read][node=Name]
579.359 - self [bound][param][data][read][node=Name]
579.360 - ------ Attributes ---------------------------------------
579.361 - NameToInfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.362 -
579.363 - =============================================
579.364 - read: FunctionDef : OffsetRange[17876,19878>
579.365 - BadZipfile [free][read][node=Name]
579.366 - RuntimeError [free][read][node=Name]
579.367 - ZIP_DEFLATED [free][read][node=Name]
579.368 - ZIP_STORED [free][read][node=Name]
579.369 - _FH_EXTRA_FIELD_LENGTH [free][read][node=Name]
579.370 - _FH_FILENAME_LENGTH [free][read][node=Name]
579.371 - binascii [free][read][node=Name]
579.372 - bytes [bound][data][read][node=Name]
579.373 - crc [bound][data][read][node=Name]
579.374 - dc [bound][data][read][node=Name]
579.375 - ex [bound][data][read][node=Name]
579.376 - fheader [bound][data][read][node=Name]
579.377 - filepos [bound][data][read][node=Name]
579.378 - fname [bound][data][read][node=Name]
579.379 - name [bound][param][data][read][node=Name]
579.380 - self [bound][param][data][read][node=Name]
579.381 - stringFileHeader [free][read][node=Name]
579.382 - struct [free][read][node=Name]
579.383 - structFileHeader [free][read][node=Name]
579.384 - zinfo [bound][data][read][node=Name]
579.385 - zlib [free][read][node=Name]
579.386 - ------ Attributes ---------------------------------------
579.387 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.388 - getinfo : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
579.389 - mode : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.390 -
579.391 - =============================================
579.392 - _writecheck: FunctionDef : OffsetRange[19879,21029>
579.393 - LargeZipFile [free][read][called][node=Name]
579.394 - RuntimeError [free][read][node=Name]
579.395 - ZIP64_LIMIT [free][read][node=Name]
579.396 - ZIP_DEFLATED [free][read][node=Name]
579.397 - ZIP_STORED [free][read][node=Name]
579.398 - self [bound][param][data][read][node=Name]
579.399 - zinfo [bound][param][data][read][node=Name]
579.400 - zlib [free][read][node=Name]
579.401 - ------ Attributes ---------------------------------------
579.402 - NameToInfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.403 - _allowZip64 : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
579.404 - debug : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.405 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.406 - mode : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.407 -
579.408 - =============================================
579.409 - write: FunctionDef : OffsetRange[21030,23534>
579.410 - CRC [bound][data][read][node=Name]
579.411 - None [free][read][node=Name]
579.412 - True [free][read][node=Name]
579.413 - ZIP_DEFLATED [free][read][node=Name]
579.414 - ZipInfo [free][read][called][node=Name]
579.415 - arcname [bound][param][data][read][node=Name]
579.416 - binascii [free][read][node=Name]
579.417 - buf [bound][data][read][node=Name]
579.418 - cmpr [bound][data][read][node=Name]
579.419 - compress_size [bound][data][read][node=Name]
579.420 - compress_type [bound][param][data][read][node=Name]
579.421 - date_time [bound][data][read][node=Name]
579.422 - file_size [bound][data][read][node=Name]
579.423 - filename [bound][param][data][read][node=Name]
579.424 - fp [bound][data][read][node=Name]
579.425 - len [free][read][called][node=Name]
579.426 - mtime [bound][data][read][node=Name]
579.427 - open [free][read][called][node=Name]
579.428 - os [free][read][node=Name]
579.429 - position [bound][data][read][node=Name]
579.430 - self [bound][param][data][read][node=Name]
579.431 - st [bound][data][read][node=Name]
579.432 - struct [free][read][node=Name]
579.433 - time [free][read][node=Name]
579.434 - zinfo [bound][data][read][node=Name]
579.435 - zlib [free][read][node=Name]
579.436 - ------ Attributes ---------------------------------------
579.437 - NameToInfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.438 - _writecheck : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
579.439 - compression : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.440 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.441 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.442 -
579.443 - =============================================
579.444 - writestr: FunctionDef : OffsetRange[23535,25110>
579.445 - True [free][read][node=Name]
579.446 - ZIP_DEFLATED [free][read][node=Name]
579.447 - ZipInfo [free][read][called][node=Name]
579.448 - binascii [free][read][node=Name]
579.449 - bytes [bound][param][data][read][node=Name]
579.450 - co [bound][data][read][node=Name]
579.451 - isinstance [free][read][called][node=Name]
579.452 - len [free][read][called][node=Name]
579.453 - self [bound][param][data][read][node=Name]
579.454 - struct [free][read][node=Name]
579.455 - time [free][read][node=Name]
579.456 - zinfo [bound][data][read][node=Name]
579.457 - zinfo_or_arcname [bound][param][data][read][node=Name]
579.458 - zlib [free][read][node=Name]
579.459 - ------ Attributes ---------------------------------------
579.460 - NameToInfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.461 - _writecheck : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
579.462 - compression : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.463 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.464 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.465 -
579.466 - =============================================
579.467 - __del__: FunctionDef : OffsetRange[25111,25220>
579.468 - self [bound][param][data][read][node=Name]
579.469 - ------ Attributes ---------------------------------------
579.470 - close : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
579.471 -
579.472 - =============================================
579.473 - close: FunctionDef : OffsetRange[25221,28949>
579.474 - None [free][read][node=Name]
579.475 - ZIP64_LIMIT [free][read][node=Name]
579.476 - centdir [bound][data][read][node=Name]
579.477 - compress_size [bound][data][read][node=Name]
579.478 - count [bound][data][read][node=Name]
579.479 - create_version [bound][data][read][node=Name]
579.480 - dosdate [bound][data][read][node=Name]
579.481 - dostime [bound][data][read][node=Name]
579.482 - dt [bound][data][read][node=Name]
579.483 - endrec [bound][data][read][node=Name]
579.484 - extra [bound][data][read][node=Name]
579.485 - extra_data [bound][data][read][node=Name]
579.486 - extract_version [bound][data][read][node=Name]
579.487 - file_size [bound][data][read][node=Name]
579.488 - header_offset [bound][data][read][node=Name]
579.489 - len [free][read][called][node=Name]
579.490 - max [free][read][called][node=Name]
579.491 - pos1 [bound][data][read][node=Name]
579.492 - pos2 [bound][data][read][node=Name]
579.493 - pos3 [bound][data][unused][node=Name]
579.494 - self [bound][param][data][read][node=Name]
579.495 - stringCentralDir [free][read][node=Name]
579.496 - stringEndArchive [free][read][node=Name]
579.497 - stringEndArchive64 [free][read][node=Name]
579.498 - stringEndArchive64Locator [free][read][node=Name]
579.499 - struct [free][read][node=Name]
579.500 - structCentralDir [free][read][node=Name]
579.501 - structEndArchive [free][read][node=Name]
579.502 - structEndArchive64 [free][read][node=Name]
579.503 - structEndArchive64Locator [free][read][node=Name]
579.504 - zinfo [bound][data][read][node=Name]
579.505 - zip64endrec [bound][data][read][node=Name]
579.506 - zip64locrec [bound][data][read][node=Name]
579.507 - ------ Attributes ---------------------------------------
579.508 - _didModify : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
579.509 - _filePassed : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
579.510 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.511 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.512 - mode : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.513 -
579.514 - =============================================
579.515 - class PyZipFile: ClassDef : OffsetRange[28949,33475>
579.516 - _get_codename [bound][private][function][def][node=FunctionDef]
579.517 - writepy [bound][function][def][node=FunctionDef]
579.518 -
579.519 - =============================================
579.520 - writepy: FunctionDef : OffsetRange[29059,32257>
579.521 - RuntimeError [free][read][node=Name]
579.522 - arcname [bound][data][read][node=Name]
579.523 - basename [bound][param][data][read][node=Name]
579.524 - dir [bound][data][unused][node=Name]
579.525 - dirlist [bound][data][read][node=Name]
579.526 - ext [bound][data][read][node=Name]
579.527 - filename [bound][data][read][node=Name]
579.528 - fname [bound][data][read][node=Name]
579.529 - initname [bound][data][read][node=Name]
579.530 - name [bound][data][read][node=Name]
579.531 - os [free][read][node=Name]
579.532 - path [bound][data][read][node=Name]
579.533 - pathname [bound][param][data][read][node=Name]
579.534 - root [bound][data][unused][node=Name]
579.535 - self [bound][param][data][read][node=Name]
579.536 - ------ Attributes ---------------------------------------
579.537 - _get_codename : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
579.538 - debug : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.539 - write : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
579.540 - writepy : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
579.541 -
579.542 - =============================================
579.543 - _get_codename: FunctionDef : OffsetRange[32258,33475>
579.544 - None [free][read][node=Name]
579.545 - True [free][read][node=Name]
579.546 - archivename [bound][data][read][node=Name]
579.547 - basename [bound][param][data][read][node=Name]
579.548 - err [bound][data][read][node=Name]
579.549 - file_py [bound][data][read][node=Name]
579.550 - file_pyc [bound][data][read][node=Name]
579.551 - file_pyo [bound][data][read][node=Name]
579.552 - fname [bound][data][read][node=Name]
579.553 - os [free][read][node=Name]
579.554 - pathname [bound][param][data][read][node=Name]
579.555 - py_compile [bound][imported][data][read][node=Import]
579.556 - self [bound][param][data][read][node=Name]
579.557 - ------ Attributes ---------------------------------------
579.558 - debug : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
579.559 -
579.560 - =============================================
579.561 - main: FunctionDef : OffsetRange[33475,35583>
579.562 - None [free][private][read][node=Name]
579.563 - True [free][private][read][node=Name]
579.564 - USAGE [bound][private][data][read][node=Name]
579.565 - ZIP_DEFLATED [free][private][node=null]
579.566 - ZipFile [free][private][read][called][node=Name]
579.567 - addToZip [bound][cell][private][function][def][read][called][node=FunctionDef]
579.568 - args [bound][param][private][data][read][node=Name]
579.569 - fp [bound][private][data][read][node=Name]
579.570 - len [free][private][read][called][node=Name]
579.571 - open [free][private][read][called][node=Name]
579.572 - os [free][private][read][node=Name]
579.573 - out [bound][private][data][read][node=Name]
579.574 - path [bound][private][data][read][node=Name]
579.575 - src [bound][private][data][read][node=Name]
579.576 - sys [free][private][read][node=Name]
579.577 - textwrap [bound][imported][private][data][read][node=Import]
579.578 - tgt [bound][private][data][read][node=Name]
579.579 - tgtdir [bound][private][data][read][node=Name]
579.580 - zf [bound][private][data][read][node=Name]
579.581 - ---------------------------------------------
579.582 - inner_free: {ZIP_DEFLATED=PRESENT, addToZip=PRESENT, os=PRESENT}
579.583 - cellvars: [addToZip]
579.584 - jy_npurecell: 1
579.585 -
579.586 - =============================================
579.587 - addToZip: FunctionDef : OffsetRange[35082,35435>
579.588 - ZIP_DEFLATED [free][private][read][node=Name]
579.589 - addToZip [free][private][read][called][node=Name]
579.590 - nm [bound][private][data][read][node=Name]
579.591 - os [free][private][read][node=Name]
579.592 - path [bound][param][private][data][read][node=Name]
579.593 - zf [bound][param][private][data][read][node=Name]
579.594 - zippath [bound][param][private][data][read][node=Name]
579.595 -
580.1 --- a/python.editor/test/unit/src/META-INF/services/org.netbeans.modules.gsf.api.SourceModelFactory Sun Jan 04 13:11:53 2015 -0600
580.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
580.3 @@ -1,2 +0,0 @@
580.4 -org.netbeans.modules.gsf.TestSourceModelFactory
580.5 -#position=1
581.1 --- a/python.editor/test/unit/src/META-INF/services/org.openide.modules.InstalledFileLocator Sun Jan 04 13:11:53 2015 -0600
581.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
581.3 @@ -1,1 +0,0 @@
581.4 -org.netbeans.modules.python.editor.InstalledFileLocatorImpl
582.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/AstPathTest.java Sun Jan 04 13:11:53 2015 -0600
582.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
582.3 @@ -1,147 +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;
582.47 -
582.48 -import java.util.Iterator;
582.49 -import org.netbeans.modules.gsf.api.CompilationInfo;
582.50 -import org.netbeans.modules.gsf.api.OffsetRange;
582.51 -import org.python.antlr.PythonTree;
582.52 -import org.python.antlr.ast.ClassDef;
582.53 -import org.python.antlr.ast.FunctionDef;
582.54 -
582.55 -/**
582.56 - *
582.57 - * @author Tor Norbye
582.58 - */
582.59 -public class AstPathTest extends PythonTestBase {
582.60 -
582.61 - public AstPathTest(String name) {
582.62 - super(name);
582.63 - }
582.64 -
582.65 - protected String annotatePath(AstPath path) {
582.66 - StringBuilder sb = new StringBuilder();
582.67 -
582.68 - Iterator<PythonTree> it = path.rootToLeaf();
582.69 - while (it.hasNext()) {
582.70 - PythonTree node = it.next();
582.71 -
582.72 - sb.append(node.getClass().getSimpleName());
582.73 - sb.append(":");
582.74 - OffsetRange range = PythonAstUtils.getRange(node);
582.75 - sb.append(range);
582.76 -
582.77 - sb.append("\n");
582.78 - }
582.79 -
582.80 - return sb.toString();
582.81 - }
582.82 -
582.83 - public AstPath getPath(String relFilePath, String caretLine) throws Exception {
582.84 - CompilationInfo info = getInfo(relFilePath);
582.85 - PythonTree root = PythonAstUtils.getRoot(info);
582.86 - int caretOffset = getCaretOffset(info.getText(), caretLine);
582.87 - AstPath path = AstPath.get(root, caretOffset);
582.88 -
582.89 - return path;
582.90 - }
582.91 -
582.92 - public void checkPath(String relFilePath, String caretLine) throws Exception {
582.93 - AstPath path = getPath(relFilePath, caretLine);
582.94 - String pathDesc = annotatePath(path);
582.95 - assertDescriptionMatches(relFilePath, pathDesc, true, ".path"); // NOI18N
582.96 - }
582.97 -
582.98 - public void testGetByCaretOffset() throws Exception {
582.99 - String relFilePath = "testfiles/ConfigParser.py";
582.100 - String caretLine = "Error.__init__(se^lf, \"Section %r already exists\" % section)";
582.101 - checkPath(relFilePath, caretLine);
582.102 - }
582.103 -
582.104 - public void testGetByNode1() throws Exception {
582.105 - String relFilePath = "testfiles/ConfigParser.py";
582.106 - String caretLine = "Error.__init__(se^lf, \"Section %r already exists\" % section)";
582.107 - AstPath path = getPath(relFilePath, caretLine);
582.108 -
582.109 - PythonTree node = path.leaf();
582.110 - PythonTree root = path.root();
582.111 - AstPath newPath = AstPath.get(root, node);
582.112 - String pathDesc = annotatePath(newPath);
582.113 - assertDescriptionMatches(relFilePath, pathDesc, true, ".path"); // NOI18N
582.114 - }
582.115 -
582.116 - public void testGetByNode2() throws Exception {
582.117 - String relFilePath = "testfiles/ConfigParser.py";
582.118 - String caretLine = "Error.__init__(se^lf, \"Section %r already exists\" % section)";
582.119 - AstPath path = getPath(relFilePath, caretLine);
582.120 -
582.121 - PythonTree node = path.leafParent();
582.122 - PythonTree root = path.root();
582.123 - AstPath newPath = AstPath.get(root, node);
582.124 - String pathDesc = annotatePath(newPath);
582.125 - assertDescriptionMatches(relFilePath, pathDesc, true, ".path"); // NOI18N
582.126 - }
582.127 -
582.128 - public void testGetTypedAncestor() throws Exception {
582.129 - String relFilePath = "testfiles/ConfigParser.py";
582.130 - String caretLine = "Error.__init__(se^lf, \"Section %r already exists\" % section)";
582.131 - AstPath path = getPath(relFilePath, caretLine);
582.132 - ClassDef def = (ClassDef)path.getTypedAncestor(ClassDef.class);
582.133 - assertNotNull(def);
582.134 - assertEquals("DuplicateSectionError", def.getInternalName());
582.135 - }
582.136 -
582.137 - public void testGetTypedAncestorFrom() throws Exception {
582.138 - String relFilePath = "testfiles/test_scope.py";
582.139 - String caretLine = "def meth^od_and_var(self):";
582.140 - AstPath path = getPath(relFilePath, caretLine);
582.141 - assertEquals(FunctionDef.class, path.leaf().getClass());
582.142 -
582.143 - PythonTree parent = path.leafParent();
582.144 - assertEquals(ClassDef.class, parent.getClass());
582.145 -
582.146 - FunctionDef def = (FunctionDef)path.getTypedAncestor(FunctionDef.class, parent);
582.147 - assertNotNull(def);
582.148 - assertEquals("test", def.getInternalName());
582.149 - }
582.150 -}
583.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/CompleteApiTest.java Sun Jan 04 13:11:53 2015 -0600
583.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
583.3 @@ -1,331 +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 2009 Sun Microsystems, Inc.
583.44 - */
583.45 -package org.netbeans.modules.python.editor;
583.46 -
583.47 -import java.util.ArrayList;
583.48 -import java.util.Arrays;
583.49 -import java.util.Collections;
583.50 -import java.util.HashMap;
583.51 -import java.util.HashSet;
583.52 -import java.util.List;
583.53 -import java.util.Map;
583.54 -import java.util.Set;
583.55 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
583.56 -import org.netbeans.modules.gsf.api.IndexDocument;
583.57 -import org.netbeans.modules.gsf.api.IndexDocumentFactory;
583.58 -import org.netbeans.modules.gsf.api.ParserResult;
583.59 -import org.openide.filesystems.FileObject;
583.60 -
583.61 -/**
583.62 - * This test ensures that we're picking up all the expected
583.63 - * APIs for the various core classes (str, list, etc).
583.64 - *
583.65 - * @author Tor Norbye
583.66 - */
583.67 -public class CompleteApiTest extends PythonTestBase {
583.68 - public CompleteApiTest(String name) {
583.69 - super(name);
583.70 - }
583.71 -
583.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
583.73 - // so on for various literal types in the python console.
583.74 - // This is for Python 2.6.1.
583.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"};
583.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"};
583.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"};
583.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"};
583.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"};
583.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"};
583.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"};
583.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"};
583.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"};
583.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"};
583.85 -
583.86 - private static void appendList(StringBuilder sb, List<String> list) {
583.87 - sb.append("{ ");
583.88 - boolean first = true;
583.89 - for (String m : list) {
583.90 - if (first) {
583.91 - first = false;
583.92 - } else {
583.93 - sb.append(", ");
583.94 - }
583.95 - sb.append('"');
583.96 - sb.append(m);
583.97 - sb.append('"');
583.98 - }
583.99 - sb.append(" }; ");
583.100 - }
583.101 -
583.102 - public void checkFile(String clz, String[] attrs, String... relFilePaths) throws Exception {
583.103 - Set<String> defined = new HashSet<String>(100);
583.104 - boolean foundClass = false;
583.105 -
583.106 - for (String relFilePath : relFilePaths) {
583.107 - List<IndexDocument> result = indexFile(relFilePath);
583.108 -
583.109 - IndexDocumentImpl clzDoc = null;
583.110 - for (IndexDocument doc : result) {
583.111 - assertTrue(doc instanceof IndexDocumentImpl);
583.112 - IndexDocumentImpl idoc = (IndexDocumentImpl)doc;
583.113 - for (int i = 0; i < idoc.indexedKeys.size(); i++) {
583.114 - if (PythonIndexer.FIELD_CLASS_NAME.equals(idoc.indexedKeys.get(i))) {
583.115 - if (clz.equals(idoc.indexedValues.get(i))) {
583.116 - clzDoc = idoc;
583.117 - break;
583.118 - }
583.119 - }
583.120 - if (clzDoc != null) {
583.121 - break;
583.122 - }
583.123 - }
583.124 - }
583.125 -
583.126 - if (clzDoc == null) {
583.127 - continue;
583.128 - }
583.129 - foundClass = true;
583.130 -
583.131 - for (int i = 0; i < clzDoc.indexedKeys.size(); i++) {
583.132 - String key = clzDoc.indexedKeys.get(i);
583.133 - if (PythonIndexer.FIELD_MEMBER.equals(key)) {
583.134 - String value = clzDoc.indexedValues.get(i);
583.135 - int semi = value.indexOf(';');
583.136 - if (semi != -1) {
583.137 - value = value.substring(0, semi);
583.138 - }
583.139 - defined.add(value);
583.140 - }
583.141 - }
583.142 - }
583.143 -
583.144 - if (!foundClass) {
583.145 - StringBuilder sb = new StringBuilder();
583.146 - sb.append("No class definition whatsoever for ");
583.147 - sb.append(clz);
583.148 - sb.append(" : ");
583.149 - appendList(sb, Arrays.asList(attrs));
583.150 -
583.151 - fail(sb.toString());
583.152 - }
583.153 -
583.154 - // Now check that all attributes are accounted for (and produce a complete list)
583.155 - List<String> missing = new ArrayList<String>();
583.156 - for (String attribute : attrs) {
583.157 - // Current exceptions - not yet handled
583.158 - if ("__reduce__".equals(attribute) ||
583.159 - "__reduce_ex__".equals(attribute)) {
583.160 - continue;
583.161 - }
583.162 -
583.163 -
583.164 - if (!defined.contains(attribute)) {
583.165 - missing.add(attribute);
583.166 - }
583.167 - }
583.168 -
583.169 - if (missing.size() > 0) {
583.170 - StringBuilder sb = new StringBuilder();
583.171 - sb.append("Class ");
583.172 - sb.append(clz);
583.173 - sb.append(" is missing definitions for: ");
583.174 - appendList(sb, missing);
583.175 -
583.176 - fail(sb.toString());
583.177 - }
583.178 -
583.179 - Set<String> extra = new HashSet<String>(defined);
583.180 - for (String attribute : attrs) {
583.181 - extra.remove(attribute);
583.182 - }
583.183 -
583.184 - if (extra.size() > 0) {
583.185 - StringBuilder sb = new StringBuilder();
583.186 - sb.append("Class ");
583.187 - sb.append(clz);
583.188 - sb.append(" is defining extra names that should not be present: ");
583.189 - List<String> extraList = new ArrayList<String>(extra);
583.190 - Collections.sort(extraList);
583.191 - appendList(sb, extraList);
583.192 -
583.193 - fail(sb.toString());
583.194 - }
583.195 - }
583.196 -
583.197 - public void testFloat() throws Exception {
583.198 - checkFile("float", FLOAT_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
583.199 - }
583.200 -
583.201 - public void testInt() throws Exception {
583.202 - checkFile("int", INT_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
583.203 - }
583.204 -
583.205 - public void testComplex() throws Exception {
583.206 - checkFile("complex", COMPLEX_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
583.207 - }
583.208 -
583.209 - public void testBool() throws Exception {
583.210 - checkFile("bool", BOOL_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
583.211 - }
583.212 -
583.213 - public void testStr() throws Exception {
583.214 - checkFile("str", STR_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
583.215 - }
583.216 -
583.217 - public void testList() throws Exception {
583.218 - checkFile("list", LIST_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
583.219 - }
583.220 -
583.221 - public void testDict() throws Exception {
583.222 - checkFile("dict", DICT_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
583.223 - }
583.224 -
583.225 - public void testTuple() throws Exception {
583.226 - checkFile("tuple", TUPLE_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
583.227 - }
583.228 -
583.229 - public void testLong() throws Exception {
583.230 - checkFile("long", LONG_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
583.231 - }
583.232 -
583.233 - public void testUnicode() throws Exception {
583.234 - checkFile("unicode", UNICODE_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
583.235 - }
583.236 -
583.237 -// Generate a list of documented APIs
583.238 -// public void testGenerateDocumentedNames() throws Exception {
583.239 -// FileObject fo = getClusterHome().getFileObject("pythonstubs/pythonstubs-2_6_1.egg");
583.240 -// assertNotNull(fo);
583.241 -// GsfTestCompilationInfo info = getInfo(fo);
583.242 -// ParserResult rpr = info.getEmbeddedResult(info.getPreferredMimeType(), 0);
583.243 -// assertNotNull(rpr);
583.244 -//
583.245 -// PythonIndexer indexer = new PythonIndexer();
583.246 -// IndexDocumentFactory factory = new IndexDocumentFactoryImpl(/*info.getIndex(info.getPreferredMimeType())*/);
583.247 -// List<IndexDocument> result = indexer.index(rpr, factory);
583.248 -// assertNotNull(result);
583.249 -//
583.250 -// String[] RELEVANT = { "int", "float", "long", "complex", "list", "dict", "tuple", "str", "unicode" };
583.251 -//
583.252 -// // Generate a name document for Python inclusion into the extract_rst file
583.253 -// // This lists all the names for each class that we've defined
583.254 -// Map<String,Set<String>> classes = new HashMap<String,Set<String>>();
583.255 -//
583.256 -// for (IndexDocument idoc : result) {
583.257 -// IndexDocumentImpl doc = (IndexDocumentImpl)idoc;
583.258 -//
583.259 -// if (doc.overrideUrl.indexOf("stub_missing") != -1) {
583.260 -// continue;
583.261 -// }
583.262 -//
583.263 -// List<String> members = new ArrayList<String>();
583.264 -// String cls = null;
583.265 -// for (int i = 0, n = doc.indexedKeys.size(); i < n; i++) {
583.266 -// String key = doc.indexedKeys.get(i);
583.267 -// if (PythonIndexer.FIELD_MEMBER.equals(key)) {
583.268 -// String member = doc.indexedValues.get(i);
583.269 -// int idx = member.indexOf(';');
583.270 -// if (idx != -1) {
583.271 -// member = member.substring(0, idx);
583.272 -// }
583.273 -// members.add(member);
583.274 -// } else if (PythonIndexer.FIELD_CLASS_NAME.equals(key)) {
583.275 -// cls = doc.indexedValues.get(i);
583.276 -// }
583.277 -// }
583.278 -// if (members.size() > 0) {
583.279 -// assertNotNull(cls);
583.280 -// boolean found = false;
583.281 -// for (String s : RELEVANT) {
583.282 -// if (s.equals(cls)) {
583.283 -// found = true;
583.284 -// break;
583.285 -// }
583.286 -// }
583.287 -// if (!found) {
583.288 -// continue;
583.289 -// }
583.290 -// Set<String> memberSet = classes.get(cls);
583.291 -// if (memberSet == null) {
583.292 -// memberSet = new HashSet<String>();
583.293 -// classes.put(cls, memberSet);
583.294 -// }
583.295 -// //memberSet.addAll(members);
583.296 -// for (String member : members) {
583.297 -// if (memberSet.contains(member)) {
583.298 -// System.err.println("WARNING: Class " + cls + " already contains " + member);
583.299 -// }
583.300 -// memberSet.add(member);
583.301 -// }
583.302 -// }
583.303 -// }
583.304 -//
583.305 -// List<String> classNames = new ArrayList<String>(classes.keySet());
583.306 -// Collections.sort(classNames);
583.307 -// StringBuilder sb = new StringBuilder();
583.308 -// for (String cls : classNames) {
583.309 -// Set<String> memberSet = classes.get(cls);
583.310 -// assertNotNull(memberSet);
583.311 -//
583.312 -// List<String> members = new ArrayList<String>(memberSet);
583.313 -// Collections.sort(members);
583.314 -// sb.append("'");
583.315 -// sb.append(cls);
583.316 -// sb.append("': [");
583.317 -// boolean first = true;
583.318 -// for (String member : members) {
583.319 -// if (first) {
583.320 -// first = false;
583.321 -// } else {
583.322 -// sb.append(", ");
583.323 -// }
583.324 -// sb.append("'");
583.325 -// sb.append(member);
583.326 -// sb.append("'");
583.327 -// }
583.328 -// sb.append("],\n");
583.329 -// }
583.330 -//
583.331 -// System.out.println(sb.toString());
583.332 -// }
583.333 -
583.334 -}
584.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/InstalledFileLocatorImpl.java Sun Jan 04 13:11:53 2015 -0600
584.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
584.3 @@ -1,92 +0,0 @@
584.4 -/*
584.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
584.6 - *
584.7 - * Copyright 1997-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 - * The Original Software is NetBeans. The Initial Developer of the Original
584.31 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
584.32 - * Microsystems, Inc. All Rights Reserved.
584.33 - *
584.34 - * If you wish your version of this file to be governed by only the CDDL
584.35 - * or only the GPL Version 2, indicate your decision by adding
584.36 - * "[Contributor] elects to include this software in this distribution
584.37 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
584.38 - * single choice of license, a recipient has the option to distribute
584.39 - * your version of this file under either the CDDL, the GPL Version 2 or
584.40 - * to extend the choice of license to its licensees as provided above.
584.41 - * However, if you add GPL Version 2 code and therefore, elected the GPL
584.42 - * Version 2 license, then the option applies only if the new code is
584.43 - * made subject to such option by the copyright holder.
584.44 - */
584.45 -package org.netbeans.modules.python.editor;
584.46 -
584.47 -import java.io.File;
584.48 -import java.io.IOException;
584.49 -import org.openide.modules.InstalledFileLocator;
584.50 -import org.openide.util.Exceptions;
584.51 -
584.52 -public final class InstalledFileLocatorImpl extends InstalledFileLocator {
584.53 -
584.54 - public InstalledFileLocatorImpl() {
584.55 - }
584.56 -
584.57 - public
584.58 - @Override
584.59 - File locate(String relativePath, String codeNameBase, boolean localized) {
584.60 - if (relativePath.equals("jython-2.5.1")) {
584.61 - return PythonTestBase.getXTestPythonHome();
584.62 - } else if (relativePath.startsWith("jython-2.5.1" + File.separator)) {
584.63 - return new File(PythonTestBase.getXTestPythonHome(), relativePath.substring("jython-2.5.1".length() + 1));
584.64 - } else if (relativePath.equals("platform_info.py")) {
584.65 - String script = System.getProperty("xtest.platform_info.py");
584.66 - if (script == null) {
584.67 - throw new RuntimeException("xtest.platform_info.rb property has to be set when running within binary distribution");
584.68 - }
584.69 - return new File(script);
584.70 - } else if ("coverage/coverage.py".equals(relativePath) || "coverage/coverage_wrapper.py".equals(relativePath)) {
584.71 - try {
584.72 - return new File(PythonTestBase.getXTestPythonHome().getParentFile(), relativePath.replace("/", File.separator)).getCanonicalFile();
584.73 - } catch (IOException ex) {
584.74 - Exceptions.printStackTrace(ex);
584.75 - throw new RuntimeException("Couldn't find coverage files");
584.76 - }
584.77 - } else if (relativePath.equals("modules/org-netbeans-modules-python-editor.jar")) {
584.78 - // During test?
584.79 - // HACK - TODO use mock
584.80 - String jsDir = System.getProperty("xtest.python.home"); // NOI18N
584.81 - if (jsDir == null) {
584.82 - throw new RuntimeException("xtest.python.home property has to be set when running within binary distribution");
584.83 - }
584.84 - File jsStubs = new File(jsDir + File.separator + ".." + File.separator + "modules" + File.separator + "org-netbeans-modules-python-editor.jar"); // NOI18N
584.85 - if (jsStubs.exists()) {
584.86 - try {
584.87 - return jsStubs.getCanonicalFile();
584.88 - } catch (IOException ex) {
584.89 - Exceptions.printStackTrace(ex);
584.90 - }
584.91 - }
584.92 - }
584.93 - return null;
584.94 - }
584.95 -}
585.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonAstOffsetsTest.java Sun Jan 04 13:11:53 2015 -0600
585.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
585.3 @@ -1,101 +0,0 @@
585.4 -/*
585.5 - * To change this template, choose Tools | Templates
585.6 - * and open the template in the editor.
585.7 - */
585.8 -
585.9 -package org.netbeans.modules.python.editor;
585.10 -
585.11 -import java.util.List;
585.12 -import java.util.Map;
585.13 -import org.netbeans.modules.gsf.api.CompilationInfo;
585.14 -import org.netbeans.modules.gsf.api.OffsetRange;
585.15 -import org.netbeans.modules.gsf.api.ParserResult;
585.16 -import org.python.antlr.PythonTree;
585.17 -import org.python.antlr.Visitor;
585.18 -
585.19 -/**
585.20 - * Test offsets in the python parse trees
585.21 - *
585.22 - * @author Tor Norbye
585.23 - */
585.24 -public class PythonAstOffsetsTest extends PythonTestBase {
585.25 - public PythonAstOffsetsTest(String testName) {
585.26 - super(testName);
585.27 - }
585.28 -
585.29 - @Override
585.30 - protected String describeNode(CompilationInfo info, Object obj, boolean includePath) throws Exception {
585.31 - return obj.toString();
585.32 - }
585.33 -
585.34 - @Override
585.35 - protected void initializeNodes(CompilationInfo info, ParserResult result, List<Object> validNodes,
585.36 - Map<Object,OffsetRange> positions, List<Object> invalidNodes) throws Exception {
585.37 - PythonTree root = PythonAstUtils.getRoot(info);
585.38 - assertNotNull(root);
585.39 -
585.40 - new TreeVisitor(validNodes, invalidNodes, positions, info).visit(root);
585.41 - }
585.42 -
585.43 - public void testOffsets1() throws Exception {
585.44 - checkOffsets("testfiles/empty.py");
585.45 - }
585.46 -
585.47 - public void testOffsets2() throws Exception {
585.48 - checkOffsets("testfiles/ConfigParser.py");
585.49 - }
585.50 -
585.51 - public void testOffsets3() throws Exception {
585.52 - checkOffsets("testfiles/datetime.py");
585.53 - }
585.54 -
585.55 - public void testOffsets4() throws Exception {
585.56 - checkOffsets("testfiles/getopt.py");
585.57 - }
585.58 -
585.59 - public void testOffsets5() throws Exception {
585.60 - checkOffsets("testfiles/test_scope.py");
585.61 - }
585.62 -
585.63 - public void testAttributes() throws Exception {
585.64 - checkOffsets("testfiles/attribute.py");
585.65 - }
585.66 -
585.67 - public void testDecorators() throws Exception {
585.68 - checkOffsets("testfiles/staticmethods.py");
585.69 - }
585.70 -
585.71 - public void test149618() throws Exception {
585.72 - checkOffsets("testfiles/issue149618.py");
585.73 - }
585.74 -
585.75 - private static class TreeVisitor extends Visitor {
585.76 - private List<Object> validNodes;
585.77 - private List<Object> invalidNodes;
585.78 - private Map<Object, OffsetRange> positions;
585.79 -
585.80 - TreeVisitor(List<Object> validNodes, List<Object> invalidNodes, Map<Object,
585.81 - OffsetRange> positions, CompilationInfo info) {
585.82 - this.validNodes = validNodes;
585.83 - this.invalidNodes = invalidNodes;
585.84 - this.positions = positions;
585.85 - }
585.86 -
585.87 - @Override
585.88 - public void traverse(PythonTree node) throws Exception {
585.89 - assertTrue(node.getCharStartIndex() <= node.getCharStopIndex());
585.90 -
585.91 - OffsetRange range = new OffsetRange(node.getCharStartIndex(), node.getCharStopIndex());
585.92 - if (range.getStart() != 0 || range.getEnd() != 0) { // Don't include 0-0 PythonTrees, these are errors
585.93 - validNodes.add(node);
585.94 - positions.put(node, range);
585.95 - } else {
585.96 - invalidNodes.add(node);
585.97 - }
585.98 -
585.99 - super.traverse(node);
585.100 - }
585.101 -
585.102 - }
585.103 -
585.104 -}
586.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonAstUtilsTest.java Sun Jan 04 13:11:53 2015 -0600
586.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
586.3 @@ -1,185 +0,0 @@
586.4 -/*
586.5 - * To change this template, choose Tools | Templates
586.6 - * and open the template in the editor.
586.7 - */
586.8 -
586.9 -package org.netbeans.modules.python.editor;
586.10 -
586.11 -import java.util.ArrayList;
586.12 -import java.util.List;
586.13 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
586.14 -import org.netbeans.modules.gsf.api.CompilationInfo;
586.15 -import org.openide.filesystems.FileObject;
586.16 -import org.openide.filesystems.FileUtil;
586.17 -import org.python.antlr.PythonTree;
586.18 -import org.python.antlr.Visitor;
586.19 -import org.python.antlr.ast.Call;
586.20 -import org.python.antlr.ast.FunctionDef;
586.21 -import org.python.antlr.base.expr;
586.22 -
586.23 -/**
586.24 - *
586.25 - * @author Tor Norbye
586.26 - */
586.27 -public class PythonAstUtilsTest extends PythonTestBase {
586.28 -
586.29 - public PythonAstUtilsTest(String testName) {
586.30 - super(testName);
586.31 - }
586.32 -
586.33 - public void testScope() throws Exception {
586.34 - String relFilePath = "testfiles/ConfigParser.py";
586.35 - String caretLine = "Error.__init__(se^lf, \"Section %r already exists\" % section)";
586.36 -
586.37 - CompilationInfo info = getInfo(relFilePath);
586.38 - PythonTree root = PythonAstUtils.getRoot(info);
586.39 - int lineOffset = caretLine.indexOf('^');
586.40 - assertTrue(lineOffset != -1);
586.41 - caretLine = caretLine.substring(0, lineOffset) + caretLine.substring(lineOffset+1);
586.42 - int offset = info.getText().indexOf(caretLine)+lineOffset;
586.43 -
586.44 - AstPath path = AstPath.get(root, offset);
586.45 -
586.46 -// assertEquals("ClassDef", PythonAstUtils.getClassDef(path).toString());
586.47 - assertEquals("ClassDef", PythonAstUtils.getClassScope(path).toString());
586.48 - assertEquals("FunctionDef", PythonAstUtils.getLocalScope(path).toString());
586.49 - }
586.50 -
586.51 - public void testGetParamters() throws Exception {
586.52 - String relFilePath = "testfiles/ConfigParser.py";
586.53 - String caretLine = "Error.__init__(se^lf, \"Section %r already exists\" % section)";
586.54 -
586.55 - CompilationInfo info = getInfo(relFilePath);
586.56 - PythonTree root = PythonAstUtils.getRoot(info);
586.57 - int lineOffset = caretLine.indexOf('^');
586.58 - assertTrue(lineOffset != -1);
586.59 - caretLine = caretLine.substring(0, lineOffset) + caretLine.substring(lineOffset+1);
586.60 - int offset = info.getText().indexOf(caretLine)+lineOffset;
586.61 -
586.62 - AstPath path = AstPath.get(root, offset);
586.63 -
586.64 - FunctionDef def = (FunctionDef)PythonAstUtils.getLocalScope(path);
586.65 - assertEquals("[self, section]", PythonAstUtils.getParameters(def).toString());
586.66 - }
586.67 -
586.68 - public void testDecorators() throws Exception {
586.69 - String relFilePath = "testfiles/staticmethods.py";
586.70 -
586.71 - CompilationInfo info = getInfo(relFilePath);
586.72 - PythonTree root = PythonAstUtils.getRoot(info);
586.73 - List<PythonTree> nodes = getAllNodes(root);
586.74 - int count = 0;
586.75 - for (PythonTree node : nodes) {
586.76 - if (node instanceof FunctionDef) {
586.77 - boolean result=PythonAstUtils.isStaticMethod(node);
586.78 - /** Three function in the relFilePath [False, True, True]**/
586.79 - if (count==0)
586.80 - assertEquals(result, false);
586.81 - if (count>1)
586.82 - assertEquals(result, true);
586.83 - count += 1;
586.84 - }
586.85 - }
586.86 - }
586.87 -
586.88 - public void testStress() throws Exception {
586.89 - List<FileObject> files = findJythonFiles();
586.90 -
586.91 - int MAX_FILES = Integer.MAX_VALUE;
586.92 -
586.93 - for (int i = 0; i < files.size() && i < MAX_FILES; i++) {
586.94 - FileObject fo = files.get(i);
586.95 - GsfTestCompilationInfo info = getInfo(fo);
586.96 - PythonTree root = PythonAstUtils.getRoot(info);
586.97 - assertNotNull(FileUtil.getFileDisplayName(fo), root);
586.98 - List<PythonTree> nodes = getAllNodes(root);
586.99 - for (PythonTree node : nodes) {
586.100 - if (node instanceof Call) {
586.101 - PythonAstUtils.getCallName((Call)node);
586.102 - PythonAstUtils.isGetter((Call)node, false);
586.103 - }
586.104 - PythonAstUtils.getDocumentation(node);
586.105 - PythonAstUtils.getDocumentationNode(node);
586.106 - if (node instanceof expr) {
586.107 - PythonAstUtils.getExprName((expr)node);
586.108 - }
586.109 - PythonAstUtils.getName(node);
586.110 - PythonAstUtils.isNameNode(node);
586.111 - PythonAstUtils.getRange(node);
586.112 - PythonAstUtils.getNameRange(info, node);
586.113 - if (node instanceof FunctionDef) {
586.114 - PythonAstUtils.getParameters((FunctionDef)node);
586.115 - }
586.116 -
586.117 - //Document doc = info.getDocument();
586.118 - //for (int offset = 0; offset < doc.getLength(); offset++) {
586.119 - // assertNull("Handling " + FileUtil.getFileDisplayName(fo) + " at offset " + offset, PythonOccurrencesMarker.error);
586.120 - //}
586.121 -
586.122 - }
586.123 -
586.124 - final List<PythonTree> defs = new ArrayList<PythonTree>();
586.125 - PythonAstUtils.addNodesByType(root, new Class[] { PythonTree.class }, defs);
586.126 - new NodeFinder(new AstPathChecker() {
586.127 - public void check(AstPath path) {
586.128 - PythonAstUtils.getClassDef(path);
586.129 - PythonAstUtils.getClassScope(path);
586.130 - PythonAstUtils.getFuncDef(path);
586.131 - PythonAstUtils.getLocalScope(path);
586.132 - PythonAstUtils.getParentClassFromNode(path, null, "");
586.133 - PythonAstUtils.getParentClassFromNode(path, path.leaf(), "");
586.134 - for (PythonTree def : defs) {
586.135 - PythonAstUtils.isClassMethod(path, (FunctionDef)def);
586.136 - }
586.137 - }
586.138 - }).visit(root);
586.139 - }
586.140 - }
586.141 -
586.142 - interface AstPathChecker {
586.143 - void check(AstPath path);
586.144 - }
586.145 -
586.146 - private static class NodeFinder extends Visitor {
586.147 - private ArrayList<PythonTree> path = new ArrayList<PythonTree>();
586.148 - private AstPathChecker checker;
586.149 -
586.150 - private NodeFinder(AstPathChecker checker) {
586.151 - this.checker = checker;
586.152 - }
586.153 -
586.154 - @Override
586.155 - public void traverse(PythonTree node) throws Exception {
586.156 - path.add(node);
586.157 -
586.158 - checker.check(new AstPath(path));
586.159 -
586.160 - super.traverse(node);
586.161 - path.remove(path.size()-1);
586.162 - }
586.163 - }
586.164 -
586.165 -// public void testFindSpecialNodeTypes() throws Exception {
586.166 -// List<FileObject> files = findJythonFiles();
586.167 -//
586.168 -// int MAX_FILES = Integer.MAX_VALUE;
586.169 -//
586.170 -// for (int i = 0; i < files.size() && i < MAX_FILES; i++) {
586.171 -// final FileObject fo = files.get(i);
586.172 -// GsfTestCompilationInfo info = getInfo(fo);
586.173 -// PythonTree root = PythonAstUtils.getRoot(info);
586.174 -// new Visitor() {
586.175 -//
586.176 -// @Override
586.177 -// public Object visitGlobal(Global node) throws Exception {
586.178 -// String s = fo.getNameExt();
586.179 -// fail(s);
586.180 -// return super.visitGlobal(node);
586.181 -// }
586.182 -//
586.183 -// }.visit(root);
586.184 -// }
586.185 -// }
586.186 -
586.187 -
586.188 -}
587.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonCodeCompleterTest.java Sun Jan 04 13:11:53 2015 -0600
587.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
587.3 @@ -1,292 +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 -package org.netbeans.modules.python.editor;
587.9 -
587.10 -import java.net.URL;
587.11 -import java.util.List;
587.12 -
587.13 -/**
587.14 - *
587.15 - * @author Tor Norbye
587.16 - */
587.17 -public class PythonCodeCompleterTest extends PythonTestBase {
587.18 - public PythonCodeCompleterTest(String testName) {
587.19 - super(testName);
587.20 - }
587.21 - private boolean skipJython = false;
587.22 -
587.23 - @Override
587.24 - protected boolean skipRhs() {
587.25 - return true;
587.26 - }
587.27 -
587.28 - @Override
587.29 - protected List<URL> getExtraCpUrls() {
587.30 - // I'm overriding various Jython classes here for tests which causes
587.31 - // confusion when it's trying to locate classes and finds it in multiple places
587.32 - if (!skipJython) {
587.33 - return super.getExtraCpUrls();
587.34 - }
587.35 -
587.36 - return null;
587.37 - }
587.38 -
587.39 - public void testLocals1() throws Exception {
587.40 - checkCompletion("testfiles/ConfigParser.py", "s^elf.section = section", true);
587.41 - }
587.42 -
587.43 - public void testClasses2() throws Exception {
587.44 - checkCompletion("testfiles/ConfigParser.py", "raise D^uplicateSectionError(section)", true);
587.45 - }
587.46 -
587.47 - public void testStringCompletion() throws Exception {
587.48 - checkCompletion("testfiles/ConfigParser.py", "in \"^rR\"", true);
587.49 - }
587.50 -
587.51 - public void testNoStringCompletion() throws Exception {
587.52 - checkCompletion("testfiles/test_scope.py", "r\"i^mport", true);
587.53 - }
587.54 -
587.55 - public void testImports2() throws Exception {
587.56 - checkCompletion("testfiles/ConfigParser.py", "import r^e", true);
587.57 - }
587.58 -
587.59 - public void testImports7() throws Exception {
587.60 - checkCompletion("testfiles/imports7.py", "import ^", true);
587.61 - }
587.62 -
587.63 - public void testImports8() throws Exception {
587.64 - checkCompletion("testfiles/imports8.py", "import distutils.com^mand", true);
587.65 - }
587.66 -
587.67 - public void testImports9() throws Exception {
587.68 - checkCompletion("testfiles/imports9.py", "from difflib import ^c", true);
587.69 - }
587.70 -
587.71 - public void testFromImports() throws Exception {
587.72 - checkCompletion("testfiles/fromimports.py", "core.^g", true);
587.73 - }
587.74 -
587.75 - public void testDoc1() throws Exception {
587.76 - try {
587.77 - skipJython = true;
587.78 - checkCompletionDocumentation("testfiles/SocketServer.py", "class TCPServer(BaseSer^ver):", true, "BaseServer");
587.79 - } finally {
587.80 - skipJython = false;
587.81 - }
587.82 - }
587.83 -
587.84 - public void testDoc2() throws Exception {
587.85 - try {
587.86 - skipJython = true;
587.87 - checkCompletionDocumentation("testfiles/SocketServer.py", "class BaseRequestHandler^:", true, "BaseRequestHandler");
587.88 - } finally {
587.89 - skipJython = false;
587.90 - }
587.91 - }
587.92 -
587.93 - public void testDoc3() throws Exception {
587.94 - try {
587.95 - skipJython = true;
587.96 - checkCompletionDocumentation("testfiles/pickle.py", "import ^re", true, "pickle");
587.97 - } finally {
587.98 - skipJython = false;
587.99 - }
587.100 - }
587.101 -
587.102 - public void testDoc5() throws Exception {
587.103 - try {
587.104 - skipJython = true;
587.105 - // Treat r"""raw strings""" specially - as preformatted content perhaps?
587.106 - checkCompletionDocumentation("testfiles/pickle.py", "decode_lo^ng", true, "decode_long");
587.107 - } finally {
587.108 - skipJython = false;
587.109 - }
587.110 - }
587.111 -
587.112 - public void testFutureImport1() throws Exception {
587.113 - try {
587.114 - skipJython = true;
587.115 - checkCompletion("testfiles/futureimport.py", "import ^", true);
587.116 - } finally {
587.117 - skipJython = false;
587.118 - }
587.119 - }
587.120 -
587.121 - public void testDoc6() throws Exception {
587.122 - // Find documentation for a method that doesn't actually have a def - it's an alias
587.123 - checkCompletionDocumentation("testfiles/compl5.py", "self.assertA^lmostEquals(1,2)", true, "assertAlmostEquals");
587.124 - }
587.125 -
587.126 - public void testObjMethodCompletion2() throws Exception {
587.127 - checkCompletion("testfiles/compl.py", "self.^my", true);
587.128 - }
587.129 -
587.130 - public void testObjMethodCompletion3() throws Exception {
587.131 - // Test that imports of symbols in a
587.132 - checkCompletion("testfiles/compl2.py", "print w^hatever.r", true);
587.133 - }
587.134 -
587.135 - public void testObjMethodCompletion5() throws Exception {
587.136 - checkCompletion("testfiles/compl2.py", "print whatever.r^", true);
587.137 - }
587.138 -
587.139 - public void testObjMethodCompletion9() throws Exception {
587.140 - checkCompletion("testfiles/compl4.py", "faen.e^", true);
587.141 - }
587.142 -
587.143 - public void testObjMethodCompletion10() throws Exception {
587.144 - checkCompletion("testfiles/compl5.py", "unittest.T^", true);
587.145 - }
587.146 -
587.147 - public void testObjMethodCompletion11() throws Exception {
587.148 - checkCompletion("testfiles/compl5.py", "x.^r", true);
587.149 - }
587.150 -
587.151 - public void testObjMethodConstructors1() throws Exception {
587.152 - checkCompletion("testfiles/compl2.py", "myvar.^close()", true);
587.153 - }
587.154 -
587.155 - public void testObjMethodConstructors2() throws Exception {
587.156 - checkCompletion("testfiles/compl2.py", "myothervar.^", true);
587.157 - }
587.158 -
587.159 - public void testObjMethodConstructors3() throws Exception {
587.160 - // Not a calling a recognized type - all-completion
587.161 - checkCompletion("testfiles/compl2.py", "unknown.fai^", true);
587.162 - }
587.163 -
587.164 - public void testOverride1() throws Exception {
587.165 - // Not a calling a recognized type - all-completion
587.166 - checkCompletion("testfiles/compl5.py", "MyTest(unittest.TestCase):\n ^", true);
587.167 - }
587.168 -
587.169 - public void testOverride2() throws Exception {
587.170 - // Not a calling a recognized type - all-completion
587.171 - checkCompletion("testfiles/compl5.py", "def ^f(self)", true);
587.172 - }
587.173 -
587.174 - public void testLocals3() throws Exception {
587.175 - checkCompletion("testfiles/occurrences2.py", "tople^velvar = 1", true);
587.176 - }
587.177 -
587.178 - public void testLocals7() throws Exception {
587.179 - checkCompletion("testfiles/occurrences2.py", "print t^oplevelvar2", true);
587.180 - }
587.181 -
587.182 - public void testKeywordFrom() throws Exception {
587.183 - // See http://www.netbeans.org/issues/show_bug.cgi?id=154131
587.184 - checkCompletion("testfiles/org.py", "from or^", true);
587.185 - }
587.186 -
587.187 - public void testProperties() throws Exception {
587.188 - checkCompletion("testfiles/properties.py", "x.ba^", true);
587.189 - }
587.190 -
587.191 - public void testParameters1() throws Exception {
587.192 - checkCompletion("testfiles/complete-calls.py", "functionfoo(foo^, bar)", true);
587.193 - }
587.194 -
587.195 - public void testParameters2() throws Exception {
587.196 - checkCompletion("testfiles/complete-calls.py", "functionfoo(foo, bar^)", true);
587.197 - }
587.198 -
587.199 - public void testParameters3() throws Exception {
587.200 - checkCompletion("testfiles/complete-calls.py", "y.foo(x^yz)", true);
587.201 - }
587.202 -
587.203 - public void testParameters4() throws Exception {
587.204 - checkCompletion("testfiles/complete-calls.py", "y.foo(xyz, b^az)", true);
587.205 - }
587.206 -
587.207 - public void testParameters5() throws Exception {
587.208 - checkCompletion("testfiles/complete-calls.py", "functionfoo(\"foo\", \"bar\", inval^id)", true);
587.209 - }
587.210 -
587.211 - public void testDecorators1() throws Exception {
587.212 - checkCompletion("testfiles/emptydecorators.py", "@^", true);
587.213 - }
587.214 -
587.215 - public void testDecorators2() throws Exception {
587.216 - checkCompletion("testfiles/decorators.py", "@c^", true);
587.217 - }
587.218 -
587.219 - public void testTypedVars1() throws Exception {
587.220 - checkCompletion("testfiles/compl5.py", "os2.^", true);
587.221 - }
587.222 -
587.223 - public void testTypedVars2() throws Exception {
587.224 - checkCompletion("testfiles/compl5.py", "os3.^", true);
587.225 - }
587.226 -
587.227 - public void testTypedVars3() throws Exception {
587.228 - checkCompletion("testfiles/compl5.py", "os4.^", true);
587.229 - }
587.230 -
587.231 - public void testTypedVars4() throws Exception {
587.232 - // No type specified
587.233 - checkCompletion("testfiles/compl5.py", "os5.xhd^", true);
587.234 - }
587.235 - // -------------------------
587.236 - // Unstable tests:
587.237 - // -------------------------
587.238 - //
587.239 - //public void testObjMethodCompletion4() throws Exception {
587.240 - // checkCompletion("testfiles/compl2.py", "print whatever.^r", true);
587.241 - //}
587.242 - //public void testObjMethodCompletion6() throws Exception {
587.243 - // checkCompletion("testfiles/compl2.py", "print sys.getfile^systeme", true);
587.244 - //}
587.245 - //public void testObjMethodCompletion7() throws Exception {
587.246 - // checkCompletion("testfiles/compl2.py", "print os.^", true);
587.247 - //}
587.248 - //public void testObjMethodCompletion8() throws Exception {
587.249 - // checkCompletion("testfiles/compl3.py", "server=SocketServer.^TCPServer", true);
587.250 - //}
587.251 - //public void testLocals4() throws Exception {
587.252 - // checkCompletion("testfiles/occurrences2.py", "print ^toplevelvar2", true);
587.253 - //}
587.254 - //public void testLocals5() throws Exception {
587.255 - // checkCompletion("testfiles/occurrences2.py", "x = ^myfunc", true);
587.256 - //}
587.257 - //public void testDoc4() throws Exception {
587.258 - // try {
587.259 - // skipJython = true;
587.260 - // checkCompletionDocumentation("testfiles/SocketServer.py", "def serve_fore^ver(self):", true, "serve_forever");
587.261 - // } finally {
587.262 - // skipJython = false;
587.263 - // }
587.264 - //}
587.265 - //public void testObjMethodCompletion1() throws Exception {
587.266 - // checkCompletion("testfiles/compl.py", "^self.my", true);
587.267 - //}
587.268 - //public void testImports3() throws Exception {
587.269 - // checkCompletion("testfiles/imports3.py", "import ^", true);
587.270 - //}
587.271 - //public void testImports4() throws Exception {
587.272 - // checkCompletion("testfiles/imports4.py", "import ^", true);
587.273 - //}
587.274 - //public void testImports5() throws Exception {
587.275 - // checkCompletion("testfiles/imports5.py", "import i^", true);
587.276 - //}
587.277 - //public void testImports6() throws Exception {
587.278 - // checkCompletion("testfiles/imports6.py", "from ^i", true);
587.279 - //}
587.280 - //public void testImports6b() throws Exception {
587.281 - // checkCompletion("testfiles/imports6.py", "from i^", true);
587.282 - //}
587.283 - //public void testKeywords() throws Exception {
587.284 - // checkCompletion("testfiles/empty.py", "^print", true);
587.285 - //}
587.286 - //public void testLocals2() throws Exception {
587.287 - // checkCompletion("testfiles/datetime.py", "^dnum = _days_before_month(y, m) + d", true);
587.288 - //}
587.289 - //public void testClasses() throws Exception {
587.290 - // checkCompletion("testfiles/ConfigParser.py", "^self.section = section", true);
587.291 - //}
587.292 - //public void testImports1() throws Exception {
587.293 - // checkCompletion("testfiles/ConfigParser.py", "import ^re", true);
587.294 - //}
587.295 -}
588.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonDeclarationFinderTest.java Sun Jan 04 13:11:53 2015 -0600
588.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
588.3 @@ -1,281 +0,0 @@
588.4 -/*
588.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
588.6 - *
588.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
588.8 - *
588.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
588.10 - * Other names may be trademarks of their respective owners.
588.11 - *
588.12 - * The contents of this file are subject to the terms of either the GNU
588.13 - * General Public License Version 2 only ("GPL") or the Common
588.14 - * Development and Distribution License("CDDL") (collectively, the
588.15 - * "License"). You may not use this file except in compliance with the
588.16 - * License. You can obtain a copy of the License at
588.17 - * http://www.netbeans.org/cddl-gplv2.html
588.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
588.19 - * specific language governing permissions and limitations under the
588.20 - * License. When distributing the software, include this License Header
588.21 - * Notice in each file and include the License file at
588.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
588.23 - * particular file as subject to the "Classpath" exception as provided
588.24 - * by Oracle in the GPL Version 2 section of the License file that
588.25 - * accompanied this code. If applicable, add the following below the
588.26 - * License Header, with the fields enclosed by brackets [] replaced by
588.27 - * your own identifying information:
588.28 - * "Portions Copyrighted [year] [name of copyright owner]"
588.29 - *
588.30 - * If you wish your version of this file to be governed by only the CDDL
588.31 - * or only the GPL Version 2, indicate your decision by adding
588.32 - * "[Contributor] elects to include this software in this distribution
588.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
588.34 - * single choice of license, a recipient has the option to distribute
588.35 - * your version of this file under either the CDDL, the GPL Version 2 or
588.36 - * to extend the choice of license to its licensees as provided above.
588.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
588.38 - * Version 2 license, then the option applies only if the new code is
588.39 - * made subject to such option by the copyright holder.
588.40 - *
588.41 - * Contributor(s):
588.42 - *
588.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
588.44 - */
588.45 -package org.netbeans.modules.python.editor;
588.46 -
588.47 -import java.net.URL;
588.48 -import java.util.Collections;
588.49 -import java.util.Comparator;
588.50 -import java.util.List;
588.51 -import javax.swing.text.BadLocationException;
588.52 -import org.netbeans.editor.BaseDocument;
588.53 -import org.netbeans.modules.gsf.GsfHtmlFormatter;
588.54 -import org.netbeans.modules.gsf.api.CompilationInfo;
588.55 -import org.netbeans.modules.gsf.api.DeclarationFinder.AlternativeLocation;
588.56 -import org.netbeans.modules.gsf.api.DeclarationFinder.DeclarationLocation;
588.57 -import org.netbeans.modules.gsf.api.ElementKind;
588.58 -import org.netbeans.modules.gsf.api.HtmlFormatter;
588.59 -import org.netbeans.modules.gsf.spi.GsfUtilities;
588.60 -import org.openide.filesystems.FileObject;
588.61 -
588.62 -/**
588.63 - *
588.64 - * @author Tor Norbye
588.65 - */
588.66 -public class PythonDeclarationFinderTest extends PythonTestBase {
588.67 -
588.68 - public PythonDeclarationFinderTest(String testName) {
588.69 - super(testName);
588.70 - }
588.71 -
588.72 - private boolean skipJython = true;
588.73 -
588.74 - @Override
588.75 - protected List<URL> getExtraCpUrls() {
588.76 - // I'm overriding various Jython classes here for tests which causes
588.77 - // confusion when it's trying to locate classes and finds it in multiple places
588.78 - if (!skipJython) {
588.79 - return super.getExtraCpUrls();
588.80 - }
588.81 -
588.82 - return null;
588.83 - }
588.84 -
588.85 - // Not yet provided by GSF so manual testing here
588.86 - protected void checkOverrides(String relFilePath, String caretLine) throws Exception {
588.87 -
588.88 - CompilationInfo info = getInfo(relFilePath);
588.89 -
588.90 - String text = info.getText();
588.91 -
588.92 - int caretDelta = caretLine.indexOf('^');
588.93 - assertTrue(caretDelta != -1);
588.94 - caretLine = caretLine.substring(0, caretDelta) + caretLine.substring(caretDelta + 1);
588.95 - int lineOffset = text.indexOf(caretLine);
588.96 - assertTrue(lineOffset != -1);
588.97 - int caretOffset = lineOffset + caretDelta;
588.98 -
588.99 - PythonDeclarationFinder finder = new PythonDeclarationFinder();
588.100 - DeclarationLocation location = finder.getSuperImplementations(info, caretOffset);
588.101 - String annotate = annotateFullDeclarationLocation(location);
588.102 - assertDescriptionMatches(relFilePath, annotate, true, ".declarations");
588.103 - }
588.104 -
588.105 - private String annotateFileLocation(DeclarationLocation location) throws BadLocationException {
588.106 - StringBuilder sb = new StringBuilder();
588.107 - FileObject fo = location.getFileObject();
588.108 - sb.append(fo.getNameExt());
588.109 - sb.append(":");
588.110 - int offset = location.getOffset();
588.111 - sb.append(offset);
588.112 - sb.append(":");
588.113 - BaseDocument document = GsfUtilities.getDocument(fo, true);
588.114 - if (document != null) {
588.115 - String text = document.getText(0, document.getLength());
588.116 - sb.append(getSourceWindow(text, offset));
588.117 - }
588.118 - sb.append("\n");
588.119 - return sb.toString();
588.120 - }
588.121 -
588.122 - private String annotateFullDeclarationLocation(DeclarationLocation location) throws BadLocationException {
588.123 - StringBuilder sb = new StringBuilder();
588.124 -
588.125 - if (location == DeclarationLocation.NONE) {
588.126 - sb.append("NONE\n");
588.127 - } else {
588.128 - if (location.getInvalidMessage() != null) {
588.129 - sb.append(location.getInvalidMessage());
588.130 - sb.append("\n");
588.131 - }
588.132 - if (location.getUrl() != null) {
588.133 - sb.append("URL: " + location.getUrl());
588.134 - sb.append("\n");
588.135 - } else {
588.136 - sb.append(annotateFileLocation(location));
588.137 - sb.append("\n\n");
588.138 - sb.append("Alternative Locations:\n");
588.139 - if (location.getAlternativeLocations() != null) {
588.140 - List<AlternativeLocation> locations = location.getAlternativeLocations();
588.141 - Collections.sort(locations, new Comparator<AlternativeLocation>() {
588.142 -
588.143 - public int compare(AlternativeLocation l1, AlternativeLocation l2) {
588.144 - String d1 = l1.getDisplayHtml(new PlainHtmlFormatter());
588.145 - String d2 = l1.getDisplayHtml(new PlainHtmlFormatter());
588.146 - int ret = d1.compareTo(d2);
588.147 - if (ret != 0) {
588.148 - return ret;
588.149 - }
588.150 - DeclarationLocation loc1 = l1.getLocation();
588.151 - DeclarationLocation loc2 = l2.getLocation();
588.152 - return loc1.toString().compareTo(loc2.toString());
588.153 - }
588.154 -
588.155 - });
588.156 - for (AlternativeLocation alt : locations) {
588.157 - sb.append(alt.getDisplayHtml(new PlainHtmlFormatter()));
588.158 - sb.append("\n");
588.159 - DeclarationLocation loc = alt.getLocation();
588.160 - sb.append(annotateFileLocation(loc));
588.161 - sb.append("\n\n");
588.162 - }
588.163 - }
588.164 - }
588.165 - }
588.166 -
588.167 - return sb.toString();
588.168 - }
588.169 -
588.170 - private class PlainHtmlFormatter extends HtmlFormatter {
588.171 - private StringBuilder sb = new StringBuilder();
588.172 -
588.173 - @Override
588.174 - public void reset() {
588.175 - sb.setLength(0);
588.176 - }
588.177 -
588.178 - @Override
588.179 - public void appendHtml(String html) {
588.180 - sb.append(html);
588.181 - }
588.182 -
588.183 - @Override
588.184 - public void appendText(String text, int fromInclusive, int toExclusive) {
588.185 - sb.append(text, fromInclusive, toExclusive);
588.186 - }
588.187 -
588.188 - @Override
588.189 - public void name(ElementKind kind, boolean start) {
588.190 - }
588.191 -
588.192 - @Override
588.193 - public void active(boolean start) {
588.194 - }
588.195 -
588.196 - @Override
588.197 - public void parameters(boolean start) {
588.198 - }
588.199 -
588.200 - @Override
588.201 - public void type(boolean start) {
588.202 - }
588.203 -
588.204 - @Override
588.205 - public void deprecated(boolean start) {
588.206 - }
588.207 -
588.208 - @Override
588.209 - public String getText() {
588.210 - return sb.toString();
588.211 - }
588.212 -
588.213 - @Override
588.214 - public void emphasis(boolean start) {
588.215 - }
588.216 - }
588.217 -
588.218 - public void testDeclaration1() throws Exception {
588.219 - checkDeclaration("testfiles/ConfigParser.py", "% (line^no, line)", "def append(self, ^lineno, line)");
588.220 - }
588.221 -
588.222 - public void testDeclaration2() throws Exception {
588.223 - checkDeclaration("testfiles/rawstringdoc.py", "import rawstr^ingdoc", "rawstringdoc.py", 0);
588.224 - }
588.225 -
588.226 - public void testDeclaration3() throws Exception {
588.227 - checkDeclaration("testfiles/ConfigParser.py", "raise Interpola^tionSyntaxError(option, section,", "class ^InterpolationSyntaxError(InterpolationError):");
588.228 - }
588.229 -
588.230 - public void testDeclaration4() throws Exception {
588.231 - checkDeclaration("testfiles/ConfigParser.py", "opt = self.optio^nxform(option)", "def ^optionxform(self, optionstr):");
588.232 - }
588.233 -
588.234 - public void testDeclaration5() throws Exception {
588.235 - checkDeclaration("testfiles/gotolocal.py", "print na^me;", "def ggg(^name)");
588.236 - }
588.237 -
588.238 - public void testDeclaration6() throws Exception {
588.239 - checkDeclaration("testfiles/datetime.py", "http://we^bexhibits.org/daylightsaving/", new URL("http://webexhibits.org/daylightsaving/"));
588.240 - }
588.241 -
588.242 - public void testDeclaration7() throws Exception {
588.243 - checkDeclaration("testfiles/datetime.py", "converter = _ti^me.localtime", "^import time as _time");
588.244 - }
588.245 -
588.246 - public void testDeclaration8() throws Exception {
588.247 - checkOverrides("testfiles/overrides.py", "def ov^erridden_method1(self, a, b): # Final");
588.248 - }
588.249 -
588.250 - public void testDeclaration9() throws Exception {
588.251 - checkOverrides("testfiles/overrides.py", "ov^erridden_method2(self, c, d): # Final");
588.252 - }
588.253 -
588.254 -// Not yet working
588.255 -// public void testDeclaration8() throws Exception {
588.256 -// checkDeclaration("testfiles/datetime.py", "_time.loc^altime", "time.rst", 0);
588.257 -// }
588.258 -
588.259 -// public void testDeclaration9() throws Exception {
588.260 -// // Broken because of Jython ast offset bug -- see PythonAstOffsetsTest.testAttributes
588.261 -// checkDeclaration("testfiles/datetime.py", "dayfrac, days = _ma^th.modf(days)", "^import math as _math");
588.262 -// }
588.263 -
588.264 -
588.265 -// Works for me but not on the build machine
588.266 -// public void testDeclaration10() throws Exception {
588.267 -// DeclarationLocation location = findDeclaration("testfiles/datetime.py", "assert ab^s(daysecondsfrac) <= 1.0");
588.268 -// assertNotNull(location);
588.269 -// assertTrue(location != DeclarationLocation.NONE);
588.270 -//
588.271 -// String message = NbBundle.getMessage(PythonDeclarationFinder.class, "BuiltinPython", "abs");
588.272 -// assertEquals(message, location.getInvalidMessage());
588.273 -// }
588.274 -
588.275 -// For some reason, the fnmatch module isn't found from the test infrastructure
588.276 -// public void testDeclaration11() throws Exception {
588.277 -// checkDeclaration("testfiles/declarations.py", "fnmatchca^se", "fnmatch.py", 0);
588.278 -// }
588.279 -
588.280 -// No such package found in the index, make custom test file
588.281 -// public void testDeclaration12() throws Exception {
588.282 -// checkDeclaration("testfiles/minicompat.py", "import xml.d^om", "xml.py", 0);
588.283 -// }
588.284 -}
589.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonFormatterTest.java Sun Jan 04 13:11:53 2015 -0600
589.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
589.3 @@ -1,145 +0,0 @@
589.4 -/*
589.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
589.6 - *
589.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
589.8 - *
589.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
589.10 - * Other names may be trademarks of their respective owners.
589.11 - *
589.12 - * The contents of this file are subject to the terms of either the GNU
589.13 - * General Public License Version 2 only ("GPL") or the Common
589.14 - * Development and Distribution License("CDDL") (collectively, the
589.15 - * "License"). You may not use this file except in compliance with the
589.16 - * License. You can obtain a copy of the License at
589.17 - * http://www.netbeans.org/cddl-gplv2.html
589.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
589.19 - * specific language governing permissions and limitations under the
589.20 - * License. When distributing the software, include this License Header
589.21 - * Notice in each file and include the License file at
589.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
589.23 - * particular file as subject to the "Classpath" exception as provided
589.24 - * by Oracle in the GPL Version 2 section of the License file that
589.25 - * accompanied this code. If applicable, add the following below the
589.26 - * License Header, with the fields enclosed by brackets [] replaced by
589.27 - * your own identifying information:
589.28 - * "Portions Copyrighted [year] [name of copyright owner]"
589.29 - *
589.30 - * If you wish your version of this file to be governed by only the CDDL
589.31 - * or only the GPL Version 2, indicate your decision by adding
589.32 - * "[Contributor] elects to include this software in this distribution
589.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
589.34 - * single choice of license, a recipient has the option to distribute
589.35 - * your version of this file under either the CDDL, the GPL Version 2 or
589.36 - * to extend the choice of license to its licensees as provided above.
589.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
589.38 - * Version 2 license, then the option applies only if the new code is
589.39 - * made subject to such option by the copyright holder.
589.40 - *
589.41 - * Contributor(s):
589.42 - *
589.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
589.44 - */
589.45 -
589.46 -package org.netbeans.modules.python.editor;
589.47 -
589.48 -/**
589.49 - *
589.50 - * @author Tor Norbye
589.51 - */
589.52 -public class PythonFormatterTest extends PythonTestBase {
589.53 -
589.54 - public PythonFormatterTest(String testName) {
589.55 - super(testName);
589.56 - }
589.57 -
589.58 - public void testFormatFile1() throws Exception {
589.59 - reformatFileContents("testfiles/ConfigParser.py", new IndentPrefs(4,4));
589.60 - }
589.61 -
589.62 - public void testFormatFile2() throws Exception {
589.63 - reformatFileContents("testfiles/imports/organize1.py", new IndentPrefs(4,4));
589.64 - }
589.65 -
589.66 - public void testFormatFile3() throws Exception {
589.67 - reformatFileContents("testfiles/datetime.py", new IndentPrefs(4,4));
589.68 - }
589.69 -
589.70 - public void testFormatFile4() throws Exception {
589.71 - reformatFileContents("testfiles/formatting.py", new IndentPrefs(4,4));
589.72 - }
589.73 -
589.74 - public void testFormatFile5() throws Exception {
589.75 - reformatFileContents("testfiles/hanging_indent.py", new IndentPrefs(2,2));
589.76 - }
589.77 -
589.78 - public void testFormatFile6() throws Exception {
589.79 - reformatFileContents("testfiles/hanging_indent2.py", new IndentPrefs(2,2));
589.80 - }
589.81 -
589.82 - public void testStarArg() throws Exception {
589.83 - reformatFileContents("testfiles/star_arg.py", new IndentPrefs(4,4));
589.84 - }
589.85 -
589.86 - public void testSimple1() throws Exception {
589.87 - format("if true\n foo\nelse\n bar\n",
589.88 - "if true\n foo\nelse\n bar\n", null);
589.89 - }
589.90 -
589.91 - public void testSimple2() throws Exception {
589.92 - format(" if true\n foo\n else\n bar\n",
589.93 - " if true\n foo\n else\n bar\n", null);
589.94 - }
589.95 -
589.96 - public void testSimple3() throws Exception {
589.97 - format("if true\n foo\nelse\n bar\n",
589.98 - "if true\n foo\nelse\n bar\n", null);
589.99 - }
589.100 -
589.101 - public void testSimple4() throws Exception {
589.102 - format("if true\n %<%foo\nelse\n bar\n%>%",
589.103 - "if true\n foo\nelse\n bar\n", null);
589.104 - }
589.105 -
589.106 - public void testSimple5() throws Exception {
589.107 - format("if \"%\" in v:\n self._interpolate_some(option, accum, v,\n section, map, depth + 1)\nelse:\n accum.append(v)\n",
589.108 - "if \"%\" in v:\n self._interpolate_some(option, accum, v,\n section, map, depth + 1)\nelse:\n accum.append(v)\n",
589.109 - null);
589.110 - }
589.111 -
589.112 - public void testSimple6() throws Exception {
589.113 - format("class Foo\n def bar\n baz\nclass Bar\n",
589.114 - "class Foo\n def bar\n baz\nclass Bar\n", null);
589.115 - }
589.116 -
589.117 - public void testInconsistent() throws Exception {
589.118 - format("if true\n bar\n if false\n hello\nif false\n baz",
589.119 - "if true\n bar\n if false\n hello\nif false\n baz",
589.120 - null);
589.121 - }
589.122 -
589.123 - public void testInconsistent2() throws Exception {
589.124 - format("if true\n bar\n %<%if false\n hello\nif false\n baz%>%",
589.125 - "if true\n bar\n if false\n hello\nif false\n baz",
589.126 - null);
589.127 - }
589.128 -
589.129 - public void testSimple7() throws Exception {
589.130 - format("if true\n if bar\n baz\nhello",
589.131 - "if true\n if bar\n baz\nhello", null);
589.132 - }
589.133 -
589.134 - public void testSimple8() throws Exception {
589.135 - format(
589.136 - "'''This is my string\n which\n should\n not be changed'''",
589.137 - "'''This is my string\n which\n should\n not be changed'''", null);
589.138 - }
589.139 -
589.140 - public void testSimple9() throws Exception {
589.141 - format(
589.142 - "'''This is my string\n which\n should\n not be changed'''\nhello\nworld\n",
589.143 - "'''This is my string\n which\n should\n not be changed'''\nhello\nworld\n", null);
589.144 - }
589.145 -
589.146 - // Test: Try removing all WHITESPACE in the document (except for line prefixes) and then reformat and compare with master!
589.147 - // Also try doubling all space!
589.148 -}
590.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonIndexTest.java Sun Jan 04 13:11:53 2015 -0600
590.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
590.3 @@ -1,69 +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;
590.47 -
590.48 -import org.openide.filesystems.FileObject;
590.49 -
590.50 -/**
590.51 - *
590.52 - * @author Tor Norbye
590.53 - */
590.54 -public class PythonIndexTest extends PythonTestBase {
590.55 -
590.56 - public PythonIndexTest(String name) {
590.57 - super(name);
590.58 - }
590.59 -
590.60 - // Unstable
590.61 -// public void testGetFileObject1() throws Exception {
590.62 -// FileObject fo = PythonIndex.getFileObject("python:Lib/zipfile.py");
590.63 -// assertNotNull(fo);
590.64 -// assertEquals("zipfile.py", fo.getNameExt());
590.65 -// }
590.66 -
590.67 - public void testGetFileObject2() throws Exception {
590.68 - FileObject fo = PythonIndex.getFileObject("cluster:pythonstubs/pythonstubs-2_6_1.egg");
590.69 - assertNotNull(fo);
590.70 - assertEquals("pythonstubs-2_6_1.egg", fo.getNameExt());
590.71 - }
590.72 -}
591.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonIndexerTest.java Sun Jan 04 13:11:53 2015 -0600
591.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
591.3 @@ -1,190 +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 -
591.9 -package org.netbeans.modules.python.editor;
591.10 -
591.11 -import org.netbeans.modules.python.editor.elements.IndexedElement;
591.12 -
591.13 -/**
591.14 - *
591.15 - * @author Tor Norbye
591.16 - */
591.17 -public class PythonIndexerTest extends PythonTestBase {
591.18 -
591.19 - public PythonIndexerTest(String testName) {
591.20 - super(testName);
591.21 - }
591.22 -
591.23 - @Override
591.24 - public String prettyPrintValue(String key, String value) {
591.25 - if (value == null) {
591.26 - return value;
591.27 - }
591.28 - int index = -1;
591.29 - if (PythonIndexer.FIELD_MEMBER.equals(key) ||PythonIndexer.FIELD_ITEM.equals(key)) {
591.30 - index = IndexedElement.FLAG_INDEX;
591.31 - } else if (PythonIndexer.FIELD_CLASS_ATTR_NAME.equals(key)) {
591.32 - index = 0;
591.33 - value = ";" + value + ";";
591.34 - }
591.35 - if (index != -1) {
591.36 - // Decode the attributes
591.37 - int attributeIndex = 0;
591.38 - for (int i = 0; i < index; i++) {
591.39 - attributeIndex = value.indexOf(';', attributeIndex+1);
591.40 - }
591.41 - int flags = IndexedElement.decode(value, attributeIndex+1, 0);
591.42 - String desc = IndexedElement.decodeFlags(flags);
591.43 - value = value.substring(0, attributeIndex) + ";" + desc + value.substring(value.indexOf(';', attributeIndex+1));
591.44 - }
591.45 -
591.46 - return value;
591.47 - }
591.48 -
591.49 -
591.50 - public void testIsIndexable1() throws Exception {
591.51 - checkIsIndexable("testfiles/javascript.js", false);
591.52 - }
591.53 -
591.54 - public void testIsIndexable2() throws Exception {
591.55 - checkIsIndexable("testfiles/compiled.pyc", false);
591.56 - }
591.57 -
591.58 - public void testIsIndexable3() throws Exception {
591.59 - checkIsIndexable("testfiles/ConfigParser.py", true);
591.60 - }
591.61 -
591.62 - public void testIsIndexable4() throws Exception {
591.63 - checkIsIndexable("testfiles/datetime.py", true);
591.64 - }
591.65 -
591.66 - public void testIsIndexable5() throws Exception {
591.67 - checkIsIndexable("testfiles/antlr_python_runtime-3.1.1-py2.5.egg", true);
591.68 - }
591.69 -
591.70 - public void testIndex1() throws Exception {
591.71 - checkIndexer("testfiles/ConfigParser.py");
591.72 - }
591.73 -
591.74 - public void testIndex2() throws Exception {
591.75 - checkIndexer("testfiles/datetime.py");
591.76 - }
591.77 -
591.78 - public void testIndex3() throws Exception {
591.79 - checkIndexer("testfiles/doc.py");
591.80 - }
591.81 -
591.82 - public void testIndex4() throws Exception {
591.83 - checkIndexer("testfiles/md5.py");
591.84 - }
591.85 -
591.86 - public void testIndex5() throws Exception {
591.87 - checkIndexer("testfiles/scope.py");
591.88 - }
591.89 -
591.90 - public void testIndex6() throws Exception {
591.91 - checkIndexer("testfiles/httplib.py");
591.92 - }
591.93 -
591.94 - public void testIndex7() throws Exception {
591.95 - checkIndexer("testfiles/minicompat.py");
591.96 - }
591.97 -
591.98 - public void testIndex8() throws Exception {
591.99 - checkIndexer("testfiles/socket.py");
591.100 - }
591.101 -
591.102 - public void testIndex9() throws Exception {
591.103 - checkIndexer("testfiles/jreload.py");
591.104 - }
591.105 -
591.106 - public void testIndex10() throws Exception {
591.107 - checkIndexer("testfiles/doctest.py");
591.108 - }
591.109 -
591.110 - public void testIndex11() throws Exception {
591.111 - checkIndexer("testfiles/zipfile.py");
591.112 - }
591.113 -
591.114 - public void testIndex12() throws Exception {
591.115 - checkIndexer("testfiles/os.py");
591.116 - }
591.117 -
591.118 - public void testIndex13() throws Exception {
591.119 - checkIndexer("testfiles/unittest.py");
591.120 - }
591.121 -
591.122 - public void testIndex14() throws Exception {
591.123 - checkIndexer("testfiles/properties.py");
591.124 - }
591.125 -
591.126 - public void testIndex15() throws Exception {
591.127 - checkIndexer("testfiles/tarfile.py");
591.128 - }
591.129 -
591.130 - public void testIndex16() throws Exception {
591.131 - checkIndexer("testfiles/rst/pickle.rst");
591.132 - }
591.133 -
591.134 - public void testRstIndex1() throws Exception {
591.135 - checkIndexer("testfiles/rst/zipfile.rst");
591.136 - }
591.137 -
591.138 - public void testRstIndex2() throws Exception {
591.139 - checkIndexer("testfiles/rst/stdtypes.rst");
591.140 - }
591.141 -
591.142 - public void testRstIndex3() throws Exception {
591.143 - checkIndexer("testfiles/rst/platform.rst");
591.144 - }
591.145 -
591.146 - public void testRstIndex4() throws Exception {
591.147 - checkIndexer("testfiles/rst/smtpd.rst");
591.148 - }
591.149 -
591.150 - public void testRstIndex5() throws Exception {
591.151 - checkIndexer("testfiles/rst/exceptions.rst");
591.152 - }
591.153 -
591.154 - public void testRstIndex6() throws Exception {
591.155 - checkIndexer("testfiles/rst/logging.rst");
591.156 - }
591.157 -
591.158 - public void testRstIndex7() throws Exception {
591.159 - checkIndexer("testfiles/rst/string.rst");
591.160 - }
591.161 -
591.162 - public void testRstIndex8() throws Exception {
591.163 - checkIndexer("testfiles/rst/bz2.rst");
591.164 - }
591.165 -
591.166 - public void testRstIndex9() throws Exception {
591.167 - checkIndexer("testfiles/rst/constants.rst");
591.168 - }
591.169 -
591.170 - public void testRstIndex10() throws Exception {
591.171 - checkIndexer("testfiles/rst/operator.rst");
591.172 - }
591.173 -
591.174 - public void testRstIndex11() throws Exception {
591.175 - checkIndexer("testfiles/rst/collections.rst");
591.176 - }
591.177 -
591.178 - public void testRstIndex12() throws Exception {
591.179 - checkIndexer("testfiles/rst/ctypes.rst");
591.180 - }
591.181 -
591.182 - public void testRstIndex13() throws Exception {
591.183 - checkIndexer("testfiles/rst/stub_missing.rst");
591.184 - }
591.185 -
591.186 - public void testIndexEgg() throws Exception {
591.187 - checkIndexer("testfiles/antlr_python_runtime-3.1.1-py2.5.egg");
591.188 - }
591.189 -
591.190 -// public void testIndexEgg2() throws Exception {
591.191 -// checkIndexer("testfiles/pythonstubs-2_6_1.egg");
591.192 -// }
591.193 -}
592.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonInstantRenameTest.java Sun Jan 04 13:11:53 2015 -0600
592.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
592.3 @@ -1,62 +0,0 @@
592.4 -/*
592.5 - * To change this template, choose Tools | Templates
592.6 - * and open the template in the editor.
592.7 - */
592.8 -
592.9 -package org.netbeans.modules.python.editor;
592.10 -
592.11 -/**
592.12 - *
592.13 - * @author Tor Norbye
592.14 - */
592.15 -public class PythonInstantRenameTest extends PythonTestBase {
592.16 -
592.17 - public PythonInstantRenameTest(String testName) {
592.18 - super(testName);
592.19 - }
592.20 -
592.21 - public void testRename1() throws Exception {
592.22 - String caretLine = "def __init__(self, m^sg=''):";
592.23 - checkRenameSections("testfiles/ConfigParser.py", caretLine);
592.24 - }
592.25 -
592.26 - public void testRename2() throws Exception {
592.27 - String caretLine = "for (ke^y, value) in self._sections[section].items():";
592.28 - checkRenameSections("testfiles/ConfigParser.py", caretLine);
592.29 - }
592.30 -
592.31 - public void testRename3() throws Exception {
592.32 - String caretLine = "raise Interpola^tionSyntaxError(option, section,";
592.33 - checkRenameSections("testfiles/ConfigParser.py", caretLine);
592.34 - }
592.35 -
592.36 - public void testRename4() throws Exception {
592.37 - String caretLine = "print toplevelv^ar4";
592.38 - checkRenameSections("testfiles/occurrences2.py", caretLine);
592.39 - }
592.40 -
592.41 - public void testRename5() throws Exception {
592.42 - String caretLine = "x = myf^unc";
592.43 - checkRenameSections("testfiles/occurrences2.py", caretLine);
592.44 - }
592.45 -
592.46 - public void testRename6() throws Exception {
592.47 - String caretLine = "print toplevel^var2";
592.48 - checkRenameSections("testfiles/occurrences2.py", caretLine);
592.49 - }
592.50 -
592.51 - public void testRename7() throws Exception {
592.52 - String caretLine = "# @type ^xy str";
592.53 - checkRenameSections("testfiles/typevars.py", caretLine);
592.54 - }
592.55 -
592.56 - public void testRename8() throws Exception {
592.57 - String caretLine = "x^y.s1";
592.58 - checkRenameSections("testfiles/typevars.py", caretLine);
592.59 - }
592.60 -
592.61 - public void testRename9() throws Exception {
592.62 - String caretLine = "print self.not^okay";
592.63 - checkRenameSections("testfiles/attributes.py", caretLine);
592.64 - }
592.65 -}
593.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonKeystrokeHandlerTest.java Sun Jan 04 13:11:53 2015 -0600
593.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
593.3 @@ -1,699 +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;
593.10 -
593.11 -import javax.swing.text.BadLocationException;
593.12 -import org.netbeans.modules.gsf.api.Formatter;
593.13 -
593.14 -/**
593.15 - *
593.16 - * @author Tor Norbye
593.17 - */
593.18 -public class PythonKeystrokeHandlerTest extends PythonTestBase {
593.19 - static {
593.20 - System.setProperty("python.fromimport", "true");
593.21 - }
593.22 -
593.23 - public PythonKeystrokeHandlerTest(String testName) {
593.24 - super(testName);
593.25 - }
593.26 -
593.27 - private void match(String original) throws BadLocationException {
593.28 - super.assertMatches(original);
593.29 - }
593.30 -
593.31 - private void insertChar(String original, char insertText, String expected) throws Exception {
593.32 - insertChar(original, insertText, expected, null);
593.33 - }
593.34 -
593.35 - private void insertChar(String original, char insertText, String expected, String selection) throws Exception {
593.36 - insertChar(original, insertText, expected, selection, false);
593.37 - }
593.38 -
593.39 - @Override
593.40 - public void deleteWord(String original, String expected) throws Exception {
593.41 - // Try deleting the word not just using the testcase but also surrounded by strings
593.42 - // to make sure there's no problem with lexer token directions
593.43 - super.deleteWord(original, expected);
593.44 - super.deleteWord(original+"foo", expected+"foo");
593.45 - super.deleteWord("foo"+original, "foo"+expected);
593.46 - super.deleteWord(original+"::", expected+"::");
593.47 - super.deleteWord(original+"::", expected+"::");
593.48 - }
593.49 -
593.50 - @Override
593.51 - protected Formatter getFormatter(IndentPrefs preferences) {
593.52 - //return new PythonFormatter();
593.53 - return null;
593.54 - }
593.55 -
593.56 - public void testReturn() throws Exception {
593.57 - insertBreak(" def foo():\n return^", " def foo():\n return\n ^");
593.58 - }
593.59 -
593.60 - public void testReturn2() throws Exception {
593.61 - insertBreak(" def foo():\n return^\n", " def foo():\n return\n ^\n");
593.62 - }
593.63 -
593.64 - public void testReturn3() throws Exception {
593.65 - insertBreak(" def foo():\n return true^\n", " def foo():\n return true\n ^\n");
593.66 - }
593.67 -
593.68 - public void testRaise1() throws Exception {
593.69 - insertBreak(" def foo():\n raise RuntimeError^\n", " def foo():\n raise RuntimeError\n ^\n");
593.70 - }
593.71 -
593.72 - public void testDefParenSkip1() throws Exception {
593.73 - insertBreak("def foo(^):\n", "def foo():\n ^\n");
593.74 - }
593.75 -
593.76 - public void testDefParenSkip2() throws Exception {
593.77 - insertBreak("class Foo(^):\n", "class Foo():\n ^\n");
593.78 - }
593.79 -
593.80 - public void testDefParenSkip3() throws Exception {
593.81 - insertBreak("def foo(self^):\n", "def foo(self):\n ^\n");
593.82 - }
593.83 -
593.84 - public void testDefParenSkip4() throws Exception {
593.85 - insertBreak("def foo(self,^):\n", "def foo(self,\n^):\n");
593.86 - }
593.87 -
593.88 - public void testDefParenSkip5() throws Exception {
593.89 - insertBreak("def foo(self^):", "def foo(self):\n ^");
593.90 - }
593.91 -
593.92 - public void testContinued() throws Exception {
593.93 - insertBreak(" def foo():\n raise RuntimeError \\^\n", " def foo():\n raise RuntimeError \\\n ^\n");
593.94 - }
593.95 -
593.96 - public void testContinued2() throws Exception {
593.97 - insertBreak("foo\\^", "foo\\\n ^");
593.98 - }
593.99 -
593.100 - public void testContinued3() throws Exception {
593.101 - insertBreak("foo\\^\n", "foo\\\n ^\n");
593.102 - }
593.103 -
593.104 - public void testNotContinued1() throws Exception {
593.105 - insertBreak("fo^o\\\n", "fo\n^o\\\n");
593.106 - }
593.107 -
593.108 - public void testPassDedent() throws Exception {
593.109 - insertBreak(" if (true):\n pass^\n", " if (true):\n pass\n ^\n");
593.110 - }
593.111 -
593.112 - public void testPassDedent2() throws Exception {
593.113 - insertBreak(" if (true):\n pass^", " if (true):\n pass\n ^");
593.114 - }
593.115 -
593.116 - public void testReindentElse() throws Exception {
593.117 - insertChar(" if (true):\n pass\n else^", ':', " if (true):\n pass\n else:^");
593.118 - }
593.119 -
593.120 - public void testReindentElse2() throws Exception {
593.121 - insertChar(" if (true):\n pass\n else^\n", ':', " if (true):\n pass\n else:^\n");
593.122 - }
593.123 -
593.124 - public void testReindentElif() throws Exception {
593.125 - insertChar(" if (true):\n pass\n elif^", ':', " if (true):\n pass\n elif:^");
593.126 - }
593.127 -
593.128 - public void testReindentElif2() throws Exception {
593.129 - insertChar(" if (true):\n pass\n elif^\n", ':', " if (true):\n pass\n elif:^\n");
593.130 - }
593.131 -
593.132 - public void testReindentExcept() throws Exception {
593.133 - insertChar(" try:\n pass\n except Foo^", ':', " try:\n pass\n except Foo:^");
593.134 - }
593.135 -
593.136 - public void testReindentExcept2() throws Exception {
593.137 - insertChar(" try:\n pass\n except Foo^\n", ':', " try:\n pass\n except Foo:^\n");
593.138 - }
593.139 -
593.140 - public void testReindentExcept3() throws Exception {
593.141 - insertChar(" try:\n pass\n finally^\n", ':', " try:\n pass\n finally:^\n");
593.142 - }
593.143 -
593.144 - public void testMultilineString() throws Exception {
593.145 - insertBreak("\"\"\"^\n", "\"\"\"\n^\n\"\"\"\n");
593.146 - }
593.147 -
593.148 - public void testMultilineString2() throws Exception {
593.149 - insertBreak(" \"\"\"^\n", " \"\"\"\n ^\n \"\"\"\n");
593.150 - }
593.151 -
593.152 - public void testMultilineString3() throws Exception {
593.153 - insertBreak("\"\"\"^", "\"\"\"\n^\n\"\"\"");
593.154 - }
593.155 -
593.156 - public void testNoMultilineString() throws Exception {
593.157 - insertBreak("# \"\"\"^\n", "# \"\"\"\n^\n");
593.158 - }
593.159 -
593.160 - public void testNoMultilineString2() throws Exception {
593.161 - insertBreak("\"\"\"^\n\n\"\"\"\n", "\"\"\"\n^\n\n\"\"\"\n");
593.162 - }
593.163 -
593.164 -// Not yet implemented
593.165 -// public void testSinglineString1() throws Exception {
593.166 -// // Not yet passing - should implement this
593.167 -// insertBreak("\"\"\"foo^\n\"\"\"", "\"\"\"foo\n\"\"\"\n^");
593.168 -// }
593.169 -//
593.170 -// public void testSinglineString2() throws Exception {
593.171 -// insertBreak("\"\"\"foo^\n\"\"\"\n", "\"\"\"foo\n\"\"\"\n^\n");
593.172 -// }
593.173 -//
593.174 -// public void testSinglineString3() throws Exception {
593.175 -// insertBreak(" \"\"\"foo^\n\"\"\"\n", " \"\"\"foo\n\"\"\"\n ^\n");
593.176 -// }
593.177 -
593.178 - public void testInsertColon1() throws Exception {
593.179 - insertChar("def foo^", '(', "def foo(^):");
593.180 - }
593.181 -
593.182 - public void testInsertColon2() throws Exception {
593.183 - insertChar("def foo^\n", '(', "def foo(^):\n");
593.184 - }
593.185 -
593.186 - public void testInsertColon3() throws Exception {
593.187 - insertChar("class A\n def foo^", '(', "class A\n def foo(self^):");
593.188 - }
593.189 -
593.190 - public void testInsertColon4() throws Exception {
593.191 - insertChar("class Abc^\n", '(', "class Abc(^):\n");
593.192 - }
593.193 -
593.194 - public void testInsertColon5() throws Exception {
593.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");
593.196 - }
593.197 -
593.198 - public void testTypethroughComma1() throws Exception {
593.199 - insertChar("class Abc(^):\n", 'a', "class Abc(a^):\n");
593.200 - }
593.201 -
593.202 - public void testTypethroughComma2() throws Exception {
593.203 - insertChar("class Abc(a^):\n", ')', "class Abc(a)^:\n");
593.204 - }
593.205 -
593.206 - public void testTypethroughComma4() throws Exception {
593.207 - insertChar("class Abc(a)^:\n", ':', "class Abc(a):^\n");
593.208 - }
593.209 -
593.210 - public void testTypethroughComma5() throws Exception {
593.211 - insertChar("def foo(^):\n", ')', "def foo()^:\n");
593.212 - }
593.213 -
593.214 - public void testTypethroughComma6() throws Exception {
593.215 - insertChar("def foo()^:\n", ':', "def foo():^\n");
593.216 - }
593.217 -
593.218 - public void testNoTypethroughComma1() throws Exception {
593.219 - insertChar("ashex = _binascii.hexlify(data[:^-1])", ':', "ashex = _binascii.hexlify(data[::^-1])");
593.220 - }
593.221 -
593.222 - public void testNoTypethroughComma2() throws Exception {
593.223 - insertChar("ashex = _binascii.hexlify(data[^:-1])", ':', "ashex = _binascii.hexlify(data[:^:-1])");
593.224 - }
593.225 -
593.226 - public void testNoTypethroughComma3() throws Exception {
593.227 - insertChar("# def foo()^:\n", ':', "# def foo():^:\n");
593.228 - }
593.229 -
593.230 - public void testFromImport() throws Exception {
593.231 - insertChar("from sys^", ' ', "from sys import ^");
593.232 - }
593.233 -
593.234 - public void testFromImport2() throws Exception {
593.235 - insertChar("from sys^\n", ' ', "from sys import ^\n");
593.236 - }
593.237 -
593.238 - public void testNoFromImport() throws Exception {
593.239 - insertChar("from sys^\n", 's', "from syss^\n");
593.240 - }
593.241 -
593.242 - public void testNoFromImport2() throws Exception {
593.243 - insertChar("from sys^ import *\n", ' ', "from sys ^ import *\n");
593.244 - }
593.245 -
593.246 - public void testBreak1() throws Exception {
593.247 - insertBreak("test1:^", "test1:\n ^");
593.248 - }
593.249 -
593.250 - public void testBreak2() throws Exception {
593.251 - insertBreak("test1:^\n", "test1:\n ^\n");
593.252 - }
593.253 -
593.254 - public void testBreak3() throws Exception {
593.255 - insertBreak("test1:\n foo^", "test1:\n foo\n ^");
593.256 - }
593.257 -
593.258 - public void testTripleQuotes1() throws Exception {
593.259 - insertChar("\"\"^", '"', "\"\"\"^");
593.260 - insertChar("\"\"^\n", '"', "\"\"\"^\n");
593.261 - }
593.262 -
593.263 - public void testTripleQuotes2() throws Exception {
593.264 - insertChar("class A:\n def foo():\n \"\"^\n",
593.265 - '"',
593.266 - "class A:\n def foo():\n \"\"\"^\n");
593.267 - }
593.268 -
593.269 - public void testTripleQuotes3() throws Exception {
593.270 - insertChar("''^", '\'', "'''^");
593.271 - insertChar("''^\n", '\'', "'''^\n");
593.272 - }
593.273 -
593.274 - public void testTripleQuotes4() throws Exception {
593.275 - insertBreak(" '''^", " '''\n ^\n '''");
593.276 - }
593.277 -
593.278 - public void testTripleQuotes5() throws Exception {
593.279 - insertBreak(" '''^\n", " '''\n ^\n '''\n");
593.280 - }
593.281 -
593.282 - public void testTripleQuotes6() throws Exception {
593.283 - insertBreak(" \"\"\"^\n", " \"\"\"\n ^\n \"\"\"\n");
593.284 - }
593.285 -
593.286 - public void testTripleQuotes7() throws Exception {
593.287 - insertBreak(" '''foo^\n", " '''foo'''\n ^\n");
593.288 - }
593.289 -
593.290 - public void testTripleQuotes8() throws Exception {
593.291 - insertBreak(" '''foo^", " '''foo'''\n ^");
593.292 - }
593.293 -
593.294 - public void testTripleQuotes9() throws Exception {
593.295 - insertBreak(" '''foo^bar\n", " '''foo\n ^bar\n");
593.296 - }
593.297 -
593.298 - public void testTripleQuotes10() throws Exception {
593.299 - insertBreak(" '''foo^'''\n", " '''foo\n ^'''\n");
593.300 - }
593.301 -
593.302 - public void testTripleQuotes11() throws Exception {
593.303 - insertBreak(" '''\n foo^", " '''\n foo'''\n ^");
593.304 - }
593.305 -
593.306 - public void testTripleQuotes12() throws Exception {
593.307 - insertBreak(" '''\n foo^\n", " '''\n foo'''\n ^\n");
593.308 - }
593.309 -
593.310 - public void testTripleQuotes13() throws Exception {
593.311 - insertBreak(" r'''\n foo^\n", " r'''\n foo'''\n ^\n");
593.312 - }
593.313 -
593.314 - public void testTripleQuotes14() throws Exception {
593.315 - insertBreak(" r'''foo^'''\n", " r'''foo\n ^'''\n");
593.316 - }
593.317 -
593.318 - public void testBreak4() throws Exception {
593.319 - insertBreak("test1:\n foo^\n", "test1:\n foo\n ^\n");
593.320 - }
593.321 -
593.322 - public void testBreak5() throws Exception {
593.323 - insertBreak(" test1: ^ foo", " test1: \n ^foo");
593.324 - }
593.325 -
593.326 - public void testBreak6() throws Exception {
593.327 - insertBreak("test1: ^", "test1: \n ^");
593.328 - insertBreak("test1: ^\n", "test1: \n ^\n");
593.329 - }
593.330 -
593.331 - public void testBreak7() throws Exception {
593.332 - insertBreak(" test1: ^", " test1: \n ^");
593.333 - insertBreak(" test1: ^\n", " test1: \n ^\n");
593.334 - }
593.335 -
593.336 - public void testBak1() throws Exception {
593.337 - // Ensure that a backspace with indent 4 will delete 3 more characters to
593.338 - // outdent one level
593.339 - deleteChar(" ^", " ^");
593.340 - }
593.341 -
593.342 - public void testBak2() throws Exception {
593.343 - deleteChar(" ^test", " ^test");
593.344 - }
593.345 -
593.346 - public void testBak3() throws Exception {
593.347 - // Make sure normal deletion works
593.348 - deleteChar("foo^", "fo^");
593.349 - }
593.350 -
593.351 - public void testBak4() throws Exception {
593.352 - // Don't delete blocks when we're not in a prefix!
593.353 - deleteChar(" # type(ff) ^int", " # type(ff)^int");
593.354 - }
593.355 -
593.356 - public void testLogicalRange1() throws Exception {
593.357 - String code = "print \"He^llo World!\"\n";
593.358 - String next = "print %<%\"He^llo World!\"%>%\n";
593.359 - assertLogicalRange(code, true, next);
593.360 - assertLogicalRange(next, false, code);
593.361 - }
593.362 -
593.363 - public void testLogicalRange2() throws Exception {
593.364 - String code = "print %<%\"He^llo World!\"%>%\n";
593.365 - String next = "%<%print \"He^llo World!\"%>%\n";
593.366 - assertLogicalRange(code, true, next);
593.367 - assertLogicalRange(next, false, code);
593.368 - }
593.369 -
593.370 - public void testLogicalRange3() throws Exception {
593.371 - String code = "class A:\n def foo():\n self.filename = file^name\n";
593.372 - String next = "class A:\n def foo():\n self.filename = %<%file^name%>%\n";
593.373 - assertLogicalRange(code, true, next);
593.374 - assertLogicalRange(next, false, code);
593.375 - }
593.376 -
593.377 - public void testLogicalRange4() throws Exception {
593.378 - String code = "class A:\n def foo():\n self.filename = %<%file^name%>%\n";
593.379 - String next = "class A:\n def foo():\n %<%self.filename = file^name%>%\n";
593.380 - assertLogicalRange(code, true, next);
593.381 - assertLogicalRange(next, false, code);
593.382 - }
593.383 -
593.384 - public void testLogicalRange5() throws Exception {
593.385 - String code = "class A:\n def foo():\n %<%self.filename = file^name%>%\n";
593.386 - String next = "class A:\n %<%def foo():\n self.filename = file^name%>%\n";
593.387 - assertLogicalRange(code, true, next);
593.388 - assertLogicalRange(next, false, code);
593.389 - }
593.390 -
593.391 - public void testLogicalRange6() throws Exception {
593.392 - String code = "class A:\n %<%def foo():\n self.filename = file^name%>%\n";
593.393 - String next = "%<%class A:\n def foo():\n self.filename = file^name%>%\n";
593.394 - assertLogicalRange(code, true, next);
593.395 - assertLogicalRange(next, false, code);
593.396 - }
593.397 -
593.398 - public void testInsertX() throws Exception {
593.399 - insertChar("c^ass", 'l', "cl^ass");
593.400 - }
593.401 -
593.402 - public void testInsertX2() throws Exception {
593.403 - insertChar("clas^", 's', "class^");
593.404 - }
593.405 -
593.406 - public void testNoMatchInComments() throws Exception {
593.407 - // End
593.408 - insertChar("# Hello^", '\'', "# Hello'^");
593.409 - insertChar("# Hello^", '"', "# Hello\"^");
593.410 - insertChar("# Hello^", '[', "# Hello[^");
593.411 - insertChar("# Hello^", '(', "# Hello(^");
593.412 -
593.413 - // Middle
593.414 - insertChar("# Hello^o", '\'', "# Hello'^o");
593.415 - insertChar("# Hello^o", '"', "# Hello\"^o");
593.416 - insertChar("# Hello^o", '[', "# Hello[^o");
593.417 - insertChar("# Hello^o", '(', "# Hello(^o");
593.418 -
593.419 - // Before newline
593.420 - insertChar("# Hello^\n", '\'', "# Hello'^\n");
593.421 - insertChar("# Hello^\n", '"', "# Hello\"^\n");
593.422 - insertChar("# Hello^\n", '[', "# Hello[^\n");
593.423 - insertChar("# Hello^\n", '(', "# Hello(^\n");
593.424 - }
593.425 -
593.426 - public void testNoMatchInStrings() throws Exception {
593.427 - insertChar("x = \"^\"", '\'', "x = \"'^\"");
593.428 - insertChar("x = \"^\"", '[', "x = \"[^\"");
593.429 - insertChar("x = \"^\"", '(', "x = \"(^\"");
593.430 - insertChar("x = \"^)\"", ')', "x = \")^)\"");
593.431 - insertChar("x = '^'", '"', "x = '\"^'");
593.432 - }
593.433 -
593.434 - public void testSingleQuotes1() throws Exception {
593.435 - insertChar("x = ^", '\'', "x = '^'");
593.436 - }
593.437 -
593.438 - public void testSingleQuotes2() throws Exception {
593.439 - insertChar("x = '^'", '\'', "x = ''^");
593.440 - }
593.441 -
593.442 - public void testSingleQuotes3() throws Exception {
593.443 - insertChar("x = '^'", 'a', "x = 'a^'");
593.444 - }
593.445 -
593.446 - public void testSingleQuotes4() throws Exception {
593.447 - insertChar("x = '\\^'", '\'', "x = '\\'^'");
593.448 - }
593.449 -
593.450 - public void testInsertBrokenQuote() throws Exception {
593.451 - insertChar("System.out.prinlnt(\"pavel^)", '"',
593.452 - "System.out.prinlnt(\"pavel\"^)");
593.453 - }
593.454 -
593.455 - public void testInsertBrokenQuote2() throws Exception {
593.456 - insertChar("System.out.prinlnt(\"pavel^\n", '"',
593.457 - "System.out.prinlnt(\"pavel\"^\n");
593.458 - }
593.459 -
593.460 - public void testInsertBrokenQuote3() throws Exception {
593.461 - insertChar("System.out.prinlnt(\"^\n", '"',
593.462 - "System.out.prinlnt(\"\"^\n");
593.463 - }
593.464 -
593.465 - public void testInsertBrokenQuote4() throws Exception {
593.466 - insertChar("System.out.prinlnt(\"pavel^", '"',
593.467 - "System.out.prinlnt(\"pavel\"^");
593.468 - }
593.469 -
593.470 - public void testDoubleQuotes1() throws Exception {
593.471 - insertChar("x = ^", '"', "x = \"^\"");
593.472 - }
593.473 -
593.474 - public void testDoubleQuotes2() throws Exception {
593.475 - insertChar("x = \"^\"", '"', "x = \"\"^");
593.476 - }
593.477 -
593.478 - public void testDoubleQuotes3() throws Exception {
593.479 - insertChar("x = \"^\"", 'a', "x = \"a^\"");
593.480 - }
593.481 -
593.482 - public void testDobuleQuotes4() throws Exception {
593.483 - insertChar("x = \"\\^\"", '"', "x = \"\\\"^\"");
593.484 - }
593.485 -
593.486 -// public void testInsertBrace1() throws Exception {
593.487 -// insertBreak("foobar({^});", "foobar({\n ^\n});");
593.488 -// }
593.489 -//
593.490 -// public void testInsertBrace2() throws Exception {
593.491 -// insertBreak("foobar([^]);", "foobar([\n ^\n]);");
593.492 -// }
593.493 -//
593.494 -// public void testInsertBrace3() throws Exception {
593.495 -// insertBreak("x = {^}", "x = {\n ^\n}");
593.496 -// }
593.497 -
593.498 - public void testInsertEnd1() throws Exception {
593.499 - insertBreak("x^", "x\n^");
593.500 - }
593.501 -
593.502 -// public void testSplitStrings1() throws Exception {
593.503 -// insertBreak(" x = 'te^st'", " x = 'te\\n\\\n^st'");
593.504 -// }
593.505 -//
593.506 -// public void testSplitStrings1b() throws Exception {
593.507 -// insertBreak(" x = '^test'", " x = '\\\n^test'");
593.508 -// }
593.509 -//
593.510 -// public void testSplitStrings2() throws Exception {
593.511 -// insertBreak(" x = 'test^'", " x = 'test\\n\\\n^'");
593.512 -// }
593.513 -//
593.514 -// public void testSplitStrings3() throws Exception {
593.515 -// insertBreak(" x = \"te^st\"", " x = \"te\\n\\\n^st\"");
593.516 -// }
593.517 -//
593.518 -
593.519 - public void testBrackets1() throws Exception {
593.520 - insertChar("x = ^", '[', "x = [^]");
593.521 - }
593.522 -
593.523 - public void testBrackets2() throws Exception {
593.524 - insertChar("x = [^]", ']', "x = []^");
593.525 - }
593.526 -
593.527 - public void testBrackets3() throws Exception {
593.528 - insertChar("x = [^]", 'a', "x = [a^]");
593.529 - }
593.530 -
593.531 - public void testBrackets4() throws Exception {
593.532 - insertChar("x = [^]", '[', "x = [[^]]");
593.533 - }
593.534 -
593.535 - public void testBrackets5() throws Exception {
593.536 - insertChar("x = [[^]]", ']', "x = [[]^]");
593.537 - }
593.538 -
593.539 - public void testBrackets6() throws Exception {
593.540 - insertChar("x = [[]^]", ']', "x = [[]]^");
593.541 - }
593.542 -
593.543 - public void testParens1() throws Exception {
593.544 - insertChar("x = ^", '(', "x = (^)");
593.545 - }
593.546 -
593.547 - public void testParens2() throws Exception {
593.548 - insertChar("x = (^)", ')', "x = ()^");
593.549 - }
593.550 -
593.551 - public void testParens3() throws Exception {
593.552 - insertChar("x = (^)", 'a', "x = (a^)");
593.553 - }
593.554 -
593.555 - public void testParens4() throws Exception {
593.556 - insertChar("x = (^)", '(', "x = ((^))");
593.557 - }
593.558 -
593.559 - public void testParens5() throws Exception {
593.560 - insertChar("x = ((^))", ')', "x = (()^)");
593.561 - }
593.562 -
593.563 - public void testParens6() throws Exception {
593.564 - insertChar("x = (()^)", ')', "x = (())^");
593.565 - }
593.566 -//
593.567 -//
593.568 -// public void testFindMatching1() throws Exception {
593.569 -// match("if (true) ^{\n^}");
593.570 -// }
593.571 -//
593.572 -// public void testFindMatching2() throws Exception {
593.573 -// match("x=^(true^)\ny=5");
593.574 -// }
593.575 -//
593.576 -// public void testFindMatching3() throws Exception {
593.577 -// match("x=^(true || (false)^)\ny=5");
593.578 -// }
593.579 -//
593.580 -// public void testFindMatching4() throws Exception {
593.581 -// match("function foo() ^{\nif (true) {\n}\n^}\n}");
593.582 -// }
593.583 -//
593.584 - public void testBackspace1() throws Exception {
593.585 - deleteChar("x^", "^");
593.586 - }
593.587 -
593.588 - public void testBackspace2() throws Exception {
593.589 - deleteChar("x^y", "^y");
593.590 - }
593.591 -
593.592 - public void testBackspace3() throws Exception {
593.593 - deleteChar("xy^z", "x^z");
593.594 - }
593.595 -
593.596 - public void testBackspace4() throws Exception {
593.597 - deleteChar("xy^z", "x^z");
593.598 - }
593.599 -
593.600 - public void testBackspace5() throws Exception {
593.601 - deleteChar("x=\"^\"", "x=^");
593.602 - }
593.603 -
593.604 - public void testBackspace6() throws Exception {
593.605 - deleteChar("x='^'", "x=^");
593.606 - }
593.607 -
593.608 - public void testBackspace7() throws Exception {
593.609 - deleteChar("x=(^)", "x=^");
593.610 - }
593.611 -
593.612 - public void testBackspace7b() throws Exception {
593.613 - deleteChar("x=[^]", "x=^");
593.614 - }
593.615 -
593.616 - public void testBackspace8() throws Exception {
593.617 - // See bug 111534
593.618 - deleteChar("x={^}", "x=^");
593.619 - }
593.620 -
593.621 - public void testBackspace9() throws Exception {
593.622 - deleteChar("def foo(^):\n", "def foo^\n");
593.623 - }
593.624 -
593.625 - public void testBackspaceComment() throws Exception {
593.626 - deleteChar("# x=[^]", "# x=^]");
593.627 - }
593.628 -
593.629 - public void testReplaceSelection1() throws Exception {
593.630 - insertChar("x = foo^", 'y', "x = y^", "foo");
593.631 - }
593.632 -
593.633 - public void testReplaceSelection2() throws Exception {
593.634 - insertChar("x = foo^", '"', "x = \"foo\"^", "foo");
593.635 - }
593.636 -
593.637 - public void testReplaceSelection4() throws Exception {
593.638 - insertChar("x = 'foo^bar'", '#', "x = '#^bar'", "foo");
593.639 - }
593.640 -
593.641 - public void testReplaceSelection5() throws Exception {
593.642 - insertChar("'(^position:absolute;'", '{', "'{^position:absolute;'", "(");
593.643 - }
593.644 -
593.645 - public void testReplaceSelection6() throws Exception {
593.646 - insertChar("'position^:absolute;'", '{', "'pos{^:absolute;'", "ition");
593.647 - }
593.648 -
593.649 - public void testReplaceSelectionChangeType1() throws Exception {
593.650 - insertChar("x = \"foo\"^", '\'', "x = 'foo'^", "\"foo\"");
593.651 - }
593.652 -
593.653 - public void testReplaceSelectionChangeType2() throws Exception {
593.654 - insertChar("x = \"foo\"^", '{', "x = {foo}^", "\"foo\"");
593.655 - }
593.656 -
593.657 - public void testReplaceSelectionNotInTemplateMode1() throws Exception {
593.658 - insertChar("x = foo^", '"', "x = \"^\"", "foo", true);
593.659 - }
593.660 -
593.661 - public void testdeleteWord() throws Exception {
593.662 - deleteWord("foo_bar_baz^", "foo_bar_^");
593.663 - }
593.664 -
593.665 - public void testdeleteWord111303() throws Exception {
593.666 - deleteWord("foo::bar^", "foo::^");
593.667 - deleteWord("Foo::Bar^", "Foo::^");
593.668 - deleteWord("Foo::Bar_Baz^", "Foo::Bar_^");
593.669 - }
593.670 - public void testdeleteWordx111305() throws Exception {
593.671 - deleteWord("foo_bar^", "foo_^");
593.672 - deleteWord("x.foo_bar^.y", "x.foo_^.y");
593.673 - }
593.674 -
593.675 - public void testdeleteWord2() throws Exception {
593.676 - deleteWord("foo_bar_baz ^", "foo_bar_baz^");
593.677 - deleteWord("foo_bar_^", "foo_^");
593.678 - }
593.679 -
593.680 - public void testdeleteWord3() throws Exception {
593.681 - deleteWord("FooBarBaz^", "FooBar^");
593.682 - }
593.683 -
593.684 - public void testDeleteWord4_110998() throws Exception {
593.685 - deleteWord("Blah::Set^Foo", "Blah::^Foo");
593.686 - }
593.687 -
593.688 - public void testdeleteWord5() throws Exception {
593.689 - deleteWord("foo_bar_^", "foo_^");
593.690 - }
593.691 -
593.692 - public void testdeleteWords() throws Exception {
593.693 - deleteWord("foo bar^", "foo ^");
593.694 - }
593.695 -
593.696 -
593.697 - public void testDeleteWord4_110998c() throws Exception {
593.698 - String before = " snark^\n";
593.699 - String after = " ^\n";
593.700 - deleteWord(before, after);
593.701 - }
593.702 -}
594.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonNameRangeTest.java Sun Jan 04 13:11:53 2015 -0600
594.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
594.3 @@ -1,95 +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;
594.10 -
594.11 -import java.util.List;
594.12 -import java.util.Map;
594.13 -import org.netbeans.modules.gsf.api.CompilationInfo;
594.14 -import org.netbeans.modules.gsf.api.OffsetRange;
594.15 -import org.netbeans.modules.gsf.api.ParserResult;
594.16 -import org.python.antlr.PythonTree;
594.17 -import org.python.antlr.Visitor;
594.18 -
594.19 -/**
594.20 - * Test the name range
594.21 - *
594.22 - * @author Tor Norbye
594.23 - */
594.24 -public class PythonNameRangeTest extends PythonTestBase {
594.25 - public PythonNameRangeTest(String testName) {
594.26 - super(testName);
594.27 - }
594.28 -
594.29 - @Override
594.30 - protected String describeNode(CompilationInfo info, Object obj, boolean includePath) throws Exception {
594.31 - return obj.toString();
594.32 - }
594.33 -
594.34 - @Override
594.35 - protected String getOffsetTestGoldenSuffix() {
594.36 - return ".nameoffsets";
594.37 - }
594.38 -
594.39 - @Override
594.40 - protected void initializeNodes(CompilationInfo info, ParserResult result, List<Object> validNodes,
594.41 - Map<Object,OffsetRange> positions, List<Object> invalidNodes) throws Exception {
594.42 - PythonTree root = PythonAstUtils.getRoot(info);
594.43 - assertNotNull(root);
594.44 -
594.45 - new TreeVisitor(validNodes, invalidNodes, positions, info).visit(root);
594.46 - }
594.47 -
594.48 - public void testOffsets1() throws Exception {
594.49 - checkOffsets("testfiles/empty.py");
594.50 - }
594.51 -
594.52 - public void testOffsets2() throws Exception {
594.53 - checkOffsets("testfiles/ConfigParser.py");
594.54 - }
594.55 -
594.56 - public void testOffsets3() throws Exception {
594.57 - checkOffsets("testfiles/datetime.py");
594.58 - }
594.59 -
594.60 - public void testOffsets4() throws Exception {
594.61 - checkOffsets("testfiles/getopt.py");
594.62 - }
594.63 -
594.64 - public void testOffsets5() throws Exception {
594.65 - checkOffsets("testfiles/test_scope.py");
594.66 - }
594.67 -
594.68 - private static class TreeVisitor extends Visitor {
594.69 - private List<Object> validNodes;
594.70 - private List<Object> invalidNodes;
594.71 - private Map<Object, OffsetRange> positions;
594.72 - private CompilationInfo info;
594.73 -
594.74 - TreeVisitor(List<Object> validNodes, List<Object> invalidNodes, Map<Object,
594.75 - OffsetRange> positions, CompilationInfo info) {
594.76 - this.validNodes = validNodes;
594.77 - this.invalidNodes = invalidNodes;
594.78 - this.positions = positions;
594.79 - this.info = info;
594.80 - }
594.81 -
594.82 - @Override
594.83 - public void traverse(PythonTree node) throws Exception {
594.84 - assertTrue(node.getCharStartIndex() <= node.getCharStopIndex());
594.85 -
594.86 - OffsetRange range = PythonAstUtils.getRange(node);
594.87 - OffsetRange nameRange = PythonAstUtils.getNameRange(info, node);
594.88 - if (!range.equals(nameRange) || PythonAstUtils.isNameNode(node)) {
594.89 - validNodes.add(node);
594.90 - positions.put(node, nameRange);
594.91 - }
594.92 -
594.93 - super.traverse(node);
594.94 - }
594.95 -
594.96 - }
594.97 -
594.98 -}
595.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonOccurrencesMarkerTest.java Sun Jan 04 13:11:53 2015 -0600
595.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
595.3 @@ -1,133 +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;
595.10 -
595.11 -import java.util.List;
595.12 -import javax.swing.text.Document;
595.13 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
595.14 -import org.openide.filesystems.FileObject;
595.15 -import org.openide.filesystems.FileUtil;
595.16 -
595.17 -/**
595.18 - *
595.19 - * @author Tor Norbye
595.20 - */
595.21 -public class PythonOccurrencesMarkerTest extends PythonTestBase {
595.22 -
595.23 - public PythonOccurrencesMarkerTest(String testName) {
595.24 - super(testName);
595.25 - }
595.26 -
595.27 - public void testMarks1() throws Exception {
595.28 - // TODO - these tests SHOULD pass symmetric but don't yet
595.29 - boolean symmetric = false;
595.30 -
595.31 - String caretLine = "def __init__(self, m^sg=''):";
595.32 - checkOccurrences("testfiles/ConfigParser.py", caretLine, symmetric);
595.33 - }
595.34 -
595.35 - public void testMarks2() throws Exception {
595.36 - // TODO - these tests SHOULD pass symmetric but don't yet
595.37 - boolean symmetric = false;
595.38 -
595.39 - String caretLine = "for (ke^y, value) in self._sections[section].items():";
595.40 - checkOccurrences("testfiles/ConfigParser.py", caretLine, symmetric);
595.41 - }
595.42 -
595.43 - public void test150581() throws Exception {
595.44 - FileObject testFile = getXTestPythonHomeFo().getFileObject("Lib/repr.py");
595.45 - assertNotNull(testFile);
595.46 - GsfTestCompilationInfo info = getInfo(testFile);
595.47 - PythonOccurrencesMarker marker = new PythonOccurrencesMarker();
595.48 - marker.setCaretPosition(786);
595.49 - marker.run(info);
595.50 - marker.getOccurrences();
595.51 - assertNull(PythonOccurrencesMarker.error);
595.52 - }
595.53 -
595.54 - // I think this test is wrong...
595.55 - //public void test150581b() throws Exception {
595.56 - // // TODO - these tests SHOULD pass symmetric but don't yet
595.57 - // boolean symmetric = false;
595.58 - //
595.59 - // String caretLine = "__builtin__.re^pr(x)";
595.60 - // checkOccurrences("testfiles/occurrences1.py", caretLine, symmetric);
595.61 - //}
595.62 -
595.63 - public void testMarks3() throws Exception {
595.64 - boolean symmetric = true;
595.65 - String caretLine = "new^format.append(zreplace)";
595.66 - checkOccurrences("testfiles/datetime.py", caretLine, symmetric);
595.67 - }
595.68 -
595.69 - public void testMarks4() throws Exception {
595.70 - boolean symmetric = true;
595.71 - String caretLine = "x = myf^unc";
595.72 - checkOccurrences("testfiles/occurrences2.py", caretLine, symmetric);
595.73 - }
595.74 -
595.75 - public void testMarks5() throws Exception {
595.76 - boolean symmetric = true;
595.77 - String caretLine = "import m^odule1";
595.78 - checkOccurrences("testfiles/occurrences2.py", caretLine, symmetric);
595.79 - }
595.80 -
595.81 - public void testMarks6() throws Exception {
595.82 - boolean symmetric = true;
595.83 - String caretLine = "import module3 as modu^le4";
595.84 - checkOccurrences("testfiles/occurrences2.py", caretLine, symmetric);
595.85 - }
595.86 -
595.87 - public void testMarks7() throws Exception {
595.88 - boolean symmetric = true;
595.89 - String caretLine = "toplevelv^ar2 =";
595.90 - checkOccurrences("testfiles/occurrences2.py", caretLine, symmetric);
595.91 - }
595.92 -
595.93 - public void testMarks8() throws Exception {
595.94 - boolean symmetric = true;
595.95 - String caretLine = "def mymethod(self,param1,pa^ram2):";
595.96 - checkOccurrences("testfiles/occurrences2.py", caretLine, symmetric);
595.97 - }
595.98 -
595.99 - public void testMarks9() throws Exception {
595.100 - boolean symmetric = true;
595.101 - String caretLine = "def _bu^ild_struct_time(";
595.102 - checkOccurrences("testfiles/datetime.py", caretLine, symmetric);
595.103 - }
595.104 -
595.105 - public void testMarks10() throws Exception {
595.106 - boolean symmetric = true;
595.107 - String caretLine = "sel^f.year, self.month, self.day = year, month, day";
595.108 - checkOccurrences("testfiles/datetime.py", caretLine, symmetric);
595.109 - }
595.110 -
595.111 - public void testMarks11() throws Exception {
595.112 - boolean symmetric = true;
595.113 - String caretLine = "# @type ^xy str";
595.114 - checkOccurrences("testfiles/typevars.py", caretLine, symmetric);
595.115 - }
595.116 -
595.117 - public void testStress() throws Exception {
595.118 - List<FileObject> files = findJythonFiles();
595.119 -
595.120 - //int MAX_FILES = Integer.MAX_VALUE;
595.121 - int MAX_FILES = 100;
595.122 -
595.123 - for (int i = 0; i < files.size() && i < MAX_FILES; i++) {
595.124 - FileObject fo = files.get(i);
595.125 - GsfTestCompilationInfo info = getInfo(fo);
595.126 - Document doc = info.getDocument();
595.127 - for (int offset = 0; offset < doc.getLength(); offset++) {
595.128 - PythonOccurrencesMarker marker = new PythonOccurrencesMarker();
595.129 - marker.setCaretPosition(offset);
595.130 - marker.run(info);
595.131 - marker.getOccurrences();
595.132 - assertNull("Handling " + FileUtil.getFileDisplayName(fo) + " at offset " + offset, PythonOccurrencesMarker.error);
595.133 - }
595.134 - }
595.135 - }
595.136 -}
596.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonParserTest.java Sun Jan 04 13:11:53 2015 -0600
596.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
596.3 @@ -1,178 +0,0 @@
596.4 -/*
596.5 - * To change this template, choose Tools | Templates
596.6 - * and open the template in the editor.
596.7 - */
596.8 -
596.9 -package org.netbeans.modules.python.editor;
596.10 -
596.11 -import java.util.List;
596.12 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
596.13 -import org.netbeans.modules.gsf.api.CompilationInfo;
596.14 -import org.python.antlr.PythonTree;
596.15 -import org.python.antlr.Visitor;
596.16 -import org.netbeans.modules.gsf.api.ParserResult;
596.17 -import org.netbeans.modules.gsf.api.Error;
596.18 -
596.19 -/**
596.20 - *
596.21 - * @author Tor Norbye
596.22 - */
596.23 -public class PythonParserTest extends PythonTestBase {
596.24 -
596.25 - public PythonParserTest(String testName) {
596.26 - super(testName);
596.27 - }
596.28 -
596.29 -// private void checkParseTree(String file, String caretLine, String nodeType) throws Exception {
596.30 -// PythonParser.runtimeException = null;
596.31 -// CompilationInfo info = getInfo(file);
596.32 -//
596.33 -// String text = info.getText();
596.34 -//
596.35 -// int caretOffset = -1;
596.36 -// if (caretLine != null) {
596.37 -// int caretDelta = caretLine.indexOf("^");
596.38 -// assertTrue(caretDelta != -1);
596.39 -// caretLine = caretLine.substring(0, caretDelta) + caretLine.substring(caretDelta + 1);
596.40 -// int lineOffset = text.indexOf(caretLine);
596.41 -// assertTrue(lineOffset != -1);
596.42 -//
596.43 -// caretOffset = lineOffset + caretDelta;
596.44 -// ((GsfTestCompilationInfo)info).setCaretOffset(caretOffset);
596.45 -// }
596.46 -//
596.47 -// PythonTree root = PythonAstUtils.getRoot(info);
596.48 -// assertNotNull("Parsing broken input failed for " + file, root);
596.49 -//
596.50 -// // Ensure that we find the node we're looking for
596.51 -// if (nodeType != null) {
596.52 -// PythonParserResult rpr = PythonAstUtils.getParseResult(info);
596.53 -// OffsetRange range = rpr.getSanitizedRange();
596.54 -// if (range.containsInclusive(caretOffset)) {
596.55 -// caretOffset = range.getStart();
596.56 -// }
596.57 -// AstPath path = AstPath.get(root, caretOffset);
596.58 -// PythonTree closest = path.leaf();
596.59 -// assertNotNull(closest);
596.60 -// String leafName = closest.getClass().getName();
596.61 -// leafName = leafName.substring(leafName.lastIndexOf('.')+1);
596.62 -// assertEquals(nodeType, closest.toString());
596.63 -// }
596.64 -// assertNull(PythonParser.runtimeException);
596.65 -// }
596.66 -
596.67 - private void checkNoParseAbort(String file) throws Exception {
596.68 - checkNoParseAbort(file, null);
596.69 - }
596.70 - private void checkNoParseAbort(String file, String caretLine) throws Exception {
596.71 - PythonParser.runtimeException = null;
596.72 - CompilationInfo info = getInfo(file);
596.73 - PythonTree root = PythonAstUtils.getRoot(info);
596.74 - assertNull(PythonParser.runtimeException != null ? PythonParser.runtimeException.toString() : "OK", PythonParser.runtimeException);
596.75 - // Check that a walk works too
596.76 - if (root != null) {
596.77 - new Visitor() {
596.78 - @Override
596.79 - public void traverse(PythonTree node) throws Exception {
596.80 - super.traverse(node);
596.81 - }
596.82 -
596.83 - }.visit(root);
596.84 - }
596.85 - }
596.86 -
596.87 - protected void checkErrors(String relFilePath, String caretLine) throws Exception {
596.88 - GsfTestCompilationInfo info = getInfo(relFilePath);
596.89 -
596.90 - if (caretLine != null) {
596.91 - int caretDelta = caretLine.indexOf("^");
596.92 - assertTrue(caretDelta != -1);
596.93 - caretLine = caretLine.substring(0, caretDelta) + caretLine.substring(caretDelta + 1);
596.94 - int lineOffset = info.getText().indexOf(caretLine);
596.95 - assertTrue("NOT FOUND: " + info.getFileObject().getName() + ":" + caretLine, lineOffset != -1);
596.96 -
596.97 - int caretOffset = lineOffset + caretDelta;
596.98 - info.setCaretOffset(caretOffset);
596.99 - }
596.100 -
596.101 - String text = info.getText();
596.102 - assertNotNull(text);
596.103 -
596.104 - ParserResult pr = info.getEmbeddedResult(info.getPreferredMimeType(), 0);
596.105 - assertNotNull(pr);
596.106 -
596.107 - List<Error> diagnostics = pr.getDiagnostics();
596.108 - String annotatedSource = annotateErrors(text, diagnostics);
596.109 - assertDescriptionMatches(relFilePath, annotatedSource, false, ".errors");
596.110 - }
596.111 -
596.112 - public void testPartial11() throws Exception {
596.113 - checkNoParseAbort("testfiles/errors1.py");
596.114 - checkErrors("testfiles/errors1.py");
596.115 - }
596.116 -
596.117 - public void testCastAbort1() throws Exception {
596.118 - checkNoParseAbort("testfiles/errors2.py");
596.119 - checkErrors("testfiles/errors2.py");
596.120 - }
596.121 -
596.122 - public void testInfiniteLoop1() throws Exception {
596.123 - checkNoParseAbort("testfiles/errors3.py");
596.124 - checkErrors("testfiles/errors3.py");
596.125 - }
596.126 -
596.127 - public void testInfiniteLoop2() throws Exception {
596.128 - checkNoParseAbort("testfiles/errors4.py");
596.129 - checkErrors("testfiles/errors4.py");
596.130 - }
596.131 -
596.132 - public void testPositions() throws Exception {
596.133 - checkNoParseAbort("testfiles/errors5.py");
596.134 - }
596.135 -
596.136 - // Not yet passing
596.137 - public void testAsKeyword() throws Exception {
596.138 - // See 150921
596.139 - checkNoParseAbort("testfiles/lib-old/Para.py");
596.140 - }
596.141 -
596.142 - public void testNpe() throws Exception {
596.143 - // See 150921
596.144 - checkNoParseAbort("testfiles/errors6.py");
596.145 - }
596.146 -
596.147 - public void testNpe2() throws Exception {
596.148 - // See 155904
596.149 - checkNoParseAbort("testfiles/errors7.py");
596.150 - }
596.151 -
596.152 - public void testCastException1() throws Exception {
596.153 - checkNoParseAbort("testfiles/errors8.py");
596.154 - }
596.155 -
596.156 - public void testCastException2() throws Exception {
596.157 - checkNoParseAbort("testfiles/errors9.py");
596.158 - }
596.159 -
596.160 - public void testPython26Syntax() throws Exception {
596.161 - checkNoParseAbort("testfiles/exceptas.py");
596.162 - }
596.163 -
596.164 - public void testMissingColons1() throws Exception {
596.165 - checkNoParseAbort("testfiles/errors10.py");
596.166 - checkErrors("testfiles/errors10.py");
596.167 - }
596.168 -
596.169 - public void testMissingColons2() throws Exception {
596.170 - checkNoParseAbort("testfiles/errors11.py");
596.171 - checkErrors("testfiles/errors11.py");
596.172 - }
596.173 -
596.174 - // https://netbeans.org/bugzilla/show_bug.cgi?id=178442
596.175 - public void testIncremental1() throws Exception {
596.176 - checkErrors("testfiles/errors12.py", "ABC,^DEF");
596.177 - }
596.178 - public void testIncremental2() throws Exception {
596.179 - checkErrors("testfiles/errors13.py", "newparam,^");
596.180 - }
596.181 -}
597.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonSemanticHighlighterTest.java Sun Jan 04 13:11:53 2015 -0600
597.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
597.3 @@ -1,45 +0,0 @@
597.4 -/*
597.5 - * To change this template, choose Tools | Templates
597.6 - * and open the template in the editor.
597.7 - */
597.8 -
597.9 -package org.netbeans.modules.python.editor;
597.10 -
597.11 -/**
597.12 - *
597.13 - * @author Tor Norbye
597.14 - */
597.15 -public class PythonSemanticHighlighterTest extends PythonTestBase {
597.16 -
597.17 - public PythonSemanticHighlighterTest(String testName) {
597.18 - super(testName);
597.19 - }
597.20 -
597.21 - public void testSemantic1() throws Exception {
597.22 - checkSemantic("testfiles/empty.py");
597.23 - }
597.24 -
597.25 - public void testSemantic2() throws Exception {
597.26 - checkSemantic("testfiles/ConfigParser.py");
597.27 - }
597.28 -
597.29 - public void testSemantic3() throws Exception {
597.30 - checkSemantic("testfiles/datetime.py");
597.31 - }
597.32 -
597.33 - public void testSemantic4() throws Exception {
597.34 - checkSemantic("testfiles/getopt.py");
597.35 - }
597.36 -
597.37 - public void testSemantic5() throws Exception {
597.38 - checkSemantic("testfiles/test_scope.py");
597.39 - }
597.40 -
597.41 - public void testDecorators() throws Exception {
597.42 - checkSemantic("testfiles/staticmethods.py");
597.43 - }
597.44 -
597.45 - public void testDecorators2() throws Exception {
597.46 - checkSemantic("testfiles/decorators.py");
597.47 - }
597.48 -}
598.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonStructureScannerTest.java Sun Jan 04 13:11:53 2015 -0600
598.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
598.3 @@ -1,61 +0,0 @@
598.4 -/*
598.5 - * To change this template, choose Tools | Templates
598.6 - * and open the template in the editor.
598.7 - */
598.8 -
598.9 -package org.netbeans.modules.python.editor;
598.10 -
598.11 -/**
598.12 - *
598.13 - * @author Tor Norbye
598.14 - */
598.15 -public class PythonStructureScannerTest extends PythonTestBase {
598.16 -
598.17 - public PythonStructureScannerTest(String testName) {
598.18 - super(testName);
598.19 - }
598.20 -
598.21 - public void testStructure1() throws Exception {
598.22 - checkStructure("testfiles/empty.py");
598.23 - }
598.24 -
598.25 - public void testStructure2() throws Exception {
598.26 - checkStructure("testfiles/ConfigParser.py");
598.27 - }
598.28 -
598.29 - public void testStructure3() throws Exception {
598.30 - checkStructure("testfiles/datetime.py");
598.31 - }
598.32 -
598.33 - public void testStructure4() throws Exception {
598.34 - checkStructure("testfiles/getopt.py");
598.35 - }
598.36 -
598.37 - public void testStructure5() throws Exception {
598.38 - checkStructure("testfiles/test_scope.py");
598.39 - }
598.40 -
598.41 - public void testFolds1() throws Exception {
598.42 - checkFolds("testfiles/empty.py");
598.43 - }
598.44 -
598.45 - public void testFolds2() throws Exception {
598.46 - checkFolds("testfiles/ConfigParser.py");
598.47 - }
598.48 -
598.49 - public void testFolds3() throws Exception {
598.50 - checkFolds("testfiles/datetime.py");
598.51 - }
598.52 -
598.53 - public void testFolds4() throws Exception {
598.54 - checkFolds("testfiles/getopt.py");
598.55 - }
598.56 -
598.57 - public void testFolds5() throws Exception {
598.58 - checkFolds("testfiles/test_scope.py");
598.59 - }
598.60 -
598.61 - public void testModifiers() throws Exception {
598.62 - checkStructure("testfiles/modifiers.py");
598.63 - }
598.64 -}
599.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonTestBase.java Sun Jan 04 13:11:53 2015 -0600
599.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
599.3 @@ -1,199 +0,0 @@
599.4 -/*
599.5 - * To change this template, choose Tools | Templates
599.6 - * and open the template in the editor.
599.7 - */
599.8 -
599.9 -package org.netbeans.modules.python.editor;
599.10 -
599.11 -import java.io.File;
599.12 -import java.net.MalformedURLException;
599.13 -import java.net.URL;
599.14 -import java.util.ArrayList;
599.15 -import java.util.Collections;
599.16 -import java.util.List;
599.17 -import java.util.Map;
599.18 -import java.util.Set;
599.19 -import org.netbeans.modules.python.editor.hints.PythonAstRule;
599.20 -import org.netbeans.modules.python.editor.hints.PythonSelectionRule;
599.21 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
599.22 -import org.netbeans.editor.BaseDocument;
599.23 -import org.netbeans.modules.gsf.GsfTestBase;
599.24 -import org.netbeans.modules.gsf.Language;
599.25 -import org.netbeans.modules.gsf.LanguageRegistry;
599.26 -import org.netbeans.modules.gsf.spi.DefaultLanguageConfig;
599.27 -import org.netbeans.modules.gsfret.hints.infrastructure.GsfHintsManager;
599.28 -import org.openide.filesystems.FileObject;
599.29 -import org.openide.filesystems.FileStateInvalidException;
599.30 -import org.openide.filesystems.FileUtil;
599.31 -import org.openide.util.Exceptions;
599.32 -import org.python.antlr.PythonTree;
599.33 -import org.python.antlr.Visitor;
599.34 -
599.35 -/**
599.36 - * @author Tor Norbye
599.37 - */
599.38 -public abstract class PythonTestBase extends GsfTestBase {
599.39 - static {
599.40 - PythonIndex.setClusterUrl(getClusterUrl().toExternalForm());
599.41 - }
599.42 -
599.43 - public PythonTestBase(String testName) {
599.44 - super(testName);
599.45 - }
599.46 -
599.47 - @Override
599.48 - protected boolean runInEQ() {
599.49 - // Must run in AWT thread (BaseKit.install() checks for that)
599.50 - return true;
599.51 - }
599.52 -
599.53 - @Override
599.54 - protected DefaultLanguageConfig getPreferredLanguage() {
599.55 - return new PythonLanguage();
599.56 - }
599.57 -
599.58 - @Override
599.59 - protected String getPreferredMimeType() {
599.60 - return PythonTokenId.PYTHON_MIME_TYPE;
599.61 - }
599.62 -
599.63 - @Override
599.64 - protected void initializeClassPaths() {
599.65 - System.setProperty("netbeans.user", getWorkDirPath());
599.66 - org.netbeans.modules.gsfret.source.usages.Index.addPreindexRoot(getClusterHome());
599.67 - org.netbeans.modules.gsfret.source.usages.Index.addPreindexRoot(getXTestPythonHomeFo().getFileObject("Lib"));
599.68 - initializeRegistry();
599.69 - super.initializeClassPaths();
599.70 - }
599.71 -
599.72 - @Override
599.73 - protected List<URL> getExtraCpUrls() {
599.74 - try {
599.75 - return Collections.singletonList(getXTestPythonHomeFo().getFileObject("Lib").getURL());
599.76 - } catch (FileStateInvalidException ex) {
599.77 - Exceptions.printStackTrace(ex);
599.78 - return null;
599.79 - }
599.80 - }
599.81 -
599.82 - @SuppressWarnings("unchecked")
599.83 - public void ensureRegistered(PythonAstRule hint) throws Exception {
599.84 - Language language = LanguageRegistry.getInstance().getLanguageByMimeType(getPreferredMimeType());
599.85 - assertNotNull(language.getHintsProvider());
599.86 - GsfHintsManager hintsManager = language.getHintsManager();
599.87 - Map<Integer, List<PythonAstRule>> hints = (Map)hintsManager.getHints();
599.88 - Set<Class> kinds = hint.getKinds();
599.89 - for (Class nodeType : kinds) {
599.90 - List<PythonAstRule> rules = hints.get(nodeType);
599.91 - assertNotNull(rules);
599.92 - boolean found = false;
599.93 - for (PythonAstRule rule : rules) {
599.94 - if (rule.getClass() == hint.getClass()) {
599.95 - found = true;
599.96 - break;
599.97 - }
599.98 - }
599.99 -
599.100 - assertTrue(found);
599.101 - }
599.102 - }
599.103 -
599.104 - @SuppressWarnings("unchecked")
599.105 - public void ensureRegistered(PythonSelectionRule hint) throws Exception {
599.106 - Language language = LanguageRegistry.getInstance().getLanguageByMimeType(getPreferredMimeType());
599.107 - assertNotNull(language.getHintsProvider());
599.108 - GsfHintsManager hintsManager = language.getHintsManager();
599.109 - List<PythonSelectionRule> hints = (List<PythonSelectionRule>) hintsManager.getSelectionHints();
599.110 - boolean found = false;
599.111 - for (PythonSelectionRule rule : hints) {
599.112 - if (rule.getClass() == hint.getClass()) {
599.113 - found = true;
599.114 - break;
599.115 - }
599.116 - }
599.117 -
599.118 - assertTrue(found);
599.119 - }
599.120 -
599.121 - // Called via reflection from GsfUtilities. This is necessary because
599.122 - // during tests, going from a FileObject to a BaseDocument only works
599.123 - // if all the correct data loaders are installed and working - and that
599.124 - // hasn't been the case; we end up with PlainDocuments instead of BaseDocuments.
599.125 - // If anyone can figure this out, please let me know and simplify the
599.126 - // test infrastructure.
599.127 - public static BaseDocument getDocumentFor(FileObject fo) {
599.128 - BaseDocument doc = GsfTestBase.createDocument(read(fo));
599.129 - doc.putProperty(org.netbeans.api.lexer.Language.class, PythonTokenId.language());
599.130 - doc.putProperty("mimeType", PythonTokenId.PYTHON_MIME_TYPE);
599.131 -
599.132 - return doc;
599.133 - }
599.134 -
599.135 - // Locate as many Python files from the JPython distribution as possible: libs, gems, etc.
599.136 - protected List<FileObject> findJythonFiles() {
599.137 - List<FileObject> l = new ArrayList<FileObject>();
599.138 - addPythonFiles(l, getXTestPythonHomeFo());
599.139 -
599.140 - return l;
599.141 - }
599.142 -
599.143 - private void addPythonFiles(List<FileObject> list, FileObject parent) {
599.144 - for (FileObject child : parent.getChildren()) {
599.145 - if (child.isFolder()) {
599.146 - if (child.getName().equals("test")) {
599.147 - // Skip test stuff
599.148 - continue;
599.149 - }
599.150 - addPythonFiles(list, child);
599.151 - } else if (child.getMIMEType().equals(PythonTokenId.PYTHON_MIME_TYPE)) {
599.152 - list.add(child);
599.153 - }
599.154 - }
599.155 - }
599.156 -
599.157 - public static File getXTestPythonHome() {
599.158 - String destDir = System.getProperty("xtest.python.home");
599.159 - if (destDir == null) {
599.160 - throw new RuntimeException("xtest.Python.home property has to be set when running within binary distribution");
599.161 - }
599.162 - return new File(destDir);
599.163 - }
599.164 -
599.165 - public static String getXTestPythonHomePath() {
599.166 - return getXTestPythonHome().getAbsolutePath();
599.167 - }
599.168 -
599.169 - public static FileObject getXTestPythonHomeFo() {
599.170 - return FileUtil.toFileObject(getXTestPythonHome());
599.171 - }
599.172 -
599.173 - public static FileObject getClusterHome() {
599.174 - return FileUtil.toFileObject(getXTestPythonHome().getParentFile());
599.175 - }
599.176 -
599.177 - public static URL getClusterUrl() {
599.178 - try {
599.179 - return getXTestPythonHome().getParentFile().toURI().toURL();
599.180 - } catch (MalformedURLException ex) {
599.181 - Exceptions.printStackTrace(ex);
599.182 - fail(ex.toString());
599.183 - return null;
599.184 - }
599.185 - }
599.186 -
599.187 - protected List<PythonTree> getAllNodes(PythonTree root) throws Exception {
599.188 - final List<PythonTree> nodes = new ArrayList<PythonTree>();
599.189 -
599.190 - Visitor visitor = new Visitor() {
599.191 -
599.192 - @Override
599.193 - public void traverse(PythonTree node) throws Exception {
599.194 - nodes.add(node);
599.195 - super.traverse(node);
599.196 - }
599.197 -
599.198 - };
599.199 - visitor.visit(root);
599.200 - return nodes;
599.201 - }
599.202 -}
600.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonTypeAnalyzerTest.java Sun Jan 04 13:11:53 2015 -0600
600.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
600.3 @@ -1,115 +0,0 @@
600.4 -/*
600.5 - * To change this template, choose Tools | Templates
600.6 - * and open the template in the editor.
600.7 - */
600.8 -
600.9 -package org.netbeans.modules.python.editor;
600.10 -
600.11 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
600.12 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
600.13 -import org.openide.filesystems.FileObject;
600.14 -import org.python.antlr.PythonTree;
600.15 -
600.16 -/**
600.17 - * Test for the Python type analyzer.
600.18 - *
600.19 - * @author Tor Norbye
600.20 - */
600.21 -public class PythonTypeAnalyzerTest extends PythonTestBase {
600.22 -
600.23 - public PythonTypeAnalyzerTest(String testName) {
600.24 - super(testName);
600.25 - }
600.26 -
600.27 - private PythonTypeAnalyzer getAnalyzer(String file, String caretLine, boolean findMethod) throws Exception {
600.28 - FileObject fo = getTestFile(file);
600.29 - GsfTestCompilationInfo info = getInfo(fo);
600.30 - PythonTree root = PythonAstUtils.getRoot(info);
600.31 - initializeRegistry();
600.32 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
600.33 -
600.34 - int caretOffset = -1;
600.35 - if (caretLine != null) {
600.36 - int caretDelta = caretLine.indexOf("^");
600.37 - assertTrue(caretDelta != -1);
600.38 - caretLine = caretLine.substring(0, caretDelta) + caretLine.substring(caretDelta + 1);
600.39 - int lineOffset = info.getText().indexOf(caretLine);
600.40 - assertTrue(lineOffset != -1);
600.41 - caretOffset = lineOffset + caretDelta;
600.42 - }
600.43 -
600.44 - AstPath path = AstPath.get(root, caretOffset);
600.45 - PythonTree node = path.leaf();
600.46 -
600.47 - if (findMethod) {
600.48 - PythonTree method = PythonAstUtils.getLocalScope(path);
600.49 - assertNotNull(method);
600.50 -
600.51 - root = method;
600.52 - }
600.53 -
600.54 - PythonTypeAnalyzer instance = new PythonTypeAnalyzer(info, index, root, node, caretOffset, caretOffset, fo);
600.55 -
600.56 - return instance;
600.57 - }
600.58 -
600.59 - public void testGetType1() throws Exception {
600.60 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/types.py", "#^FIRST_CARET_POS", true);
600.61 -
600.62 - assertEquals("SomeOtherClass", instance.getType("x"));
600.63 - assertEquals("SomeOtherClass", instance.getType("y"));
600.64 - assertEquals("SomeOtherClass", instance.getType("z"));
600.65 - assertEquals("str", instance.getType("yz"));
600.66 - assertEquals("int", instance.getType("w"));
600.67 - assertEquals(null, instance.getType("unknown"));
600.68 - }
600.69 -
600.70 - public void testGetType2() throws Exception {
600.71 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/types.py", "#^SECOND_CARET_POS", true);
600.72 -
600.73 - assertEquals("Other", instance.getType("x"));
600.74 - assertEquals("int", instance.getType("y"));
600.75 - assertEquals("str", instance.getType("z"));
600.76 - assertEquals("str", instance.getType("yz"));
600.77 - assertEquals("int", instance.getType("w"));
600.78 - assertEquals(null, instance.getType("unknown"));
600.79 - }
600.80 -
600.81 - public void testGetType3() throws Exception {
600.82 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/compl2.py", "unknown^", true);
600.83 -
600.84 - assertEquals("ZipFile", instance.getType("myothervar"));
600.85 - assertEquals("file", instance.getType("myvar"));
600.86 - assertEquals(null, instance.getType("unknown"));
600.87 - }
600.88 -
600.89 - public void testTypeAssertions1() throws Exception {
600.90 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/types.py", "#^FIRST_CARET_POS", true);
600.91 -
600.92 - assertEquals("int", instance.getType("defined1"));
600.93 - }
600.94 -
600.95 - public void testTypeAssertions2() throws Exception {
600.96 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/types.py", "#^SECOND_CARET_POS", true);
600.97 -
600.98 - assertEquals("str", instance.getType("defined1"));
600.99 - }
600.100 -
600.101 - public void testTypeAssertions3() throws Exception {
600.102 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/types.py", "#^SECOND_CARET_POS", true);
600.103 -
600.104 - assertEquals("str", instance.getType("s"));
600.105 - }
600.106 -
600.107 - public void testTypeExceptionVars1() throws Exception {
600.108 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/exceptas.py", "% ex.^e", true);
600.109 -
600.110 - assertEquals("MyError", instance.getType("ex"));
600.111 - }
600.112 -
600.113 - public void testTypeExceptionVars2() throws Exception {
600.114 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/exceptas.py", "% ex2.^e", true);
600.115 -
600.116 - assertEquals("MyError", instance.getType("ex2"));
600.117 - }
600.118 -}
601.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonUtilsTest.java Sun Jan 04 13:11:53 2015 -0600
601.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
601.3 @@ -1,138 +0,0 @@
601.4 -/*
601.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
601.6 - *
601.7 - * Copyright 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 - * If you wish your version of this file to be governed by only the CDDL
601.31 - * or only the GPL Version 2, indicate your decision by adding
601.32 - * "[Contributor] elects to include this software in this distribution
601.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
601.34 - * single choice of license, a recipient has the option to distribute
601.35 - * your version of this file under either the CDDL, the GPL Version 2 or
601.36 - * to extend the choice of license to its licensees as provided above.
601.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
601.38 - * Version 2 license, then the option applies only if the new code is
601.39 - * made subject to such option by the copyright holder.
601.40 - *
601.41 - * Contributor(s):
601.42 - *
601.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
601.44 - */
601.45 -package org.netbeans.modules.python.editor;
601.46 -
601.47 -import java.util.ArrayList;
601.48 -import java.util.Arrays;
601.49 -import java.util.Collections;
601.50 -import java.util.List;
601.51 -import org.netbeans.modules.python.api.Util;
601.52 -import org.openide.filesystems.FileObject;
601.53 -import org.openide.filesystems.FileUtil;
601.54 -
601.55 -/**
601.56 - *
601.57 - * @author Tor Norbye
601.58 - */
601.59 -public class PythonUtilsTest extends PythonTestBase {
601.60 -
601.61 - public PythonUtilsTest(String name) {
601.62 - super(name);
601.63 - }
601.64 -
601.65 - public void testGetOffsetByLineCol() throws Exception {
601.66 - assertEquals(5, PythonUtils.getOffsetByLineCol("fooooooooo\nHello\n", 0, 5));
601.67 - }
601.68 -
601.69 - public void testGetOffsetByLineCol2() throws Exception {
601.70 - assertEquals(5, PythonUtils.getOffsetByLineCol("fooooooooo", 0, 5));
601.71 - }
601.72 -
601.73 - public void testGetOffsetByLineCol3() throws Exception {
601.74 - assertEquals(2, PythonUtils.getOffsetByLineCol("o\nHello\n", 1, 0));
601.75 - }
601.76 -
601.77 - public void testGetOffsetByLineCol4() throws Exception {
601.78 - assertEquals(4, PythonUtils.getOffsetByLineCol("o\nHello\n", 1, 2));
601.79 - }
601.80 -
601.81 - public void testGetOffsetByLineCol5() throws Exception {
601.82 - assertEquals(8, PythonUtils.getOffsetByLineCol("o\nHello\n", 2, 0));
601.83 - }
601.84 -
601.85 - public void testGetOffsetByLineCol6() throws Exception {
601.86 - assertEquals(8, PythonUtils.getOffsetByLineCol("o\nHello\n", 50, 0));
601.87 - }
601.88 -
601.89 - public void testGetOffsetByLineCol7() throws Exception {
601.90 - assertEquals(2, PythonUtils.getOffsetByLineCol("o\nHello\n", 1, -1));
601.91 - }
601.92 - public void checkRoots(FileObject[] expected, FileObject[] path) throws Exception {
601.93 - List<FileObject> pythonPath = Arrays.asList(path);
601.94 -
601.95 - List<FileObject> roots = Util.findUniqueRoots(pythonPath);
601.96 - List<String> list = new ArrayList<String>();
601.97 - for (FileObject root : roots) {
601.98 - list.add(FileUtil.getFileDisplayName(root));
601.99 - }
601.100 - Collections.sort(list);
601.101 - List<FileObject> expectedList = Arrays.asList(expected);
601.102 - Collections.sort(list);
601.103 -
601.104 - List<String> elist = new ArrayList<String>();
601.105 - for (FileObject root : expectedList) {
601.106 - elist.add(FileUtil.getFileDisplayName(root));
601.107 - }
601.108 - Collections.sort(elist);
601.109 -
601.110 - assertEquals(elist.toString(), list.toString());
601.111 - }
601.112 -
601.113 - public void testFindUniqueRoots() throws Exception {
601.114 - FileObject path1 = getTestFile("testfiles/package/subpackage1");
601.115 - FileObject path2 = getTestFile("testfiles/package/subpackage2");
601.116 - FileObject path3 = getTestFile("testfiles/toppkg");
601.117 - FileObject path4 = getTestFile("testfiles/package");
601.118 - FileObject path5 = getTestFile("testfiles/");
601.119 - FileObject path6 = getTestFile("testfiles/toppkg/medpkg/lowpkg");
601.120 -
601.121 - checkRoots(
601.122 - new FileObject[]{path5},
601.123 - new FileObject[]{path1, path2, path3, path4, path5, path6});
601.124 -
601.125 - checkRoots(
601.126 - new FileObject[]{path4, path3},
601.127 - new FileObject[]{path6, path3, path4});
601.128 -
601.129 - checkRoots(
601.130 - new FileObject[]{path1, path2},
601.131 - new FileObject[]{path1, path2});
601.132 -
601.133 - checkRoots(
601.134 - new FileObject[]{path6},
601.135 - new FileObject[]{path6});
601.136 -
601.137 - checkRoots(
601.138 - new FileObject[]{path1, path3},
601.139 - new FileObject[]{path1, path3, path6});
601.140 - }
601.141 -}
602.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/RstFormatterTest.java Sun Jan 04 13:11:53 2015 -0600
602.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
602.3 @@ -1,263 +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 2008 Sun Microsystems, Inc.
602.44 - */
602.45 -
602.46 -package org.netbeans.modules.python.editor;
602.47 -
602.48 -import java.util.ArrayList;
602.49 -import java.util.List;
602.50 -import org.netbeans.editor.BaseDocument;
602.51 -import org.netbeans.modules.gsf.api.CompilationInfo;
602.52 -import org.netbeans.modules.gsf.api.ElementKind;
602.53 -import org.netbeans.modules.python.editor.elements.IndexedElement;
602.54 -import org.netbeans.modules.python.editor.elements.IndexedMethod;
602.55 -import org.openide.filesystems.FileObject;
602.56 -import org.openide.filesystems.FileUtil;
602.57 -import org.python.antlr.PythonTree;
602.58 -import org.python.antlr.ast.ClassDef;
602.59 -import org.python.antlr.ast.FunctionDef;
602.60 -import org.python.antlr.ast.Module;
602.61 -
602.62 -/**
602.63 - *
602.64 - * @author Tor Norbye
602.65 - */
602.66 -public class RstFormatterTest extends PythonTestBase {
602.67 -
602.68 - public RstFormatterTest(String name) {
602.69 - super(name);
602.70 - }
602.71 -
602.72 - private IndexedElement getFakeElement(String name, ElementKind kind, String url, String rhs, List<String> parameters) {
602.73 - IndexedElement fakeElement;
602.74 - if (parameters != null) {
602.75 - assert kind == ElementKind.METHOD;
602.76 - String clz = "Unknown";
602.77 - StringBuilder sb2 = new StringBuilder();
602.78 - sb2.append(name);
602.79 -
602.80 - sb2.append(";F;0;"); // NOI18N
602.81 -
602.82 - boolean first = true;
602.83 - for (String s : parameters) {
602.84 - if (first) {
602.85 - first = false;
602.86 - } else {
602.87 - sb2.append(',');
602.88 - }
602.89 - sb2.append(s);
602.90 - }
602.91 - sb2.append(';');
602.92 - String signature = sb2.toString();
602.93 - fakeElement = new IndexedMethod(name, kind, url, rhs, clz, signature);
602.94 - } else {
602.95 - String clz = null;
602.96 - String signature = null;
602.97 - fakeElement = new IndexedElement(name, kind, url, rhs, clz, signature);
602.98 - }
602.99 -
602.100 - return fakeElement;
602.101 - }
602.102 -
602.103 - private void checkDocumentation(String testFile, String name, ElementKind kind) throws Exception {
602.104 - FileObject fo = getTestFile(testFile);
602.105 - String url = FileUtil.toFile(fo).toURI().toURL().toExternalForm();
602.106 - String rhs = null;
602.107 -
602.108 - IndexedElement fakeElement = getFakeElement(name, kind, url, rhs, null);
602.109 - String html = RstFormatter.getDocumentation(fakeElement);
602.110 -
602.111 - assertDescriptionMatches(testFile, "<html><body>" + html + "</body></html>", true, ".html");
602.112 - }
602.113 -
602.114 - public void formatFile(String file) throws Exception {
602.115 - if (file.endsWith(".rst")) {
602.116 - StringBuilder sb = new StringBuilder();
602.117 - sb.append("<html><body>\n"); // NOI18N
602.118 - String rst = readFile(getTestFile(file));
602.119 - sb.append(RstFormatter.document(rst));
602.120 - sb.append("</body></html>\n");
602.121 -
602.122 - assertDescriptionMatches(file, sb.toString(), false, ".html");
602.123 -
602.124 - return;
602.125 - }
602.126 -
602.127 - CompilationInfo info = getInfo(file);
602.128 -
602.129 - List<PythonTree> result = new ArrayList<PythonTree>();
602.130 - PythonTree root = PythonAstUtils.getRoot(info);
602.131 - PythonAstUtils.addNodesByType(root, new Class[] { Module.class, FunctionDef.class, ClassDef.class }, result);
602.132 -
602.133 - StringBuilder sb = new StringBuilder();
602.134 - sb.append("<html><body>\n"); // NOI18N
602.135 -
602.136 - for (PythonTree node : result) {
602.137 - PythonTree docNode = PythonAstUtils.getDocumentationNode(node);
602.138 - if (docNode != null) {
602.139 - String name = "";
602.140 - ElementKind kind = ElementKind.OTHER;
602.141 - List<String> parameters = null;
602.142 - if (node instanceof FunctionDef) {
602.143 - kind = ElementKind.METHOD;
602.144 - FunctionDef func = (FunctionDef)node;
602.145 - name = func.getInternalName();
602.146 - parameters = PythonAstUtils.getParameters(func);
602.147 - } else if (node instanceof Module) {
602.148 - name = info.getFileObject().getNameExt();
602.149 - kind = ElementKind.MODULE;
602.150 - } else if (node instanceof ClassDef) {
602.151 - kind = ElementKind.CLASS;
602.152 - name = ((ClassDef)node).getInternalName();
602.153 - }
602.154 - String url = FileUtil.toFile(info.getFileObject()).toURI().toURL().toExternalForm();
602.155 - String rhs = null;
602.156 -
602.157 - IndexedElement fakeElement = getFakeElement(name, kind, url, rhs, parameters);
602.158 -
602.159 - String s = RstFormatter.document(info, node, fakeElement);
602.160 - if (s != null && s.length() > 0) {
602.161 - sb.append("<h2 style=\"color: green\">Next Comment</h2>\n"); // NOI18N
602.162 - sb.append(s);
602.163 - }
602.164 - }
602.165 - }
602.166 - sb.append("</body></html>\n");
602.167 -
602.168 - assertDescriptionMatches(file, sb.toString(), false, ".html");
602.169 - }
602.170 -
602.171 - public void testExtract1() throws Exception {
602.172 - RstFormatter formatter = new RstFormatter();
602.173 - BaseDocument doc = getDocument(getTestFile("testfiles/rst/stdtypes.rst"));
602.174 - String rst = formatter.extractRst("dict", null, ElementKind.CLASS, doc, null);
602.175 - assertTrue(rst, rst.trim().startsWith("Return a new dictionary initialized from "));
602.176 - }
602.177 -
602.178 - public void testExtract2() throws Exception {
602.179 - RstFormatter formatter = new RstFormatter();
602.180 - BaseDocument doc = getDocument(getTestFile("testfiles/rst/stdtypes.rst"));
602.181 - String rst = formatter.extractRst("hex", null, ElementKind.METHOD, doc, null);
602.182 - assertTrue(rst, rst.trim().startsWith("Return a representation of a floating-point number as a hexadecimal"));
602.183 - }
602.184 -
602.185 - public void testExtract3() throws Exception {
602.186 - RstFormatter formatter = new RstFormatter();
602.187 - BaseDocument doc = getDocument(getTestFile("testfiles/rst/stdtypes.rst"));
602.188 - String rst = formatter.extractRst("encoding", null, ElementKind.ATTRIBUTE, doc, null);
602.189 - assertTrue(rst, rst.trim().startsWith("The encoding that this file uses. When Unicode strings are written to a file,"));
602.190 - }
602.191 -
602.192 - public void testExtract4() throws Exception {
602.193 - RstFormatter formatter = new RstFormatter();
602.194 - BaseDocument doc = getDocument(getTestFile("testfiles/rst/platform.rst"));
602.195 - String[] signatureHolder = new String[1];
602.196 - String rst = formatter.extractRst("machine", null, ElementKind.METHOD, doc, signatureHolder);
602.197 - assertTrue(rst, rst.trim().startsWith("Returns the machine type, e.g"));
602.198 - assertEquals("machine()", signatureHolder[0]);
602.199 - }
602.200 -
602.201 - public void testExtract5() throws Exception {
602.202 - RstFormatter formatter = new RstFormatter();
602.203 - BaseDocument doc = getDocument(getTestFile("testfiles/rst/zipfile.rst"));
602.204 - String rst = formatter.extractRst("ZIP_STORED", null, ElementKind.ATTRIBUTE, doc, null);
602.205 - assertTrue(rst, rst.trim().startsWith("The numeric constant for an uncompressed archive membe"));
602.206 - }
602.207 -
602.208 - public void testExtract6() throws Exception {
602.209 - RstFormatter formatter = new RstFormatter();
602.210 - BaseDocument doc = getDocument(getTestFile("testfiles/rst/zipfile.rst"));
602.211 - String rst = formatter.extractRst("zipfile", null, ElementKind.MODULE, doc, null);
602.212 - assertTrue(rst, rst.trim().startsWith(":synopsis: Read and write ZIP-format archive files"));
602.213 - }
602.214 -
602.215 - public void testFormatBig1() throws Exception {
602.216 - formatFile("testfiles/ConfigParser.py");
602.217 - }
602.218 -
602.219 - public void testRawStringDoc() throws Exception {
602.220 - formatFile("testfiles/rawstringdoc.py");
602.221 - }
602.222 -
602.223 - public void testGetDoc1() throws Exception {
602.224 - checkDocumentation("testfiles/rst/zipfile.rst", "ZIP_STORED", ElementKind.ATTRIBUTE);
602.225 - }
602.226 -
602.227 - public void testGetDoc2() throws Exception {
602.228 - checkDocumentation("testfiles/rst/stdtypes.rst", "dict", ElementKind.CLASS);
602.229 - }
602.230 -
602.231 - public void testGetDoc3() throws Exception {
602.232 - checkDocumentation("testfiles/rst/zipfile.rst", "write", ElementKind.METHOD);
602.233 - }
602.234 -
602.235 - public void testGetDoc4() throws Exception {
602.236 - checkDocumentation("testfiles/rst/stdtypes.rst", "close", ElementKind.METHOD);
602.237 - }
602.238 -
602.239 - public void testGetDoc5() throws Exception {
602.240 - checkDocumentation("testfiles/rst/operator.rst", "__delitem__", ElementKind.METHOD);
602.241 - }
602.242 -
602.243 - public void testFormatAll1() throws Exception {
602.244 - formatFile("testfiles/rst/string.rst");
602.245 - }
602.246 -
602.247 - public void testFormatAll2() throws Exception {
602.248 - formatFile("testfiles/rst/stdtypes.rst");
602.249 - }
602.250 -
602.251 - public void testFormatAll3() throws Exception {
602.252 - formatFile("testfiles/rst/zipfile.rst");
602.253 - }
602.254 -
602.255 - public void testFormatAll4() throws Exception {
602.256 - formatFile("testfiles/rst/platform.rst");
602.257 - }
602.258 -
602.259 - public void testFormatAll5() throws Exception {
602.260 - formatFile("testfiles/rst/smtpd.rst");
602.261 - }
602.262 -
602.263 - public void testFormatAll6() throws Exception {
602.264 - formatFile("testfiles/rst/stub_missing.rst");
602.265 - }
602.266 -}
603.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/codecoverage/CodeCoverageTestHelper.java Sun Jan 04 13:11:53 2015 -0600
603.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
603.3 @@ -1,89 +0,0 @@
603.4 -package org.netbeans.modules.python.editor.codecoverage;
603.5 -
603.6 -import org.netbeans.api.project.Project;
603.7 -import org.netbeans.api.project.ProjectManager;
603.8 -import org.netbeans.editor.BaseDocument;
603.9 -import org.netbeans.editor.Utilities;
603.10 -import org.netbeans.modules.gsf.GsfTestBase;
603.11 -import org.netbeans.modules.gsf.codecoverage.api.CoverageProvider;
603.12 -import org.netbeans.modules.gsf.codecoverage.api.CoverageType;
603.13 -import org.netbeans.modules.gsf.codecoverage.api.FileCoverageDetails;
603.14 -import org.openide.filesystems.FileObject;
603.15 -import org.openide.xml.XMLUtil;
603.16 -
603.17 -public class CodeCoverageTestHelper {
603.18 - public static String annotateCoverage(CoverageProvider provider, FileObject fo, FileCoverageDetails details, BaseDocument doc) throws Exception {
603.19 - StringBuilder sb = new StringBuilder();
603.20 -
603.21 - sb.append("<html>\n");
603.22 - sb.append("<head>\n");
603.23 - sb.append("<style>\n");
603.24 - sb.append("div { white-space: pre; font-family: monospace; margin: 0px; padding: 0px }\n");
603.25 - sb.append(".covered { background-color: CCFFCC }\n");
603.26 - sb.append(".partial { background-color: FFFFCC }\n");
603.27 - sb.append(".not_covered { background-color: FFCCCC }\n");
603.28 - sb.append(".inferred { background-color: E0FFE0 }\n");
603.29 - sb.append(".unknown { background-color: EEEEEE }\n");
603.30 - sb.append("</style>\n");
603.31 - sb.append("</head>\n");
603.32 - sb.append("<body>\n<h1>File Coverage for ");
603.33 - sb.append(fo.getNameExt());
603.34 - sb.append("</h1>\n");
603.35 - int offset = 0;
603.36 - int lineno = 0;
603.37 - int maxLines = details.getLineCount();
603.38 - while (offset < doc.getLength() && lineno < maxLines) {
603.39 - CoverageType type = details.getType(lineno);
603.40 - String line = doc.getText(offset, Utilities.getRowEnd(doc, offset) - offset);
603.41 - sb.append("<div class=\"");
603.42 - switch (type) {
603.43 - case COVERED:
603.44 - sb.append("covered");
603.45 - break;
603.46 - case UNKNOWN:
603.47 - sb.append("unknown");
603.48 - break;
603.49 - case INFERRED:
603.50 - sb.append("inferred");
603.51 - break;
603.52 - case PARTIAL:
603.53 - sb.append("partial");
603.54 - break;
603.55 - case NOT_COVERED:
603.56 - sb.append("not_covered");
603.57 - break;
603.58 - }
603.59 - sb.append("\">");
603.60 - sb.append(XMLUtil.toElementContent(line));
603.61 - sb.append("</div>\n");
603.62 -
603.63 - offset = Utilities.getRowEnd(doc, offset) + 1;
603.64 - lineno++;
603.65 - }
603.66 -
603.67 - sb.append("\n</body></html>\n");
603.68 -
603.69 - return sb.toString();
603.70 - }
603.71 -
603.72 - public static void checkCoverage(GsfTestBase test, String projectPath, String exeFile) throws Exception {
603.73 - FileObject projectDir = test.getTestFile(projectPath);
603.74 - GsfTestBase.assertNotNull(projectDir);
603.75 - String relFilePath = projectPath + "/" + exeFile; // NOI18N
603.76 - FileObject fo = test.getTestFile(relFilePath);
603.77 - GsfTestBase.assertNotNull(fo);
603.78 - BaseDocument doc = test.getDocument(fo);
603.79 - GsfTestBase.assertNotNull(doc);
603.80 -
603.81 - Project project = ProjectManager.getDefault().findProject(projectDir);
603.82 - GsfTestBase.assertNotNull(project);
603.83 - CoverageProvider provider = project.getLookup().lookup(CoverageProvider.class);
603.84 - GsfTestBase.assertNotNull(provider);
603.85 - GsfTestBase.assertTrue(provider.isEnabled());
603.86 - FileCoverageDetails details = provider.getDetails(fo, doc);
603.87 -
603.88 - String annotatedSource = annotateCoverage(provider, fo, details, doc);
603.89 - test.assertDescriptionMatches(relFilePath, annotatedSource, false, ".coverage.html");
603.90 - }
603.91 -}
603.92 -
604.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/codecoverage/PythonCoverageProviderTest.java Sun Jan 04 13:11:53 2015 -0600
604.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
604.3 @@ -1,134 +0,0 @@
604.4 -/*
604.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
604.6 - *
604.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
604.8 - *
604.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
604.10 - * Other names may be trademarks of their respective owners.
604.11 - *
604.12 - * The contents of this file are subject to the terms of either the GNU
604.13 - * General Public License Version 2 only ("GPL") or the Common
604.14 - * Development and Distribution License("CDDL") (collectively, the
604.15 - * "License"). You may not use this file except in compliance with the
604.16 - * License. You can obtain a copy of the License at
604.17 - * http://www.netbeans.org/cddl-gplv2.html
604.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
604.19 - * specific language governing permissions and limitations under the
604.20 - * License. When distributing the software, include this License Header
604.21 - * Notice in each file and include the License file at
604.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
604.23 - * particular file as subject to the "Classpath" exception as provided
604.24 - * by Oracle in the GPL Version 2 section of the License file that
604.25 - * accompanied this code. If applicable, add the following below the
604.26 - * License Header, with the fields enclosed by brackets [] replaced by
604.27 - * your own identifying information:
604.28 - * "Portions Copyrighted [year] [name of copyright owner]"
604.29 - *
604.30 - * If you wish your version of this file to be governed by only the CDDL
604.31 - * or only the GPL Version 2, indicate your decision by adding
604.32 - * "[Contributor] elects to include this software in this distribution
604.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
604.34 - * single choice of license, a recipient has the option to distribute
604.35 - * your version of this file under either the CDDL, the GPL Version 2 or
604.36 - * to extend the choice of license to its licensees as provided above.
604.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
604.38 - * Version 2 license, then the option applies only if the new code is
604.39 - * made subject to such option by the copyright holder.
604.40 - *
604.41 - * Contributor(s):
604.42 - *
604.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
604.44 - */
604.45 -package org.netbeans.modules.python.editor.codecoverage;
604.46 -
604.47 -import java.util.concurrent.Future;
604.48 -import org.netbeans.api.project.Project;
604.49 -import org.netbeans.editor.BaseDocument;
604.50 -import org.netbeans.modules.python.api.PythonExecution;
604.51 -import org.netbeans.modules.python.api.PythonPlatform;
604.52 -import org.netbeans.modules.python.api.PythonPlatformManager;
604.53 -import org.netbeans.modules.python.editor.PythonTestBase;
604.54 -import org.openide.filesystems.FileObject;
604.55 -import org.openide.filesystems.FileUtil;
604.56 -
604.57 -/**
604.58 - *
604.59 - * @author Tor Norbye
604.60 - */
604.61 -public class PythonCoverageProviderTest extends PythonTestBase {
604.62 - public PythonCoverageProviderTest(String name) {
604.63 - super(name);
604.64 - }
604.65 -
604.66 - private void recordCoverage(String projectPath, String exeFile) throws Exception {
604.67 - Project project = getTestProject(projectPath);
604.68 - assertNotNull(project);
604.69 - PythonCoverageProvider provider = PythonCoverageProvider.get(project);
604.70 - assertNotNull(provider);
604.71 -
604.72 - provider.setEnabled(true);
604.73 -
604.74 - String relFilePath = projectPath + "/" + exeFile; // NOI18N
604.75 - FileObject fo = getTestFile(relFilePath);
604.76 - assertNotNull(fo);
604.77 - BaseDocument doc = getDocument(fo);
604.78 - assertNotNull(doc);
604.79 -
604.80 - String script = FileUtil.toFile(fo).getAbsolutePath();
604.81 - PythonExecution pyexec = new PythonExecution();
604.82 - pyexec.setDisplayName(fo.getName());
604.83 - String path = FileUtil.toFile(project.getProjectDirectory()).getAbsolutePath();
604.84 - pyexec.setWorkingDirectory(path);
604.85 - PythonPlatformManager manager = PythonPlatformManager.getInstance();
604.86 - PythonPlatform platform = manager.getPlatform(manager.getDefaultPlatform());
604.87 - pyexec.setCommand(platform.getInterpreterCommand());
604.88 - pyexec.setScript(script);
604.89 - pyexec.setCommandArgs(platform.getInterpreterArgs());
604.90 - pyexec.setShowControls(false);
604.91 - pyexec.setShowInput(false);
604.92 - pyexec.setShowWindow(false);
604.93 - pyexec.addStandardRecognizers();
604.94 -
604.95 - pyexec = provider.wrapWithCoverage(pyexec);
604.96 - Future<Integer> run = pyexec.run();
604.97 - run.get();
604.98 - }
604.99 -
604.100 - private void checkCoverage(String projectPath, String exeFile) throws Exception {
604.101 - checkCoverage(projectPath, exeFile, exeFile);
604.102 - }
604.103 -
604.104 - private void checkCoverage(String projectPath, String exeFile, String checkFile) throws Exception {
604.105 - recordCoverage(projectPath, exeFile);
604.106 - // TODO - assert that we have coverage data run at this point... might be delayed..
604.107 - // Perhaps add a little delay
604.108 - try {
604.109 - Thread.sleep(1000);
604.110 - } catch (InterruptedException ire) {
604.111 - fail();
604.112 - }
604.113 -
604.114 - CodeCoverageTestHelper.checkCoverage(this, projectPath, checkFile);
604.115 - }
604.116 -
604.117 - public void testCoverage1() throws Exception {
604.118 - checkCoverage("testfiles/codecoverage/CoveragePrj", "src/coverageprj.py");
604.119 - }
604.120 -
604.121 - public void testCoverage2() throws Exception {
604.122 - checkCoverage("testfiles/codecoverage/CoveragePrj", "src/md5driver.py");
604.123 - }
604.124 -
604.125 - public void testCoverage3() throws Exception {
604.126 - checkCoverage("testfiles/codecoverage/CoveragePrj", "src/coverageprj2.py");
604.127 - }
604.128 -
604.129 - public void testCoverage4() throws Exception {
604.130 - checkCoverage("testfiles/codecoverage/CoveragePrj", "src/coverageprj3.py");
604.131 - }
604.132 -
604.133 - public void testCoverage5() throws Exception {
604.134 - checkCoverage("testfiles/codecoverage/CoveragePrj2", "src/romantest9.py", "src/roman9.py");
604.135 - }
604.136 -
604.137 -}
605.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/elements/IndexedElementTest.java Sun Jan 04 13:11:53 2015 -0600
605.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
605.3 @@ -1,473 +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.elements;
605.47 -
605.48 -import java.net.URL;
605.49 -import java.util.List;
605.50 -import org.netbeans.modules.gsf.api.CompilationInfo;
605.51 -import org.netbeans.modules.gsf.api.Index.SearchResult;
605.52 -import org.netbeans.modules.python.editor.PythonAstUtils;
605.53 -import org.netbeans.modules.python.editor.PythonIndexer;
605.54 -import org.netbeans.modules.python.editor.PythonTestBase;
605.55 -import org.netbeans.modules.python.editor.RstFormatter;
605.56 -import org.python.antlr.PythonTree;
605.57 -
605.58 -/**
605.59 - *
605.60 - * @author Tor Norbye
605.61 - */
605.62 -public class IndexedElementTest extends PythonTestBase {
605.63 -
605.64 - public IndexedElementTest(String name) {
605.65 - super(name);
605.66 - }
605.67 -
605.68 - @Override
605.69 - protected List<URL> getExtraCpUrls() {
605.70 - // I'm overriding various Jython classes here for tests which causes
605.71 - // confusion when it's trying to locate classes and finds it in multiple places
605.72 -// if (!skipJython) {
605.73 -// return super.getExtraCpUrls();
605.74 -// }
605.75 -
605.76 - return null;
605.77 - }
605.78 -
605.79 - public void checkCreate(String testFile) throws Exception {
605.80 - List<SearchResult> maps;
605.81 - if (testFile.endsWith(".indexed")) {
605.82 - maps = createTestMapsFromIndexFile(getTestFile(testFile));
605.83 - } else {
605.84 - maps = createTestMaps(getTestFile(testFile));
605.85 - }
605.86 -
605.87 -// PythonIndex pythonIndex = PythonIndex.get(null, null);
605.88 -
605.89 - int mapNo = -1;
605.90 - for (SearchResult map : maps) {
605.91 - mapNo++;
605.92 -
605.93 - //if (mapNo < 1853) {
605.94 - // continue;
605.95 - //}
605.96 -
605.97 - String url = map.getPersistentUrl();
605.98 - assertNotNull(url);
605.99 -
605.100 -// String clz = map.getValue("class");
605.101 -// if (clz != null) {
605.102 -// String fqn = map.getValue("fqn");
605.103 -// String attrs = map.getValue("clzattrs");
605.104 -//
605.105 -// String originalAttrs = attrs;
605.106 -// if (attrs != null) {
605.107 -// int flags = IndexedElement.stringToFlags(attrs);
605.108 -// if (flags != 0) {
605.109 -// int begin = attrs.indexOf("|");
605.110 -// assertTrue(begin != -1);
605.111 -// int end = attrs.indexOf(';', begin);
605.112 -// if (end == -1) {
605.113 -// end = attrs.length();
605.114 -// }
605.115 -// attrs = attrs.substring(0, begin) + IndexedElement.encode(flags) + attrs.substring(end);
605.116 -// ((TestSearchResult)map).setValue("attrs", attrs);
605.117 -//
605.118 -// }
605.119 -// }
605.120 -//
605.121 -// IndexedClass cm = rubyIndex.createClass(fqn, clz, map);
605.122 -//
605.123 -// if (originalAttrs != null) {
605.124 -// if (originalAttrs.indexOf("|STATIC") != -1) {
605.125 -// assertTrue(fqn+";"+originalAttrs, cm.isStatic());
605.126 -// }
605.127 -// if (originalAttrs.indexOf("|NODOC") != -1) {
605.128 -// assertTrue(fqn+";"+originalAttrs, cm.isNoDoc());
605.129 -// }
605.130 -// if (originalAttrs.indexOf("|TOP_LEVEL") != -1) {
605.131 -// assertTrue(fqn+";"+originalAttrs, cm.isTopLevel());
605.132 -// }
605.133 -// if (originalAttrs.indexOf("|DOCUMENTED") != -1) {
605.134 -// assertTrue(fqn+";"+originalAttrs, cm.isDocumented());
605.135 -// }
605.136 -// if (originalAttrs.indexOf("|PRIVATE") != -1) {
605.137 -// assertTrue(fqn+";"+originalAttrs, cm.isPrivate());
605.138 -// }
605.139 -// if (originalAttrs.indexOf("|PROTECTED") != -1) {
605.140 -// assertTrue(fqn+";"+originalAttrs, cm.isProtected());
605.141 -// }
605.142 -// }
605.143 -//
605.144 -// boolean skip = false;
605.145 -// // Skip known problems
605.146 -// skip = !Character.isUpperCase(cm.getName().charAt(0));
605.147 -// if (url.endsWith("/action_controller.rb") || url.endsWith("/active_record.rb") || url.endsWith("/action_mailer.rb") || url.endsWith("/action_view.rb")) {
605.148 -// // These classes are faked up by RubyIndexer
605.149 -// skip = true;
605.150 -// }
605.151 -// if (fqn.equals("Object")) {
605.152 -// // Top level methods may not specify Object
605.153 -// skip = true;
605.154 -// }
605.155 -//
605.156 -// if (!skip) {
605.157 -// assertEquals(url, cm.getFileUrl());
605.158 -// assertNotNull(cm.getFileUrl(), cm.getFileObject());
605.159 -// CompilationInfo[] compilationInfoHolder = new CompilationInfo[1];
605.160 -// PythonTree node = AstUtilities.getForeignNode(cm, compilationInfoHolder);
605.161 -// assertNotNull("Map " + mapNo + ", url=" + url + ":" + fqn, node);
605.162 -// } // else: Lots of problems with lowerclass class names - comes from anonymous classes assigned to variables
605.163 -// }
605.164 -
605.165 - String[] methods = map.getValues("member");
605.166 - if (methods != null) {
605.167 - //System.err.println("Checking url " + url + ", " + methods.length + " methods");
605.168 - int methodCount = -1;
605.169 - for (String signature : methods) {
605.170 - methodCount++;
605.171 - //String methodName = signature.substring(0, signature.indexOf('('));
605.172 - String originalSignature = signature;
605.173 - int flags = IndexedMethod.stringToFlags(signature);
605.174 - if (flags != 0) {
605.175 - int begin = signature.indexOf("|",1); //1: "|" is a valid method name
605.176 - assertTrue(begin != -1);
605.177 - int end = signature.indexOf(';', begin);
605.178 - if (end == -1) {
605.179 - end = signature.length();
605.180 - }
605.181 - signature = signature.substring(0, begin) + IndexedElement.encode(flags) + signature.substring(end);
605.182 - }
605.183 -
605.184 - String clz = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
605.185 - String module = map.getValue(PythonIndexer.FIELD_IN);
605.186 - IndexedElement method = IndexedElement.create(signature, module, url, clz);
605.187 -
605.188 - assertEquals(url, method.getFilenameUrl());
605.189 -
605.190 - if (originalSignature.indexOf("|STATIC") != -1) {
605.191 - assertTrue(originalSignature, method.isStatic());
605.192 - }
605.193 - if (originalSignature.indexOf("|DEPRECATED") != -1) {
605.194 - assertTrue(originalSignature, method.isDeprecated());
605.195 - }
605.196 - if (originalSignature.indexOf("|NODOC") != -1) {
605.197 - assertTrue(originalSignature, method.isNoDoc());
605.198 - }
605.199 -// if (originalSignature.indexOf("|BLOCK_OPTIONAL") != -1) {
605.200 -// assertTrue(originalSignature, method.isBlockOptional());
605.201 -// }
605.202 -// if (originalSignature.indexOf("|TOP_LEVEL") != -1) {
605.203 -// assertTrue(originalSignature, method.isTopLevel());
605.204 -// }
605.205 - if (originalSignature.indexOf("|DOCUMENTED") != -1) {
605.206 - assertTrue(originalSignature, method.isDocumented());
605.207 - }
605.208 - if (originalSignature.indexOf("|PRIVATE") != -1) {
605.209 - assertTrue(originalSignature, method.isPrivate());
605.210 - }
605.211 -// if (originalSignature.indexOf("|PROTECTED") != -1) {
605.212 -// assertTrue(originalSignature, method.isProtected());
605.213 -// }
605.214 -
605.215 -// // Known exceptions
605.216 -// if (url.endsWith("/schema_definitions.rb")) {
605.217 -// // These are generated dynamically, no actual AST node
605.218 -// continue;
605.219 -// }
605.220 -// // The bug here is that there is a sessions_key local variable we store
605.221 -// // a class on -- but this isn't a class named session_key!!
605.222 -// // Too late to mess with that now
605.223 -// if (url.endsWith("/scenario_runner.rb")) {
605.224 -// continue;
605.225 -// }
605.226 -// if (url.endsWith("/drb_server.rb")) {
605.227 -// continue;
605.228 -// }
605.229 -// if (url.endsWith("/set.rb")) {
605.230 -// // Another innerclass
605.231 -// continue;
605.232 -// }
605.233 -// if (url.endsWith("/testrunner.rb")) {
605.234 -// // Another innerclass
605.235 -// continue;
605.236 -// }
605.237 -// if (signature.indexOf("hyphenate_to") != -1) {
605.238 -// continue;
605.239 -// }
605.240 -
605.241 - assertNotNull(method.getFilenameUrl(), method.getFileObject());
605.242 - if (method.isDocumented()) {
605.243 - String doc = RstFormatter.getDocumentation(method);
605.244 - //CompilationInfo[] compilationInfoHolder = new CompilationInfo[1];
605.245 - //PythonTree node = PythonAstUtils.getForeignNode(method, compilationInfoHolder);
605.246 - //assertNotNull("Map " + mapNo + ":" + methodCount + ", url=" + url + ":" + signature + "; " + method.getSignature(), node);
605.247 - assertTrue(method.attributes, doc != null && doc.length() > 0);
605.248 - }
605.249 - if (method.isDocOnly()) {
605.250 - assertTrue(method.getFilenameUrl().indexOf(".rst") != -1);
605.251 - }
605.252 - if (!method.getFilenameUrl().endsWith(".rst")) {
605.253 - CompilationInfo[] compilationInfoHolder = new CompilationInfo[1];
605.254 - PythonTree node = PythonAstUtils.getForeignNode(method, compilationInfoHolder);
605.255 - assertNotNull("Map " + mapNo + ":" + methodCount + ", url=" + url + ":" + signature + "; " + method.getSignature(), node);
605.256 - }
605.257 - }
605.258 - }
605.259 -
605.260 - String[] items = map.getValues("items");
605.261 - if (items != null) {
605.262 - //System.err.println("Checking url " + url + ", " + items.length + " methods");
605.263 - int methodCount = -1;
605.264 - for (String signature : items) {
605.265 - methodCount++;
605.266 - String originalSignature = signature;
605.267 - int flags = IndexedMethod.stringToFlags(signature);
605.268 - if (flags != 0) {
605.269 - int begin = signature.indexOf("|",1); //1: "|" is a valid method name
605.270 - assertTrue(begin != -1);
605.271 - int end = signature.indexOf(';', begin);
605.272 - if (end == -1) {
605.273 - end = signature.length();
605.274 - }
605.275 - signature = signature.substring(0, begin) + IndexedElement.encode(flags) + signature.substring(end);
605.276 - }
605.277 -
605.278 - String module = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
605.279 - IndexedElement method = IndexedElement.create(signature, module, url, null);
605.280 -
605.281 - assertEquals(url, method.getFilenameUrl());
605.282 -
605.283 - if (originalSignature.indexOf("|STATIC") != -1) {
605.284 - assertTrue(originalSignature, method.isStatic());
605.285 - }
605.286 - if (originalSignature.indexOf("|DEPRECATED") != -1) {
605.287 - assertTrue(originalSignature, method.isDeprecated());
605.288 - }
605.289 - if (originalSignature.indexOf("|NODOC") != -1) {
605.290 - assertTrue(originalSignature, method.isNoDoc());
605.291 - }
605.292 -// if (originalSignature.indexOf("|BLOCK_OPTIONAL") != -1) {
605.293 -// assertTrue(originalSignature, method.isBlockOptional());
605.294 -// }
605.295 -// if (originalSignature.indexOf("|TOP_LEVEL") != -1) {
605.296 -// assertTrue(originalSignature, method.isTopLevel());
605.297 -// }
605.298 - if (originalSignature.indexOf("|DOCUMENTED") != -1) {
605.299 - assertTrue(originalSignature, method.isDocumented());
605.300 - }
605.301 - if (originalSignature.indexOf("|PRIVATE") != -1) {
605.302 - assertTrue(originalSignature, method.isPrivate());
605.303 - }
605.304 -// if (originalSignature.indexOf("|PROTECTED") != -1) {
605.305 -// assertTrue(originalSignature, method.isProtected());
605.306 -// }
605.307 -
605.308 -// // Known exceptions
605.309 -// if (url.endsWith("/schema_definitions.rb")) {
605.310 -// // These are generated dynamically, no actual AST node
605.311 -// continue;
605.312 -// }
605.313 -// // The bug here is that there is a sessions_key local variable we store
605.314 -// // a class on -- but this isn't a class named session_key!!
605.315 -// // Too late to mess with that now
605.316 -// if (url.endsWith("/scenario_runner.rb")) {
605.317 -// continue;
605.318 -// }
605.319 -// if (url.endsWith("/drb_server.rb")) {
605.320 -// continue;
605.321 -// }
605.322 -// if (url.endsWith("/set.rb")) {
605.323 -// // Another innerclass
605.324 -// continue;
605.325 -// }
605.326 -// if (url.endsWith("/testrunner.rb")) {
605.327 -// // Another innerclass
605.328 -// continue;
605.329 -// }
605.330 -// if (signature.indexOf("hyphenate_to") != -1) {
605.331 -// continue;
605.332 -// }
605.333 -
605.334 - assertNotNull(method.getFilenameUrl(), method.getFileObject());
605.335 - if (method.isDocumented()) {
605.336 - String doc = RstFormatter.getDocumentation(method);
605.337 - assertTrue(doc != null && doc.length() > 0);
605.338 - }
605.339 - if (method.isDocOnly()) {
605.340 - assertTrue(method.getFilenameUrl().indexOf(".rst") != -1);
605.341 - }
605.342 -
605.343 - if (!method.getFilenameUrl().endsWith(".rst")) {
605.344 - CompilationInfo[] compilationInfoHolder = new CompilationInfo[1];
605.345 - PythonTree node = PythonAstUtils.getForeignNode(method, compilationInfoHolder);
605.346 - assertNotNull("Map " + mapNo + ":" + methodCount + ", url=" + url + ":" + signature + "; " + method.getSignature(), node);
605.347 - }
605.348 - }
605.349 - }
605.350 -
605.351 - }
605.352 - }
605.353 -
605.354 - public void testIndex1() throws Exception {
605.355 - checkCreate("testfiles/ConfigParser.py.indexed");
605.356 - }
605.357 -
605.358 - public void testIndex2() throws Exception {
605.359 - checkCreate("testfiles/datetime.py.indexed");
605.360 - }
605.361 -
605.362 - public void testIndex3() throws Exception {
605.363 - checkCreate("testfiles/doc.py.indexed");
605.364 - }
605.365 -
605.366 - public void testIndex4() throws Exception {
605.367 - checkCreate("testfiles/md5.py.indexed");
605.368 - }
605.369 -
605.370 - public void testIndex5() throws Exception {
605.371 - checkCreate("testfiles/scope.py.indexed");
605.372 - }
605.373 -
605.374 - public void testIndex6() throws Exception {
605.375 - checkCreate("testfiles/httplib.py.indexed");
605.376 - }
605.377 -
605.378 - public void testIndex7() throws Exception {
605.379 - checkCreate("testfiles/minicompat.py.indexed");
605.380 - }
605.381 -
605.382 - public void testIndex8() throws Exception {
605.383 - checkCreate("testfiles/socket.py.indexed");
605.384 - }
605.385 -
605.386 - public void testIndex9() throws Exception {
605.387 - checkCreate("testfiles/jreload.py.indexed");
605.388 - }
605.389 -
605.390 - public void testIndex10() throws Exception {
605.391 - checkCreate("testfiles/doctest.py.indexed");
605.392 - }
605.393 -
605.394 - public void testIndex11() throws Exception {
605.395 - checkCreate("testfiles/zipfile.py");
605.396 - }
605.397 -
605.398 - public void testIndex12() throws Exception {
605.399 - checkCreate("testfiles/os.py");
605.400 - }
605.401 -
605.402 - public void testIndex13() throws Exception {
605.403 - checkCreate("testfiles/unittest.py");
605.404 - }
605.405 -
605.406 - public void testIndex14() throws Exception {
605.407 - checkCreate("testfiles/properties.py");
605.408 - }
605.409 -
605.410 - public void testIndex15() throws Exception {
605.411 - checkCreate("testfiles/tarfile.py");
605.412 - }
605.413 -
605.414 - public void testIndex16() throws Exception {
605.415 - checkCreate("testfiles/rst/pickle.rst");
605.416 - }
605.417 -
605.418 - public void testRstIndex1() throws Exception {
605.419 - checkCreate("testfiles/rst/zipfile.rst.indexed");
605.420 - }
605.421 -
605.422 - // Known fail -- I'm not properly indexing the set < other and set > other stuff
605.423 - // in the stdtypes.rst file!
605.424 - //public void testRstIndex2() throws Exception {
605.425 - // checkCreate("testfiles/rst/stdtypes.rst.indexed");
605.426 - //}
605.427 -
605.428 - public void testRstIndex3() throws Exception {
605.429 - checkCreate("testfiles/rst/platform.rst.indexed");
605.430 - }
605.431 -
605.432 - public void testRstIndex4() throws Exception {
605.433 - checkCreate("testfiles/rst/smtpd.rst.indexed");
605.434 - }
605.435 -
605.436 - public void testRstIndex5() throws Exception {
605.437 - checkCreate("testfiles/rst/exceptions.rst.indexed");
605.438 - }
605.439 -
605.440 - public void testRstIndex6() throws Exception {
605.441 - checkCreate("testfiles/rst/logging.rst.indexed");
605.442 - }
605.443 -
605.444 - public void testRstIndex7() throws Exception {
605.445 - checkCreate("testfiles/rst/string.rst");
605.446 - }
605.447 -
605.448 - public void testRstIndex8() throws Exception {
605.449 - checkCreate("testfiles/rst/bz2.rst");
605.450 - }
605.451 -
605.452 - public void testRstIndex9() throws Exception {
605.453 - checkCreate("testfiles/rst/constants.rst");
605.454 - }
605.455 -
605.456 - public void testRstIndex10() throws Exception {
605.457 - checkCreate("testfiles/rst/operator.rst");
605.458 - }
605.459 -
605.460 - public void testRstIndex11() throws Exception {
605.461 - checkCreate("testfiles/rst/collections.rst");
605.462 - }
605.463 -
605.464 - public void testRstIndex12() throws Exception {
605.465 - checkCreate("testfiles/rst/ctypes.rst");
605.466 - }
605.467 -
605.468 - public void testRstIndex13() throws Exception {
605.469 - checkCreate("testfiles/rst/stub_missing.rst");
605.470 - }
605.471 -
605.472 -// public void testIndexEgg() throws Exception {
605.473 -// checkCreate("testfiles/antlr_python_runtime-3.1.1-py2.5.egg");
605.474 -// }
605.475 -
605.476 -}
606.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/AccessToProtectedTest.java Sun Jan 04 13:11:53 2015 -0600
606.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
606.3 @@ -1,64 +0,0 @@
606.4 -/*
606.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
606.6 - *
606.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
606.8 - *
606.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
606.10 - * Other names may be trademarks of their respective owners.
606.11 - *
606.12 - * The contents of this file are subject to the terms of either the GNU
606.13 - * General Public License Version 2 only ("GPL") or the Common
606.14 - * Development and Distribution License("CDDL") (collectively, the
606.15 - * "License"). You may not use this file except in compliance with the
606.16 - * License. You can obtain a copy of the License at
606.17 - * http://www.netbeans.org/cddl-gplv2.html
606.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
606.19 - * specific language governing permissions and limitations under the
606.20 - * License. When distributing the software, include this License Header
606.21 - * Notice in each file and include the License file at
606.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
606.23 - * particular file as subject to the "Classpath" exception as provided
606.24 - * by Oracle in the GPL Version 2 section of the License file that
606.25 - * accompanied this code. If applicable, add the following below the
606.26 - * License Header, with the fields enclosed by brackets [] replaced by
606.27 - * your own identifying information:
606.28 - * "Portions Copyrighted [year] [name of copyright owner]"
606.29 - *
606.30 - * If you wish your version of this file to be governed by only the CDDL
606.31 - * or only the GPL Version 2, indicate your decision by adding
606.32 - * "[Contributor] elects to include this software in this distribution
606.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
606.34 - * single choice of license, a recipient has the option to distribute
606.35 - * your version of this file under either the CDDL, the GPL Version 2 or
606.36 - * to extend the choice of license to its licensees as provided above.
606.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
606.38 - * Version 2 license, then the option applies only if the new code is
606.39 - * made subject to such option by the copyright holder.
606.40 - *
606.41 - * Contributor(s):
606.42 - *
606.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
606.44 - */
606.45 -
606.46 -package org.netbeans.modules.python.editor.hints;
606.47 -
606.48 -import org.netbeans.modules.python.editor.PythonTestBase;
606.49 -
606.50 -public class AccessToProtectedTest extends PythonTestBase {
606.51 -
606.52 - public AccessToProtectedTest(String testName) {
606.53 - super(testName);
606.54 - }
606.55 -
606.56 - private PythonAstRule createRule() {
606.57 - return new AccessToProtected();
606.58 - }
606.59 -
606.60 - public void testRegistered() throws Exception {
606.61 - ensureRegistered(createRule());
606.62 - }
606.63 -
606.64 - public void testAccessToProtected() throws Exception {
606.65 - findHints(this, createRule(), "testfiles/attributes.py", null, null);
606.66 - }
606.67 -}
607.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/AllAssignExistsTest.java Sun Jan 04 13:11:53 2015 -0600
607.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
607.3 @@ -1,72 +0,0 @@
607.4 -/*
607.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
607.6 - *
607.7 - * Copyright 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 - * If you wish your version of this file to be governed by only the CDDL
607.31 - * or only the GPL Version 2, indicate your decision by adding
607.32 - * "[Contributor] elects to include this software in this distribution
607.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
607.34 - * single choice of license, a recipient has the option to distribute
607.35 - * your version of this file under either the CDDL, the GPL Version 2 or
607.36 - * to extend the choice of license to its licensees as provided above.
607.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
607.38 - * Version 2 license, then the option applies only if the new code is
607.39 - * made subject to such option by the copyright holder.
607.40 - *
607.41 - * Contributor(s):
607.42 - *
607.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
607.44 - */
607.45 -
607.46 -package org.netbeans.modules.python.editor.hints;
607.47 -
607.48 -import org.netbeans.modules.python.editor.PythonTestBase;
607.49 -
607.50 -/**
607.51 - *
607.52 - * @author Tor Norbye
607.53 - */
607.54 -public class AllAssignExistsTest extends PythonTestBase {
607.55 -
607.56 - public AllAssignExistsTest(String testName) {
607.57 - super(testName);
607.58 - }
607.59 -
607.60 - private PythonAstRule createRule() {
607.61 - return new AllAssignExists();
607.62 - }
607.63 -
607.64 - public void testRegistered() throws Exception {
607.65 - ensureRegistered(createRule());
607.66 - }
607.67 -
607.68 - public void testAssign1() throws Exception {
607.69 - findHints(this, createRule(), "testfiles/all.py", null, null);
607.70 - }
607.71 -
607.72 - public void testAssign2() throws Exception {
607.73 - findHints(this, createRule(), "testfiles/all2.py", null, null);
607.74 - }
607.75 -}
608.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/AssignToVariableTest.java Sun Jan 04 13:11:53 2015 -0600
608.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
608.3 @@ -1,98 +0,0 @@
608.4 -/*
608.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
608.6 - *
608.7 - * Copyright 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 - * If you wish your version of this file to be governed by only the CDDL
608.31 - * or only the GPL Version 2, indicate your decision by adding
608.32 - * "[Contributor] elects to include this software in this distribution
608.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
608.34 - * single choice of license, a recipient has the option to distribute
608.35 - * your version of this file under either the CDDL, the GPL Version 2 or
608.36 - * to extend the choice of license to its licensees as provided above.
608.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
608.38 - * Version 2 license, then the option applies only if the new code is
608.39 - * made subject to such option by the copyright holder.
608.40 - *
608.41 - * Contributor(s):
608.42 - *
608.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
608.44 - */
608.45 -
608.46 -package org.netbeans.modules.python.editor.hints;
608.47 -
608.48 -import org.netbeans.modules.python.editor.PythonTestBase;
608.49 -
608.50 -/**
608.51 - *
608.52 - * @author Tor Norbye
608.53 - */
608.54 -public class AssignToVariableTest extends PythonTestBase {
608.55 -
608.56 - public AssignToVariableTest(String testName) {
608.57 - super(testName);
608.58 - }
608.59 -
608.60 - private PythonAstRule createRule() {
608.61 - return new AssignToVariable();
608.62 - }
608.63 -
608.64 - public void testRegistered() throws Exception {
608.65 - ensureRegistered(createRule());
608.66 - }
608.67 -
608.68 - public void testAssign1() throws Exception {
608.69 - findHints(this, createRule(), "testfiles/assign.py", null, "^\"foo\"");
608.70 - }
608.71 -
608.72 - public void testAssign2() throws Exception {
608.73 - findHints(this, createRule(), "testfiles/assign.py", null, "3+1^");
608.74 - }
608.75 -
608.76 - public void testAssign3() throws Exception {
608.77 - findHints(this, createRule(), "testfiles/assign.py", null, "^get_preprocess2");
608.78 - }
608.79 -
608.80 - public void testNoHint() throws Exception {
608.81 - findHints(this, createRule(), "testfiles/ConfigParser.py", null, "d = s^elf._defaults.copy()");
608.82 - }
608.83 -
608.84 - public void testNoHint2() throws Exception {
608.85 - findHints(this, createRule(), "testfiles/ConfigParser.py", null, "\"\"\"Raised when^ a section is multiply-created.");
608.86 - }
608.87 -
608.88 - public void testNoHint3() throws Exception {
608.89 - // Contains call that is not a getter
608.90 - findHints(this, createRule(), "testfiles/assign.py", null, "^preprocess1");
608.91 - }
608.92 -
608.93 - public void testNoHint4() throws Exception {
608.94 - // Don't assign docstrings
608.95 - findHints(this, createRule(), "testfiles/assign2.py", null, "^\"year -> 1");
608.96 - }
608.97 -
608.98 - public void testFixAssign() throws Exception {
608.99 - applyHint(this, createRule(), "testfiles/assign.py", "^3+1", "Assign");
608.100 - }
608.101 -}
609.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/AttributeDefinedOutsideInitTest.java Sun Jan 04 13:11:53 2015 -0600
609.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
609.3 @@ -1,64 +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 -
609.46 -package org.netbeans.modules.python.editor.hints;
609.47 -
609.48 -import org.netbeans.modules.python.editor.PythonTestBase;
609.49 -
609.50 -public class AttributeDefinedOutsideInitTest extends PythonTestBase {
609.51 -
609.52 - public AttributeDefinedOutsideInitTest(String testName) {
609.53 - super(testName);
609.54 - }
609.55 -
609.56 - private PythonAstRule createRule() {
609.57 - return new AttributeDefinedOutsideInit();
609.58 - }
609.59 -
609.60 - public void testRegistered() throws Exception {
609.61 - ensureRegistered(createRule());
609.62 - }
609.63 -
609.64 - public void testAttributeDefinedOutsideInit() throws Exception {
609.65 - findHints(this, createRule(), "testfiles/attributes.py", null, null);
609.66 - }
609.67 -}
610.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/ClassCircularRedundancyTest.java Sun Jan 04 13:11:53 2015 -0600
610.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
610.3 @@ -1,64 +0,0 @@
610.4 -/*
610.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
610.6 - *
610.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
610.8 - *
610.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
610.10 - * Other names may be trademarks of their respective owners.
610.11 - *
610.12 - * The contents of this file are subject to the terms of either the GNU
610.13 - * General Public License Version 2 only ("GPL") or the Common
610.14 - * Development and Distribution License("CDDL") (collectively, the
610.15 - * "License"). You may not use this file except in compliance with the
610.16 - * License. You can obtain a copy of the License at
610.17 - * http://www.netbeans.org/cddl-gplv2.html
610.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
610.19 - * specific language governing permissions and limitations under the
610.20 - * License. When distributing the software, include this License Header
610.21 - * Notice in each file and include the License file at
610.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
610.23 - * particular file as subject to the "Classpath" exception as provided
610.24 - * by Oracle in the GPL Version 2 section of the License file that
610.25 - * accompanied this code. If applicable, add the following below the
610.26 - * License Header, with the fields enclosed by brackets [] replaced by
610.27 - * your own identifying information:
610.28 - * "Portions Copyrighted [year] [name of copyright owner]"
610.29 - *
610.30 - * If you wish your version of this file to be governed by only the CDDL
610.31 - * or only the GPL Version 2, indicate your decision by adding
610.32 - * "[Contributor] elects to include this software in this distribution
610.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
610.34 - * single choice of license, a recipient has the option to distribute
610.35 - * your version of this file under either the CDDL, the GPL Version 2 or
610.36 - * to extend the choice of license to its licensees as provided above.
610.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
610.38 - * Version 2 license, then the option applies only if the new code is
610.39 - * made subject to such option by the copyright holder.
610.40 - *
610.41 - * Contributor(s):
610.42 - *
610.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
610.44 - */
610.45 -
610.46 -package org.netbeans.modules.python.editor.hints;
610.47 -
610.48 -import org.netbeans.modules.python.editor.PythonTestBase;
610.49 -
610.50 -public class ClassCircularRedundancyTest extends PythonTestBase {
610.51 -
610.52 - public ClassCircularRedundancyTest(String testName) {
610.53 - super(testName);
610.54 - }
610.55 -
610.56 - private PythonAstRule createRule() {
610.57 - return new ClassCircularRedundancy();
610.58 - }
610.59 -
610.60 - public void testRegistered() throws Exception {
610.61 - ensureRegistered(createRule());
610.62 - }
610.63 -
610.64 - public void testCircularRedundancy() throws Exception {
610.65 - findHints(this, createRule(), "testfiles/circularredundancy.py", null, null);
610.66 - }
610.67 -}
611.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/CreateDocStringTest.java Sun Jan 04 13:11:53 2015 -0600
611.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
611.3 @@ -1,68 +0,0 @@
611.4 -/*
611.5 - * To change this template, choose Tools | Templates
611.6 - * and open the template in the editor.
611.7 - */
611.8 -
611.9 -package org.netbeans.modules.python.editor.hints;
611.10 -
611.11 -import org.netbeans.modules.python.editor.PythonTestBase;
611.12 -
611.13 -/**
611.14 - *
611.15 - * @author Tor Norbye
611.16 - */
611.17 -public class CreateDocStringTest extends PythonTestBase {
611.18 -
611.19 - public CreateDocStringTest(String testName) {
611.20 - super(testName);
611.21 - }
611.22 -
611.23 - private PythonAstRule createRule() {
611.24 - return new CreateDocString();
611.25 - }
611.26 -
611.27 - public void testRegistered() throws Exception {
611.28 - ensureRegistered(createRule());
611.29 - }
611.30 -
611.31 - public void testHint1() throws Exception {
611.32 - findHints(this, createRule(), "testfiles/create_docstring.py", null, "def set^up");
611.33 - }
611.34 -
611.35 - public void testHint2() throws Exception {
611.36 - // There should be no matches here!
611.37 - findHints(this, createRule(), "testfiles/create_docstring.py", null, "a^lready");
611.38 - }
611.39 -
611.40 - public void testHint3() throws Exception {
611.41 - findHints(this, createRule(), "testfiles/create_docstring.py", null, "Datagram^RequestHandler");
611.42 - }
611.43 -
611.44 - public void testFix1() throws Exception {
611.45 - applyHint(this, createRule(), "testfiles/create_docstring.py", "def set^up", "one");
611.46 - }
611.47 -
611.48 - public void testFix2() throws Exception {
611.49 - applyHint(this, createRule(), "testfiles/create_docstring.py", "def set^up", "multi");
611.50 - }
611.51 -
611.52 - public void testFix3() throws Exception {
611.53 - applyHint(this, createRule(), "testfiles/create_docstring.py", "Datagram^RequestHandler", "one");
611.54 - }
611.55 -
611.56 - public void testFix4() throws Exception {
611.57 - applyHint(this, createRule(), "testfiles/create_docstring.py", "Datagram^RequestHandler", "multi");
611.58 - }
611.59 -
611.60 - public void testFix5() throws Exception {
611.61 - applyHint(this, createRule(), "testfiles/create_docstring2.py", "def fa^", "one");
611.62 - }
611.63 -
611.64 - public void testFix6() throws Exception {
611.65 - applyHint(this, createRule(), "testfiles/create_docstring3.py", "def fa^", "one");
611.66 - }
611.67 -
611.68 - public void testFix7() throws Exception {
611.69 - applyHint(this, createRule(), "testfiles/create_docstring4.py", "def sec^", "one");
611.70 - }
611.71 -}
612.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/DeprecationsTest.java Sun Jan 04 13:11:53 2015 -0600
612.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
612.3 @@ -1,35 +0,0 @@
612.4 -/*
612.5 - * To change this template, choose Tools | Templates
612.6 - * and open the template in the editor.
612.7 - */
612.8 -
612.9 -package org.netbeans.modules.python.editor.hints;
612.10 -
612.11 -import org.netbeans.modules.python.editor.PythonTestBase;
612.12 -
612.13 -/**
612.14 - *
612.15 - * @author Tor Norbye
612.16 - */
612.17 -public class DeprecationsTest extends PythonTestBase {
612.18 -
612.19 - public DeprecationsTest(String testName) {
612.20 - super(testName);
612.21 - }
612.22 -
612.23 - private PythonAstRule createRule() {
612.24 - return new Deprecations();
612.25 - }
612.26 -
612.27 - public void testRegistered() throws Exception {
612.28 - ensureRegistered(createRule());
612.29 - }
612.30 -
612.31 - public void testNoHints() throws Exception {
612.32 - findHints(this, createRule(), "testfiles/test_scope.py", null, null);
612.33 - }
612.34 -
612.35 - public void testDeprecations() throws Exception {
612.36 - findHints(this, createRule(), "testfiles/deprecated-imports.py", null, null);
612.37 - }
612.38 -}
613.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/ExtractCodeTest.java Sun Jan 04 13:11:53 2015 -0600
613.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
613.3 @@ -1,104 +0,0 @@
613.4 -/*
613.5 - * To change this template, choose Tools | Templates
613.6 - * and open the template in the editor.
613.7 - */
613.8 -
613.9 -package org.netbeans.modules.python.editor.hints;
613.10 -
613.11 -import org.netbeans.modules.python.editor.PythonTestBase;
613.12 -
613.13 -/**
613.14 - *
613.15 - * @author Tor Norbye
613.16 - */
613.17 -public class ExtractCodeTest extends PythonTestBase {
613.18 -
613.19 - public ExtractCodeTest(String testName) {
613.20 - super(testName);
613.21 - }
613.22 -
613.23 - private PythonSelectionRule createRule() {
613.24 - return new ExtractCode();
613.25 - }
613.26 -
613.27 - public void testRegistered() throws Exception {
613.28 - ensureRegistered(createRule());
613.29 - }
613.30 -
613.31 - public void testHint1() throws Exception {
613.32 - checkHints(createRule(), "testfiles/extract1.py",
613.33 - "^# Beginning of extraction segment",
613.34 - "# End of extraction segment^");
613.35 - }
613.36 -
613.37 - public void testFix1() throws Exception {
613.38 - applyHint(this, createRule(), "testfiles/extract1.py",
613.39 - "^# Beginning of extraction segment",
613.40 - "# End of extraction segment^",
613.41 - "Extract Method", true);
613.42 - }
613.43 -
613.44 - public void testFix1b() throws Exception {
613.45 - applyHint(this, createRule(), "testfiles/extract1.py",
613.46 - "^ # Beginning of extraction segment",
613.47 - "# End of extraction segment^",
613.48 - "Extract Method", true);
613.49 - }
613.50 -
613.51 - public void testFix2() throws Exception {
613.52 - applyHint(this, createRule(), "testfiles/extract2.py",
613.53 - "^simple_code = 1",
613.54 - "simple_code = simple_code+1^",
613.55 - "Extract Method", true);
613.56 - }
613.57 -
613.58 - public void testFix3() throws Exception {
613.59 - applyHint(this, createRule(), "testfiles/extract2.py",
613.60 - "^not_used = 1",
613.61 - "print simple_code + not_used^",
613.62 - "Extract Method", true);
613.63 - }
613.64 -
613.65 - public void testFix4() throws Exception {
613.66 - applyHint(this, createRule(), "testfiles/datetime.py",
613.67 - "^assert 1 <= month <= 12, month",
613.68 - "assert 1 <= month <= 12, month^",
613.69 - "Extract Method", true);
613.70 - }
613.71 -
613.72 - public void testFix5() throws Exception {
613.73 - // 150932: Quickfix extract method does not change all instances of the chosen name
613.74 - applyHint(this, createRule(), "testfiles/extract4.py",
613.75 - "^if _a >a:",
613.76 - "c = b^",
613.77 - "Extract Method", true);
613.78 - }
613.79 -
613.80 - public void testFix6() throws Exception {
613.81 - applyHint(this, createRule(), "testfiles/extract5.py",
613.82 - "^if _a >a:",
613.83 - "c = b^",
613.84 - "Extract Method", true);
613.85 - }
613.86 -
613.87 - public void testFix7() throws Exception {
613.88 - applyHint(this, createRule(), "testfiles/extract1.py",
613.89 - "^not_used_in_block = 1",
613.90 - "read_after_block_only = 4\n^",
613.91 - "Extract Method", true);
613.92 - }
613.93 -
613.94 - //public void testFix4() throws Exception {
613.95 - // applyHint(this, createRule(), "testfiles/extract2.py",
613.96 - // "^preprocess(foo, source, output_file, macros, include_dirs, extra_preargs, extra_postargs);",
613.97 - // "get_preprocess(self, source, output_file, macros, include_dirs, extra_preargs, extra_postargs)^",
613.98 - // "Extract Method");
613.99 - //}
613.100 -
613.101 - public void testFix8() throws Exception {
613.102 - applyHint(this, createRule(), "testfiles/ConfigParser.py",
613.103 - "^try:",
613.104 - "raise NoSectionError(section)^",
613.105 - "Extract Method", true);
613.106 - }
613.107 -}
614.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/InputOutputFinderTest.java Sun Jan 04 13:11:53 2015 -0600
614.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
614.3 @@ -1,173 +0,0 @@
614.4 -/*
614.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
614.6 - *
614.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
614.8 - *
614.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
614.10 - * Other names may be trademarks of their respective owners.
614.11 - *
614.12 - * The contents of this file are subject to the terms of either the GNU
614.13 - * General Public License Version 2 only ("GPL") or the Common
614.14 - * Development and Distribution License("CDDL") (collectively, the
614.15 - * "License"). You may not use this file except in compliance with the
614.16 - * License. You can obtain a copy of the License at
614.17 - * http://www.netbeans.org/cddl-gplv2.html
614.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
614.19 - * specific language governing permissions and limitations under the
614.20 - * License. When distributing the software, include this License Header
614.21 - * Notice in each file and include the License file at
614.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
614.23 - * particular file as subject to the "Classpath" exception as provided
614.24 - * by Oracle in the GPL Version 2 section of the License file that
614.25 - * accompanied this code. If applicable, add the following below the
614.26 - * License Header, with the fields enclosed by brackets [] replaced by
614.27 - * your own identifying information:
614.28 - * "Portions Copyrighted [year] [name of copyright owner]"
614.29 - *
614.30 - * If you wish your version of this file to be governed by only the CDDL
614.31 - * or only the GPL Version 2, indicate your decision by adding
614.32 - * "[Contributor] elects to include this software in this distribution
614.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
614.34 - * single choice of license, a recipient has the option to distribute
614.35 - * your version of this file under either the CDDL, the GPL Version 2 or
614.36 - * to extend the choice of license to its licensees as provided above.
614.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
614.38 - * Version 2 license, then the option applies only if the new code is
614.39 - * made subject to such option by the copyright holder.
614.40 - *
614.41 - * Contributor(s):
614.42 - *
614.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
614.44 - */
614.45 -
614.46 -package org.netbeans.modules.python.editor.hints;
614.47 -
614.48 -import java.util.Collections;
614.49 -import java.util.HashSet;
614.50 -import java.util.List;
614.51 -import java.util.Set;
614.52 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
614.53 -import org.netbeans.modules.python.editor.AstPath;
614.54 -import org.netbeans.modules.python.editor.PythonAstUtils;
614.55 -import org.netbeans.modules.python.editor.PythonTestBase;
614.56 -import org.python.antlr.PythonTree;
614.57 -
614.58 -/**
614.59 - *
614.60 - * @author Tor Norbye
614.61 - */
614.62 -public class InputOutputFinderTest extends PythonTestBase {
614.63 -
614.64 - public InputOutputFinderTest(String name) {
614.65 - super(name);
614.66 - }
614.67 -
614.68 - InputOutputFinder getFinder(String source) throws Exception {
614.69 - String BEGIN = "%<%"; // NOI18N
614.70 - String END = "%>%"; // NOI18N
614.71 - int sourceStartPos = source.indexOf(BEGIN);
614.72 - if (sourceStartPos != -1) {
614.73 - source = source.substring(0, sourceStartPos) + source.substring(sourceStartPos+BEGIN.length());
614.74 - }
614.75 -
614.76 - int caretPos = source.indexOf('^');
614.77 - if (caretPos != -1) {
614.78 - source = source.substring(0, caretPos) + source.substring(caretPos+1);
614.79 - }
614.80 -
614.81 - int sourceEndPos = source.indexOf(END);
614.82 - if (sourceEndPos != -1) {
614.83 - source = source.substring(0, sourceEndPos) + source.substring(sourceEndPos+END.length());
614.84 - }
614.85 -
614.86 - GsfTestCompilationInfo info = getInfoForText(source, "temp.py");
614.87 - assertNotNull(info);
614.88 -
614.89 - if (caretPos != -1) {
614.90 - info.setCaretOffset(caretPos);
614.91 - }
614.92 -
614.93 - PythonTree root = PythonAstUtils.getRoot(info);
614.94 - assertNotNull(root);
614.95 -
614.96 - PythonTree startNode = AstPath.get(root, sourceStartPos).leaf();
614.97 - PythonTree endNode = AstPath.get(root, sourceEndPos).leaf();
614.98 -
614.99 - List<PythonTree> applicableBlocks = Collections.emptyList();
614.100 - InputOutputFinder finder = new InputOutputFinder(startNode, endNode, applicableBlocks);
614.101 -
614.102 - PythonTree scope = PythonAstUtils.getLocalScope(AstPath.get(root, sourceStartPos));
614.103 - assertNotNull(scope);
614.104 - finder.visit(scope);
614.105 -
614.106 - return finder;
614.107 - }
614.108 -
614.109 - public void testCall() throws Exception {
614.110 - InputOutputFinder finder = getFinder("foo = 1;\n%<%foo()%>%\nprint foo\n");
614.111 - Set<String> inputVars = finder.getInputVars();
614.112 - assertEquals(Collections.emptySet(), inputVars);
614.113 -
614.114 - Set<String> outputVars = finder.getOutputVars();
614.115 - assertEquals(Collections.emptySet(), outputVars);
614.116 - }
614.117 -
614.118 - public void testVariableRead() throws Exception {
614.119 - InputOutputFinder finder = getFinder("x = 1\ny = 2\n%<%print x+y%>%");
614.120 - Set<String> inputVars = finder.getInputVars();
614.121 - Set<String> expected = new HashSet<String>() {{
614.122 - add("x");
614.123 - add("y");
614.124 - }};
614.125 - assertEquals(expected, inputVars);
614.126 -
614.127 - Set<String> outputVars = finder.getOutputVars();
614.128 - assertEquals(Collections.emptySet(), outputVars);
614.129 - }
614.130 -
614.131 - public void testVariableWrite() throws Exception {
614.132 - InputOutputFinder finder = getFinder("%<%y = 1%>%\nprint y\n");
614.133 - Set<String> inputVars = finder.getInputVars();
614.134 - assertEquals(Collections.emptySet(), inputVars);
614.135 -
614.136 - Set<String> outputVars = finder.getOutputVars();
614.137 - Set<String> expected = new HashSet<String>() {{
614.138 - add("y");
614.139 - }};
614.140 - assertEquals(expected, outputVars);
614.141 - }
614.142 -
614.143 - public void testIncrement() throws Exception {
614.144 - InputOutputFinder finder = getFinder("%<%x = x + 1%>%\nprint x");
614.145 - Set<String> inputVars = finder.getInputVars();
614.146 - Set<String> expected = new HashSet<String>() {{
614.147 - add("x");
614.148 - }};
614.149 - assertEquals(expected, inputVars);
614.150 -
614.151 - Set<String> outputVars = finder.getOutputVars();
614.152 - expected = new HashSet<String>() {{
614.153 - add("x");
614.154 - }};
614.155 - assertEquals(expected, outputVars);
614.156 - }
614.157 -
614.158 -
614.159 - public void testAssignment() throws Exception {
614.160 - InputOutputFinder finder = getFinder(
614.161 - "x = 5\n" +
614.162 - "%<%y = x + 1%>%\n" +
614.163 - "print y");
614.164 - Set<String> inputVars = finder.getInputVars();
614.165 - Set<String> expected = new HashSet<String>() {{
614.166 - add("x");
614.167 - }};
614.168 - assertEquals(expected, inputVars);
614.169 -
614.170 - Set<String> outputVars = finder.getOutputVars();
614.171 - expected = new HashSet<String>() {{
614.172 - add("y");
614.173 - }};
614.174 - assertEquals(expected, outputVars);
614.175 - }
614.176 -}
615.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/NameRuleTest.java Sun Jan 04 13:11:53 2015 -0600
615.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
615.3 @@ -1,67 +0,0 @@
615.4 -/*
615.5 - * To change this template, choose Tools | Templates
615.6 - * and open the template in the editor.
615.7 - */
615.8 -package org.netbeans.modules.python.editor.hints;
615.9 -
615.10 -import org.netbeans.modules.python.editor.PythonTestBase;
615.11 -
615.12 -/**
615.13 - *
615.14 - * @author Tor Norbye
615.15 - */
615.16 -public class NameRuleTest extends PythonTestBase {
615.17 - public NameRuleTest(String testName) {
615.18 - super(testName);
615.19 - }
615.20 -
615.21 - private PythonAstRule createRule() {
615.22 - return new NameRule();
615.23 - }
615.24 -
615.25 - public void testRegistered() throws Exception {
615.26 - ensureRegistered(createRule());
615.27 - }
615.28 -
615.29 - public void testHint1() throws Exception {
615.30 - findHints(this, createRule(), "testfiles/ConfigParser.py", null, null);
615.31 - }
615.32 -
615.33 - public void testHint2() throws Exception {
615.34 - findHints(this, createRule(), "testfiles/names.py", null, null);
615.35 - }
615.36 -
615.37 - public void testHint3() throws Exception {
615.38 - findHints(this, createRule(), "testfiles/names2.py", null, null);
615.39 - }
615.40 -
615.41 - public void testHint4() throws Exception {
615.42 - findHints(this, createRule(), "testfiles/getopt.py", null, null);
615.43 - }
615.44 -
615.45 - public void testHint5() throws Exception {
615.46 - findHints(this, createRule(), "testfiles/datetime.py", null, null);
615.47 - }
615.48 -
615.49 - public void testHint6() throws Exception {
615.50 - findHints(this, createRule(), "testfiles/test_scope.py", null, null);
615.51 - }
615.52 -
615.53 - public void testHint7() throws Exception {
615.54 - findHints(this, createRule(), "testfiles/staticmethods.py", null, null);
615.55 - }
615.56 -
615.57 - public void testFix1() throws Exception {
615.58 - applyHint(this, createRule(), "testfiles/names2.py",
615.59 - "^def noargs()",
615.60 - "def noargs()^",
615.61 - "Insert a new first param");
615.62 - }
615.63 -
615.64 - public void testFix2() throws Exception {
615.65 - applyHint(this, createRule(), "testfiles/names2.py",
615.66 - "^def bad2(filename)",
615.67 - "bad2(filename)^",
615.68 - "Rename");
615.69 - }
615.70 -}
616.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/NameStyleTest.java Sun Jan 04 13:11:53 2015 -0600
616.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
616.3 @@ -1,99 +0,0 @@
616.4 -/*
616.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
616.6 - *
616.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
616.8 - *
616.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
616.10 - * Other names may be trademarks of their respective owners.
616.11 - *
616.12 - * The contents of this file are subject to the terms of either the GNU
616.13 - * General Public License Version 2 only ("GPL") or the Common
616.14 - * Development and Distribution License("CDDL") (collectively, the
616.15 - * "License"). You may not use this file except in compliance with the
616.16 - * License. You can obtain a copy of the License at
616.17 - * http://www.netbeans.org/cddl-gplv2.html
616.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
616.19 - * specific language governing permissions and limitations under the
616.20 - * License. When distributing the software, include this License Header
616.21 - * Notice in each file and include the License file at
616.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
616.23 - * particular file as subject to the "Classpath" exception as provided
616.24 - * by Oracle in the GPL Version 2 section of the License file that
616.25 - * accompanied this code. If applicable, add the following below the
616.26 - * License Header, with the fields enclosed by brackets [] replaced by
616.27 - * your own identifying information:
616.28 - * "Portions Copyrighted [year] [name of copyright owner]"
616.29 - *
616.30 - * If you wish your version of this file to be governed by only the CDDL
616.31 - * or only the GPL Version 2, indicate your decision by adding
616.32 - * "[Contributor] elects to include this software in this distribution
616.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
616.34 - * single choice of license, a recipient has the option to distribute
616.35 - * your version of this file under either the CDDL, the GPL Version 2 or
616.36 - * to extend the choice of license to its licensees as provided above.
616.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
616.38 - * Version 2 license, then the option applies only if the new code is
616.39 - * made subject to such option by the copyright holder.
616.40 - *
616.41 - * Contributor(s):
616.42 - *
616.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
616.44 - */
616.45 -package org.netbeans.modules.python.editor.hints;
616.46 -
616.47 -import org.netbeans.junit.NbTestCase;
616.48 -
616.49 -/**
616.50 - *
616.51 - * @author Tor Norbye
616.52 - */
616.53 -public class NameStyleTest extends NbTestCase {
616.54 - public NameStyleTest(String name) {
616.55 - super(name);
616.56 - }
616.57 -
616.58 - public void testComplies() {
616.59 - assertTrue(NameStyle.NO_PREFERENCE.complies("foo"));
616.60 - assertTrue(NameStyle.NO_PREFERENCE.complies("s_43"));
616.61 - assertTrue(NameStyle.NO_PREFERENCE.complies("Ffoo"));
616.62 -
616.63 - assertTrue(NameStyle.CAPITALIZED_WITH_UNDERSCORES.complies("FOO"));
616.64 - assertTrue(NameStyle.CAPITALIZED_WITH_UNDERSCORES.complies("FOO_BAR"));
616.65 - assertTrue(NameStyle.CAPITALIZED_WITH_UNDERSCORES.complies("_FOO_BAR"));
616.66 - assertTrue(NameStyle.CAPITALIZED_WITH_UNDERSCORES.complies("__FOO_BAR__"));
616.67 - assertTrue(NameStyle.CAPITALIZED_WITH_UNDERSCORES.complies("FOO1"));
616.68 - assertTrue(!NameStyle.CAPITALIZED_WITH_UNDERSCORES.complies("foo"));
616.69 -
616.70 - assertTrue(NameStyle.CAPITALIZED_WORDS.complies("FooF"));
616.71 - assertTrue(NameStyle.CAPITALIZED_WORDS.complies("FooBar"));
616.72 - assertTrue(!NameStyle.CAPITALIZED_WORDS.complies("fooBar"));
616.73 - assertTrue(!NameStyle.CAPITALIZED_WORDS.complies("foobar"));
616.74 -
616.75 - assertTrue(NameStyle.LOWERCASE.complies("foobar"));
616.76 - assertTrue(NameStyle.LOWERCASE.complies("__foobar"));
616.77 - assertTrue(!NameStyle.LOWERCASE.complies("__Foobar"));
616.78 - assertTrue(!NameStyle.LOWERCASE.complies("__fooBar"));
616.79 -
616.80 - assertTrue(NameStyle.LOWERCASE_WITH_UNDERSCORES.complies("foo"));
616.81 - assertTrue(NameStyle.LOWERCASE_WITH_UNDERSCORES.complies("foo_bar"));
616.82 - assertTrue(!NameStyle.LOWERCASE_WITH_UNDERSCORES.complies("foo_Bar"));
616.83 -
616.84 - assertTrue(NameStyle.MIXED_CASE.complies("foobar"));
616.85 - assertTrue(NameStyle.MIXED_CASE.complies("fooBar"));
616.86 - assertTrue(!NameStyle.MIXED_CASE.complies("FooBar"));
616.87 - assertTrue(!NameStyle.MIXED_CASE.complies("foo_bar"));
616.88 - assertTrue(!NameStyle.MIXED_CASE.complies("Foobar"));
616.89 -
616.90 - assertTrue(NameStyle.UPPERCASE.complies("FOOBAR"));
616.91 - assertTrue(NameStyle.UPPERCASE.complies("F"));
616.92 - assertTrue(NameStyle.UPPERCASE.complies("__FOOBAR__"));
616.93 - assertTrue(NameStyle.UPPERCASE.complies("_FOOBAR"));
616.94 - assertTrue(!NameStyle.UPPERCASE.complies("FOO_BAR"));
616.95 - assertTrue(!NameStyle.UPPERCASE.complies("FooBar"));
616.96 -
616.97 - assertTrue(NameStyle.UPPERCASE_WITH_UNDERSCORES.complies("FOOBAR"));
616.98 - assertTrue(NameStyle.UPPERCASE_WITH_UNDERSCORES.complies("FOO_BAR"));
616.99 - assertTrue(NameStyle.UPPERCASE_WITH_UNDERSCORES.complies("__FOO_BAR__"));
616.100 - assertTrue(!NameStyle.UPPERCASE_WITH_UNDERSCORES.complies("FooBar"));
616.101 - }
616.102 -}
617.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/RelativeImportsTest.java Sun Jan 04 13:11:53 2015 -0600
617.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
617.3 @@ -1,59 +0,0 @@
617.4 -/*
617.5 - * To change this template, choose Tools | Templates
617.6 - * and open the template in the editor.
617.7 - */
617.8 -
617.9 -package org.netbeans.modules.python.editor.hints;
617.10 -
617.11 -import org.netbeans.modules.python.editor.PythonTestBase;
617.12 -
617.13 -/**
617.14 - *
617.15 - * @author Tor Norbye
617.16 - */
617.17 -public class RelativeImportsTest extends PythonTestBase {
617.18 -
617.19 - public RelativeImportsTest(String testName) {
617.20 - super(testName);
617.21 - }
617.22 -
617.23 - private PythonAstRule createRule() {
617.24 - return new RelativeImports();
617.25 - }
617.26 -
617.27 - public void testRegistered() throws Exception {
617.28 - ensureRegistered(createRule());
617.29 - }
617.30 -
617.31 - public void testNoHints() throws Exception {
617.32 - findHints(this, createRule(), "testfiles/pickle.py", null, null);
617.33 - }
617.34 -
617.35 - public void testHint1() throws Exception {
617.36 - findHints(this, createRule(), "testfiles/toppkg/medpkg/lowpkg/imports.py", null, null);
617.37 - }
617.38 -
617.39 - public void testHint2() throws Exception {
617.40 - findHints(this, createRule(), "testfiles/package/subpackage1/moduleX.py", null, null);
617.41 - }
617.42 -
617.43 - public void testFix1() throws Exception {
617.44 - applyHint(this, createRule(), "testfiles/toppkg/medpkg/lowpkg/imports.py", "from .m^oduleY import spam", "Replace");
617.45 - }
617.46 -
617.47 - public void testFix2() throws Exception {
617.48 - applyHint(this, createRule(), "testfiles/toppkg/medpkg/lowpkg/imports.py", "fr^om ..subpackage1 import moduleY", "Replace");
617.49 - }
617.50 -
617.51 - public void testFix3() throws Exception {
617.52 - applyHint(this, createRule(), "testfiles/toppkg/medpkg/lowpkg/imports.py", "fr^om ...package import bar", "Replace");
617.53 - }
617.54 -
617.55 - public void testFix4() throws Exception {
617.56 - applyHint(this, createRule(), "testfiles/package/subpackage1/moduleX.py", "f^rom . import moduleY", "Replace");
617.57 - }
617.58 -
617.59 - public void testFix5() throws Exception {
617.60 - applyHint(this, createRule(), "testfiles/package/subpackage1/moduleX.py", "from .m^oduleY import spam", "Replace");
617.61 - }
617.62 -}
618.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/SplitImportsTest.java Sun Jan 04 13:11:53 2015 -0600
618.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
618.3 @@ -1,39 +0,0 @@
618.4 -/*
618.5 - * To change this template, choose Tools | Templates
618.6 - * and open the template in the editor.
618.7 - */
618.8 -
618.9 -package org.netbeans.modules.python.editor.hints;
618.10 -
618.11 -import org.netbeans.modules.python.editor.PythonTestBase;
618.12 -
618.13 -/**
618.14 - *
618.15 - * @author Tor Norbye
618.16 - */
618.17 -public class SplitImportsTest extends PythonTestBase {
618.18 -
618.19 - public SplitImportsTest(String testName) {
618.20 - super(testName);
618.21 - }
618.22 -
618.23 - private PythonAstRule createRule() {
618.24 - return new SplitImports();
618.25 - }
618.26 -
618.27 - public void testRegistered() throws Exception {
618.28 - ensureRegistered(createRule());
618.29 - }
618.30 -
618.31 - public void testHint1() throws Exception {
618.32 - findHints(this, createRule(), "testfiles/split_imports.py", null, null);
618.33 - }
618.34 -
618.35 - public void testFix1() throws Exception {
618.36 - applyHint(this, createRule(), "testfiles/split_imports.py", "^import sys, os, foobar", "Split");
618.37 - }
618.38 -
618.39 - public void testFix2() throws Exception {
618.40 - applyHint(this, createRule(), "testfiles/split_imports.py", "^import sys as whatever, os as bar", "Split");
618.41 - }
618.42 -}
619.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/SurroundWithTest.java Sun Jan 04 13:11:53 2015 -0600
619.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
619.3 @@ -1,110 +0,0 @@
619.4 -/*
619.5 - * To change this template, choose Tools | Templates
619.6 - * and open the template in the editor.
619.7 - */
619.8 -
619.9 -package org.netbeans.modules.python.editor.hints;
619.10 -
619.11 -import org.netbeans.modules.python.editor.PythonTestBase;
619.12 -
619.13 -/**
619.14 - *
619.15 - * @author Tor Norbye
619.16 - */
619.17 -public class SurroundWithTest extends PythonTestBase {
619.18 -
619.19 - public SurroundWithTest(String testName) {
619.20 - super(testName);
619.21 - }
619.22 -
619.23 - private PythonSelectionRule createRule() {
619.24 - return new SurroundWith();
619.25 - }
619.26 -
619.27 - public void testRegistered() throws Exception {
619.28 - ensureRegistered(createRule());
619.29 - }
619.30 -
619.31 - public void testHint1() throws Exception {
619.32 - checkHints(createRule(), "testfiles/datetime.py",
619.33 - "^for dim in _DAYS_IN_MONTH[1:]:",
619.34 - "del dbm, dim^");
619.35 - }
619.36 -
619.37 - public void testHint2() throws Exception {
619.38 - checkHints(createRule(), "testfiles/datetime.py",
619.39 - "^\"year -> number of days in year (366 if a leap year, else 365).\"",
619.40 - "\"year -> number of days in year (366 if a leap year, else 365).\"^");
619.41 - }
619.42 -
619.43 - public void testHint3() throws Exception {
619.44 - checkHints(createRule(), "testfiles/datetime.py",
619.45 - "^# Now compute how many 4-year cycles precede it.",
619.46 - "^ # And now how many single years.");
619.47 - }
619.48 -
619.49 - public void testHint4() throws Exception {
619.50 - checkHints(createRule(), "testfiles/simple.py",
619.51 - "^x = 1",
619.52 - "y = 2^");
619.53 - }
619.54 -
619.55 - public void testNoHint1() throws Exception {
619.56 - checkHints(createRule(), "testfiles/datetime.py",
619.57 - "f^or dim in _DAYS_IN_MONTH[1:]:",
619.58 - "del dbm, dim^");
619.59 - }
619.60 -
619.61 - public void testNoHint2() throws Exception {
619.62 - checkHints(createRule(), "testfiles/datetime.py",
619.63 - "^for dim in _DAYS_IN_MONTH[1:]:",
619.64 - "del dbm, di^m");
619.65 - }
619.66 -
619.67 - public void testNoHint3() throws Exception {
619.68 - checkHints(createRule(), "testfiles/datetime.py",
619.69 - "^def _is_leap(year):",
619.70 - " return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)^");
619.71 - }
619.72 -
619.73 - public void testNoHint4() throws Exception {
619.74 - checkHints(createRule(), "testfiles/datetime.py",
619.75 - "def ^_days_before_year(year):",
619.76 - "def _days_before_year^(year):");
619.77 - }
619.78 -
619.79 - public void testFix1() throws Exception {
619.80 - applyHint(this, createRule(), "testfiles/datetime.py",
619.81 - "^assert 1 <= month <= 12, month",
619.82 - "return 29^",
619.83 - "Surround With Try/Except\n");
619.84 - }
619.85 -
619.86 - public void testFix2() throws Exception {
619.87 - applyHint(this, createRule(), "testfiles/datetime.py",
619.88 - "^assert 1 <= month <= 12, month",
619.89 - "return 29^",
619.90 - "Surround With Try/Except/Finally");
619.91 - }
619.92 -
619.93 - public void testFix3() throws Exception {
619.94 - applyHint(this, createRule(), "testfiles/datetime.py",
619.95 - "^assert 1 <= month <= 12, month",
619.96 - "return 29^",
619.97 - "Surround With Try/Finally");
619.98 - }
619.99 -
619.100 - public void testFix4() throws Exception {
619.101 - applyHint(this, createRule(), "testfiles/surround.py",
619.102 - "^ print \"second\"",
619.103 - "^ print \"third\"",
619.104 - "Surround With Try/Finally");
619.105 - }
619.106 -
619.107 - public void testFix5() throws Exception {
619.108 - applyHint(this, createRule(), "testfiles/datetime.py",
619.109 - "^_DI400Y = _days_before_year(401)",
619.110 - "^_DI4Y = _days_before_year(5)",
619.111 - "Surround With Try/Finally");
619.112 - }
619.113 -}
620.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/UnresolvedClassComponentsTest.java Sun Jan 04 13:11:53 2015 -0600
620.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
620.3 @@ -1,77 +0,0 @@
620.4 -/*
620.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
620.6 - *
620.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
620.8 - *
620.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
620.10 - * Other names may be trademarks of their respective owners.
620.11 - *
620.12 - * The contents of this file are subject to the terms of either the GNU
620.13 - * General Public License Version 2 only ("GPL") or the Common
620.14 - * Development and Distribution License("CDDL") (collectively, the
620.15 - * "License"). You may not use this file except in compliance with the
620.16 - * License. You can obtain a copy of the License at
620.17 - * http://www.netbeans.org/cddl-gplv2.html
620.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
620.19 - * specific language governing permissions and limitations under the
620.20 - * License. When distributing the software, include this License Header
620.21 - * Notice in each file and include the License file at
620.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
620.23 - * particular file as subject to the "Classpath" exception as provided
620.24 - * by Oracle in the GPL Version 2 section of the License file that
620.25 - * accompanied this code. If applicable, add the following below the
620.26 - * License Header, with the fields enclosed by brackets [] replaced by
620.27 - * your own identifying information:
620.28 - * "Portions Copyrighted [year] [name of copyright owner]"
620.29 - *
620.30 - * If you wish your version of this file to be governed by only the CDDL
620.31 - * or only the GPL Version 2, indicate your decision by adding
620.32 - * "[Contributor] elects to include this software in this distribution
620.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
620.34 - * single choice of license, a recipient has the option to distribute
620.35 - * your version of this file under either the CDDL, the GPL Version 2 or
620.36 - * to extend the choice of license to its licensees as provided above.
620.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
620.38 - * Version 2 license, then the option applies only if the new code is
620.39 - * made subject to such option by the copyright holder.
620.40 - *
620.41 - * Contributor(s):
620.42 - *
620.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
620.44 - */
620.45 -
620.46 -package org.netbeans.modules.python.editor.hints;
620.47 -
620.48 -import org.netbeans.modules.python.editor.PythonTestBase;
620.49 -
620.50 -/**
620.51 - *
620.52 - * @author Tor Norbye
620.53 - */
620.54 -public class UnresolvedClassComponentsTest extends PythonTestBase {
620.55 -
620.56 - public UnresolvedClassComponentsTest(String name) {
620.57 - super(name);
620.58 - }
620.59 -
620.60 - private PythonAstRule createRule() {
620.61 - return new UnresolvedClassComponents();
620.62 - }
620.63 -
620.64 - public void testRegistered() throws Exception {
620.65 - ensureRegistered(createRule());
620.66 - }
620.67 -
620.68 - public void testUnresolvedAttribute() throws Exception {
620.69 - findHints(this, createRule(), "testfiles/unresolvedattributes.py", null, null);
620.70 - }
620.71 -
620.72 - public void testUnresolvedParent() throws Exception {
620.73 - // Make sure wildcard imports work
620.74 - findHints(this, createRule(), "testfiles/unresolvedparents.py", null, null);
620.75 - }
620.76 -
620.77 - public void testUnresolvedCleanCase() throws Exception {
620.78 - findHints(this, createRule(), "testfiles/httplib.py", null, null);
620.79 - }
620.80 -}
621.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/UnresolvedDetectorTest.java Sun Jan 04 13:11:53 2015 -0600
621.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
621.3 @@ -1,95 +0,0 @@
621.4 -/*
621.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
621.6 - *
621.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
621.8 - *
621.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
621.10 - * Other names may be trademarks of their respective owners.
621.11 - *
621.12 - * The contents of this file are subject to the terms of either the GNU
621.13 - * General Public License Version 2 only ("GPL") or the Common
621.14 - * Development and Distribution License("CDDL") (collectively, the
621.15 - * "License"). You may not use this file except in compliance with the
621.16 - * License. You can obtain a copy of the License at
621.17 - * http://www.netbeans.org/cddl-gplv2.html
621.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
621.19 - * specific language governing permissions and limitations under the
621.20 - * License. When distributing the software, include this License Header
621.21 - * Notice in each file and include the License file at
621.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
621.23 - * particular file as subject to the "Classpath" exception as provided
621.24 - * by Oracle in the GPL Version 2 section of the License file that
621.25 - * accompanied this code. If applicable, add the following below the
621.26 - * License Header, with the fields enclosed by brackets [] replaced by
621.27 - * your own identifying information:
621.28 - * "Portions Copyrighted [year] [name of copyright owner]"
621.29 - *
621.30 - * If you wish your version of this file to be governed by only the CDDL
621.31 - * or only the GPL Version 2, indicate your decision by adding
621.32 - * "[Contributor] elects to include this software in this distribution
621.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
621.34 - * single choice of license, a recipient has the option to distribute
621.35 - * your version of this file under either the CDDL, the GPL Version 2 or
621.36 - * to extend the choice of license to its licensees as provided above.
621.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
621.38 - * Version 2 license, then the option applies only if the new code is
621.39 - * made subject to such option by the copyright holder.
621.40 - *
621.41 - * Contributor(s):
621.42 - *
621.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
621.44 - */
621.45 -
621.46 -package org.netbeans.modules.python.editor.hints;
621.47 -
621.48 -import org.netbeans.modules.python.editor.PythonTestBase;
621.49 -
621.50 -/**
621.51 - *
621.52 - * @author Tor Norbye
621.53 - */
621.54 -public class UnresolvedDetectorTest extends PythonTestBase {
621.55 -
621.56 - public UnresolvedDetectorTest(String name) {
621.57 - super(name);
621.58 - }
621.59 -
621.60 - private PythonAstRule createRule() {
621.61 - return new UnresolvedDetector();
621.62 - }
621.63 -
621.64 - public void testRegistered() throws Exception {
621.65 - ensureRegistered(createRule());
621.66 - }
621.67 -
621.68 - public void testUnresolvedHints() throws Exception {
621.69 - findHints(this, createRule(), "testfiles/unresolved.py", null, null);
621.70 - }
621.71 -
621.72 - public void testUnresolvedHints2() throws Exception {
621.73 - // Make sure wildcard imports work
621.74 - findHints(this, createRule(), "testfiles/unresolved2.py", null, null);
621.75 - }
621.76 -
621.77 - public void testUnresolvedHints3() throws Exception {
621.78 - // Make sure wildcard imports work
621.79 - findHints(this, createRule(), "testfiles/unresolved3.py", null, null);
621.80 - }
621.81 -
621.82 - public void testUnresolvedHints4() throws Exception {
621.83 - findHints(this, createRule(), "testfiles/unresolved4.py", null, null);
621.84 - }
621.85 -
621.86 - public void testUnresolvedHints5() throws Exception {
621.87 - findHints(this, createRule(), "testfiles/unresolved5.py", null, null);
621.88 - }
621.89 -
621.90 - public void testUnresolvedHints6() throws Exception {
621.91 - // Test free variables in function/method
621.92 - findHints(this, createRule(), "testfiles/unresolved6.py", null, null);
621.93 - }
621.94 -
621.95 - public void testUnresolvedHints7() throws Exception {
621.96 - findHints(this, createRule(), "testfiles/datetime.py", null, null);
621.97 - }
621.98 -}
622.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/UnusedDetectorTest.java Sun Jan 04 13:11:53 2015 -0600
622.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
622.3 @@ -1,114 +0,0 @@
622.4 -/*
622.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
622.6 - *
622.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
622.8 - *
622.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
622.10 - * Other names may be trademarks of their respective owners.
622.11 - *
622.12 - * The contents of this file are subject to the terms of either the GNU
622.13 - * General Public License Version 2 only ("GPL") or the Common
622.14 - * Development and Distribution License("CDDL") (collectively, the
622.15 - * "License"). You may not use this file except in compliance with the
622.16 - * License. You can obtain a copy of the License at
622.17 - * http://www.netbeans.org/cddl-gplv2.html
622.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
622.19 - * specific language governing permissions and limitations under the
622.20 - * License. When distributing the software, include this License Header
622.21 - * Notice in each file and include the License file at
622.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
622.23 - * particular file as subject to the "Classpath" exception as provided
622.24 - * by Oracle in the GPL Version 2 section of the License file that
622.25 - * accompanied this code. If applicable, add the following below the
622.26 - * License Header, with the fields enclosed by brackets [] replaced by
622.27 - * your own identifying information:
622.28 - * "Portions Copyrighted [year] [name of copyright owner]"
622.29 - *
622.30 - * If you wish your version of this file to be governed by only the CDDL
622.31 - * or only the GPL Version 2, indicate your decision by adding
622.32 - * "[Contributor] elects to include this software in this distribution
622.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
622.34 - * single choice of license, a recipient has the option to distribute
622.35 - * your version of this file under either the CDDL, the GPL Version 2 or
622.36 - * to extend the choice of license to its licensees as provided above.
622.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
622.38 - * Version 2 license, then the option applies only if the new code is
622.39 - * made subject to such option by the copyright holder.
622.40 - *
622.41 - * Contributor(s):
622.42 - *
622.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
622.44 - */
622.45 -package org.netbeans.modules.python.editor.hints;
622.46 -
622.47 -import java.util.prefs.Preferences;
622.48 -import org.netbeans.modules.gsf.LanguageRegistry;
622.49 -import org.netbeans.modules.gsfret.hints.infrastructure.GsfHintsManager;
622.50 -import org.netbeans.modules.python.editor.PythonTestBase;
622.51 -
622.52 -/**
622.53 - *
622.54 - * @author Tor Norbye
622.55 - */
622.56 -public class UnusedDetectorTest extends PythonTestBase {
622.57 - public UnusedDetectorTest(String name) {
622.58 - super(name);
622.59 - }
622.60 -
622.61 - private void setHintOptions(boolean skipParams, boolean skipTupleAssigns, String ignoreNames) {
622.62 - org.netbeans.modules.gsf.Language language = LanguageRegistry.getInstance().getLanguageByMimeType(getPreferredMimeType());
622.63 - GsfHintsManager hintsManager = getHintsManager(language);
622.64 - Preferences prefs = hintsManager.getPreferences(createRule());
622.65 - UnusedDetector.setSkipParameters(prefs, skipParams);
622.66 - UnusedDetector.setSkipTupleAssignments(prefs, skipTupleAssigns);
622.67 - UnusedDetector.setIgnoreNames(prefs, ignoreNames);
622.68 - }
622.69 -
622.70 - private PythonAstRule createRule() {
622.71 - return new UnusedDetector();
622.72 - }
622.73 -
622.74 - public void testRegistered() throws Exception {
622.75 - ensureRegistered(createRule());
622.76 - }
622.77 -
622.78 - public void testUnusedHints() throws Exception {
622.79 - setHintOptions(false, false, "");
622.80 - findHints(this, createRule(), "testfiles/datetime.py", null, null);
622.81 - }
622.82 -
622.83 - public void testUnusedHints2() throws Exception {
622.84 - setHintOptions(false, false, "");
622.85 - findHints(this, createRule(), "testfiles/ConfigParser.py", null, null);
622.86 - }
622.87 -
622.88 - public void testUnusedHints3() throws Exception {
622.89 - setHintOptions(true, false, "");
622.90 - findHints(this, createRule(), "testfiles/datetime.py", null, null);
622.91 - }
622.92 -
622.93 - public void testUnusedHints4() throws Exception {
622.94 - setHintOptions(true, false, "");
622.95 - findHints(this, createRule(), "testfiles/datetime.py", null, null);
622.96 - }
622.97 -
622.98 - public void testUnusedHints5() throws Exception {
622.99 - setHintOptions(false, false, " jday, mm ");
622.100 - findHints(this, createRule(), "testfiles/datetime.py", null, null);
622.101 - }
622.102 -
622.103 - public void testUnusedHints6() throws Exception {
622.104 - setHintOptions(false, false, "");
622.105 - findHints(this, createRule(), "testfiles/delete.py", null, null);
622.106 - }
622.107 -
622.108 - public void testUnusedHints7() throws Exception {
622.109 - setHintOptions(false, false, "");
622.110 - findHints(this, createRule(), "testfiles/tuples.py", null, null);
622.111 - }
622.112 -
622.113 - public void testUnusedHints8() throws Exception {
622.114 - setHintOptions(true, true, "");
622.115 - findHints(this, createRule(), "testfiles/tuples.py", null, null);
622.116 - }
622.117 -}
623.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/UnusedImportsTest.java Sun Jan 04 13:11:53 2015 -0600
623.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
623.3 @@ -1,109 +0,0 @@
623.4 -/*
623.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
623.6 - *
623.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
623.8 - *
623.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
623.10 - * Other names may be trademarks of their respective owners.
623.11 - *
623.12 - * The contents of this file are subject to the terms of either the GNU
623.13 - * General Public License Version 2 only ("GPL") or the Common
623.14 - * Development and Distribution License("CDDL") (collectively, the
623.15 - * "License"). You may not use this file except in compliance with the
623.16 - * License. You can obtain a copy of the License at
623.17 - * http://www.netbeans.org/cddl-gplv2.html
623.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
623.19 - * specific language governing permissions and limitations under the
623.20 - * License. When distributing the software, include this License Header
623.21 - * Notice in each file and include the License file at
623.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
623.23 - * particular file as subject to the "Classpath" exception as provided
623.24 - * by Oracle in the GPL Version 2 section of the License file that
623.25 - * accompanied this code. If applicable, add the following below the
623.26 - * License Header, with the fields enclosed by brackets [] replaced by
623.27 - * your own identifying information:
623.28 - * "Portions Copyrighted [year] [name of copyright owner]"
623.29 - *
623.30 - * If you wish your version of this file to be governed by only the CDDL
623.31 - * or only the GPL Version 2, indicate your decision by adding
623.32 - * "[Contributor] elects to include this software in this distribution
623.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
623.34 - * single choice of license, a recipient has the option to distribute
623.35 - * your version of this file under either the CDDL, the GPL Version 2 or
623.36 - * to extend the choice of license to its licensees as provided above.
623.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
623.38 - * Version 2 license, then the option applies only if the new code is
623.39 - * made subject to such option by the copyright holder.
623.40 - *
623.41 - * Contributor(s):
623.42 - *
623.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
623.44 - */
623.45 -
623.46 -package org.netbeans.modules.python.editor.hints;
623.47 -
623.48 -import org.netbeans.modules.python.editor.PythonTestBase;
623.49 -
623.50 -/**
623.51 - *
623.52 - * @author Tor Norbye
623.53 - */
623.54 -public class UnusedImportsTest extends PythonTestBase {
623.55 -
623.56 - public UnusedImportsTest(String name) {
623.57 - super(name);
623.58 - }
623.59 -
623.60 - private PythonAstRule createRule() {
623.61 - return new UnusedImports();
623.62 - }
623.63 -
623.64 - public void testRegistered() throws Exception {
623.65 - ensureRegistered(createRule());
623.66 - }
623.67 -
623.68 - public void testHints() throws Exception {
623.69 - findHints(this, createRule(), "testfiles/unusedimports1.py", null, null);
623.70 - }
623.71 -
623.72 - public void testNoHints2() throws Exception {
623.73 - // The operator import isn't unused - it's responsible for importing abs() even though
623.74 - // abs() would otherwise have been imported by the builtin functions module.
623.75 - findHints(this, createRule(), "testfiles/unusedimports3.py", null, null);
623.76 - }
623.77 -
623.78 - public void testNoHints3() throws Exception {
623.79 - findHints(this, createRule(), "testfiles/futureimport.py", null, null);
623.80 - }
623.81 -
623.82 - public void testNoHints4() throws Exception {
623.83 - // No unused import detection in __init__.py files!
623.84 - findHints(this, createRule(), "testfiles/package/subpackage1/__init__.py", null, null);
623.85 - }
623.86 -
623.87 - public void testNoHints5() throws Exception {
623.88 - // No unused import detection in __init__.py files!
623.89 - findHints(this, createRule(), "testfiles/imports/__init__.py", null, null);
623.90 - }
623.91 -
623.92 - public void testFix1() throws Exception {
623.93 - applyHint(this, createRule(), "testfiles/unusedimports1.py", "import ur^import", "Remove Unused");
623.94 - }
623.95 -
623.96 - public void testFix2() throws Exception {
623.97 - applyHint(this, createRule(), "testfiles/unusedimports1.py", "import ur^import", "Remove All");
623.98 - }
623.99 -
623.100 - public void testFix3() throws Exception {
623.101 - applyHint(this, createRule(), "testfiles/unusedimports1.py", "import ur^import", "Organize");
623.102 - }
623.103 -
623.104 - public void testFix4() throws Exception {
623.105 - applyHint(this, createRule(), "testfiles/unusedimports1.py", "from foo import Sy^m1, Sym2", "Sym1");
623.106 - }
623.107 -
623.108 - public void testFix5() throws Exception {
623.109 - // BUGGY -- there should be no comma at the end of sys! TODO FIXME
623.110 - applyHint(this, createRule(), "testfiles/unusedimports2.py", "import sys, os, f^our", "four");
623.111 - }
623.112 -}
624.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/imports/ImportManagerTest.java Sun Jan 04 13:11:53 2015 -0600
624.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
624.3 @@ -1,377 +0,0 @@
624.4 -/*
624.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
624.6 - *
624.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
624.8 - *
624.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
624.10 - * Other names may be trademarks of their respective owners.
624.11 - *
624.12 - * The contents of this file are subject to the terms of either the GNU
624.13 - * General Public License Version 2 only ("GPL") or the Common
624.14 - * Development and Distribution License("CDDL") (collectively, the
624.15 - * "License"). You may not use this file except in compliance with the
624.16 - * License. You can obtain a copy of the License at
624.17 - * http://www.netbeans.org/cddl-gplv2.html
624.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
624.19 - * specific language governing permissions and limitations under the
624.20 - * License. When distributing the software, include this License Header
624.21 - * Notice in each file and include the License file at
624.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
624.23 - * particular file as subject to the "Classpath" exception as provided
624.24 - * by Oracle in the GPL Version 2 section of the License file that
624.25 - * accompanied this code. If applicable, add the following below the
624.26 - * License Header, with the fields enclosed by brackets [] replaced by
624.27 - * your own identifying information:
624.28 - * "Portions Copyrighted [year] [name of copyright owner]"
624.29 - *
624.30 - * If you wish your version of this file to be governed by only the CDDL
624.31 - * or only the GPL Version 2, indicate your decision by adding
624.32 - * "[Contributor] elects to include this software in this distribution
624.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
624.34 - * single choice of license, a recipient has the option to distribute
624.35 - * your version of this file under either the CDDL, the GPL Version 2 or
624.36 - * to extend the choice of license to its licensees as provided above.
624.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
624.38 - * Version 2 license, then the option applies only if the new code is
624.39 - * made subject to such option by the copyright holder.
624.40 - *
624.41 - * Contributor(s):
624.42 - *
624.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
624.44 - */
624.45 -
624.46 -package org.netbeans.modules.python.editor.imports;
624.47 -
624.48 -import java.util.ArrayList;
624.49 -import java.util.Collections;
624.50 -import java.util.HashMap;
624.51 -import java.util.HashSet;
624.52 -import java.util.List;
624.53 -import java.util.Map;
624.54 -import java.util.Set;
624.55 -import java.util.prefs.Preferences;
624.56 -import javax.swing.JEditorPane;
624.57 -import javax.swing.text.Document;
624.58 -import org.netbeans.editor.BaseDocument;
624.59 -import org.netbeans.modules.editor.indent.spi.CodeStylePreferences;
624.60 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
624.61 -import org.netbeans.modules.gsf.api.EditList;
624.62 -import org.netbeans.modules.gsf.api.NameKind;
624.63 -import org.netbeans.modules.python.editor.PythonAstUtils;
624.64 -import org.netbeans.modules.python.editor.PythonIndex;
624.65 -import org.netbeans.modules.python.editor.PythonTestBase;
624.66 -import org.netbeans.modules.python.editor.elements.IndexedElement;
624.67 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
624.68 -import org.netbeans.modules.python.editor.options.CodeStyle.ImportCleanupStyle;
624.69 -import org.netbeans.modules.python.editor.options.FmtOptions;
624.70 -import org.openide.filesystems.FileObject;
624.71 -import org.openide.loaders.DataObject;
624.72 -
624.73 -/**
624.74 - *
624.75 - * @author Tor Norbye
624.76 - */
624.77 -public class ImportManagerTest extends PythonTestBase {
624.78 -
624.79 - public ImportManagerTest(String name) {
624.80 - super(name);
624.81 - }
624.82 -
624.83 - @Override
624.84 - protected void setUp() throws Exception {
624.85 - super.setUp();
624.86 -
624.87 - // Make sure the test file is indexed
624.88 - FileObject fo = getTestFile("testfiles/imports/definitions.py");
624.89 - GsfTestCompilationInfo info = getInfo(fo);
624.90 - assertNotNull(PythonAstUtils.getRoot(info));
624.91 - info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
624.92 - // Force init of the index for both files that we care about
624.93 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE), info.getFileObject());
624.94 - Set<IndexedElement> classes = index.getClasses("DecimalException", NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, null, false);
624.95 - assertTrue(classes.size() > 0);
624.96 - }
624.97 -
624.98 - private void applyImports(String testFile, boolean commentOut) throws Exception {
624.99 - GsfTestCompilationInfo info = getInfo(getTestFile(testFile));
624.100 - info.getDocument();
624.101 - JEditorPane target = getPane(info.getText());
624.102 - Document doc = target.getDocument();
624.103 -
624.104 - DataObject dobj = DataObject.find(info.getFileObject());
624.105 - assertNotNull(dobj);
624.106 - doc.putProperty(Document.StreamDescriptionProperty, dobj);
624.107 -
624.108 - Preferences prefs = CodeStylePreferences.get(doc).getPreferences();
624.109 - if (commentOut) {
624.110 - prefs.put(FmtOptions.cleanupUnusedImports, ImportCleanupStyle.COMMENT_OUT.name());
624.111 - } else {
624.112 - prefs.put(FmtOptions.cleanupUnusedImports, ImportCleanupStyle.DELETE.name());
624.113 - }
624.114 -
624.115 - new FixImportsAction().actionPerformed(null, target);
624.116 -
624.117 - String text = doc.getText(0, doc.getLength());
624.118 - assertDescriptionMatches(testFile, text, true, ".imported");
624.119 - }
624.120 -
624.121 - private void checkImports(String testFile) throws Exception {
624.122 - GsfTestCompilationInfo info = getInfo(getTestFile(testFile));
624.123 - Document doc = info.getDocument();
624.124 - DataObject dobj = DataObject.find(info.getFileObject());
624.125 - assertNotNull(dobj);
624.126 - doc.putProperty(Document.StreamDescriptionProperty, dobj);
624.127 -
624.128 - List<String> ambiguousSymbols = new ArrayList<String>();
624.129 - Set<ImportEntry> unused = new HashSet<ImportEntry>();
624.130 - Set<ImportEntry> duplicates = new HashSet<ImportEntry>();
624.131 - Map<String, String> defaultLists = new HashMap<String, String>();
624.132 - Map<String, List<String>> alternatives = new HashMap<String, List<String>>();
624.133 -
624.134 - ImportManager manager = new ImportManager(info, (BaseDocument)doc);
624.135 - boolean ambiguous = manager.computeImports(ambiguousSymbols, defaultLists, alternatives, unused, duplicates);
624.136 -
624.137 - StringBuilder sb = new StringBuilder();
624.138 - sb.append("Requires user interaction: ");
624.139 - if (ambiguous) {
624.140 - sb.append("Yes");
624.141 - } else {
624.142 - sb.append("No");
624.143 - }
624.144 - sb.append("\n");
624.145 - if (unused.size() > 0) {
624.146 - sb.append("Unused imports:\n");
624.147 - List<ImportEntry> unusedList = new ArrayList<ImportEntry>(unused);
624.148 - Collections.sort(unusedList);
624.149 - for (ImportEntry entry : unusedList) {
624.150 - sb.append(" ");
624.151 - sb.append(entry.module);
624.152 - if (entry.symbol != null) {
624.153 - sb.append(" ");
624.154 - sb.append(entry.symbol);
624.155 - }
624.156 - if (entry.asName != null) {
624.157 - sb.append(" ");
624.158 - sb.append(entry.asName);
624.159 - }
624.160 - sb.append("\n");
624.161 - }
624.162 - }
624.163 - if (duplicates.size() > 0) {
624.164 - sb.append("Duplicate imports:\n");
624.165 - List<ImportEntry> duplicatesList = new ArrayList<ImportEntry>(duplicates);
624.166 - Collections.sort(duplicatesList);
624.167 - for (ImportEntry entry : duplicatesList) {
624.168 - sb.append(" ");
624.169 - sb.append(entry.module);
624.170 - if (entry.symbol != null) {
624.171 - sb.append(" ");
624.172 - sb.append(entry.symbol);
624.173 - }
624.174 - if (entry.asName != null) {
624.175 - sb.append(" ");
624.176 - sb.append(entry.asName);
624.177 - }
624.178 - sb.append("\n");
624.179 - }
624.180 - }
624.181 - if (ambiguousSymbols.size() > 0) {
624.182 - sb.append("Unresolved Symbols:\n");
624.183 - for (int i = 0; i < ambiguousSymbols.size(); i ++) {
624.184 - String symbol = ambiguousSymbols.get(i);
624.185 - sb.append(" ");
624.186 - sb.append(symbol);
624.187 - sb.append("\n");
624.188 - String deflt = defaultLists.get(symbol);
624.189 - List<String> choices = alternatives.get(symbol);
624.190 - for (String choice : choices) {
624.191 - sb.append(" ");
624.192 - if (choice.equals(deflt)) {
624.193 - sb.append("*");
624.194 - }
624.195 - if (choice.startsWith("<html>")) {
624.196 - sb.append("<cannot resolve>");
624.197 - } else {
624.198 - sb.append(choice);
624.199 - }
624.200 - sb.append("\n");
624.201 - }
624.202 - }
624.203 - }
624.204 -
624.205 - assertDescriptionMatches(testFile, sb.toString(), false, ".imports");
624.206 - }
624.207 -
624.208 - private void checkOrganize(String testFile, boolean systemLibsFirst, boolean splitImports, boolean commentOut, boolean sort, boolean separateFrom) throws Exception {
624.209 - GsfTestCompilationInfo info = getInfo(getTestFile(testFile));
624.210 - Document doc = info.getDocument();
624.211 - DataObject dobj = DataObject.find(info.getFileObject());
624.212 - assertNotNull(dobj);
624.213 - doc.putProperty(Document.StreamDescriptionProperty, dobj);
624.214 -
624.215 - EditList edits = new EditList((BaseDocument)doc);
624.216 - Preferences prefs = CodeStylePreferences.get(doc).getPreferences();
624.217 - if (commentOut) {
624.218 - prefs.put(FmtOptions.cleanupUnusedImports, ImportCleanupStyle.COMMENT_OUT.name());
624.219 - } else {
624.220 - prefs.put(FmtOptions.cleanupUnusedImports, ImportCleanupStyle.DELETE.name());
624.221 - }
624.222 - prefs.putBoolean(FmtOptions.oneImportPerLine, splitImports);
624.223 - prefs.putBoolean(FmtOptions.systemLibsFirst, systemLibsFirst);
624.224 - prefs.putBoolean(FmtOptions.sortImports, sort);
624.225 - prefs.putBoolean(FmtOptions.separateFromImps, separateFrom);
624.226 -
624.227 - ImportManager manager = new ImportManager(info, (BaseDocument)doc);
624.228 - manager.rewriteMainImports(edits, Collections.<ImportEntry>emptyList(), Collections.<ImportEntry>emptySet());
624.229 - edits.apply();
624.230 -
624.231 - String text = doc.getText(0, doc.getLength());
624.232 - assertDescriptionMatches(testFile, text, true, ".imported");
624.233 - }
624.234 -
624.235 - public void testIsImported1() throws Exception {
624.236 - GsfTestCompilationInfo info = getInfo(getTestFile("testfiles/imports/imports1.py"));
624.237 -
624.238 - /*
624.239 - import foo
624.240 - import bar as BAR
624.241 - import module1, module2, module3
624.242 - from module4 import Class1
624.243 - from module5 import Class2 as Class3
624.244 - */
624.245 - assertFalse(new ImportManager(info).isImported("foo", "Whatever"));
624.246 - assertTrue(new ImportManager(info).isImported("foo", null));
624.247 - assertTrue(new ImportManager(info).isImported("bar", "BAR"));
624.248 - assertFalse(new ImportManager(info).isImported("bar", "FOO"));
624.249 - assertTrue(new ImportManager(info).isImported("module1", null));
624.250 - assertFalse(new ImportManager(info).isImported("module1", "Whatever"));
624.251 - assertFalse(new ImportManager(info).isImported("module2", "Whatever"));
624.252 - assertTrue(new ImportManager(info).isImported("module4", "Class1"));
624.253 - assertFalse(new ImportManager(info).isImported("module4", "Class2"));
624.254 - assertFalse(new ImportManager(info).isImported("module5", "Class2"));
624.255 - assertTrue(new ImportManager(info).isImported("module5", "Class3"));
624.256 - }
624.257 -
624.258 -// public void testFixImports1() throws Exception {
624.259 -// applyImports("testfiles/imports/imports1.py", false);
624.260 -// }
624.261 -//
624.262 -// public void testFixImports2() throws Exception {
624.263 -// applyImports("testfiles/imports/imports1.py", true);
624.264 -// }
624.265 -//
624.266 -// public void testFixImports3() throws Exception {
624.267 -// applyImports("testfiles/imports/imports2.py", true);
624.268 -// }
624.269 -//
624.270 -// public void testFixImports4() throws Exception {
624.271 -// applyImports("testfiles/imports/imports3.py", true);
624.272 -// }
624.273 -//
624.274 -// public void testFixImports5() throws Exception {
624.275 -// checkImports("testfiles/imports/imports1.py");
624.276 -// }
624.277 -//
624.278 -// public void testFixImports6() throws Exception {
624.279 -// checkImports("testfiles/imports/imports2.py");
624.280 -// }
624.281 -//
624.282 -// public void testFixImports7() throws Exception {
624.283 -// checkImports("testfiles/imports/imports3.py");
624.284 -// }
624.285 -//
624.286 -// public void testFixDuplicates1() throws Exception {
624.287 -// checkImports("testfiles/imports/duplicates1.py");
624.288 -// }
624.289 -//
624.290 -// public void testFixDuplicates2() throws Exception {
624.291 -// checkImports("testfiles/imports/duplicates2.py");
624.292 -// }
624.293 -//
624.294 -// public void testFixDuplicates2b() throws Exception {
624.295 -// applyImports("testfiles/imports/duplicates2.py", true);
624.296 -// }
624.297 -//
624.298 -// public void testFixDuplicates3() throws Exception {
624.299 -// checkImports("testfiles/imports/duplicates3.py");
624.300 -// }
624.301 -//
624.302 -// public void testFixDuplicates3b() throws Exception {
624.303 -// applyImports("testfiles/imports/duplicates3.py", true);
624.304 -// }
624.305 -//
624.306 -// public void testFixDuplicates4() throws Exception {
624.307 -// checkImports("testfiles/imports/duplicates4.py");
624.308 -// }
624.309 -//
624.310 -// public void testFixDuplicates4b() throws Exception {
624.311 -// applyImports("testfiles/imports/duplicates4.py", true);
624.312 -// }
624.313 -//
624.314 -// public void testFixDuplicates5() throws Exception {
624.315 -// checkImports("testfiles/imports/duplicates5.py");
624.316 -// }
624.317 -//
624.318 -// public void testFixDuplicates5b() throws Exception {
624.319 -// applyImports("testfiles/imports/duplicates5.py", true);
624.320 -// }
624.321 -//
624.322 -// public void testFixDuplicates6() throws Exception {
624.323 -// checkImports("testfiles/imports/duplicates6.py");
624.324 -// }
624.325 -//
624.326 -// public void testFixDuplicates6b() throws Exception {
624.327 -// applyImports("testfiles/imports/duplicates6.py", true);
624.328 -// }
624.329 -//
624.330 -// public void testFixDuplicates7() throws Exception {
624.331 -// applyImports("testfiles/imports/duplicates7.py", true);
624.332 -// }
624.333 -
624.334 - public void testFixOrganize1() throws Exception {
624.335 - checkOrganize("testfiles/imports/organize1.py", true, true, false, true, false);
624.336 - }
624.337 -
624.338 - public void testFixOrganize2() throws Exception {
624.339 - checkOrganize("testfiles/imports/organize1.py", true, false, false, true, false);
624.340 - }
624.341 -
624.342 - public void testFixOrganize3() throws Exception {
624.343 - checkOrganize("testfiles/imports/organize1.py", true, true, false, true, false);
624.344 - }
624.345 -
624.346 - public void testFixOrganize4() throws Exception {
624.347 - checkOrganize("testfiles/imports/organize1.py", false, true, true, true, false);
624.348 - }
624.349 -
624.350 - public void testFixOrganize5() throws Exception {
624.351 - checkOrganize("testfiles/imports/organize1.py", true, false, false, true, false);
624.352 - }
624.353 -
624.354 - public void testFixOrganize6() throws Exception {
624.355 - checkOrganize("testfiles/imports/imports1.py", true, true, false, true, false);
624.356 - }
624.357 -
624.358 - public void testFixOrganize7() throws Exception {
624.359 - checkOrganize("testfiles/imports/organize1.py", true, true, false, false, false);
624.360 - }
624.361 -
624.362 - public void testFixOrganize8() throws Exception {
624.363 - checkOrganize("testfiles/imports/organize2.py", true, true, false, true, false);
624.364 - }
624.365 -
624.366 - public void testSortFutureImports() throws Exception {
624.367 - // 156442: Python __future__ imports not sorted properly
624.368 - checkOrganize("testfiles/imports/futures.py", false, true, false, true, true);
624.369 - }
624.370 -
624.371 - public void testFixInit() throws Exception {
624.372 - checkOrganize("testfiles/package/subpackage1/__init__.py", true, true, false, true, false);
624.373 - }
624.374 -
624.375 - public void testFixInit2() throws Exception {
624.376 - checkOrganize("testfiles/imports/__init__.py", true, true, false, true, false);
624.377 - }
624.378 -
624.379 - // TODO - try manually importing zlib - doesn't go to the right place (and check for system libs)
624.380 -}
625.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/CallTest.java Sun Jan 04 13:11:53 2015 -0600
625.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
625.3 @@ -1,255 +0,0 @@
625.4 -/*
625.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
625.6 - *
625.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
625.8 - *
625.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
625.10 - * Other names may be trademarks of their respective owners.
625.11 - *
625.12 - * The contents of this file are subject to the terms of either the GNU
625.13 - * General Public License Version 2 only ("GPL") or the Common
625.14 - * Development and Distribution License("CDDL") (collectively, the
625.15 - * "License"). You may not use this file except in compliance with the
625.16 - * License. You can obtain a copy of the License at
625.17 - * http://www.netbeans.org/cddl-gplv2.html
625.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
625.19 - * specific language governing permissions and limitations under the
625.20 - * License. When distributing the software, include this License Header
625.21 - * Notice in each file and include the License file at
625.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
625.23 - * particular file as subject to the "Classpath" exception as provided
625.24 - * by Oracle in the GPL Version 2 section of the License file that
625.25 - * accompanied this code. If applicable, add the following below the
625.26 - * License Header, with the fields enclosed by brackets [] replaced by
625.27 - * your own identifying information:
625.28 - * "Portions Copyrighted [year] [name of copyright owner]"
625.29 - *
625.30 - * Contributor(s):
625.31 - *
625.32 - * The Original Software is NetBeans. The Initial Developer of the Original
625.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
625.34 - * Microsystems, Inc. All Rights Reserved.
625.35 - *
625.36 - * If you wish your version of this file to be governed by only the CDDL
625.37 - * or only the GPL Version 2, indicate your decision by adding
625.38 - * "[Contributor] elects to include this software in this distribution
625.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
625.40 - * single choice of license, a recipient has the option to distribute
625.41 - * your version of this file under either the CDDL, the GPL Version 2 or
625.42 - * to extend the choice of license to its licensees as provided above.
625.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
625.44 - * Version 2 license, then the option applies only if the new code is
625.45 - * made subject to such option by the copyright holder.
625.46 - */
625.47 -
625.48 -package org.netbeans.modules.python.editor.lexer;
625.49 -
625.50 -import javax.swing.text.Document;
625.51 -import org.netbeans.api.lexer.TokenHierarchy;
625.52 -import org.netbeans.editor.BaseDocument;
625.53 -import org.netbeans.modules.python.editor.PythonTestBase;
625.54 -
625.55 -/**
625.56 - *
625.57 - * @author Tor Norbye
625.58 - */
625.59 -public class CallTest extends PythonTestBase {
625.60 -
625.61 - public CallTest(String testName) {
625.62 - super(testName);
625.63 - }
625.64 -
625.65 - private Call getCall(String source) {
625.66 - int caretPos = source.indexOf('^');
625.67 -
625.68 - source = source.substring(0, caretPos) + source.substring(caretPos + 1);
625.69 -
625.70 - BaseDocument doc = getDocument(source);
625.71 -
625.72 - TokenHierarchy<Document> th = TokenHierarchy.get((Document) doc);
625.73 - Call call = Call.getCallType(doc, th, caretPos);
625.74 -
625.75 - return call;
625.76 - }
625.77 -
625.78 - public void testCall1() throws Exception {
625.79 - Call call = getCall("File.ex^");
625.80 - assertEquals("File", call.getLhs());
625.81 - assertEquals("File", call.getType());
625.82 - assertTrue(call.isSimpleIdentifier());
625.83 - assertTrue(call.isStatic());
625.84 - }
625.85 -
625.86 - public void testCall1c() throws Exception {
625.87 - Call call = getCall("File.ex^ ");
625.88 - assertEquals("File", call.getLhs());
625.89 - assertEquals("File", call.getType());
625.90 - assertTrue(call.isSimpleIdentifier());
625.91 - assertTrue(call.isStatic());
625.92 - }
625.93 -
625.94 - public void testCall2() throws Exception {
625.95 - Call call = getCall("xy.ex^");
625.96 - assertEquals("xy", call.getLhs());
625.97 - assertEquals(null, call.getType());
625.98 - }
625.99 -
625.100 - public void testCall2b() throws Exception {
625.101 - Call call = getCall("xy.^");
625.102 - assertEquals("xy", call.getLhs());
625.103 - assertEquals(null, call.getType());
625.104 - }
625.105 -
625.106 - public void testCall2c() throws Exception {
625.107 - Call call = getCall("xy.ex^ ");
625.108 - assertEquals("xy", call.getLhs());
625.109 - assertEquals(null, call.getType());
625.110 - }
625.111 -
625.112 - public void testCall2d() throws Exception {
625.113 - Call call = getCall("xy.^ ");
625.114 - assertEquals("xy", call.getLhs());
625.115 - assertEquals(null, call.getType());
625.116 - }
625.117 -
625.118 - public void testCall3() throws Exception {
625.119 - Call call = getCall("\"foo\".gsu^");
625.120 - assertEquals("StringType", call.getType());
625.121 - assertFalse(call.isSimpleIdentifier());
625.122 - assertFalse(call.isStatic());
625.123 - }
625.124 -
625.125 - public void testCall3b() throws Exception {
625.126 - Call call = getCall("\"foo\".^");
625.127 - assertEquals("StringType", call.getType());
625.128 - assertFalse(call.isSimpleIdentifier());
625.129 - assertFalse(call.isStatic());
625.130 - }
625.131 -
625.132 - public void testCall5() throws Exception {
625.133 - Call call = getCall("[1,2,3].each^");
625.134 - assertEquals("ListType", call.getType());
625.135 - assertFalse(call.isSimpleIdentifier());
625.136 - assertFalse(call.isStatic());
625.137 - }
625.138 -
625.139 - public void testCall5b() throws Exception {
625.140 - Call call = getCall("[1,2,3].^");
625.141 - assertEquals("ListType", call.getType());
625.142 - assertFalse(call.isSimpleIdentifier());
625.143 - assertFalse(call.isStatic());
625.144 - }
625.145 -
625.146 - public void testCall6() throws Exception {
625.147 - Call call = getCall("{:x=>:y}.foo^");
625.148 - assertEquals("DictType", call.getType());
625.149 - assertFalse(call.isSimpleIdentifier());
625.150 - assertFalse(call.isStatic());
625.151 - }
625.152 -
625.153 - public void testCall6b() throws Exception {
625.154 - Call call = getCall("{:x=>:y}.^");
625.155 - assertEquals("DictType", call.getType());
625.156 - assertFalse(call.isSimpleIdentifier());
625.157 - assertFalse(call.isStatic());
625.158 - }
625.159 -
625.160 - public void testCalll2() throws Exception {
625.161 - Call call = getCall("True.foo^");
625.162 - assertEquals("BooleanType", call.getType());
625.163 - assertFalse(call.isSimpleIdentifier());
625.164 - assertFalse(call.isStatic());
625.165 - }
625.166 -
625.167 - public void testCalll2b() throws Exception {
625.168 - Call call = getCall("True.^");
625.169 - assertEquals("BooleanType", call.getType());
625.170 - assertFalse(call.isSimpleIdentifier());
625.171 - assertFalse(call.isStatic());
625.172 - }
625.173 -
625.174 - public void testCalll3() throws Exception {
625.175 - Call call = getCall("False.foo^");
625.176 - assertEquals("BooleanType", call.getType());
625.177 - assertFalse(call.isSimpleIdentifier());
625.178 - assertFalse(call.isStatic());
625.179 - }
625.180 -
625.181 - public void testCalll3b() throws Exception {
625.182 - Call call = getCall("False.^");
625.183 - assertEquals("BooleanType", call.getType());
625.184 - assertFalse(call.isSimpleIdentifier());
625.185 - assertFalse(call.isStatic());
625.186 - }
625.187 -
625.188 - public void testCall14() throws Exception {
625.189 - Call call = getCall("self.foo^");
625.190 - assertEquals("self", call.getType());
625.191 - assertEquals("self", call.getLhs());
625.192 - }
625.193 -
625.194 - public void testCall14b() throws Exception {
625.195 - Call call = getCall("self.^");
625.196 - assertEquals("self", call.getType());
625.197 - assertEquals("self", call.getLhs());
625.198 - }
625.199 -
625.200 - public void testCalll5() throws Exception {
625.201 - Call call = getCall("super.foo^");
625.202 - assertEquals("super", call.getType());
625.203 - assertEquals("super", call.getLhs());
625.204 - }
625.205 -
625.206 - public void testCalll5b() throws Exception {
625.207 - Call call = getCall("super.^");
625.208 - assertEquals("super", call.getType());
625.209 - assertEquals("super", call.getLhs());
625.210 - }
625.211 -
625.212 - public void testCall20() throws Exception {
625.213 - Call call = getCall("foo.bar.ex^");
625.214 - assertEquals("foo.bar", call.getLhs());
625.215 - assertEquals(null, call.getType());
625.216 - }
625.217 -
625.218 - public void testCallUnknown() throws Exception {
625.219 - Call call = getCall("getFoo().x^");
625.220 - assertSame(Call.UNKNOWN, call);
625.221 - }
625.222 -
625.223 - public void testCallLocal() throws Exception {
625.224 - Call call = getCall("foo^");
625.225 - assertSame(Call.LOCAL, call);
625.226 - }
625.227 -
625.228 - public void testCallOperator1() throws Exception {
625.229 - Call call = getCall("=foo^");
625.230 - assertSame(Call.LOCAL, call);
625.231 - }
625.232 -
625.233 - public void testCallOperator2() throws Exception {
625.234 - Call call = getCall("+foo^");
625.235 - assertSame(Call.LOCAL, call);
625.236 - }
625.237 -
625.238 - public void testCallOperator3() throws Exception {
625.239 - Call call = getCall("=SocketServer.^");
625.240 - assertEquals("SocketServer", call.getLhs());
625.241 - assertEquals("SocketServer", call.getType());
625.242 - }
625.243 -
625.244 - public void testParen() throws Exception {
625.245 - Call call = getCall("(SocketServer.^");
625.246 - assertEquals("SocketServer", call.getLhs());
625.247 - assertEquals("SocketServer", call.getType());
625.248 - }
625.249 -
625.250 - public void testParen2() throws Exception {
625.251 - Call call = getCall("[SocketServer.^");
625.252 - assertEquals("SocketServer", call.getLhs());
625.253 - assertEquals("SocketServer", call.getType());
625.254 - }
625.255 -
625.256 - // TODO - test complex numbers and tuples, lists and dicts,
625.257 - // etc. See http://www.python.org/doc/2.5.2/lib/module-types.html
625.258 -}
626.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonCommentLexerTest.java Sun Jan 04 13:11:53 2015 -0600
626.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
626.3 @@ -1,202 +0,0 @@
626.4 -/*
626.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
626.6 - *
626.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
626.8 - *
626.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
626.10 - * Other names may be trademarks of their respective owners.
626.11 - *
626.12 - * The contents of this file are subject to the terms of either the GNU
626.13 - * General Public License Version 2 only ("GPL") or the Common
626.14 - * Development and Distribution License("CDDL") (collectively, the
626.15 - * "License"). You may not use this file except in compliance with the
626.16 - * License. You can obtain a copy of the License at
626.17 - * http://www.netbeans.org/cddl-gplv2.html
626.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
626.19 - * specific language governing permissions and limitations under the
626.20 - * License. When distributing the software, include this License Header
626.21 - * Notice in each file and include the License file at
626.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
626.23 - * particular file as subject to the "Classpath" exception as provided
626.24 - * by Oracle in the GPL Version 2 section of the License file that
626.25 - * accompanied this code. If applicable, add the following below the
626.26 - * License Header, with the fields enclosed by brackets [] replaced by
626.27 - * your own identifying information:
626.28 - * "Portions Copyrighted [year] [name of copyright owner]"
626.29 - *
626.30 - * If you wish your version of this file to be governed by only the CDDL
626.31 - * or only the GPL Version 2, indicate your decision by adding
626.32 - * "[Contributor] elects to include this software in this distribution
626.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
626.34 - * single choice of license, a recipient has the option to distribute
626.35 - * your version of this file under either the CDDL, the GPL Version 2 or
626.36 - * to extend the choice of license to its licensees as provided above.
626.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
626.38 - * Version 2 license, then the option applies only if the new code is
626.39 - * made subject to such option by the copyright holder.
626.40 - *
626.41 - * Contributor(s):
626.42 - *
626.43 - * Portions Copyrighted 2009 Sun Microsystems, Inc.
626.44 - */
626.45 -
626.46 -package org.netbeans.modules.python.editor.lexer;
626.47 -
626.48 -import java.util.logging.Level;
626.49 -import java.util.logging.Logger;
626.50 -import org.netbeans.api.lexer.TokenHierarchy;
626.51 -import org.netbeans.api.lexer.TokenSequence;
626.52 -import org.netbeans.junit.NbTestCase;
626.53 -import org.netbeans.lib.lexer.test.LexerTestUtilities;
626.54 -
626.55 -/**
626.56 - *
626.57 - * @author tor
626.58 - */
626.59 -public class PythonCommentLexerTest extends NbTestCase{
626.60 -
626.61 - public PythonCommentLexerTest(String testName) {
626.62 - super(testName);
626.63 - }
626.64 -
626.65 - @Override
626.66 - protected void setUp() throws java.lang.Exception {
626.67 - Logger.getLogger(PythonLexer.class.getName()).setLevel(Level.FINEST);
626.68 - }
626.69 -
626.70 - @Override
626.71 - protected void tearDown() throws java.lang.Exception {
626.72 - }
626.73 -
626.74 - @Override
626.75 - protected Level logLevel() {
626.76 - // enabling logging
626.77 - return Level.INFO; // uncomment this to have logging from PyhonLexer
626.78 - // we are only interested in a single logger, so we set its level in setUp(),
626.79 - // as returning Level.FINEST here would log from all loggers
626.80 - }
626.81 -
626.82 - public void testTypeVars() {
626.83 - String text = "Whatever @type foo int bye";
626.84 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
626.85 - TokenSequence ts = hi.tokenSequence();
626.86 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
626.87 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
626.88 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
626.89 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.VARNAME, "foo");
626.90 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
626.91 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPE, "int");
626.92 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, " bye");
626.93 - assertFalse(ts.moveNext());
626.94 - }
626.95 -
626.96 - public void testTypeVarsWithColon() {
626.97 - String text = "Whatever @type foo: int bye";
626.98 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
626.99 - TokenSequence ts = hi.tokenSequence();
626.100 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
626.101 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
626.102 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
626.103 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.VARNAME, "foo");
626.104 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, ": ");
626.105 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPE, "int");
626.106 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, " bye");
626.107 - assertFalse(ts.moveNext());
626.108 - }
626.109 -
626.110 - public void testTodo() {
626.111 - String text = "Whatever TODO this TODOS SANTOS TODO";
626.112 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
626.113 - TokenSequence ts = hi.tokenSequence();
626.114 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
626.115 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TODO, "TODO");
626.116 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, " this TODOS SANTOS ");
626.117 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TODO, "TODO");
626.118 - assertFalse(ts.moveNext());
626.119 - }
626.120 -
626.121 - public void testTodo2() {
626.122 - String text = "STODO"; // Not a TODO
626.123 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
626.124 - TokenSequence ts = hi.tokenSequence();
626.125 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "STODO");
626.126 - assertFalse(ts.moveNext());
626.127 - }
626.128 -
626.129 - public void testEof1() {
626.130 - String text = "Whatever @type foo int ";
626.131 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
626.132 - TokenSequence ts = hi.tokenSequence();
626.133 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
626.134 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
626.135 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
626.136 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.VARNAME, "foo");
626.137 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
626.138 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPE, "int");
626.139 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, " ");
626.140 - assertFalse(ts.moveNext());
626.141 - }
626.142 -
626.143 - public void testEof2() {
626.144 - String text = "Whatever @type foo int";
626.145 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
626.146 - TokenSequence ts = hi.tokenSequence();
626.147 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
626.148 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
626.149 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
626.150 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.VARNAME, "foo");
626.151 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
626.152 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPE, "int");
626.153 - assertFalse(ts.moveNext());
626.154 - }
626.155 -
626.156 - public void testEof3() {
626.157 - String text = "Whatever @type foo ";
626.158 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
626.159 - TokenSequence ts = hi.tokenSequence();
626.160 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
626.161 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
626.162 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
626.163 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.VARNAME, "foo");
626.164 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
626.165 - assertFalse(ts.moveNext());
626.166 - }
626.167 -
626.168 - public void testEof4() {
626.169 - String text = "Whatever @type foo";
626.170 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
626.171 - TokenSequence ts = hi.tokenSequence();
626.172 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
626.173 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
626.174 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
626.175 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.VARNAME, "foo");
626.176 - assertFalse(ts.moveNext());
626.177 - }
626.178 -
626.179 - public void testEof5() {
626.180 - String text = "Whatever @type ";
626.181 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
626.182 - TokenSequence ts = hi.tokenSequence();
626.183 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
626.184 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
626.185 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
626.186 - assertFalse(ts.moveNext());
626.187 - }
626.188 -
626.189 - public void testEof6() {
626.190 - String text = "Whatever @type";
626.191 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
626.192 - TokenSequence ts = hi.tokenSequence();
626.193 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
626.194 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
626.195 - assertFalse(ts.moveNext());
626.196 - }
626.197 -
626.198 - public void testEof7() {
626.199 - String text = "Whatever ";
626.200 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
626.201 - TokenSequence ts = hi.tokenSequence();
626.202 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
626.203 - assertFalse(ts.moveNext());
626.204 - }
626.205 -}
627.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonIncrementalLexingTest.java Sun Jan 04 13:11:53 2015 -0600
627.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
627.3 @@ -1,124 +0,0 @@
627.4 -/*
627.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
627.6 - *
627.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
627.8 - *
627.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
627.10 - * Other names may be trademarks of their respective owners.
627.11 - *
627.12 - * The contents of this file are subject to the terms of either the GNU
627.13 - * General Public License Version 2 only ("GPL") or the Common
627.14 - * Development and Distribution License("CDDL") (collectively, the
627.15 - * "License"). You may not use this file except in compliance with the
627.16 - * License. You can obtain a copy of the License at
627.17 - * http://www.netbeans.org/cddl-gplv2.html
627.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
627.19 - * specific language governing permissions and limitations under the
627.20 - * License. When distributing the software, include this License Header
627.21 - * Notice in each file and include the License file at
627.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
627.23 - * particular file as subject to the "Classpath" exception as provided
627.24 - * by Oracle in the GPL Version 2 section of the License file that
627.25 - * accompanied this code. If applicable, add the following below the
627.26 - * License Header, with the fields enclosed by brackets [] replaced by
627.27 - * your own identifying information:
627.28 - * "Portions Copyrighted [year] [name of copyright owner]"
627.29 - *
627.30 - * Contributor(s):
627.31 - *
627.32 - * The Original Software is NetBeans. The Initial Developer of the Original
627.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
627.34 - * Microsystems, Inc. All Rights Reserved.
627.35 - *
627.36 - * If you wish your version of this file to be governed by only the CDDL
627.37 - * or only the GPL Version 2, indicate your decision by adding
627.38 - * "[Contributor] elects to include this software in this distribution
627.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
627.40 - * single choice of license, a recipient has the option to distribute
627.41 - * your version of this file under either the CDDL, the GPL Version 2 or
627.42 - * to extend the choice of license to its licensees as provided above.
627.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
627.44 - * Version 2 license, then the option applies only if the new code is
627.45 - * made subject to such option by the copyright holder.
627.46 - */
627.47 -
627.48 -package org.netbeans.modules.python.editor.lexer;
627.49 -
627.50 -import junit.framework.TestCase;
627.51 -// Grr, this doesn't work outside the NB build tree!!! GRRRR
627.52 -import org.netbeans.lib.lexer.test.FixedTextDescriptor;
627.53 -import org.netbeans.lib.lexer.test.RandomCharDescriptor;
627.54 -import org.netbeans.lib.lexer.test.RandomModifyDescriptor;
627.55 -import org.netbeans.lib.lexer.test.RandomTextProvider;
627.56 -import org.netbeans.lib.lexer.test.TestRandomModify;
627.57 -
627.58 -/**
627.59 - * Randomly edit the document and test the incremental operation
627.60 - *
627.61 - */
627.62 -public class PythonIncrementalLexingTest extends TestCase {
627.63 -
627.64 - public PythonIncrementalLexingTest(String testName) {
627.65 - super(testName);
627.66 - }
627.67 -
627.68 - @Override
627.69 - protected void setUp() throws java.lang.Exception {
627.70 - // Set-up testing environment
627.71 - System.setProperty("netbeans.debug.lexer.test", "true");
627.72 - }
627.73 -
627.74 - public void testRandom() throws Exception {
627.75 - test(0);
627.76 - }
627.77 -
627.78 - private void test(long seed) throws Exception {
627.79 - TestRandomModify randomModify = new TestRandomModify(seed);
627.80 - randomModify.setLanguage(PythonTokenId.language());
627.81 -
627.82 - //randomModify.setDebugOperation(true);
627.83 - //randomModify.setDebugDocumentText(true);
627.84 - //randomModify.setDebugHierarchy(true);
627.85 -
627.86 - FixedTextDescriptor[] fixedTexts = new FixedTextDescriptor[] {
627.87 - FixedTextDescriptor.create("'''", 0.2),
627.88 - FixedTextDescriptor.create("<=", 0.2),
627.89 - };
627.90 -
627.91 - RandomCharDescriptor[] regularChars = new RandomCharDescriptor[] {
627.92 - RandomCharDescriptor.letter(0.3),
627.93 - RandomCharDescriptor.space(0.3),
627.94 - RandomCharDescriptor.lf(0.3),
627.95 - RandomCharDescriptor.chars(new char[] { '+', '-', '*', '/', ':'}, 0.3),
627.96 - };
627.97 -
627.98 - RandomCharDescriptor[] anyChar = new RandomCharDescriptor[] {
627.99 - RandomCharDescriptor.anyChar(1.0),
627.100 - };
627.101 -
627.102 - RandomTextProvider regularTextProvider = new RandomTextProvider(regularChars, fixedTexts);
627.103 - RandomTextProvider anyCharTextProvider = new RandomTextProvider(anyChar, fixedTexts);
627.104 -
627.105 - randomModify.test(
627.106 - new RandomModifyDescriptor[] {
627.107 - new RandomModifyDescriptor(1000, regularTextProvider,
627.108 - 0.2, 0.2, 0.1,
627.109 - 0.2, 0.2,
627.110 - 0.0, 0.0),
627.111 - }
627.112 - );
627.113 -
627.114 - randomModify.test(
627.115 - new RandomModifyDescriptor[] {
627.116 - new RandomModifyDescriptor(1000, anyCharTextProvider,
627.117 - 0.4, 0.2, 0.2,
627.118 - 0.1, 0.1,
627.119 - 0.0, 0.0),
627.120 - new RandomModifyDescriptor(1000, anyCharTextProvider,
627.121 - 0.2, 0.2, 0.1,
627.122 - 0.4, 0.3,
627.123 - 0.0, 0.0),
627.124 - }
627.125 - );
627.126 - }
627.127 -}
628.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonLexerTest.java Sun Jan 04 13:11:53 2015 -0600
628.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
628.3 @@ -1,421 +0,0 @@
628.4 -/*
628.5 - * To change this template, choose Tools | Templates
628.6 - * and open the template in the editor.
628.7 - */
628.8 -
628.9 -package org.netbeans.modules.python.editor.lexer;
628.10 -
628.11 -
628.12 -import java.util.ConcurrentModificationException;
628.13 -import javax.swing.text.BadLocationException;
628.14 -import java.util.logging.Level;
628.15 -import java.util.logging.Logger;
628.16 -import javax.swing.text.Document;
628.17 -import org.netbeans.api.lexer.Language;
628.18 -import org.netbeans.api.lexer.TokenHierarchy;
628.19 -import org.netbeans.api.lexer.TokenSequence;
628.20 -import org.netbeans.junit.NbTestCase;
628.21 -import org.netbeans.lib.lexer.test.LexerTestUtilities;
628.22 -import org.netbeans.lib.lexer.test.ModificationTextDocument;
628.23 -
628.24 -/**
628.25 - *
628.26 - * @author Tor Norbye
628.27 - */
628.28 -public class PythonLexerTest extends NbTestCase {
628.29 -
628.30 - public PythonLexerTest(String testName) {
628.31 - super(testName);
628.32 - }
628.33 -
628.34 - @Override
628.35 - protected void setUp() throws java.lang.Exception {
628.36 - Logger.getLogger(PythonLexer.class.getName()).setLevel(Level.FINEST);
628.37 - }
628.38 -
628.39 - @Override
628.40 - protected void tearDown() throws java.lang.Exception {
628.41 - }
628.42 -
628.43 - @Override
628.44 - protected Level logLevel() {
628.45 - // enabling logging
628.46 - return Level.INFO; // uncomment this to have logging from PyhonLexer
628.47 - // we are only interested in a single logger, so we set its level in setUp(),
628.48 - // as returning Level.FINEST here would log from all loggers
628.49 - }
628.50 -
628.51 - public void test1() {
628.52 - String text =
628.53 - "# this is the first comment\n" +
628.54 - "SPAM = 1 # and this is the second comment\n" +
628.55 - " # ... and now a third!\n" +
628.56 - "STRING = \"# This is not a comment.\"";
628.57 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.58 - TokenSequence ts = hi.tokenSequence();
628.59 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "# this is the first comment");
628.60 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.61 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "SPAM");
628.62 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.63 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
628.64 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.65 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.INT_LITERAL, "1");
628.66 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.67 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "# and this is the second comment");
628.68 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.69 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.70 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "# ... and now a third!");
628.71 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.72 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "STRING");
628.73 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.74 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
628.75 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.76 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
628.77 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "# This is not a comment.");
628.78 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
628.79 - }
628.80 -
628.81 - public void test2() {
628.82 - String text =
628.83 - "#! /usr/bin/python\n" +
628.84 - "print \"Hello World!\"\t\n";
628.85 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.86 - TokenSequence ts = hi.tokenSequence();
628.87 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "#! /usr/bin/python");
628.88 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.89 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_KEYWORD, "print");
628.90 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.91 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
628.92 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "Hello World!");
628.93 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
628.94 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, "\t");
628.95 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.96 - assertFalse(ts.moveNext());
628.97 - }
628.98 -
628.99 - public void test3() {
628.100 - String text =
628.101 - "#! /usr/bin/python\n" +
628.102 - "print \"Hello World!\"\t";
628.103 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.104 - TokenSequence ts = hi.tokenSequence();
628.105 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "#! /usr/bin/python");
628.106 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.107 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_KEYWORD, "print");
628.108 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.109 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
628.110 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "Hello World!");
628.111 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
628.112 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, "\t");
628.113 - assertFalse(ts.moveNext());
628.114 - }
628.115 -
628.116 - public void test4() throws BadLocationException {
628.117 - Document doc = new ModificationTextDocument();
628.118 - // Assign a language to the document
628.119 - doc.putProperty(Language.class, PythonTokenId.language());
628.120 - TokenHierarchy<?> hi = TokenHierarchy.get(doc);
628.121 - assertNotNull("Null token hierarchy for document", hi);
628.122 - TokenSequence<?> ts = hi.tokenSequence();
628.123 -
628.124 - // Newline in empty doc: this started happening around June 1st 2009
628.125 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.126 -
628.127 - assertFalse(ts.moveNext());
628.128 -
628.129 - // Insert text into document
628.130 - String text =
628.131 - "#! /usr/bin/python\n" +
628.132 - "print \"Hello World!\"";
628.133 - doc.insertString(0, text, null);
628.134 -
628.135 - // Last token sequence should throw exception - new must be obtained
628.136 - try {
628.137 - ts.moveNext();
628.138 - fail("TokenSequence.moveNext() did not throw exception as expected.");
628.139 - } catch (ConcurrentModificationException e) {
628.140 - // Expected exception
628.141 - }
628.142 -
628.143 - ts = hi.tokenSequence();
628.144 -
628.145 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "#! /usr/bin/python");
628.146 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.147 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_KEYWORD, "print");
628.148 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.149 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
628.150 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "Hello World!");
628.151 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
628.152 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.153 -
628.154 - assertFalse(ts.moveNext());
628.155 -
628.156 - LexerTestUtilities.incCheck(doc, false);
628.157 -
628.158 - int offset = text.length() - 1;
628.159 -
628.160 - doc.remove(offset, 1);
628.161 -
628.162 - ts = hi.tokenSequence();
628.163 -
628.164 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "#! /usr/bin/python");
628.165 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.166 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_KEYWORD, "print");
628.167 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.168 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
628.169 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ERROR, "Hello World!\n");
628.170 -
628.171 - assertFalse(ts.moveNext());
628.172 -
628.173 - LexerTestUtilities.incCheck(doc, false);
628.174 - }
628.175 -
628.176 - public void testSpecialChars() {
628.177 - String text =
628.178 - "x(3,2.0)\n" +
628.179 - "if (foo.bar[0]):\n";
628.180 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.181 - TokenSequence ts = hi.tokenSequence();
628.182 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
628.183 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.LPAREN, "(");
628.184 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.INT_LITERAL, "3");
628.185 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMA, ",");
628.186 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.FLOAT_LITERAL, "2.0");
628.187 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.RPAREN, ")");
628.188 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.189 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IF, "if");
628.190 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.191 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.LPAREN, "(");
628.192 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "foo");
628.193 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.DOT, ".");
628.194 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "bar");
628.195 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.LBRACKET, "[");
628.196 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.INT_LITERAL, "0");
628.197 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.RBRACKET, "]");
628.198 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.RPAREN, ")");
628.199 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COLON, ":");
628.200 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.201 - assertFalse(ts.moveNext());
628.202 - }
628.203 -
628.204 - public void testStrings1() {
628.205 - String text =
628.206 - "x=UR'''this is\na\nstring\\nwith\\n\\nescapes\n '''";
628.207 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.208 - TokenSequence ts = hi.tokenSequence();
628.209 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
628.210 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
628.211 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "UR'''");
628.212 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "this is\na\nstring\\nwith\\n\\nescapes\n ");
628.213 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "'''");
628.214 - assertFalse(ts.moveNext());
628.215 - }
628.216 -
628.217 - public void testStrings2() {
628.218 - String text =
628.219 - "x=UR'''this is\na\nstring\\nwith\\n\\nescapes\n ";
628.220 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.221 - TokenSequence ts = hi.tokenSequence();
628.222 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
628.223 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
628.224 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "UR'''");
628.225 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ERROR, "this is\na\nstring\\nwith\\n\\nescapes\n ");
628.226 - assertFalse(ts.moveNext());
628.227 - }
628.228 -
628.229 - public void testStrings3() {
628.230 - String text =
628.231 - "x=UR\"\"\"this is\na\nstring\\nwith\\n\\nescapes\n \"\"\"";
628.232 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.233 - TokenSequence ts = hi.tokenSequence();
628.234 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
628.235 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
628.236 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "UR\"\"\"");
628.237 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "this is\na\nstring\\nwith\\n\\nescapes\n ");
628.238 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"\"\"");
628.239 - assertFalse(ts.moveNext());
628.240 - }
628.241 -
628.242 - public void testStrings4() {
628.243 - String text =
628.244 - "x=R\"\"\"this is\na\nstring\\nwith\\n\\nescapes\n \"\"\"";
628.245 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.246 - TokenSequence ts = hi.tokenSequence();
628.247 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
628.248 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
628.249 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "R\"\"\"");
628.250 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "this is\na\nstring\\nwith\\n\\nescapes\n ");
628.251 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"\"\"");
628.252 - assertFalse(ts.moveNext());
628.253 - }
628.254 -
628.255 - public void testStrings5() {
628.256 - String text =
628.257 - "x=u\"\"\"this is\na\nstring\\nwith\\n\\nescapes\n \"\"\"";
628.258 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.259 - TokenSequence ts = hi.tokenSequence();
628.260 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
628.261 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
628.262 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "u\"\"\"");
628.263 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "this is\na\nstring\\nwith\\n\\nescapes\n ");
628.264 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"\"\"");
628.265 - assertFalse(ts.moveNext());
628.266 - }
628.267 -
628.268 - public void testDotPrefix() {
628.269 - String text =
628.270 - ".5";
628.271 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.272 - TokenSequence ts = hi.tokenSequence();
628.273 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.FLOAT_LITERAL, ".5");
628.274 - assertFalse(ts.moveNext());
628.275 -
628.276 - text = "x.y";
628.277 - hi = TokenHierarchy.create(text, PythonTokenId.language());
628.278 - ts = hi.tokenSequence();
628.279 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
628.280 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.DOT, ".");
628.281 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "y");
628.282 - assertFalse(ts.moveNext());
628.283 - }
628.284 -
628.285 - public void testExponential() {
628.286 - String text =
628.287 - "1e100";
628.288 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.289 - TokenSequence ts = hi.tokenSequence();
628.290 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.FLOAT_LITERAL, "1e100");
628.291 - assertFalse(ts.moveNext());
628.292 - }
628.293 -
628.294 - public void testExponential2() {
628.295 - String text =
628.296 - "3.14e-10";
628.297 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.298 - TokenSequence ts = hi.tokenSequence();
628.299 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.FLOAT_LITERAL, "3.14e-10");
628.300 - assertFalse(ts.moveNext());
628.301 - }
628.302 -
628.303 - public void testImaginary() {
628.304 - String text =
628.305 - "3.14e-10j";
628.306 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.307 - TokenSequence ts = hi.tokenSequence();
628.308 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.FLOAT_LITERAL, "3.14e-10j");
628.309 - assertFalse(ts.moveNext());
628.310 - }
628.311 -
628.312 - public void testChars1() {
628.313 - String text =
628.314 - "x = \"\"";
628.315 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.316 - TokenSequence ts = hi.tokenSequence();
628.317 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
628.318 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.319 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
628.320 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.321 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
628.322 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
628.323 - assertFalse(ts.moveNext());
628.324 - }
628.325 -
628.326 - public void testChars2() {
628.327 - String text =
628.328 - "x = \"'\"";
628.329 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.330 - TokenSequence ts = hi.tokenSequence();
628.331 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
628.332 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.333 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
628.334 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.335 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
628.336 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "'");
628.337 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
628.338 - assertFalse(ts.moveNext());
628.339 - }
628.340 -
628.341 - public void testCornerCases() {
628.342 - String text =
628.343 - "\"";
628.344 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.345 - TokenSequence ts = hi.tokenSequence();
628.346 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
628.347 - assertFalse(ts.moveNext());
628.348 - }
628.349 -
628.350 - public void testCornerCases2() {
628.351 - String text =
628.352 - "\"foo";
628.353 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.354 - TokenSequence ts = hi.tokenSequence();
628.355 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
628.356 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ERROR, "foo");
628.357 - assertFalse(ts.moveNext());
628.358 - }
628.359 -
628.360 - public void testEmptyString1() {
628.361 - String text =
628.362 - "\"\"\"\"\"\"";
628.363 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.364 - TokenSequence ts = hi.tokenSequence();
628.365 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"\"\"");
628.366 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"\"\"");
628.367 - assertFalse(ts.moveNext());
628.368 - }
628.369 -
628.370 - public void testEmptyString2() {
628.371 - String text =
628.372 - "''''''";
628.373 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.374 - TokenSequence ts = hi.tokenSequence();
628.375 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "'''");
628.376 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "'''");
628.377 - assertFalse(ts.moveNext());
628.378 - }
628.379 -
628.380 - public void testEmptyString3() {
628.381 - String text =
628.382 - "''";
628.383 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.384 - TokenSequence ts = hi.tokenSequence();
628.385 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "'");
628.386 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "'");
628.387 - assertFalse(ts.moveNext());
628.388 - }
628.389 -
628.390 - public void testEmptyString4() {
628.391 - String text =
628.392 - "\"\"";
628.393 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.394 - TokenSequence ts = hi.tokenSequence();
628.395 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
628.396 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
628.397 - assertFalse(ts.moveNext());
628.398 - }
628.399 -
628.400 - public void testDecorators1() {
628.401 - String text =
628.402 - "@foo\ndef bar:\n";
628.403 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.404 - TokenSequence ts = hi.tokenSequence();
628.405 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.DECORATOR, "@foo");
628.406 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.407 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.DEF, "def");
628.408 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
628.409 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "bar");
628.410 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COLON, ":");
628.411 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
628.412 - assertFalse(ts.moveNext());
628.413 - }
628.414 -
628.415 - public void testDecorators2() {
628.416 - String text =
628.417 - "@,";
628.418 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
628.419 - TokenSequence ts = hi.tokenSequence();
628.420 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.DECORATOR, "@");
628.421 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMA, ",");
628.422 - assertFalse(ts.moveNext());
628.423 - }
628.424 -}
629.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonLexerUtilsTest.java Sun Jan 04 13:11:53 2015 -0600
629.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
629.3 @@ -1,225 +0,0 @@
629.4 -/*
629.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
629.6 - *
629.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
629.8 - *
629.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
629.10 - * Other names may be trademarks of their respective owners.
629.11 - *
629.12 - * The contents of this file are subject to the terms of either the GNU
629.13 - * General Public License Version 2 only ("GPL") or the Common
629.14 - * Development and Distribution License("CDDL") (collectively, the
629.15 - * "License"). You may not use this file except in compliance with the
629.16 - * License. You can obtain a copy of the License at
629.17 - * http://www.netbeans.org/cddl-gplv2.html
629.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
629.19 - * specific language governing permissions and limitations under the
629.20 - * License. When distributing the software, include this License Header
629.21 - * Notice in each file and include the License file at
629.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
629.23 - * particular file as subject to the "Classpath" exception as provided
629.24 - * by Oracle in the GPL Version 2 section of the License file that
629.25 - * accompanied this code. If applicable, add the following below the
629.26 - * License Header, with the fields enclosed by brackets [] replaced by
629.27 - * your own identifying information:
629.28 - * "Portions Copyrighted [year] [name of copyright owner]"
629.29 - *
629.30 - * If you wish your version of this file to be governed by only the CDDL
629.31 - * or only the GPL Version 2, indicate your decision by adding
629.32 - * "[Contributor] elects to include this software in this distribution
629.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
629.34 - * single choice of license, a recipient has the option to distribute
629.35 - * your version of this file under either the CDDL, the GPL Version 2 or
629.36 - * to extend the choice of license to its licensees as provided above.
629.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
629.38 - * Version 2 license, then the option applies only if the new code is
629.39 - * made subject to such option by the copyright holder.
629.40 - *
629.41 - * Contributor(s):
629.42 - *
629.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
629.44 - */
629.45 -
629.46 -package org.netbeans.modules.python.editor.lexer;
629.47 -
629.48 -import org.netbeans.editor.BaseDocument;
629.49 -import org.netbeans.modules.gsf.api.OffsetRange;
629.50 -import org.netbeans.modules.python.editor.PythonTestBase;
629.51 -
629.52 -/**
629.53 - *
629.54 - * @author Tor Norbye
629.55 - */
629.56 -public class PythonLexerUtilsTest extends PythonTestBase {
629.57 -
629.58 - public PythonLexerUtilsTest(String name) {
629.59 - super(name);
629.60 - }
629.61 -
629.62 - public void testNarrow() throws Exception {
629.63 - BaseDocument doc = getDocument(getTestFile("testfiles/extract1.py"));
629.64 - String s = doc.getText(0, doc.getLength());
629.65 -
629.66 - int start = getCaretOffset(s, "^# Beginning of extraction segment");
629.67 - int end = getCaretOffset(s, "# End of extraction segment^");
629.68 - OffsetRange range = new OffsetRange(start, end);
629.69 -
629.70 - OffsetRange result = PythonLexerUtils.narrow(doc, range, true);
629.71 -
629.72 - OffsetRange expected = new OffsetRange(
629.73 - getCaretOffset(s, "^read_after_block = 5"),
629.74 - getCaretOffset(s, "print param_read_in_block^")
629.75 - );
629.76 -
629.77 - assertEquals(expected, result);
629.78 - }
629.79 -
629.80 - public void testNarrow2() throws Exception {
629.81 - BaseDocument doc = getDocument(getTestFile("testfiles/extract1.py"));
629.82 - String s = doc.getText(0, doc.getLength());
629.83 -
629.84 - int start = getCaretOffset(s, "^read_after_block = 5");
629.85 - int end = getCaretOffset(s, "read_after_block = 5^");
629.86 - OffsetRange range = new OffsetRange(start, end);
629.87 -
629.88 - OffsetRange result = PythonLexerUtils.narrow(doc, range, true);
629.89 -
629.90 - assertEquals(range, result);
629.91 - }
629.92 -
629.93 - public void testNarrow3() throws Exception {
629.94 - BaseDocument doc = getDocument(getTestFile("testfiles/extract1.py"));
629.95 - String s = doc.getText(0, doc.getLength());
629.96 -
629.97 - int start = getCaretOffset(s, "^ read_after_block = 5");
629.98 - int end = getCaretOffset(s, "read_after_block = 5^");
629.99 - OffsetRange range = new OffsetRange(start, end);
629.100 -
629.101 - OffsetRange result = PythonLexerUtils.narrow(doc, range, true);
629.102 -
629.103 - OffsetRange expected = new OffsetRange(
629.104 - getCaretOffset(s, "^read_after_block = 5"),
629.105 - getCaretOffset(s, "read_after_block = 5^")
629.106 - );
629.107 -
629.108 - assertEquals(expected, result);
629.109 - }
629.110 -
629.111 -
629.112 - public void testNarrow4() throws Exception {
629.113 - BaseDocument doc = getDocument(getTestFile("testfiles/extract1.py"));
629.114 - String s = doc.getText(0, doc.getLength());
629.115 -
629.116 - int start = getCaretOffset(s, "= 4\n^");
629.117 - int end = getCaretOffset(s, "^ print local1");
629.118 - OffsetRange range = new OffsetRange(start, end);
629.119 -
629.120 - OffsetRange result = PythonLexerUtils.narrow(doc, range, false);
629.121 -
629.122 - OffsetRange expected = new OffsetRange(
629.123 - getCaretOffset(s, "^# Beginning of extraction segment"),
629.124 - getCaretOffset(s, "# End of extraction segment^")
629.125 - );
629.126 -
629.127 - assertEquals(expected, result);
629.128 - }
629.129 -
629.130 - public void testNarrow5() throws Exception {
629.131 - BaseDocument doc = getDocument(getTestFile("testfiles/extract1.py"));
629.132 - String s = doc.getText(0, doc.getLength());
629.133 -
629.134 - int start = getCaretOffset(s, "r^ead_after_block = 5");
629.135 - int end = getCaretOffset(s, "# End of extraction segment^");
629.136 - OffsetRange range = new OffsetRange(start, end);
629.137 -
629.138 - OffsetRange result = PythonLexerUtils.narrow(doc, range, true);
629.139 - assertEquals(OffsetRange.NONE, result);
629.140 - }
629.141 -
629.142 - public void testNarrow6() throws Exception {
629.143 - BaseDocument doc = getDocument(getTestFile("testfiles/extract1.py"));
629.144 - String s = doc.getText(0, doc.getLength());
629.145 -
629.146 - int start = getCaretOffset(s, "^# Beginning of extraction segment");
629.147 - int end = getCaretOffset(s, "print param_read_in_bloc^k");
629.148 - OffsetRange range = new OffsetRange(start, end);
629.149 -
629.150 - OffsetRange result = PythonLexerUtils.narrow(doc, range, true);
629.151 - assertEquals(OffsetRange.NONE, result);
629.152 - }
629.153 -
629.154 - public void testFindSpaceBegin() {
629.155 - // Spaces in strings don't count
629.156 - String s = "x = 'f oo'";
629.157 - BaseDocument doc = getDocument(s);
629.158 - assertEquals(0, PythonLexerUtils.findSpaceBegin(doc, 0));
629.159 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 1));
629.160 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 2));
629.161 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 3));
629.162 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 4));
629.163 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 5));
629.164 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 6));
629.165 - assertEquals(7, PythonLexerUtils.findSpaceBegin(doc, 7));
629.166 - assertEquals(8, PythonLexerUtils.findSpaceBegin(doc, 8));
629.167 - assertEquals(9, PythonLexerUtils.findSpaceBegin(doc, 9));
629.168 - assertEquals(10, PythonLexerUtils.findSpaceBegin(doc, 10));
629.169 - }
629.170 -
629.171 - public void testFindSpaceBeginNoNewlines() {
629.172 - // Spaces in strings don't count
629.173 - String s = "x = \n 'f oo'";
629.174 - BaseDocument doc = getDocument(s);
629.175 - assertEquals(0, PythonLexerUtils.findSpaceBegin(doc, 0));
629.176 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 1));
629.177 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 2));
629.178 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 3));
629.179 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 4));
629.180 - assertEquals(5, PythonLexerUtils.findSpaceBegin(doc, 5));
629.181 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 6));
629.182 - assertEquals(7, PythonLexerUtils.findSpaceBegin(doc, 7));
629.183 - assertEquals(8, PythonLexerUtils.findSpaceBegin(doc, 8));
629.184 - assertEquals(9, PythonLexerUtils.findSpaceBegin(doc, 9));
629.185 - assertEquals(10, PythonLexerUtils.findSpaceBegin(doc, 10));
629.186 - }
629.187 -
629.188 - public void testFindSpaceBeginNoNewlinesBlank() {
629.189 - String s = "x = \n ";
629.190 - BaseDocument doc = getDocument(s);
629.191 - assertEquals(0, PythonLexerUtils.findSpaceBegin(doc, 0));
629.192 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 1));
629.193 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 2));
629.194 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 3));
629.195 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 4));
629.196 - assertEquals(5, PythonLexerUtils.findSpaceBegin(doc, 5));
629.197 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 6));
629.198 - assertEquals(7, PythonLexerUtils.findSpaceBegin(doc, 7));
629.199 - assertEquals(8, PythonLexerUtils.findSpaceBegin(doc, 8));
629.200 - }
629.201 -
629.202 - public void testFindSpaceBeginLineContinuation() {
629.203 - String s = "foo(a, \n f";
629.204 - BaseDocument doc = getDocument(s);
629.205 - assertEquals(0, PythonLexerUtils.findSpaceBegin(doc, 0));
629.206 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 1));
629.207 - assertEquals(2, PythonLexerUtils.findSpaceBegin(doc, 2));
629.208 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 3));
629.209 - assertEquals(4, PythonLexerUtils.findSpaceBegin(doc, 4));
629.210 - assertEquals(5, PythonLexerUtils.findSpaceBegin(doc, 5));
629.211 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 6));
629.212 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 7));
629.213 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 8));
629.214 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 9));
629.215 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 10));
629.216 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 11));
629.217 - assertEquals(12, PythonLexerUtils.findSpaceBegin(doc, 12));
629.218 - }
629.219 - public void testFindSpaceBeginBlanks() {
629.220 - String s = " \n ";
629.221 - BaseDocument doc = getDocument(s);
629.222 - assertEquals(0, PythonLexerUtils.findSpaceBegin(doc, 0));
629.223 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 1));
629.224 - assertEquals(2, PythonLexerUtils.findSpaceBegin(doc, 2));
629.225 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 3));
629.226 - assertEquals(4, PythonLexerUtils.findSpaceBegin(doc, 4));
629.227 - }
629.228 -}
630.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonStringLexerTest.java Sun Jan 04 13:11:53 2015 -0600
630.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
630.3 @@ -1,121 +0,0 @@
630.4 -/*
630.5 - * To change this template, choose Tools | Templates
630.6 - * and open the template in the editor.
630.7 - */
630.8 -
630.9 -package org.netbeans.modules.python.editor.lexer;
630.10 -
630.11 -import java.util.logging.Level;
630.12 -import java.util.logging.Logger;
630.13 -import org.netbeans.api.lexer.TokenHierarchy;
630.14 -import org.netbeans.api.lexer.TokenSequence;
630.15 -import org.netbeans.junit.NbTestCase;
630.16 -import org.netbeans.lib.lexer.test.LexerTestUtilities;
630.17 -
630.18 -/**
630.19 - *
630.20 - * @author Tor Norbye
630.21 - */
630.22 -public class PythonStringLexerTest extends NbTestCase {
630.23 -
630.24 - public PythonStringLexerTest(String testName) {
630.25 - super(testName);
630.26 - }
630.27 -
630.28 - @Override
630.29 - protected void setUp() throws java.lang.Exception {
630.30 - Logger.getLogger(PythonStringLexer.class.getName()).setLevel(Level.FINEST);
630.31 - }
630.32 -
630.33 - @Override
630.34 - protected void tearDown() throws java.lang.Exception {
630.35 - }
630.36 -
630.37 - @Override
630.38 - protected Level logLevel() {
630.39 - // enabling logging
630.40 - return Level.INFO; // uncomment this to have logging from PyhonLexer
630.41 - // we are only interested in a single logger, so we set its level in setUp(),
630.42 - // as returning Level.FINEST here would log from all loggers
630.43 - }
630.44 -
630.45 - public void test1() {
630.46 - String text =
630.47 - "\nThis is the \"example\" module.\n\nThe example module supplies one function, factorial(). For example,\n\n>>> factorial(5)120\n";
630.48 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
630.49 - TokenSequence ts = hi.tokenSequence();
630.50 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\nThis is the \"example\" module.\n\nThe example module supplies one function, factorial(). For example,\n\n");
630.51 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.EMBEDDED_PYTHON, ">>> factorial(5)120");
630.52 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\n");
630.53 - assertFalse(ts.moveNext());
630.54 - }
630.55 -
630.56 - public void test2() {
630.57 - String text =
630.58 - "\n>>\n";
630.59 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
630.60 - TokenSequence ts = hi.tokenSequence();
630.61 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\n>>\n");
630.62 - assertFalse(ts.moveNext());
630.63 - }
630.64 -
630.65 - public void test3() {
630.66 - String text =
630.67 - "\n>>>\n";
630.68 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
630.69 - TokenSequence ts = hi.tokenSequence();
630.70 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\n");
630.71 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, ">>>\n");
630.72 - assertFalse(ts.moveNext());
630.73 - }
630.74 -
630.75 - public void test4() {
630.76 - String text =
630.77 - "\n>>> \n";
630.78 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
630.79 - TokenSequence ts = hi.tokenSequence();
630.80 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\n");
630.81 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, ">>> \n");
630.82 - assertFalse(ts.moveNext());
630.83 - }
630.84 -
630.85 - public void test5() {
630.86 - String text =
630.87 - "\n>>>";
630.88 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
630.89 - TokenSequence ts = hi.tokenSequence();
630.90 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\n");
630.91 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, ">>>");
630.92 - assertFalse(ts.moveNext());
630.93 - }
630.94 -
630.95 - public void test6() {
630.96 - String text =
630.97 - "\n>>>>";
630.98 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
630.99 - TokenSequence ts = hi.tokenSequence();
630.100 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\n");
630.101 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, ">>>>");
630.102 - assertFalse(ts.moveNext());
630.103 - }
630.104 -
630.105 - public void test8() {
630.106 - String text =
630.107 - "\\";
630.108 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
630.109 - TokenSequence ts = hi.tokenSequence();
630.110 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_INVALID, "\\");
630.111 - assertFalse(ts.moveNext());
630.112 - }
630.113 -
630.114 - public void test9() {
630.115 - String text =
630.116 - "a\\nb";
630.117 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
630.118 - TokenSequence ts = hi.tokenSequence();
630.119 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "a");
630.120 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_ESCAPE, "\\n");
630.121 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "b");
630.122 - assertFalse(ts.moveNext());
630.123 - }
630.124 -}
631.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonStringTokenDumpTest.java Sun Jan 04 13:11:53 2015 -0600
631.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
631.3 @@ -1,69 +0,0 @@
631.4 -/*
631.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
631.6 - *
631.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
631.8 - *
631.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
631.10 - * Other names may be trademarks of their respective owners.
631.11 - *
631.12 - * The contents of this file are subject to the terms of either the GNU
631.13 - * General Public License Version 2 only ("GPL") or the Common
631.14 - * Development and Distribution License("CDDL") (collectively, the
631.15 - * "License"). You may not use this file except in compliance with the
631.16 - * License. You can obtain a copy of the License at
631.17 - * http://www.netbeans.org/cddl-gplv2.html
631.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
631.19 - * specific language governing permissions and limitations under the
631.20 - * License. When distributing the software, include this License Header
631.21 - * Notice in each file and include the License file at
631.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
631.23 - * particular file as subject to the "Classpath" exception as provided
631.24 - * by Oracle in the GPL Version 2 section of the License file that
631.25 - * accompanied this code. If applicable, add the following below the
631.26 - * License Header, with the fields enclosed by brackets [] replaced by
631.27 - * your own identifying information:
631.28 - * "Portions Copyrighted [year] [name of copyright owner]"
631.29 - *
631.30 - * Contributor(s):
631.31 - *
631.32 - * The Original Software is NetBeans. The Initial Developer of the Original
631.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
631.34 - * Microsystems, Inc. All Rights Reserved.
631.35 - *
631.36 - * If you wish your version of this file to be governed by only the CDDL
631.37 - * or only the GPL Version 2, indicate your decision by adding
631.38 - * "[Contributor] elects to include this software in this distribution
631.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
631.40 - * single choice of license, a recipient has the option to distribute
631.41 - * your version of this file under either the CDDL, the GPL Version 2 or
631.42 - * to extend the choice of license to its licensees as provided above.
631.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
631.44 - * Version 2 license, then the option applies only if the new code is
631.45 - * made subject to such option by the copyright holder.
631.46 - */
631.47 -
631.48 -package org.netbeans.modules.python.editor.lexer;
631.49 -
631.50 -import org.netbeans.junit.NbTestCase;
631.51 -import org.netbeans.lib.lexer.test.LexerTestUtilities;
631.52 -
631.53 -/**
631.54 - * Test tokens dump of Python -string- code input.
631.55 - */
631.56 -public class PythonStringTokenDumpTest extends NbTestCase {
631.57 -
631.58 - public PythonStringTokenDumpTest(String testName) {
631.59 - super(testName);
631.60 - }
631.61 -
631.62 - @Override
631.63 - protected void setUp() throws java.lang.Exception {
631.64 - // Set-up testing environment
631.65 - LexerTestUtilities.setTesting(true);
631.66 - }
631.67 -
631.68 - public void testInput() throws Exception {
631.69 - LexerTestUtilities.checkTokenDump(this, "testfiles/syntax-string.py.txt",
631.70 - PythonStringTokenId.language);
631.71 - }
631.72 -}
632.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonTokenDumpTest.java Sun Jan 04 13:11:53 2015 -0600
632.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
632.3 @@ -1,69 +0,0 @@
632.4 -/*
632.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
632.6 - *
632.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
632.8 - *
632.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
632.10 - * Other names may be trademarks of their respective owners.
632.11 - *
632.12 - * The contents of this file are subject to the terms of either the GNU
632.13 - * General Public License Version 2 only ("GPL") or the Common
632.14 - * Development and Distribution License("CDDL") (collectively, the
632.15 - * "License"). You may not use this file except in compliance with the
632.16 - * License. You can obtain a copy of the License at
632.17 - * http://www.netbeans.org/cddl-gplv2.html
632.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
632.19 - * specific language governing permissions and limitations under the
632.20 - * License. When distributing the software, include this License Header
632.21 - * Notice in each file and include the License file at
632.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
632.23 - * particular file as subject to the "Classpath" exception as provided
632.24 - * by Oracle in the GPL Version 2 section of the License file that
632.25 - * accompanied this code. If applicable, add the following below the
632.26 - * License Header, with the fields enclosed by brackets [] replaced by
632.27 - * your own identifying information:
632.28 - * "Portions Copyrighted [year] [name of copyright owner]"
632.29 - *
632.30 - * Contributor(s):
632.31 - *
632.32 - * The Original Software is NetBeans. The Initial Developer of the Original
632.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
632.34 - * Microsystems, Inc. All Rights Reserved.
632.35 - *
632.36 - * If you wish your version of this file to be governed by only the CDDL
632.37 - * or only the GPL Version 2, indicate your decision by adding
632.38 - * "[Contributor] elects to include this software in this distribution
632.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
632.40 - * single choice of license, a recipient has the option to distribute
632.41 - * your version of this file under either the CDDL, the GPL Version 2 or
632.42 - * to extend the choice of license to its licensees as provided above.
632.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
632.44 - * Version 2 license, then the option applies only if the new code is
632.45 - * made subject to such option by the copyright holder.
632.46 - */
632.47 -
632.48 -package org.netbeans.modules.python.editor.lexer;
632.49 -
632.50 -import org.netbeans.junit.NbTestCase;
632.51 -import org.netbeans.lib.lexer.test.LexerTestUtilities;
632.52 -
632.53 -/**
632.54 - * Test tokens dump of Python code input. Based on Java one by Mila Metelka.
632.55 - */
632.56 -public class PythonTokenDumpTest extends NbTestCase {
632.57 -
632.58 - public PythonTokenDumpTest(String testName) {
632.59 - super(testName);
632.60 - }
632.61 -
632.62 - @Override
632.63 - protected void setUp() throws java.lang.Exception {
632.64 - // Set-up testing environment
632.65 - LexerTestUtilities.setTesting(true);
632.66 - }
632.67 -
632.68 - public void testInput() throws Exception {
632.69 - LexerTestUtilities.checkTokenDump(this, "testfiles/syntax.py.txt",
632.70 - PythonTokenId.language());
632.71 - }
632.72 -}
633.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/scopes/SymbolTableTest.java Sun Jan 04 13:11:53 2015 -0600
633.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
633.3 @@ -1,265 +0,0 @@
633.4 -/*
633.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
633.6 - *
633.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
633.8 - *
633.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
633.10 - * Other names may be trademarks of their respective owners.
633.11 - *
633.12 - * The contents of this file are subject to the terms of either the GNU
633.13 - * General Public License Version 2 only ("GPL") or the Common
633.14 - * Development and Distribution License("CDDL") (collectively, the
633.15 - * "License"). You may not use this file except in compliance with the
633.16 - * License. You can obtain a copy of the License at
633.17 - * http://www.netbeans.org/cddl-gplv2.html
633.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
633.19 - * specific language governing permissions and limitations under the
633.20 - * License. When distributing the software, include this License Header
633.21 - * Notice in each file and include the License file at
633.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
633.23 - * particular file as subject to the "Classpath" exception as provided
633.24 - * by Oracle in the GPL Version 2 section of the License file that
633.25 - * accompanied this code. If applicable, add the following below the
633.26 - * License Header, with the fields enclosed by brackets [] replaced by
633.27 - * your own identifying information:
633.28 - * "Portions Copyrighted [year] [name of copyright owner]"
633.29 - *
633.30 - * If you wish your version of this file to be governed by only the CDDL
633.31 - * or only the GPL Version 2, indicate your decision by adding
633.32 - * "[Contributor] elects to include this software in this distribution
633.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
633.34 - * single choice of license, a recipient has the option to distribute
633.35 - * your version of this file under either the CDDL, the GPL Version 2 or
633.36 - * to extend the choice of license to its licensees as provided above.
633.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
633.38 - * Version 2 license, then the option applies only if the new code is
633.39 - * made subject to such option by the copyright holder.
633.40 - *
633.41 - * Contributor(s):
633.42 - *
633.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
633.44 - */
633.45 -package org.netbeans.modules.python.editor.scopes;
633.46 -
633.47 -import java.util.ArrayList;
633.48 -import java.util.Collections;
633.49 -import java.util.List;
633.50 -import java.util.Map;
633.51 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
633.52 -import org.netbeans.modules.gsf.api.NameKind;
633.53 -import org.netbeans.modules.python.editor.AstPath;
633.54 -import org.netbeans.modules.python.editor.PythonAstUtils;
633.55 -import org.netbeans.modules.python.editor.PythonParserResult;
633.56 -import org.netbeans.modules.python.editor.PythonTestBase;
633.57 -import org.netbeans.modules.python.editor.PythonUtils;
633.58 -import org.openide.filesystems.FileObject;
633.59 -import org.openide.filesystems.FileUtil;
633.60 -import org.python.antlr.PythonTree;
633.61 -import org.python.antlr.Visitor;
633.62 -
633.63 -/**
633.64 - *
633.65 - * @author Tor Norbye
633.66 - */
633.67 -public class SymbolTableTest extends PythonTestBase {
633.68 -
633.69 - public SymbolTableTest(String name) {
633.70 - super(name);
633.71 - }
633.72 -
633.73 - @SuppressWarnings("unchecked")
633.74 - public void checkScopes(String relFilePath) throws Exception {
633.75 - GsfTestCompilationInfo info = getInfo(getTestFile(relFilePath));
633.76 - PythonTree root = PythonAstUtils.getRoot(info);
633.77 - assertNotNull(root);
633.78 - PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
633.79 - SymbolTable scopeManager = parseResult.getSymbolTable();
633.80 - Map<PythonTree, ScopeInfo> scopes = scopeManager.getScopes();
633.81 -
633.82 - StringBuilder sb = new StringBuilder();
633.83 - List<PythonTree> nodes = new ArrayList<PythonTree>(scopes.keySet());
633.84 - Collections.sort(nodes, PythonUtils.NODE_POS_COMPARATOR);
633.85 -
633.86 - for (PythonTree node : nodes) {
633.87 - ScopeInfo scope = scopes.get(node);
633.88 - String dump = scope.dump();
633.89 - sb.append(dump);
633.90 - sb.append("\n");
633.91 - }
633.92 -
633.93 - assertDescriptionMatches(relFilePath, sb.toString(), false, ".scopes");
633.94 - }
633.95 -
633.96 - public void testScopes1() throws Exception {
633.97 - checkScopes("testfiles/datetime.py");
633.98 - }
633.99 -
633.100 - public void testScopes2() throws Exception {
633.101 - checkScopes("testfiles/unusedimports1.py");
633.102 - }
633.103 -
633.104 - public void testScopes3() throws Exception {
633.105 - checkScopes("testfiles/compl.py");
633.106 - }
633.107 -
633.108 - public void testScopes4() throws Exception {
633.109 - checkScopes("testfiles/scope.py");
633.110 - }
633.111 -
633.112 - public void testScopes5() throws Exception {
633.113 - checkScopes("testfiles/mimetypes.py");
633.114 - }
633.115 -
633.116 - public void testScopes6() throws Exception {
633.117 - checkScopes("testfiles/scope2.py");
633.118 - }
633.119 -
633.120 - public void testScopes7() throws Exception {
633.121 - checkScopes("testfiles/unresolved.py");
633.122 - }
633.123 -
633.124 - public void testScopes8() throws Exception {
633.125 - checkScopes("testfiles/ConfigParser.py");
633.126 - }
633.127 -
633.128 - public void testScopes9() throws Exception {
633.129 - checkScopes("testfiles/old-decorators1.py");
633.130 - }
633.131 -
633.132 - public void testScopes10() throws Exception {
633.133 - checkScopes("testfiles/old-decorators2.py");
633.134 - }
633.135 -
633.136 - public void testScopes11() throws Exception {
633.137 - // Generates duplicate arg warning!
633.138 - checkScopes("testfiles/formatting.py");
633.139 - }
633.140 -
633.141 - public void testScopes12() throws Exception {
633.142 - // Make sure we handle __all__ generators
633.143 - checkScopes("testfiles/tokenize.py");
633.144 - }
633.145 -
633.146 - public void testScopes13() throws Exception {
633.147 - // Make sure we invalidate the __all__ list if we're messing with it
633.148 - checkScopes("testfiles/os.py");
633.149 - }
633.150 -
633.151 - public void testScopes14() throws Exception {
633.152 - checkScopes("testfiles/zipfile.py");
633.153 - }
633.154 -
633.155 - public void testScopes15() throws Exception {
633.156 - checkScopes("testfiles/scope3.py");
633.157 - }
633.158 -
633.159 - public void testScopes16() throws Exception {
633.160 - checkScopes("testfiles/unittest.py");
633.161 - }
633.162 -
633.163 - public void testScopes17() throws Exception {
633.164 - checkScopes("testfiles/delete2.py");
633.165 - }
633.166 -
633.167 - // Unstable
633.168 - //public void testScopes17() throws Exception {
633.169 - // checkScopes("testfiles/attributes.py");
633.170 - //}
633.171 - //
633.172 - // Unstable
633.173 - //public void testScopes18() throws Exception {
633.174 - // checkScopes("testfiles/decorators.py");
633.175 - //}
633.176 -
633.177 - public void testStress() throws Exception {
633.178 - initializeClassPaths();
633.179 -
633.180 - List<FileObject> files = findJythonFiles();
633.181 -
633.182 - int MAX_FILES = Integer.MAX_VALUE;
633.183 -
633.184 - for (int i = 0; i < files.size() && i < MAX_FILES; i++) {
633.185 - // Don't take too long for regular test runs -- just check 20 files
633.186 - // Comment out occasionally for a full run
633.187 - if (i == 20) {
633.188 - break;
633.189 - }
633.190 - final FileObject fo = files.get(i);
633.191 - final GsfTestCompilationInfo info = getInfo(fo);
633.192 - final PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
633.193 - final SymbolTable scopeManager = parseResult.getSymbolTable();
633.194 -
633.195 - System.err.println("Scanning " + FileUtil.getFileDisplayName(fo));
633.196 -
633.197 - scopeManager.getErrors();
633.198 - scopeManager.getFilename();
633.199 - scopeManager.getImports();
633.200 - scopeManager.getImportsFrom();
633.201 - scopeManager.getMainImports();
633.202 - scopeManager.getPublicSymbols();
633.203 - scopeManager.getUnresolved(info);
633.204 - scopeManager.getUnresolvedNames(info);
633.205 - scopeManager.getUnused(false, false);
633.206 - scopeManager.getUnused(false, true);
633.207 - scopeManager.getUnused(true, false);
633.208 - scopeManager.getUnused(true, true);
633.209 - scopeManager.getUnusedImports();
633.210 -
633.211 - PythonTree root = PythonAstUtils.getRoot(info);
633.212 - assertNotNull(FileUtil.getFileDisplayName(fo), root);
633.213 - List<PythonTree> nodes = getAllNodes(root);
633.214 - final List<PythonTree> defs = new ArrayList<PythonTree>();
633.215 - PythonAstUtils.addNodesByType(root, new Class[] { PythonTree.class }, defs);
633.216 - new NodeFinder(new AstPathChecker() {
633.217 - public void check(AstPath path) {
633.218 - PythonTree scope = PythonAstUtils.getLocalScope(path);
633.219 - PythonTree node = path.leaf();
633.220 -
633.221 - PythonAstUtils.isNameNode(node);
633.222 - String name = PythonAstUtils.getName(node);
633.223 - if (name != null) {
633.224 - scopeManager.findDeclaration(scope, name, false);
633.225 - scopeManager.findDeclaration(scope, name, true);
633.226 - scopeManager.getOccurrences(scope, name, false);
633.227 - scopeManager.getOccurrences(scope, name, true);
633.228 - scopeManager.isPrivate(node, name);
633.229 - }
633.230 - if (scope != null) {
633.231 - scopeManager.getDefinedElements(info, scope, "", NameKind.PREFIX);
633.232 - }
633.233 - }
633.234 - }).visit(root);
633.235 -
633.236 - for (PythonTree node : nodes) {
633.237 - scopeManager.isTopLevel(node);
633.238 - scopeManager.error("testerror", true, node);
633.239 - }
633.240 - }
633.241 - }
633.242 -
633.243 - interface AstPathChecker {
633.244 - void check(AstPath path);
633.245 - }
633.246 -
633.247 - private static class NodeFinder extends Visitor {
633.248 - private ArrayList<PythonTree> path = new ArrayList<PythonTree>();
633.249 - private AstPathChecker checker;
633.250 -
633.251 - private NodeFinder(AstPathChecker checker) {
633.252 - this.checker = checker;
633.253 - }
633.254 -
633.255 - @Override
633.256 - public void traverse(PythonTree node) throws Exception {
633.257 - path.add(node);
633.258 -
633.259 - checker.check(new AstPath(path));
633.260 -
633.261 - super.traverse(node);
633.262 - path.remove(path.size()-1);
633.263 - }
633.264 - }
633.265 -
633.266 - // TODO - test the various other functions -- unused, unresolved, etc!
633.267 -
633.268 -}
634.1 --- a/python.help/src/org/netbeans/modules/python/help/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
634.2 +++ b/python.help/src/org/netbeans/modules/python/help/Bundle.properties Sat Feb 28 17:25:32 2015 -0800
634.3 @@ -1,5 +1,5 @@
634.4 OpenIDE-Module-Display-Category=Help
634.5 OpenIDE-Module-Long-Description=\
634.6 IDE Help for Python support in NetBeans
634.7 -OpenIDE-Module-Name=python.help
634.8 +OpenIDE-Module-Name=Python Help
634.9 OpenIDE-Module-Short-Description=Help set for nbPython
635.1 --- a/python.kit/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
635.2 +++ b/python.kit/nbproject/project.xml Sat Feb 28 17:25:32 2015 -0800
635.3 @@ -46,7 +46,7 @@
635.4 <dependency>
635.5 <code-name-base>org.netbeans.modules.python.editor</code-name-base>
635.6 <run-dependency>
635.7 - <specification-version>1.6</specification-version>
635.8 + <specification-version>1.0</specification-version>
635.9 </run-dependency>
635.10 </dependency>
635.11 <dependency>
635.12 @@ -79,6 +79,12 @@
635.13 <specification-version>0.1</specification-version>
635.14 </run-dependency>
635.15 </dependency>
635.16 + <dependency>
635.17 + <code-name-base>org.netbeans.modules.python.project2</code-name-base>
635.18 + <run-dependency>
635.19 + <specification-version>1.0</specification-version>
635.20 + </run-dependency>
635.21 + </dependency>
635.22 </module-dependencies>
635.23 <public-packages/>
635.24 </data>
636.1 --- a/python.platform/src/org/netbeans/modules/python/platform/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
636.2 +++ b/python.platform/src/org/netbeans/modules/python/platform/Bundle.properties Sat Feb 28 17:25:32 2015 -0800
636.3 @@ -1,4 +1,4 @@
636.4 CTL_PythonManagerAction=Python Platforms
636.5 OpenIDE-Module-Display-Category=Python
636.6 -OpenIDE-Module-Name=python.platform
636.7 +OpenIDE-Module-Name=Python Platform
636.8 OpenIDE-Module-Short-Description=Python Platform Manager
637.1 --- a/python.platform/src/org/netbeans/modules/python/platform/panels/PythonPlatformPanel.java Sun Jan 04 13:11:53 2015 -0600
637.2 +++ b/python.platform/src/org/netbeans/modules/python/platform/panels/PythonPlatformPanel.java Sat Feb 28 17:25:32 2015 -0800
637.3 @@ -460,7 +460,7 @@
637.4 //Exceptions.printStackTrace(ex);
637.5 }catch(Exception ex){
637.6 NotifyDescriptor message = new Message(
637.7 - "Invalid Python Type", NotifyDescriptor.ERROR_MESSAGE); // was Invlaid and platform_info.py is NOT where expected
637.8 + "Invalid Python Type", NotifyDescriptor.ERROR_MESSAGE); // was Invaid and platform_info.py is NOT where expected
637.9 DialogDisplayer.getDefault().notify(message);
637.10 }
637.11 }
638.1 --- a/python.project/nbproject/project.properties Sun Jan 04 13:11:53 2015 -0600
638.2 +++ b/python.project/nbproject/project.properties Sat Feb 28 17:25:32 2015 -0800
638.3 @@ -8,7 +8,7 @@
638.4 auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesAfterClassHeader=0
638.5 auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch=false
638.6 auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaceAfterTypeCast=false
638.7 -javac.source=1.6
638.8 +javac.source=1.7
638.9 javac.compilerargs=-Xlint -Xlint:-serial
638.10
638.11 test-unit-sys-prop.xtest.python.home=${netbeans.dest.dir}/python/jython-2.5.1
639.1 --- a/python.project/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
639.2 +++ b/python.project/nbproject/project.xml Sat Feb 28 17:25:32 2015 -0800
639.3 @@ -6,6 +6,24 @@
639.4 <code-name-base>org.netbeans.modules.python.project</code-name-base>
639.5 <module-dependencies>
639.6 <dependency>
639.7 + <code-name-base>org.netbeans.api.annotations.common</code-name-base>
639.8 + <build-prerequisite/>
639.9 + <compile-dependency/>
639.10 + <run-dependency>
639.11 + <release-version>1</release-version>
639.12 + <specification-version>1.25</specification-version>
639.13 + </run-dependency>
639.14 + </dependency>
639.15 + <dependency>
639.16 + <code-name-base>org.netbeans.api.java.classpath</code-name-base>
639.17 + <build-prerequisite/>
639.18 + <compile-dependency/>
639.19 + <run-dependency>
639.20 + <release-version>1</release-version>
639.21 + <specification-version>1.48</specification-version>
639.22 + </run-dependency>
639.23 + </dependency>
639.24 + <dependency>
639.25 <code-name-base>org.netbeans.api.progress</code-name-base>
639.26 <build-prerequisite/>
639.27 <compile-dependency/>
639.28 @@ -40,15 +58,6 @@
639.29 </run-dependency>
639.30 </dependency>
639.31 <dependency>
639.32 - <code-name-base>org.netbeans.modules.gsfpath.api</code-name-base>
639.33 - <build-prerequisite/>
639.34 - <compile-dependency/>
639.35 - <run-dependency>
639.36 - <release-version>1</release-version>
639.37 - <specification-version>0.30</specification-version>
639.38 - </run-dependency>
639.39 - </dependency>
639.40 - <dependency>
639.41 <code-name-base>org.netbeans.modules.project.ant</code-name-base>
639.42 <build-prerequisite/>
639.43 <compile-dependency/>
639.44 @@ -109,6 +118,14 @@
639.45 </run-dependency>
639.46 </dependency>
639.47 <dependency>
639.48 + <code-name-base>org.netbeans.modules.python.source</code-name-base>
639.49 + <build-prerequisite/>
639.50 + <compile-dependency/>
639.51 + <run-dependency>
639.52 + <specification-version>1.0</specification-version>
639.53 + </run-dependency>
639.54 + </dependency>
639.55 + <dependency>
639.56 <code-name-base>org.netbeans.modules.queries</code-name-base>
639.57 <build-prerequisite/>
639.58 <compile-dependency/>
639.59 @@ -174,14 +191,6 @@
639.60 </run-dependency>
639.61 </dependency>
639.62 <dependency>
639.63 - <code-name-base>org.openide.util.ui</code-name-base>
639.64 - <build-prerequisite/>
639.65 - <compile-dependency/>
639.66 - <run-dependency>
639.67 - <specification-version>9.3</specification-version>
639.68 - </run-dependency>
639.69 - </dependency>
639.70 - <dependency>
639.71 <code-name-base>org.openide.util</code-name-base>
639.72 <build-prerequisite/>
639.73 <compile-dependency/>
639.74 @@ -198,6 +207,14 @@
639.75 </run-dependency>
639.76 </dependency>
639.77 <dependency>
639.78 + <code-name-base>org.openide.util.ui</code-name-base>
639.79 + <build-prerequisite/>
639.80 + <compile-dependency/>
639.81 + <run-dependency>
639.82 + <specification-version>9.3</specification-version>
639.83 + </run-dependency>
639.84 + </dependency>
639.85 + <dependency>
639.86 <code-name-base>org.openide.windows</code-name-base>
639.87 <build-prerequisite/>
639.88 <compile-dependency/>
639.89 @@ -215,66 +232,6 @@
639.90 </run-dependency>
639.91 </dependency>
639.92 </module-dependencies>
639.93 - <test-dependencies>
639.94 - <test-type>
639.95 - <name>unit</name>
639.96 - <test-dependency>
639.97 - <code-name-base>org.netbeans.libs.junit4</code-name-base>
639.98 - <compile-dependency/>
639.99 - </test-dependency>
639.100 - <test-dependency>
639.101 - <code-name-base>org.netbeans.modules.editor.lib</code-name-base>
639.102 - <compile-dependency/>
639.103 - </test-dependency>
639.104 - <test-dependency>
639.105 - <code-name-base>org.netbeans.modules.editor.mimelookup</code-name-base>
639.106 - <recursive/>
639.107 - <compile-dependency/>
639.108 - <test/>
639.109 - </test-dependency>
639.110 - <test-dependency>
639.111 - <code-name-base>org.netbeans.modules.editor.mimelookup.impl</code-name-base>
639.112 - </test-dependency>
639.113 - <test-dependency>
639.114 - <code-name-base>org.netbeans.modules.editor.util</code-name-base>
639.115 - <recursive/>
639.116 - <compile-dependency/>
639.117 - </test-dependency>
639.118 - <test-dependency>
639.119 - <code-name-base>org.netbeans.modules.gsf</code-name-base>
639.120 - <recursive/>
639.121 - <compile-dependency/>
639.122 - <test/>
639.123 - </test-dependency>
639.124 - <test-dependency>
639.125 - <code-name-base>org.netbeans.modules.lexer</code-name-base>
639.126 - <compile-dependency/>
639.127 - <test/>
639.128 - </test-dependency>
639.129 - <test-dependency>
639.130 - <code-name-base>org.netbeans.modules.masterfs</code-name-base>
639.131 - </test-dependency>
639.132 - <test-dependency>
639.133 - <code-name-base>org.netbeans.modules.nbjunit</code-name-base>
639.134 - <recursive/>
639.135 - <compile-dependency/>
639.136 - </test-dependency>
639.137 - <test-dependency>
639.138 - <code-name-base>org.netbeans.modules.python.editor</code-name-base>
639.139 - <recursive/>
639.140 - <compile-dependency/>
639.141 - <test/>
639.142 - </test-dependency>
639.143 - <test-dependency>
639.144 - <code-name-base>org.netbeans.modules.python.project</code-name-base>
639.145 - <recursive/>
639.146 - <compile-dependency/>
639.147 - </test-dependency>
639.148 - <test-dependency>
639.149 - <code-name-base>org.openide.util</code-name-base>
639.150 - </test-dependency>
639.151 - </test-type>
639.152 - </test-dependencies>
639.153 <public-packages>
639.154 <package>org.netbeans.modules.python.project.spi</package>
639.155 <package>org.netbeans.modules.python.project</package>
640.1 --- a/python.project/src/org/netbeans/modules/python/project/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
640.2 +++ b/python.project/src/org/netbeans/modules/python/project/Bundle.properties Sat Feb 28 17:25:32 2015 -0800
640.3 @@ -3,8 +3,8 @@
640.4 Provides a basic project type which can hold Python source code.
640.5 OpenIDE-Module-Name=Python Projects
640.6 OpenIDE-Module-Short-Description=Project type for Python sources.
640.7 -Templates/Project/Python/PythonProject.xml=Python Project
640.8 -Templates/Project/Python/ExistingPythonProject.xml=Python Project with Existing Sources
640.9 +Templates/Project/Python/PythonProject.xml=Python Project - Ant
640.10 +Templates/Project/Python/ExistingPythonProject.xml=Python Project with Existing Sources - Ant
640.11 #SourceRoots
640.12 NAME_src.dir=Sources
640.13 NAME_test.src.dir=Tests
641.1 --- a/python.project/src/org/netbeans/modules/python/project/PythonBaseProject.java Sun Jan 04 13:11:53 2015 -0600
641.2 +++ b/python.project/src/org/netbeans/modules/python/project/PythonBaseProject.java Sat Feb 28 17:25:32 2015 -0800
641.3 @@ -16,8 +16,8 @@
641.4 import org.netbeans.api.project.Project;
641.5 import org.netbeans.api.project.ProjectInformation;
641.6 import org.netbeans.api.project.ProjectManager;
641.7 -import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
641.8 -import org.netbeans.modules.gsfpath.api.classpath.GlobalPathRegistry;
641.9 +//import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
641.10 +//import org.netbeans.modules.gsfpath.api.classpath.GlobalPathRegistry;
641.11 import org.netbeans.modules.python.editor.codecoverage.PythonCoverageProvider;
641.12 import org.netbeans.spi.project.AuxiliaryConfiguration;
641.13 import org.netbeans.spi.project.support.ant.AntProjectHelper;
642.1 --- a/python.project/src/org/netbeans/modules/python/project/PythonProject.java Sun Jan 04 13:11:53 2015 -0600
642.2 +++ b/python.project/src/org/netbeans/modules/python/project/PythonProject.java Sat Feb 28 17:25:32 2015 -0800
642.3 @@ -2,7 +2,6 @@
642.4 * To change this template, choose Tools | Templates
642.5 * and open the template in the editor.
642.6 */
642.7 -
642.8 package org.netbeans.modules.python.project;
642.9
642.10 import java.beans.PropertyChangeListener;
642.11 @@ -10,15 +9,16 @@
642.12 import java.io.IOException;
642.13 import javax.swing.Icon;
642.14 import javax.swing.ImageIcon;
642.15 +import org.netbeans.api.java.classpath.ClassPath;
642.16 +import org.netbeans.api.java.classpath.GlobalPathRegistry;
642.17 import org.netbeans.modules.python.api.PythonPlatformProvider;
642.18 import org.netbeans.modules.python.project.gsf.ClassPathProviderImpl;
642.19 import org.netbeans.modules.python.project.ui.customizer.PythonCustomizerProvider;
642.20 import org.netbeans.api.project.Project;
642.21 import org.netbeans.api.project.ProjectInformation;
642.22 import org.netbeans.api.project.ProjectManager;
642.23 -import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
642.24 -import org.netbeans.modules.gsfpath.api.classpath.GlobalPathRegistry;
642.25 import org.netbeans.modules.python.editor.codecoverage.PythonCoverageProvider;
642.26 +import org.netbeans.modules.python.source.queries.SourceLevelQueryImplementation;
642.27 import org.netbeans.spi.project.AuxiliaryConfiguration;
642.28 import org.netbeans.spi.project.support.ant.AntProjectHelper;
642.29 import org.netbeans.spi.project.support.ant.ProjectXmlSavedHook;
642.30 @@ -47,82 +47,86 @@
642.31 * @author Tomas Zezula
642.32 */
642.33 public class PythonProject implements Project {
642.34 -
642.35 +
642.36 private static final ImageIcon PROJECT_ICON = ImageUtilities.loadImageIcon("org/netbeans/modules/python/project/resources/py_25_16.png", false);
642.37 -
642.38 +
642.39 protected AntProjectHelper helper;
642.40 - protected UpdateHelper updateHelper;
642.41 - protected LogicalViewProvider logicalView = new PythonLogicalView(this);
642.42 - protected SourceRoots sourceRoots;
642.43 - protected SourceRoots testRoots;
642.44 - protected Lookup lkp;
642.45 - protected PropertyEvaluator evaluator;
642.46 - protected ReferenceHelper refHelper;
642.47 - protected AuxiliaryConfiguration aux;
642.48 -
642.49 + protected UpdateHelper updateHelper;
642.50 + protected LogicalViewProvider logicalView = new PythonLogicalView(this);
642.51 + protected SourceRoots sourceRoots;
642.52 + protected SourceRoots testRoots;
642.53 + protected Lookup lkp;
642.54 + protected PropertyEvaluator evaluator;
642.55 + protected ReferenceHelper refHelper;
642.56 + protected AuxiliaryConfiguration aux;
642.57 +
642.58 public PythonProject(final AntProjectHelper helper) {
642.59 assert helper != null;
642.60 this.helper = helper;
642.61 - this.updateHelper = new UpdateHelper(UpdateImplementation.NULL,helper);
642.62 + this.updateHelper = new UpdateHelper(UpdateImplementation.NULL, helper);
642.63 this.evaluator = createEvaluator();
642.64 - this.aux = helper.createAuxiliaryConfiguration();
642.65 + this.aux = helper.createAuxiliaryConfiguration();
642.66 refHelper = new ReferenceHelper(helper, aux, evaluator);
642.67 this.sourceRoots = SourceRoots.create(updateHelper, evaluator, refHelper, false);
642.68 this.testRoots = SourceRoots.create(updateHelper, evaluator, refHelper, true);
642.69 this.lkp = createLookup();
642.70 }
642.71 -public PythonProject()
642.72 -{
642.73 -
642.74 -}
642.75 +
642.76 + public PythonProject() {
642.77 +
642.78 + }
642.79 +
642.80 + @Override
642.81 public FileObject getProjectDirectory() {
642.82 return helper.getProjectDirectory();
642.83 }
642.84 -
642.85 - public PropertyEvaluator createEvaluator() {
642.86 +
642.87 + public PropertyEvaluator createEvaluator() {
642.88 PropertyEvaluator privateProps = PropertyUtils.sequentialPropertyEvaluator(
642.89 helper.getStockPropertyPreprovider(),
642.90 helper.getPropertyProvider(AntProjectHelper.PRIVATE_PROPERTIES_PATH));
642.91 return PropertyUtils.sequentialPropertyEvaluator(
642.92 - helper.getStockPropertyPreprovider(),
642.93 + helper.getStockPropertyPreprovider(),
642.94 helper.getPropertyProvider(AntProjectHelper.PRIVATE_PROPERTIES_PATH),
642.95 PropertyUtils.userPropertiesProvider(privateProps,
642.96 - "user.properties.file", FileUtil.toFile(getProjectDirectory())), // NOI18N
642.97 + "user.properties.file", FileUtil.toFile(getProjectDirectory())), // NOI18N
642.98 helper.getPropertyProvider(AntProjectHelper.PROJECT_PROPERTIES_PATH));
642.99 }
642.100 -
642.101 - private Lookup createLookup () {
642.102 +
642.103 + private Lookup createLookup() {
642.104 return Lookups.fixed(new Object[]{
642.105 - this, //project spec requires a project be in it's own lookup
642.106 - aux, //Auxiliary configuartion to store bookmarks and so on
642.107 - new PythonActionProvider(this), //Provides Standard like build and cleen
642.108 - new ClassPathProviderImpl(this),
642.109 - new Info(), // Project information Implementation
642.110 - logicalView, // Logical view if project implementation
642.111 - new PythonOpenedHook(), //Called by project framework when project is opened (closed)
642.112 - new PythonProjectXmlSavedHook(), //Called when project.xml changes
642.113 - new PythonSources(this, helper,evaluator,sourceRoots,testRoots), //Python source grops - used by package view, factories, refactoring, ...
642.114 - new PythonProjectOperations(this), //move, rename, copy of project
642.115 - new RecommendedTemplatesImpl(this.updateHelper), // Recommended Templates
642.116 - new PythonCustomizerProvider(this), //Project custmoizer
642.117 - new PythonProjectFileEncodingQuery(getEvaluator()), //Provides encoding of the project - used by editor, runtime
642.118 - new PythonSharabilityQuery(helper, getEvaluator(), getSourceRoots(), getTestRoots()), //Sharabilit info - used by VCS
642.119 - helper.createCacheDirectoryProvider(), //Cache provider
642.120 - helper.createAuxiliaryProperties(), // AuxiliaryConfiguraion provider - used by bookmarks, project Preferences, etc
642.121 - new PythonPlatformProvider(getEvaluator()),
642.122 - new PythonCoverageProvider(this)
642.123 - });
642.124 + this, //project spec requires a project be in it's own lookup
642.125 + aux, //Auxiliary configuartion to store bookmarks and so on
642.126 + new PythonActionProvider(this), //Provides Standard like build and cleen
642.127 + new ClassPathProviderImpl(this),
642.128 + new Info(), // Project information Implementation
642.129 + logicalView, // Logical view if project implementation
642.130 + new PythonOpenedHook(), //Called by project framework when project is opened (closed)
642.131 + new PythonProjectXmlSavedHook(), //Called when project.xml changes
642.132 + new PythonSources(this, helper, evaluator, sourceRoots, testRoots), //Python source grops - used by package view, factories, refactoring, ...
642.133 + new PythonProjectOperations(this), //move, rename, copy of project
642.134 + new RecommendedTemplatesImpl(this.updateHelper), // Recommended Templates
642.135 + new PythonCustomizerProvider(this), //Project custmoizer
642.136 + new PythonProjectFileEncodingQuery(getEvaluator()), //Provides encoding of the project - used by editor, runtime
642.137 + new PythonSharabilityQuery(helper, getEvaluator(), getSourceRoots(), getTestRoots()), //Sharabilit info - used by VCS
642.138 + helper.createCacheDirectoryProvider(), //Cache provider
642.139 + helper.createAuxiliaryProperties(), // AuxiliaryConfiguraion provider - used by bookmarks, project Preferences, etc
642.140 + new PythonPlatformProvider(getEvaluator()),
642.141 + new PythonCoverageProvider(this),
642.142 + new PythonProjectSourceLevelQuery(evaluator, "")
642.143 + });
642.144 }
642.145 -
642.146 - public Lookup getLookup() {
642.147 +
642.148 + @Override
642.149 + public Lookup getLookup() {
642.150 return lkp;
642.151 }
642.152 -
642.153 - public SourceRoots getSourceRoots () {
642.154 +
642.155 + public SourceRoots getSourceRoots() {
642.156 return this.sourceRoots;
642.157 }
642.158 -
642.159 - public SourceRoots getTestRoots () {
642.160 +
642.161 + public SourceRoots getTestRoots() {
642.162 return this.testRoots;
642.163 }
642.164
642.165 @@ -134,20 +138,21 @@
642.166 return getTestRoots().getRoots();
642.167 }
642.168
642.169 - public PropertyEvaluator getEvaluator () {
642.170 + public PropertyEvaluator getEvaluator() {
642.171 return evaluator;
642.172 }
642.173 -
642.174 - AntProjectHelper getHelper () {
642.175 +
642.176 + AntProjectHelper getHelper() {
642.177 return this.helper;
642.178 }
642.179 -
642.180 +
642.181 public FileObject getSrcFolder() {
642.182 return getProjectDirectory();
642.183 - }
642.184 -
642.185 - public String getName () {
642.186 + }
642.187 +
642.188 + public String getName() {
642.189 return ProjectManager.mutex().readAccess(new Mutex.Action<String>() {
642.190 + @Override
642.191 public String run() {
642.192 Element data = getHelper().getPrimaryConfigurationData(true);
642.193 NodeList nl = data.getElementsByTagNameNS(PythonProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name"); // NOI18N
642.194 @@ -162,9 +167,10 @@
642.195 }
642.196 });
642.197 }
642.198 -
642.199 +
642.200 void setName(final String name) {
642.201 ProjectManager.mutex().writeAccess(new Runnable() {
642.202 + @Override
642.203 public void run() {
642.204 Element data = getHelper().getPrimaryConfigurationData(true);
642.205 NodeList nl = data.getElementsByTagNameNS(PythonProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name"); // NOI18N
642.206 @@ -178,48 +184,56 @@
642.207 } else {
642.208 nameEl = data.getOwnerDocument().createElementNS(
642.209 PythonProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name"); // NOI18N
642.210 - data.insertBefore(nameEl, /* OK if null */data.getChildNodes().item(0));
642.211 + data.insertBefore(nameEl, /* OK if null */ data.getChildNodes().item(0));
642.212 }
642.213 nameEl.appendChild(data.getOwnerDocument().createTextNode(name));
642.214 getHelper().putPrimaryConfigurationData(data, true);
642.215 }
642.216 });
642.217 }
642.218 -
642.219 - private final class Info implements ProjectInformation{
642.220 -
642.221 +
642.222 + private final class Info implements ProjectInformation {
642.223 +
642.224 private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
642.225 -
642.226 - public void addPropertyChangeListener(PropertyChangeListener listener) {
642.227 +
642.228 + @Override
642.229 + public void addPropertyChangeListener(PropertyChangeListener listener) {
642.230 propertyChangeSupport.addPropertyChangeListener(listener);
642.231 }
642.232 -
642.233 +
642.234 + @Override
642.235 public void removePropertyChangeListener(PropertyChangeListener listener) {
642.236 propertyChangeSupport.removePropertyChangeListener(listener);
642.237 }
642.238
642.239 + @Override
642.240 public String getDisplayName() {
642.241 return getName();
642.242 }
642.243
642.244 + @Override
642.245 public Icon getIcon() {
642.246 return PROJECT_ICON;
642.247 }
642.248
642.249 + @Override
642.250 public String getName() {
642.251 return PythonProject.this.getName();
642.252 }
642.253
642.254 + @Override
642.255 public Project getProject() {
642.256 return PythonProject.this;
642.257 }
642.258 -
642.259 +
642.260 void firePropertyChange(String prop) {
642.261 - propertyChangeSupport.firePropertyChange(prop , null, null);
642.262 + propertyChangeSupport.firePropertyChange(prop, null, null);
642.263 }
642.264 }
642.265 -
642.266 +
642.267 public final class PythonOpenedHook extends ProjectOpenedHook {
642.268 +
642.269 + @Override
642.270 protected void projectOpened() {
642.271 // register project's classpaths to GlobalPathRegistry
642.272 final ClassPathProviderImpl cpProvider = getLookup().lookup(ClassPathProviderImpl.class);
642.273 @@ -234,7 +248,8 @@
642.274 }
642.275 }
642.276
642.277 - protected void projectClosed() {
642.278 + @Override
642.279 + protected void projectClosed() {
642.280 // unregister project's classpaths to GlobalPathRegistry
642.281 final ClassPathProviderImpl cpProvider = getLookup().lookup(ClassPathProviderImpl.class);
642.282 assert cpProvider != null;
642.283 @@ -247,49 +262,53 @@
642.284 }
642.285 }
642.286 }
642.287 -
642.288 +
642.289 public final class PythonProjectXmlSavedHook extends ProjectXmlSavedHook {
642.290 -
642.291 - public PythonProjectXmlSavedHook() {}
642.292 -
642.293 +
642.294 + public PythonProjectXmlSavedHook() {
642.295 + }
642.296 +
642.297 + @Override
642.298 protected void projectXmlSaved() throws IOException {
642.299 Info info = getLookup().lookup(Info.class);
642.300 assert info != null;
642.301 info.firePropertyChange(ProjectInformation.PROP_NAME);
642.302 info.firePropertyChange(ProjectInformation.PROP_DISPLAY_NAME);
642.303 - }
642.304 + }
642.305 }
642.306 +
642.307 private static final class RecommendedTemplatesImpl implements RecommendedTemplates, PrivilegedTemplates {
642.308 -
642.309 - RecommendedTemplatesImpl (UpdateHelper helper) {
642.310 +
642.311 + RecommendedTemplatesImpl(UpdateHelper helper) {
642.312 this.helper = helper;
642.313 }
642.314 -
642.315 +
642.316 private final UpdateHelper helper;
642.317 -
642.318 +
642.319 // List of primarily supported templates
642.320 -
642.321 - private static final String[] APPLICATION_TYPES = new String[] {
642.322 - "python", // NOI18N
642.323 - "XML", // NOI18N
642.324 - "simple-files" // NOI18N
642.325 + private static final String[] APPLICATION_TYPES = new String[]{
642.326 + "python", // NOI18N
642.327 + "XML", // NOI18N
642.328 + "simple-files" // NOI18N
642.329 };
642.330 -
642.331 - private static final String[] PRIVILEGED_NAMES = new String[] {
642.332 +
642.333 + private static final String[] PRIVILEGED_NAMES = new String[]{
642.334 "Templates/Python/_package", // NOI18N
642.335 "Templates/Python/_module.py", //NOI18N
642.336 "Templates/Python/_main.py", // NOI18N
642.337 "Templates/Python/_empty_module.py", // NOI18N
642.338 "Templates/Python/_test.py", // NOI18N
642.339 };
642.340 -
642.341 +
642.342 + @Override
642.343 public String[] getRecommendedTypes() {
642.344 return APPLICATION_TYPES;
642.345 }
642.346 -
642.347 +
642.348 + @Override
642.349 public String[] getPrivilegedTemplates() {
642.350 return PRIVILEGED_NAMES;
642.351 }
642.352 -
642.353 +
642.354 }
642.355 }
643.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
643.2 +++ b/python.project/src/org/netbeans/modules/python/project/PythonProjectSourceLevelQuery.java Sat Feb 28 17:25:32 2015 -0800
643.3 @@ -0,0 +1,98 @@
643.4 +/*
643.5 + * To change this license header, choose License Headers in Project Properties.
643.6 + * To change this template file, choose Tools | Templates
643.7 + * and open the template in the editor.
643.8 + */
643.9 +package org.netbeans.modules.python.project;
643.10 +
643.11 +import java.beans.PropertyChangeEvent;
643.12 +import java.beans.PropertyChangeListener;
643.13 +import javax.swing.event.ChangeListener;
643.14 +import org.netbeans.api.annotations.common.CheckForNull;
643.15 +import org.netbeans.api.annotations.common.NonNull;
643.16 +import org.netbeans.modules.python.source.queries.SourceLevelQueryImplementation;
643.17 +import org.netbeans.spi.project.support.ant.PropertyEvaluator;
643.18 +import org.openide.filesystems.FileObject;
643.19 +import org.openide.util.ChangeSupport;
643.20 +import org.openide.util.WeakListeners;
643.21 +
643.22 +/**
643.23 + *
643.24 + * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
643.25 + */
643.26 +class PythonProjectSourceLevelQuery implements SourceLevelQueryImplementation {
643.27 +
643.28 + private static final String PLATFORM_ACTIVE = "platform.active"; //NOI18N
643.29 +
643.30 + private final PropertyEvaluator eval;
643.31 + private final Result result;
643.32 +
643.33 + PythonProjectSourceLevelQuery(
643.34 + @NonNull final PropertyEvaluator eval,
643.35 + @NonNull final String platformType) {
643.36 + assert eval != null;
643.37 + assert platformType != null;
643.38 + this.eval = eval;
643.39 + this.result = new R();
643.40 + }
643.41 +
643.42 + @Override
643.43 + public Result getSourceLevel(FileObject javaFile) {
643.44 + return this.result;
643.45 + }
643.46 +
643.47 + @CheckForNull
643.48 + static String findSourceLevel (
643.49 + @NonNull final PropertyEvaluator eval) {
643.50 + return findValue(eval);
643.51 + }
643.52 +
643.53 + @CheckForNull
643.54 + private static String findValue(
643.55 + @NonNull final PropertyEvaluator eval) {
643.56 + final String activePlatform = eval.getProperty(PLATFORM_ACTIVE);
643.57 + return activePlatform;
643.58 + }
643.59 +
643.60 + private class R implements Result, PropertyChangeListener {
643.61 +
643.62 + private final ChangeSupport cs = new ChangeSupport(this);
643.63 +
643.64 + @SuppressWarnings("LeakingThisInConstructor")
643.65 + private R() {
643.66 + eval.addPropertyChangeListener(WeakListeners.propertyChange(this, eval));
643.67 + }
643.68 +
643.69 + @Override
643.70 + public String getSourceLevel() {
643.71 + return findSourceLevel(eval);
643.72 + }
643.73 +
643.74 + @Override
643.75 + public void addChangeListener(ChangeListener listener) {
643.76 + this.cs.addChangeListener(listener);
643.77 + }
643.78 +
643.79 + @Override
643.80 + public void removeChangeListener(ChangeListener listener) {
643.81 + this.cs.removeChangeListener(listener);
643.82 + }
643.83 +
643.84 + @Override
643.85 + public void propertyChange(PropertyChangeEvent evt) {
643.86 + final String name = evt.getPropertyName();
643.87 + if (name == null ||
643.88 + PLATFORM_ACTIVE.equals(name)) {
643.89 + this.cs.fireChange();
643.90 + }
643.91 + }
643.92 +
643.93 + @Override
643.94 + public String toString() {
643.95 + final String sl = getSourceLevel();
643.96 + return sl == null ? "" : sl; //NOI18M
643.97 + }
643.98 +
643.99 + }
643.100 +
643.101 +}
644.1 --- a/python.project/src/org/netbeans/modules/python/project/actions/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
644.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
644.3 @@ -1,1 +0,0 @@
644.4 -CTL_OptionPythonConsole=Python Console
645.1 --- a/python.project/src/org/netbeans/modules/python/project/gsf/BootClassPathImplementation.java Sun Jan 04 13:11:53 2015 -0600
645.2 +++ b/python.project/src/org/netbeans/modules/python/project/gsf/BootClassPathImplementation.java Sat Feb 28 17:25:32 2015 -0800
645.3 @@ -44,9 +44,6 @@
645.4 package org.netbeans.modules.python.project.gsf;
645.5
645.6 import java.beans.PropertyChangeEvent;
645.7 -import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
645.8 -import org.netbeans.modules.gsfpath.spi.classpath.PathResourceImplementation;
645.9 -import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
645.10 import java.beans.PropertyChangeListener;
645.11 import java.beans.PropertyChangeSupport;
645.12 import java.net.URL;
645.13 @@ -58,6 +55,9 @@
645.14 import org.netbeans.modules.python.project.PythonProject;
645.15 import org.netbeans.modules.python.project.PythonProjectUtil;
645.16 import org.netbeans.modules.python.project.ui.customizer.PythonProjectProperties;
645.17 +import org.netbeans.spi.java.classpath.ClassPathImplementation;
645.18 +import org.netbeans.spi.java.classpath.PathResourceImplementation;
645.19 +import org.netbeans.spi.java.classpath.support.ClassPathSupport;
645.20 import org.netbeans.spi.project.support.ant.PropertyEvaluator;
645.21 import org.openide.util.Parameters;
645.22 import org.openide.util.RequestProcessor;
646.1 --- a/python.project/src/org/netbeans/modules/python/project/gsf/ClassPathProviderImpl.java Sun Jan 04 13:11:53 2015 -0600
646.2 +++ b/python.project/src/org/netbeans/modules/python/project/gsf/ClassPathProviderImpl.java Sat Feb 28 17:25:32 2015 -0800
646.3 @@ -45,14 +45,19 @@
646.4
646.5 import java.util.HashMap;
646.6 import java.util.Map;
646.7 +import org.netbeans.api.java.classpath.ClassPath;
646.8 import org.netbeans.modules.python.project.PythonProject;
646.9 import org.netbeans.modules.python.project.SourceRoots;
646.10 import org.netbeans.modules.python.project.util.Pair;
646.11 -import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
646.12 -import org.netbeans.modules.gsfpath.spi.classpath.ClassPathFactory;
646.13 -import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
646.14 -import org.netbeans.modules.gsfpath.spi.classpath.ClassPathProvider;
646.15 -import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
646.16 +import org.netbeans.spi.java.classpath.ClassPathFactory;
646.17 +import org.netbeans.spi.java.classpath.ClassPathImplementation;
646.18 +import org.netbeans.spi.java.classpath.ClassPathProvider;
646.19 +import org.netbeans.spi.java.classpath.support.ClassPathSupport;
646.20 +//import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
646.21 +//import org.netbeans.modules.gsfpath.spi.classpath.ClassPathFactory;
646.22 +//import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
646.23 +//import org.netbeans.modules.gsfpath.spi.classpath.ClassPathProvider;
646.24 +//import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
646.25 import org.openide.filesystems.FileObject;
646.26 import org.openide.filesystems.FileUtil;
646.27
647.1 --- a/python.project/src/org/netbeans/modules/python/project/gsf/CompilePathImplementation.java Sun Jan 04 13:11:53 2015 -0600
647.2 +++ b/python.project/src/org/netbeans/modules/python/project/gsf/CompilePathImplementation.java Sat Feb 28 17:25:32 2015 -0800
647.3 @@ -54,11 +54,14 @@
647.4 import java.util.concurrent.atomic.AtomicBoolean;
647.5 import java.util.logging.Logger;
647.6 import org.netbeans.api.project.ProjectManager;
647.7 -import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
647.8 -import org.netbeans.modules.gsfpath.spi.classpath.PathResourceImplementation;
647.9 -import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
647.10 +//import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
647.11 +//import org.netbeans.modules.gsfpath.spi.classpath.PathResourceImplementation;
647.12 +//import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
647.13 import org.netbeans.modules.python.project.PythonProject;
647.14 import org.netbeans.modules.python.project.ui.customizer.PythonProjectProperties;
647.15 +import org.netbeans.spi.java.classpath.ClassPathImplementation;
647.16 +import org.netbeans.spi.java.classpath.PathResourceImplementation;
647.17 +import org.netbeans.spi.java.classpath.support.ClassPathSupport;
647.18 import org.netbeans.spi.project.support.ant.PropertyEvaluator;
647.19 import org.netbeans.spi.project.support.ant.PropertyUtils;
647.20 import org.openide.filesystems.FileObject;
648.1 --- a/python.project/src/org/netbeans/modules/python/project/gsf/SourcePathImplementation.java Sun Jan 04 13:11:53 2015 -0600
648.2 +++ b/python.project/src/org/netbeans/modules/python/project/gsf/SourcePathImplementation.java Sat Feb 28 17:25:32 2015 -0800
648.3 @@ -51,9 +51,12 @@
648.4 import java.beans.PropertyChangeSupport;
648.5 import java.net.URL;
648.6 import org.netbeans.modules.python.project.SourceRoots;
648.7 -import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
648.8 -import org.netbeans.modules.gsfpath.spi.classpath.PathResourceImplementation;
648.9 -import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
648.10 +import org.netbeans.spi.java.classpath.ClassPathImplementation;
648.11 +import org.netbeans.spi.java.classpath.PathResourceImplementation;
648.12 +import org.netbeans.spi.java.classpath.support.ClassPathSupport;
648.13 +//import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
648.14 +//import org.netbeans.modules.gsfpath.spi.classpath.PathResourceImplementation;
648.15 +//import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
648.16 import org.openide.util.WeakListeners;
648.17
648.18 /**
649.1 --- a/python.project/src/org/netbeans/modules/python/project/templates/EmptyPythonProjectDescription.html Sun Jan 04 13:11:53 2015 -0600
649.2 +++ b/python.project/src/org/netbeans/modules/python/project/templates/EmptyPythonProjectDescription.html Sat Feb 28 17:25:32 2015 -0800
649.3 @@ -7,6 +7,6 @@
649.4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
649.5 </head>
649.6 <body>
649.7 - New Empty Python Project
649.8 + New Empty Python Project using Ant
649.9 </body>
649.10 </html>
650.1 --- a/python.project/src/org/netbeans/modules/python/project/templates/ExistingPythonProjectDescription.html Sun Jan 04 13:11:53 2015 -0600
650.2 +++ b/python.project/src/org/netbeans/modules/python/project/templates/ExistingPythonProjectDescription.html Sat Feb 28 17:25:32 2015 -0800
650.3 @@ -9,6 +9,6 @@
650.4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
650.5 </head>
650.6 <body>
650.7 - New Python Project with Existing Sources
650.8 + New Python Project with Existing Sources using Ant
650.9 </body>
650.10 </html>
651.1 --- a/python.project/src/org/netbeans/modules/python/project/templates/NewPythonProjectWizardIterator.java Sun Jan 04 13:11:53 2015 -0600
651.2 +++ b/python.project/src/org/netbeans/modules/python/project/templates/NewPythonProjectWizardIterator.java Sat Feb 28 17:25:32 2015 -0800
651.3 @@ -38,7 +38,6 @@
651.4
651.5 public class NewPythonProjectWizardIterator implements WizardDescriptor.ProgressInstantiatingIterator {
651.6
651.7 - static final String SET_AS_MAIN = "setAsMain"; //NOI18N
651.8 static final String MAIN_FILE ="mainFile"; //NOI18N
651.9 static final String PROP_PROJECT_NAME = "projectName"; //NOI18N
651.10 static final String PROP_PROJECT_LOCATION = "pojectLocation"; //NOI18N
652.1 --- a/python.project/src/org/netbeans/modules/python/project/templates/PanelOptionsVisual.form Sun Jan 04 13:11:53 2015 -0600
652.2 +++ b/python.project/src/org/netbeans/modules/python/project/templates/PanelOptionsVisual.form Sat Feb 28 17:25:32 2015 -0800
652.3 @@ -25,10 +25,6 @@
652.4 <DimensionLayout dim="0">
652.5 <Group type="103" groupAlignment="0" attributes="0">
652.6 <Group type="102" alignment="0" attributes="0">
652.7 - <Component id="setAsMainCheckBox" min="-2" max="-2" attributes="0"/>
652.8 - <EmptySpace pref="353" max="32767" attributes="0"/>
652.9 - </Group>
652.10 - <Group type="102" alignment="0" attributes="0">
652.11 <Group type="103" groupAlignment="0" attributes="0">
652.12 <Component id="createMainCheckBox" alignment="0" min="-2" max="-2" attributes="0"/>
652.13 <Component id="jLabel1" alignment="0" min="-2" max="-2" attributes="0"/>
652.14 @@ -41,7 +37,7 @@
652.15 <Component id="manage" min="-2" max="-2" attributes="0"/>
652.16 <EmptySpace min="-2" pref="4" max="-2" attributes="0"/>
652.17 </Group>
652.18 - <Component id="mainFileTextField" alignment="0" pref="353" max="32767" attributes="0"/>
652.19 + <Component id="mainFileTextField" alignment="0" max="32767" attributes="0"/>
652.20 </Group>
652.21 </Group>
652.22 </Group>
652.23 @@ -49,8 +45,7 @@
652.24 <DimensionLayout dim="1">
652.25 <Group type="103" groupAlignment="0" attributes="0">
652.26 <Group type="102" attributes="0">
652.27 - <Component id="setAsMainCheckBox" min="-2" max="-2" attributes="0"/>
652.28 - <EmptySpace min="-2" pref="5" max="-2" attributes="0"/>
652.29 + <EmptySpace max="-2" attributes="0"/>
652.30 <Group type="103" groupAlignment="3" attributes="0">
652.31 <Component id="createMainCheckBox" alignment="3" min="-2" max="-2" attributes="0"/>
652.32 <Component id="mainFileTextField" alignment="3" min="-2" max="-2" attributes="0"/>
652.33 @@ -63,7 +58,7 @@
652.34 </Group>
652.35 <Component id="manage" alignment="0" min="-2" max="-2" attributes="0"/>
652.36 </Group>
652.37 - <EmptySpace pref="50" max="32767" attributes="0"/>
652.38 + <EmptySpace max="32767" attributes="0"/>
652.39 </Group>
652.40 </Group>
652.41 </DimensionLayout>
652.42 @@ -101,25 +96,6 @@
652.43 </Property>
652.44 </AccessibilityProperties>
652.45 </Component>
652.46 - <Component class="javax.swing.JCheckBox" name="setAsMainCheckBox">
652.47 - <Properties>
652.48 - <Property name="selected" type="boolean" value="true"/>
652.49 - <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
652.50 - <ResourceString bundle="org/netbeans/modules/python/project/templates/Bundle.properties" key="LBL_setAsMainCheckBox" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
652.51 - </Property>
652.52 - </Properties>
652.53 - <AccessibilityProperties>
652.54 - <Property name="AccessibleContext.accessibleName" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
652.55 - <ResourceString bundle="org/netbeans/modules/python/project/templates/Bundle.properties" key="ACSN_setAsMainCheckBox" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
652.56 - </Property>
652.57 - <Property name="AccessibleContext.accessibleDescription" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
652.58 - <ResourceString bundle="org/netbeans/modules/python/project/templates/Bundle.properties" key="ACSD_setAsMainCheckBox" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
652.59 - </Property>
652.60 - </AccessibilityProperties>
652.61 - <AuxValues>
652.62 - <AuxValue name="generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
652.63 - </AuxValues>
652.64 - </Component>
652.65 <Component class="javax.swing.JLabel" name="jLabel1">
652.66 <Properties>
652.67 <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
653.1 --- a/python.project/src/org/netbeans/modules/python/project/templates/PanelOptionsVisual.java Sun Jan 04 13:11:53 2015 -0600
653.2 +++ b/python.project/src/org/netbeans/modules/python/project/templates/PanelOptionsVisual.java Sat Feb 28 17:25:32 2015 -0800
653.3 @@ -99,7 +99,6 @@
653.4 mainFileTextField.setEnabled( lastMainClassCheck );
653.5 break;
653.6 case EXISTING:
653.7 - setAsMainCheckBox.setVisible( true );
653.8 createMainCheckBox.setVisible( false );
653.9 mainFileTextField.setVisible( false );
653.10 break;
653.11 @@ -154,7 +153,6 @@
653.12
653.13 createMainCheckBox = new javax.swing.JCheckBox();
653.14 mainFileTextField = new javax.swing.JTextField();
653.15 - setAsMainCheckBox = new javax.swing.JCheckBox();
653.16 jLabel1 = new javax.swing.JLabel();
653.17 platforms = org.netbeans.modules.python.api.PlatformComponentFactory.getPythonPlatformsComboxBox();
653.18 manage = new javax.swing.JButton();
653.19 @@ -164,9 +162,6 @@
653.20
653.21 mainFileTextField.setText("main");
653.22
653.23 - setAsMainCheckBox.setSelected(true);
653.24 - org.openide.awt.Mnemonics.setLocalizedText(setAsMainCheckBox, org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("LBL_setAsMainCheckBox")); // NOI18N
653.25 -
653.26 jLabel1.setLabelFor(platforms);
653.27 org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(PanelOptionsVisual.class, "TXT_PythonPlatform")); // NOI18N
653.28
653.29 @@ -182,9 +177,6 @@
653.30 layout.setHorizontalGroup(
653.31 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
653.32 .addGroup(layout.createSequentialGroup()
653.33 - .addComponent(setAsMainCheckBox)
653.34 - .addContainerGap(353, Short.MAX_VALUE))
653.35 - .addGroup(layout.createSequentialGroup()
653.36 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
653.37 .addComponent(createMainCheckBox)
653.38 .addComponent(jLabel1))
653.39 @@ -195,13 +187,12 @@
653.40 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
653.41 .addComponent(manage)
653.42 .addGap(4, 4, 4))
653.43 - .addComponent(mainFileTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)))
653.44 + .addComponent(mainFileTextField)))
653.45 );
653.46 layout.setVerticalGroup(
653.47 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
653.48 .addGroup(layout.createSequentialGroup()
653.49 - .addComponent(setAsMainCheckBox)
653.50 - .addGap(5, 5, 5)
653.51 + .addContainerGap()
653.52 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
653.53 .addComponent(createMainCheckBox)
653.54 .addComponent(mainFileTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
653.55 @@ -211,15 +202,13 @@
653.56 .addComponent(jLabel1)
653.57 .addComponent(platforms, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
653.58 .addComponent(manage))
653.59 - .addContainerGap(50, Short.MAX_VALUE))
653.60 + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
653.61 );
653.62
653.63 createMainCheckBox.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ACSN_createMainCheckBox")); // NOI18N
653.64 createMainCheckBox.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ACSD_createMainCheckBox")); // NOI18N
653.65 mainFileTextField.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ASCN_mainClassTextFiled")); // NOI18N
653.66 mainFileTextField.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ASCD_mainClassTextFiled")); // NOI18N
653.67 - setAsMainCheckBox.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ACSN_setAsMainCheckBox")); // NOI18N
653.68 - setAsMainCheckBox.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ACSD_setAsMainCheckBox")); // NOI18N
653.69
653.70 getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(PanelOptionsVisual.class, "ACSN_PanelOptionsVisual")); // NOI18N
653.71 getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(PanelOptionsVisual.class, "ACSD_PanelOptionsVisual")); // NOI18N
653.72 @@ -286,7 +275,6 @@
653.73 }
653.74
653.75 void store( WizardDescriptor d ) {
653.76 - d.putProperty(NewPythonProjectWizardIterator.SET_AS_MAIN, setAsMainCheckBox.isSelected() && setAsMainCheckBox.isVisible() ? Boolean.TRUE : Boolean.FALSE ); // NOI18N
653.77 d.putProperty(NewPythonProjectWizardIterator.MAIN_FILE, createMainCheckBox.isSelected() && createMainCheckBox.isVisible() ? mainFileTextField.getText() : null ); // NOI18N
653.78 PythonPlatform platform = PlatformComponentFactory.getPlatform(platforms);
653.79 if (platform != null) {
653.80 @@ -300,7 +288,6 @@
653.81 private javax.swing.JTextField mainFileTextField;
653.82 private javax.swing.JButton manage;
653.83 private javax.swing.JComboBox platforms;
653.84 - private javax.swing.JCheckBox setAsMainCheckBox;
653.85 // End of variables declaration//GEN-END:variables
653.86
653.87 private void mainFileChanged () {
654.1 --- a/python.project/src/org/netbeans/modules/python/project/ui/PackageRootNode.java Sun Jan 04 13:11:53 2015 -0600
654.2 +++ b/python.project/src/org/netbeans/modules/python/project/ui/PackageRootNode.java Sat Feb 28 17:25:32 2015 -0800
654.3 @@ -155,7 +155,7 @@
654.4 public @Override String getDisplayName() {
654.5 String s = super.getDisplayName ();
654.6
654.7 - try {
654.8 + try {
654.9 s = file.getFileSystem ().getDecorator ().annotateName (s, files);
654.10 } catch (FileStateInvalidException e) {
654.11 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
655.1 --- a/python.project/src/org/netbeans/modules/python/project/ui/PackageViewChildren.java Sun Jan 04 13:11:53 2015 -0600
655.2 +++ b/python.project/src/org/netbeans/modules/python/project/ui/PackageViewChildren.java Sat Feb 28 17:25:32 2015 -0800
655.3 @@ -87,8 +87,8 @@
655.4 import org.openide.filesystems.FileRenameEvent;
655.5 import org.openide.filesystems.FileStateInvalidException;
655.6 import org.openide.filesystems.FileSystem;
655.7 +import org.openide.filesystems.FileUIUtils;
655.8 import org.openide.filesystems.FileUtil;
655.9 -import org.openide.filesystems.FileUIUtils;
655.10 import org.openide.filesystems.StatusDecorator;
655.11 import org.openide.loaders.ChangeableDataFilter;
655.12 import org.openide.loaders.DataFilter;
656.1 --- a/python.project/test/unit/data/testfiles/compl2.py Sun Jan 04 13:11:53 2015 -0600
656.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
656.3 @@ -1,1 +0,0 @@
656.4 -#Test for compl2
656.5 \ No newline at end of file
657.1 --- a/python.project/test/unit/data/testfiles/tests/compl2_test.py Sun Jan 04 13:11:53 2015 -0600
657.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
657.3 @@ -1,15 +0,0 @@
657.4 -import sys as whatever
657.5 -import os
657.6 -
657.7 -print whatever.r
657.8 -print os.r
657.9 -print sys.getfilesysteme
657.10 -
657.11 -myvar = file()
657.12 -myvar.close()
657.13 -
657.14 -myothervar = ZipFile()
657.15 -myothervar.x
657.16 -
657.17 -unknown.fai
657.18 -
658.1 --- a/python.project/test/unit/src/org/netbeans/modules/python/project/GotoTestTest.java Sun Jan 04 13:11:53 2015 -0600
658.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
658.3 @@ -1,122 +0,0 @@
658.4 -/*
658.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
658.6 - *
658.7 - * Copyright 1997-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 - * Contributor(s):
658.31 - *
658.32 - * The Original Software is NetBeans. The Initial Developer of the Original
658.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
658.34 - * Microsystems, Inc. All Rights Reserved.
658.35 - *
658.36 - * If you wish your version of this file to be governed by only the CDDL
658.37 - * or only the GPL Version 2, indicate your decision by adding
658.38 - * "[Contributor] elects to include this software in this distribution
658.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
658.40 - * single choice of license, a recipient has the option to distribute
658.41 - * your version of this file under either the CDDL, the GPL Version 2 or
658.42 - * to extend the choice of license to its licensees as provided above.
658.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
658.44 - * Version 2 license, then the option applies only if the new code is
658.45 - * made subject to such option by the copyright holder.
658.46 - */
658.47 -package org.netbeans.modules.python.project;
658.48 -
658.49 -import org.netbeans.modules.python.editor.PythonTestBase;
658.50 -import org.netbeans.spi.gototest.TestLocator.LocationResult;
658.51 -
658.52 -/**
658.53 - * @author Tor Norbye
658.54 - */
658.55 -public class GotoTestTest extends PythonTestBase {
658.56 -
658.57 - private GotoTest gotoTest;
658.58 -
658.59 - public GotoTestTest(String testName) {
658.60 - super(testName);
658.61 - }
658.62 - private static LocationResult NONE = null;
658.63 -
658.64 - @Override
658.65 - protected void setUp() throws Exception {
658.66 - super.setUp();
658.67 -
658.68 - gotoTest = new GotoTest();
658.69 - }
658.70 -
658.71 - public void testGotoTestUnit() {
658.72 - LocationResult loc = gotoTest.findTest(getTestFile("testfiles/compl2.py"), -1);
658.73 - assertNotSame(NONE, loc);
658.74 - assertEquals(getTestFile("testfiles/tests/compl2_test.py"), loc.getFileObject());
658.75 - }
658.76 -
658.77 - public void testGotoTestUnit2() {
658.78 - LocationResult loc = gotoTest.findTested(getTestFile("testfiles/tests/compl2_test.py"), -1);
658.79 - assertNotSame(NONE, loc);
658.80 - assertEquals(getTestFile("testfiles/compl2.py"), loc.getFileObject());
658.81 - }
658.82 -
658.83 - public void testGotoTestUnit3() {
658.84 - LocationResult loc = gotoTest.findTest(getTestFile("testfiles/foo.py"), -1);
658.85 - assertNotSame(NONE, loc);
658.86 - assertEquals(getTestFile("testfiles/foo_test.py"), loc.getFileObject());
658.87 - }
658.88 -
658.89 - public void testGotoTestUnit4() {
658.90 - LocationResult loc = gotoTest.findTested(getTestFile("testfiles/foo_test.py"), -1);
658.91 - assertNotSame(NONE, loc);
658.92 - assertEquals(getTestFile("testfiles/foo.py"), loc.getFileObject());
658.93 - }
658.94 -
658.95 - public void testGotoTestUnit5() {
658.96 - LocationResult loc = gotoTest.findTest(getTestFile("testfiles/bar.py"), -1);
658.97 - assertNotSame(NONE, loc);
658.98 - assertEquals(getTestFile("testfiles/test_bar.py"), loc.getFileObject());
658.99 - }
658.100 -
658.101 - public void testGotoTestUnit6() {
658.102 - LocationResult loc = gotoTest.findTested(getTestFile("testfiles/test_bar.py"), -1);
658.103 - assertNotSame(NONE, loc);
658.104 - assertEquals(getTestFile("testfiles/bar.py"), loc.getFileObject());
658.105 - }
658.106 -
658.107 - public void testGotoTestUnit7() {
658.108 - LocationResult loc = gotoTest.findTest(getTestFile("testfiles/dir/baz.py"), -1);
658.109 - assertNotSame(NONE, loc);
658.110 - assertEquals(getTestFile("testfiles/tests/test_baz.py"), loc.getFileObject());
658.111 - }
658.112 -
658.113 - public void testGotoTestUnit8() {
658.114 - LocationResult loc = gotoTest.findTest(getTestFile("testfiles/whatever.py"), -1);
658.115 - assertNotSame(NONE, loc);
658.116 - assertEquals(getTestFile("testfiles/testwhatever.py"), loc.getFileObject());
658.117 - }
658.118 -
658.119 - // Not yet working
658.120 - //public void testGotoTestUnit8() {
658.121 - // LocationResult loc = gotoTest.findTested(getTestFile("testfiles/tests/test_baz.py"), -1);
658.122 - // assertNotSame(NONE, loc);
658.123 - // assertEquals(getTestFile("testfiles/dir/baz.py"), loc.getFileObject());
658.124 - //}
658.125 -}
659.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
659.2 +++ b/python.project2/build.xml Sat Feb 28 17:25:32 2015 -0800
659.3 @@ -0,0 +1,8 @@
659.4 +<?xml version="1.0" encoding="UTF-8"?>
659.5 +<!-- You may freely edit this file. See harness/README in the NetBeans platform -->
659.6 +<!-- for some information on what you could do (e.g. targets to override). -->
659.7 +<!-- If you delete this file and reopen the project it will be recreated. -->
659.8 +<project name="contrib/python.project2" default="netbeans" basedir=".">
659.9 + <description>Builds, tests, and runs the project org.netbeans.modules.python.project.</description>
659.10 + <import file="../../nbbuild/templates/projectized.xml"/>
659.11 +</project>
660.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
660.2 +++ b/python.project2/manifest.mf Sat Feb 28 17:25:32 2015 -0800
660.3 @@ -0,0 +1,7 @@
660.4 +Manifest-Version: 1.0
660.5 +AutoUpdate-Show-In-Client: true
660.6 +OpenIDE-Module: org.netbeans.modules.python.project2
660.7 +OpenIDE-Module-Layer: org/netbeans/modules/python/project2/layer.xml
660.8 +OpenIDE-Module-Localizing-Bundle: org/netbeans/modules/python/project2/Bundle.properties
660.9 +OpenIDE-Module-Specification-Version: 1.0
660.10 +
661.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
661.2 +++ b/python.project2/nbproject/project.properties Sat Feb 28 17:25:32 2015 -0800
661.3 @@ -0,0 +1,15 @@
661.4 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs=true
661.5 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width=4
661.6 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab=4
661.7 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=4
661.8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80
661.9 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=project
661.10 +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineArrayInit=true
661.11 +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesAfterClassHeader=0
661.12 +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch=false
661.13 +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaceAfterTypeCast=false
661.14 +javac.source=1.7
661.15 +javac.compilerargs=-Xlint -Xlint:-serial
661.16 +
661.17 +test-unit-sys-prop.xtest.python.home=${netbeans.dest.dir}/python/jython-2.5.1
661.18 +test-unit-sys-prop.xtest.platform_info.py=${netbeans.dest.dir}/python/platform_info.py
662.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
662.2 +++ b/python.project2/nbproject/project.xml Sat Feb 28 17:25:32 2015 -0800
662.3 @@ -0,0 +1,203 @@
662.4 +<?xml version="1.0" encoding="UTF-8"?>
662.5 +<project xmlns="http://www.netbeans.org/ns/project/1">
662.6 + <type>org.netbeans.modules.apisupport.project</type>
662.7 + <configuration>
662.8 + <data xmlns="http://www.netbeans.org/ns/nb-module-project/3">
662.9 + <code-name-base>org.netbeans.modules.python.project2</code-name-base>
662.10 + <module-dependencies>
662.11 + <dependency>
662.12 + <code-name-base>org.netbeans.api.annotations.common</code-name-base>
662.13 + <build-prerequisite/>
662.14 + <compile-dependency/>
662.15 + <run-dependency>
662.16 + <release-version>1</release-version>
662.17 + <specification-version>1.25</specification-version>
662.18 + </run-dependency>
662.19 + </dependency>
662.20 + <dependency>
662.21 + <code-name-base>org.netbeans.api.java.classpath</code-name-base>
662.22 + <build-prerequisite/>
662.23 + <compile-dependency/>
662.24 + <run-dependency>
662.25 + <release-version>1</release-version>
662.26 + <specification-version>1.48</specification-version>
662.27 + </run-dependency>
662.28 + </dependency>
662.29 + <dependency>
662.30 + <code-name-base>org.netbeans.api.progress</code-name-base>
662.31 + <build-prerequisite/>
662.32 + <compile-dependency/>
662.33 + <run-dependency>
662.34 + <release-version>1</release-version>
662.35 + <specification-version>1.40</specification-version>
662.36 + </run-dependency>
662.37 + </dependency>
662.38 + <dependency>
662.39 + <code-name-base>org.netbeans.api.progress.nb</code-name-base>
662.40 + <build-prerequisite/>
662.41 + <compile-dependency/>
662.42 + <run-dependency>
662.43 + <specification-version>1.44</specification-version>
662.44 + </run-dependency>
662.45 + </dependency>
662.46 + <dependency>
662.47 + <code-name-base>org.netbeans.api.templates</code-name-base>
662.48 + <build-prerequisite/>
662.49 + <compile-dependency/>
662.50 + <run-dependency>
662.51 + <specification-version>1.2</specification-version>
662.52 + </run-dependency>
662.53 + </dependency>
662.54 + <dependency>
662.55 + <code-name-base>org.netbeans.modules.projectapi</code-name-base>
662.56 + <build-prerequisite/>
662.57 + <compile-dependency/>
662.58 + <run-dependency>
662.59 + <release-version>1</release-version>
662.60 + <specification-version>1.62</specification-version>
662.61 + </run-dependency>
662.62 + </dependency>
662.63 + <dependency>
662.64 + <code-name-base>org.netbeans.modules.projectuiapi</code-name-base>
662.65 + <build-prerequisite/>
662.66 + <compile-dependency/>
662.67 + <run-dependency>
662.68 + <release-version>1</release-version>
662.69 + <specification-version>1.79</specification-version>
662.70 + </run-dependency>
662.71 + </dependency>
662.72 + <dependency>
662.73 + <code-name-base>org.netbeans.modules.projectuiapi.base</code-name-base>
662.74 + <build-prerequisite/>
662.75 + <compile-dependency/>
662.76 + <run-dependency>
662.77 + <release-version>1</release-version>
662.78 + <specification-version>1.79</specification-version>
662.79 + </run-dependency>
662.80 + </dependency>
662.81 + <dependency>
662.82 + <code-name-base>org.netbeans.modules.python.core</code-name-base>
662.83 + <build-prerequisite/>
662.84 + <compile-dependency/>
662.85 + <run-dependency>
662.86 + <specification-version>1.0</specification-version>
662.87 + </run-dependency>
662.88 + </dependency>
662.89 + <dependency>
662.90 + <code-name-base>org.netbeans.modules.python.editor</code-name-base>
662.91 + <build-prerequisite/>
662.92 + <compile-dependency/>
662.93 + <run-dependency>
662.94 + <specification-version>1.0</specification-version>
662.95 + </run-dependency>
662.96 + </dependency>
662.97 + <dependency>
662.98 + <code-name-base>org.netbeans.modules.python.source</code-name-base>
662.99 + <build-prerequisite/>
662.100 + <compile-dependency/>
662.101 + <run-dependency>
662.102 + <specification-version>1.0</specification-version>
662.103 + </run-dependency>
662.104 + </dependency>
662.105 + <dependency>
662.106 + <code-name-base>org.netbeans.modules.queries</code-name-base>
662.107 + <build-prerequisite/>
662.108 + <compile-dependency/>
662.109 + <run-dependency>
662.110 + <release-version>1</release-version>
662.111 + <specification-version>1.39.1</specification-version>
662.112 + </run-dependency>
662.113 + </dependency>
662.114 + <dependency>
662.115 + <code-name-base>org.openide.actions</code-name-base>
662.116 + <build-prerequisite/>
662.117 + <compile-dependency/>
662.118 + <run-dependency>
662.119 + <specification-version>6.8.0.1</specification-version>
662.120 + </run-dependency>
662.121 + </dependency>
662.122 + <dependency>
662.123 + <code-name-base>org.openide.awt</code-name-base>
662.124 + <build-prerequisite/>
662.125 + <compile-dependency/>
662.126 + <run-dependency>
662.127 + <specification-version>7.62.1</specification-version>
662.128 + </run-dependency>
662.129 + </dependency>
662.130 + <dependency>
662.131 + <code-name-base>org.openide.dialogs</code-name-base>
662.132 + <build-prerequisite/>
662.133 + <compile-dependency/>
662.134 + <run-dependency>
662.135 + <specification-version>7.6</specification-version>
662.136 + </run-dependency>
662.137 + </dependency>
662.138 + <dependency>
662.139 + <code-name-base>org.openide.filesystems</code-name-base>
662.140 + <build-prerequisite/>
662.141 + <compile-dependency/>
662.142 + <run-dependency>
662.143 + <specification-version>9.0</specification-version>
662.144 + </run-dependency>
662.145 + </dependency>
662.146 + <dependency>
662.147 + <code-name-base>org.openide.filesystems.nb</code-name-base>
662.148 + <build-prerequisite/>
662.149 + <compile-dependency/>
662.150 + <run-dependency>
662.151 + <specification-version>9.2</specification-version>
662.152 + </run-dependency>
662.153 + </dependency>
662.154 + <dependency>
662.155 + <code-name-base>org.openide.loaders</code-name-base>
662.156 + <build-prerequisite/>
662.157 + <compile-dependency/>
662.158 + <run-dependency>
662.159 + <specification-version>7.61</specification-version>
662.160 + </run-dependency>
662.161 + </dependency>
662.162 + <dependency>
662.163 + <code-name-base>org.openide.nodes</code-name-base>
662.164 + <build-prerequisite/>
662.165 + <compile-dependency/>
662.166 + <run-dependency>
662.167 + <specification-version>7.39.1</specification-version>
662.168 + </run-dependency>
662.169 + </dependency>
662.170 + <dependency>
662.171 + <code-name-base>org.openide.util</code-name-base>
662.172 + <build-prerequisite/>
662.173 + <compile-dependency/>
662.174 + <run-dependency>
662.175 + <specification-version>9.3</specification-version>
662.176 + </run-dependency>
662.177 + </dependency>
662.178 + <dependency>
662.179 + <code-name-base>org.openide.util.lookup</code-name-base>
662.180 + <build-prerequisite/>
662.181 + <compile-dependency/>
662.182 + <run-dependency>
662.183 + <specification-version>8.25.1</specification-version>
662.184 + </run-dependency>
662.185 + </dependency>
662.186 + <dependency>
662.187 + <code-name-base>org.openide.util.ui</code-name-base>
662.188 + <build-prerequisite/>
662.189 + <compile-dependency/>
662.190 + <run-dependency>
662.191 + <specification-version>9.3</specification-version>
662.192 + </run-dependency>
662.193 + </dependency>
662.194 + <dependency>
662.195 + <code-name-base>org.openide.windows</code-name-base>
662.196 + <build-prerequisite/>
662.197 + <compile-dependency/>
662.198 + <run-dependency>
662.199 + <specification-version>6.71.1</specification-version>
662.200 + </run-dependency>
662.201 + </dependency>
662.202 + </module-dependencies>
662.203 + <public-packages/>
662.204 + </data>
662.205 + </configuration>
662.206 +</project>
663.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
663.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/Bundle.properties Sat Feb 28 17:25:32 2015 -0800
663.3 @@ -0,0 +1,2 @@
663.4 +OpenIDE-Module-Name=Python Project 2
663.5 +Templates/Project/Python/PythonProject2.xml=Python Project - Setuptools
664.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
664.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/Python2LogicalView.java Sat Feb 28 17:25:32 2015 -0800
664.3 @@ -0,0 +1,180 @@
664.4 +package org.netbeans.modules.python.project2;
664.5 +
664.6 +import java.awt.Image;
664.7 +import java.io.CharConversionException;
664.8 +import java.util.ArrayList;
664.9 +import java.util.List;
664.10 +import javax.swing.Action;
664.11 +import org.netbeans.api.project.FileOwnerQuery;
664.12 +import org.netbeans.api.project.Project;
664.13 +import org.netbeans.api.project.ProjectUtils;
664.14 +import org.netbeans.modules.python.project2.ui.ChangePackageViewTypeAction;
664.15 +import org.netbeans.modules.python.project2.ui.PackageView;
664.16 +import org.netbeans.spi.project.ActionProvider;
664.17 +import org.netbeans.spi.project.ui.LogicalViewProvider;
664.18 +import org.netbeans.spi.project.ui.support.CommonProjectActions;
664.19 +import org.netbeans.spi.project.ui.support.DefaultProjectOperations;
664.20 +import org.netbeans.spi.project.ui.support.NodeFactorySupport;
664.21 +import org.netbeans.spi.project.ui.support.ProjectSensitiveActions;
664.22 +import org.openide.actions.FindAction;
664.23 +import org.openide.filesystems.FileObject;
664.24 +import org.openide.filesystems.FileUtil;
664.25 +import org.openide.nodes.AbstractNode;
664.26 +import org.openide.nodes.Node;
664.27 +import org.openide.util.HelpCtx;
664.28 +import org.openide.util.ImageUtilities;
664.29 +import org.openide.util.NbBundle;
664.30 +import org.openide.util.Utilities;
664.31 +import org.openide.util.actions.SystemAction;
664.32 +import org.openide.util.lookup.Lookups;
664.33 +import org.openide.xml.XMLUtil;
664.34 +import static org.netbeans.modules.python.project2.Bundle.*;
664.35 +
664.36 +/**
664.37 + *
664.38 + * @author alley
664.39 + * @author Tomas Zezula
664.40 + */
664.41 +@NbBundle.Messages({"# {0} - Path to of project",
664.42 + "PythonLogicalView.ProjectTooltipDescription=Python project in {0}",
664.43 + "LBL_RunAction_Name=Run",
664.44 + "LBL_DebugAction_Name=Debug",
664.45 + "LBL_TestAction_Name=Test",
664.46 + "LBL_BuildAction_Name=Build Egg",
664.47 + "LBL_CleanBuildAction_Name=Clean and Build Egg"})
664.48 +class Python2LogicalView implements LogicalViewProvider {
664.49 +
664.50 + private static final Image brokenProjectBadge = ImageUtilities.loadImage("org/netbeans/modules/python/project2/resources/brokenProjectBadge.gif", true);
664.51 + private final PythonProject2 project;
664.52 +
664.53 + public Python2LogicalView(PythonProject2 project) {
664.54 + this.project = project;
664.55 + }
664.56 +
664.57 + @Override
664.58 + public Node createLogicalView() {
664.59 + return new PythonProjectNode();
664.60 + }
664.61 +
664.62 + @Override
664.63 + public Node findPath(Node root, Object target) {
664.64 + Project p = root.getLookup().lookup(Project.class);
664.65 + if (p == null) {
664.66 + return null;
664.67 + }
664.68 + if (target instanceof FileObject) {
664.69 + FileObject targetFO = (FileObject) target;
664.70 + Project owner = FileOwnerQuery.getOwner(targetFO);
664.71 + if (!p.equals(owner)) {
664.72 + return null; // Don't waste time if project does not own the fo
664.73 + }
664.74 +
664.75 + for (Node n : root.getChildren().getNodes(true)) {
664.76 + Node result = PackageView.findPath(n, target);
664.77 + if (result != null) {
664.78 + return result;
664.79 + }
664.80 + }
664.81 + }
664.82 +
664.83 + return null;
664.84 + }
664.85 +
664.86 + private final class PythonProjectNode extends AbstractNode {
664.87 +
664.88 + private boolean broken; //for future use, marks the project as broken
664.89 +
664.90 + public PythonProjectNode() {
664.91 + super(NodeFactorySupport.createCompositeChildren(project, "Projects/org-netbeans-modules-python-project2/Nodes"),
664.92 + Lookups.singleton(project));
664.93 + setIconBaseWithExtension("org/netbeans/modules/python/project2/resources/py_25_16.png");
664.94 + super.setName(ProjectUtils.getInformation(project).getDisplayName());
664.95 + }
664.96 +
664.97 + public
664.98 + @Override
664.99 + String getShortDescription() {
664.100 + //todo: Add python platform description
664.101 + String dirName = FileUtil.getFileDisplayName(project.getProjectDirectory());
664.102 + return PythonLogicalView_ProjectTooltipDescription(dirName);
664.103 + }
664.104 +
664.105 + public
664.106 + @Override
664.107 + String getHtmlDisplayName() {
664.108 + String dispName = super.getDisplayName();
664.109 + try {
664.110 + dispName = XMLUtil.toElementContent(dispName);
664.111 + } catch (CharConversionException ex) {
664.112 + return dispName;
664.113 + }
664.114 + // XXX text colors should be taken from UIManager, not hard-coded!
664.115 + return broken ? "<font color=\"#A40000\">" + dispName + "</font>" : null; //NOI18N
664.116 + }
664.117 +
664.118 + @Override
664.119 + public Image getIcon(int type) {
664.120 + Image original = super.getIcon(type);
664.121 + return broken ? ImageUtilities.mergeImages(original, brokenProjectBadge, 8, 0) : original;
664.122 + }
664.123 +
664.124 + @Override
664.125 + public Image getOpenedIcon(int type) {
664.126 + Image original = super.getOpenedIcon(type);
664.127 + return broken ? ImageUtilities.mergeImages(original, brokenProjectBadge, 8, 0) : original;
664.128 + }
664.129 +
664.130 + @Override
664.131 + public Action[] getActions(boolean context) {
664.132 + return getAdditionalActions();
664.133 + }
664.134 +
664.135 + @Override
664.136 + public boolean canRename() {
664.137 + return true;
664.138 + }
664.139 +
664.140 + @Override
664.141 + public void setName(String s) {
664.142 + DefaultProjectOperations.performDefaultRenameOperation(project, s);
664.143 + }
664.144 +
664.145 + @Override
664.146 + public HelpCtx getHelpCtx() {
664.147 + return new HelpCtx(PythonProjectNode.class);
664.148 + }
664.149 +
664.150 + private Action[] getAdditionalActions() {
664.151 + final List<Action> actions = new ArrayList<>();
664.152 + actions.add(CommonProjectActions.newFileAction());
664.153 + actions.add(null);
664.154 + actions.add(ProjectSensitiveActions.projectCommandAction(ActionProvider.COMMAND_RUN, LBL_RunAction_Name(), null)); // NOI18N
664.155 + actions.add(ProjectSensitiveActions.projectCommandAction(ActionProvider.COMMAND_DEBUG, LBL_DebugAction_Name(), null)); // NOI18N
664.156 +// actions.add(ProjectSensitiveActions.projectCommandAction(ActionProvider.COMMAND_TEST, LBL_TestAction_Name(), null)); // NOI18N
664.157 + actions.add(ProjectSensitiveActions.projectCommandAction(ActionProvider.COMMAND_BUILD, LBL_BuildAction_Name(), null)); // NOI18N
664.158 + actions.add(ProjectSensitiveActions.projectCommandAction(ActionProvider.COMMAND_REBUILD, LBL_CleanBuildAction_Name(), null)); // NOI18N
664.159 + actions.add(null);
664.160 +// actions.add(CoverageActionFactory.createCollectorAction(null, null));
664.161 +// actions.add(null);
664.162 + actions.add(CommonProjectActions.setAsMainProjectAction());
664.163 + actions.add(CommonProjectActions.openSubprojectsAction());
664.164 + actions.add(CommonProjectActions.closeProjectAction());
664.165 + actions.add(null);
664.166 + actions.add(CommonProjectActions.renameProjectAction());
664.167 + actions.add(CommonProjectActions.moveProjectAction());
664.168 + actions.add(CommonProjectActions.copyProjectAction());
664.169 + actions.add(CommonProjectActions.deleteProjectAction());
664.170 + actions.add(null);
664.171 + actions.add(new ChangePackageViewTypeAction());
664.172 + actions.add(null);
664.173 + actions.add(SystemAction.get(FindAction.class));
664.174 +
664.175 + // honor 57874 contact
664.176 + actions.addAll(Utilities.actionsForPath("Projects/Actions")); //NOI18N
664.177 +
664.178 + actions.add(null);
664.179 + actions.add(CommonProjectActions.customizeProjectAction());
664.180 + return actions.toArray(new Action[actions.size()]);
664.181 + }
664.182 + }
664.183 +}
665.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
665.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/PythonActionProvider.java Sat Feb 28 17:25:32 2015 -0800
665.3 @@ -0,0 +1,93 @@
665.4 +package org.netbeans.modules.python.project2;
665.5 +
665.6 +import java.util.LinkedHashMap;
665.7 +import java.util.Map;
665.8 +import java.util.Set;
665.9 +import org.netbeans.modules.python.project2.ui.actions.Command;
665.10 +import org.netbeans.modules.python.project2.ui.actions.RunCommand;
665.11 +import org.netbeans.modules.python.project2.ui.actions.RunSingleCommand;
665.12 +import org.netbeans.spi.project.ActionProvider;
665.13 +import org.openide.LifecycleManager;
665.14 +import org.openide.util.Lookup;
665.15 +import org.openide.util.RequestProcessor;
665.16 +
665.17 +/**
665.18 + *
665.19 + * @author alley
665.20 + * @author Tomas Zezula
665.21 + */
665.22 +public class PythonActionProvider implements ActionProvider {
665.23 +
665.24 + private final Map<String, Command> commands;
665.25 +
665.26 + public PythonActionProvider(PythonProject2 project) {
665.27 + assert project != null;
665.28 + commands = new LinkedHashMap<String, Command>();
665.29 + Command[] commandArray = new Command[]{
665.30 + // new DeleteCommand(project),
665.31 + // new CopyCommand(project),
665.32 + // new MoveCommand(project),
665.33 + // new RenameCommand(project),
665.34 + // new CleanCommand(project),
665.35 + new RunSingleCommand(project, false),
665.36 + new RunSingleCommand(project, true), // Run as Test
665.37 + new RunCommand(project, false),
665.38 + new RunCommand(project, true), // Run project as Test
665.39 + // new DebugCommand(project) ,
665.40 + // new DebugSingleCommand(project, false),
665.41 + // new DebugSingleCommand(project, true), // Debug as Test
665.42 + // new BuildCommand(project), //Build Egg
665.43 + // new CleanBuildCommand(project) //Clean and Build Egg
665.44 + };
665.45 + for (Command command : commandArray) {
665.46 + commands.put(command.getCommandId(), command);
665.47 + }
665.48 + }
665.49 +
665.50 +// public static TestRunner getTestRunner(TestRunner.TestType testType) {
665.51 +// Collection<? extends TestRunner> testRunners = Lookup.getDefault().lookupAll(TestRunner.class);
665.52 +// for (TestRunner each : testRunners) {
665.53 +// if (each.supports(testType)) {
665.54 +// return each;
665.55 +// }
665.56 +// }
665.57 +// return null;
665.58 +// }
665.59 + @Override
665.60 + public String[] getSupportedActions() {
665.61 + final Set<String> names = commands.keySet();
665.62 + return names.toArray(new String[names.size()]);
665.63 + }
665.64 +
665.65 + @Override
665.66 + public void invokeAction(final String commandName, final Lookup context) throws IllegalArgumentException {
665.67 + final Command command = findCommand(commandName);
665.68 + assert command != null;
665.69 + if (command.saveRequired()) {
665.70 + LifecycleManager.getDefault().saveAll();
665.71 + }
665.72 + if (!command.asyncCallRequired()) {
665.73 + command.invokeAction(context);
665.74 + } else {
665.75 + RequestProcessor.getDefault().post(new Runnable() {
665.76 + @Override
665.77 + public void run() {
665.78 + command.invokeAction(context);
665.79 + }
665.80 + });
665.81 + }
665.82 + }
665.83 +
665.84 + @Override
665.85 + public boolean isActionEnabled(String commandName, Lookup context) throws IllegalArgumentException {
665.86 + final Command command = findCommand(commandName);
665.87 + assert command != null;
665.88 + return command.isActionEnabled(context);
665.89 + }
665.90 +
665.91 + private Command findCommand(final String commandName) {
665.92 + assert commandName != null;
665.93 + return commands.get(commandName);
665.94 + }
665.95 +
665.96 +}
666.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
666.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/PythonAuxilaryConfig.java Sat Feb 28 17:25:32 2015 -0800
666.3 @@ -0,0 +1,524 @@
666.4 +/*
666.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
666.6 + *
666.7 + * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
666.8 + *
666.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
666.10 + * Other names may be trademarks of their respective owners.
666.11 + *
666.12 + * The contents of this file are subject to the terms of either the GNU
666.13 + * General Public License Version 2 only ("GPL") or the Common
666.14 + * Development and Distribution License("CDDL") (collectively, the
666.15 + * "License"). You may not use this file except in compliance with the
666.16 + * License. You can obtain a copy of the License at
666.17 + * http://www.netbeans.org/cddl-gplv2.html
666.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
666.19 + * specific language governing permissions and limitations under the
666.20 + * License. When distributing the software, include this License Header
666.21 + * Notice in each file and include the License file at
666.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
666.23 + * particular file as subject to the "Classpath" exception as provided
666.24 + * by Oracle in the GPL Version 2 section of the License file that
666.25 + * accompanied this code. If applicable, add the following below the
666.26 + * License Header, with the fields enclosed by brackets [] replaced by
666.27 + * your own identifying information:
666.28 + * "Portions Copyrighted [year] [name of copyright owner]"
666.29 + *
666.30 + * If you wish your version of this file to be governed by only the CDDL
666.31 + * or only the GPL Version 2, indicate your decision by adding
666.32 + * "[Contributor] elects to include this software in this distribution
666.33 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
666.34 + * single choice of license, a recipient has the option to distribute
666.35 + * your version of this file under either the CDDL, the GPL Version 2 or
666.36 + * to extend the choice of license to its licensees as provided above.
666.37 + * However, if you add GPL Version 2 code and therefore, elected the GPL
666.38 + * Version 2 license, then the option applies only if the new code is
666.39 + * made subject to such option by the copyright holder.
666.40 + *
666.41 + * Contributor(s):
666.42 + *
666.43 + * Portions Copyrighted 2008 Sun Microsystems, Inc.
666.44 + */
666.45 +
666.46 +package org.netbeans.modules.python.project2;
666.47 +
666.48 +import java.beans.PropertyChangeListener;
666.49 +import java.beans.PropertyChangeSupport;
666.50 +import java.io.ByteArrayOutputStream;
666.51 +import java.io.IOException;
666.52 +import java.io.OutputStream;
666.53 +import java.io.StringReader;
666.54 +import java.util.Collection;
666.55 +import java.util.Collections;
666.56 +import java.util.HashSet;
666.57 +import java.util.Set;
666.58 +import java.util.concurrent.atomic.AtomicBoolean;
666.59 +import java.util.logging.Level;
666.60 +import java.util.logging.Logger;
666.61 +import javax.xml.parsers.DocumentBuilder;
666.62 +import javax.xml.parsers.DocumentBuilderFactory;
666.63 +import javax.xml.parsers.ParserConfigurationException;
666.64 +import org.netbeans.api.annotations.common.NonNull;
666.65 +import static org.netbeans.modules.python.project2.Bundle.*;
666.66 +import org.netbeans.spi.project.AuxiliaryConfiguration;
666.67 +import org.netbeans.spi.project.ui.ProjectProblemsProvider;
666.68 +import org.netbeans.spi.project.ui.ProjectProblemsProvider.ProjectProblem;
666.69 +import org.openide.filesystems.FileChangeAdapter;
666.70 +import org.openide.filesystems.FileEvent;
666.71 +import org.openide.filesystems.FileObject;
666.72 +import org.openide.filesystems.FileRenameEvent;
666.73 +import org.openide.filesystems.FileSystem.AtomicAction;
666.74 +import org.openide.filesystems.FileUtil;
666.75 +import org.openide.util.Exceptions;
666.76 +import org.openide.util.NbBundle.Messages;
666.77 +import org.openide.util.RequestProcessor;
666.78 +import org.openide.xml.XMLUtil;
666.79 +import org.w3c.dom.DOMException;
666.80 +import org.w3c.dom.Document;
666.81 +import org.w3c.dom.Element;
666.82 +import org.w3c.dom.Node;
666.83 +import org.w3c.dom.NodeList;
666.84 +import org.xml.sax.InputSource;
666.85 +import org.xml.sax.SAXException;
666.86 +
666.87 +/**
666.88 + * implementation of AuxiliaryConfiguration that relies on FileObject's attributes
666.89 + * for the non shared elements and on ${basedir}/nb-configuration file for share ones.
666.90 + * @author mkleint
666.91 + */
666.92 +public class PythonAuxilaryConfig implements AuxiliaryConfiguration {
666.93 + public static final String BROKEN_NBCONFIG = "BROKENNBCONFIG"; //NOI18N
666.94 +
666.95 + private static final String AUX_CONFIG = "AuxilaryConfiguration"; //NOI18N
666.96 + public static final String CONFIG_FILE_NAME = "nb-configuration.xml"; //NOI18N
666.97 +
666.98 + private static final Logger LOG = Logger.getLogger(PythonAuxilaryConfig.class.getName());
666.99 + private static final RequestProcessor RP = new RequestProcessor(PythonAuxilaryConfig.class);
666.100 + private static final int SAVING_DELAY = 100;
666.101 + private RequestProcessor.Task savingTask;
666.102 + private Document scheduledDocument;
666.103 + private Document cachedDoc;
666.104 + private static final Document DELETED_FILE_DOCUMENT = XMLUtil.createDocument(AUX_CONFIG, null, null, null);
666.105 + private static final Document BROKEN_DOCUMENT = XMLUtil.createDocument(AUX_CONFIG, null, null, null);
666.106 + private final Object configIOLock = new Object();
666.107 + private final FileObject projectDirectory;
666.108 + private ProblemProvider pp;
666.109 + private final FileChangeAdapter fileChange;
666.110 + private final AtomicBoolean fileChangeSet = new AtomicBoolean(false);
666.111 +
666.112 + public PythonAuxilaryConfig(FileObject dir, boolean longtermInstance) {
666.113 + this.projectDirectory = dir;
666.114 +
666.115 + if (longtermInstance) {
666.116 + pp = new ProblemProvider();
666.117 + fileChange = new FileChangeAdapter() {
666.118 +
666.119 + @Override
666.120 + public void fileRenamed(FileRenameEvent fe) {
666.121 + if (CONFIG_FILE_NAME.equals(fe.getName() + "." + fe.getExt())) {
666.122 + resetCache();
666.123 + }
666.124 + }
666.125 +
666.126 + @Override
666.127 + public void fileDeleted(FileEvent fe) {
666.128 + if (CONFIG_FILE_NAME.equals(fe.getFile().getNameExt())) {
666.129 + resetCache();
666.130 + }
666.131 + }
666.132 +
666.133 + @Override
666.134 + public void fileChanged(FileEvent fe) {
666.135 + if (CONFIG_FILE_NAME.equals(fe.getFile().getNameExt())) {
666.136 + resetCache();
666.137 + }
666.138 + }
666.139 +
666.140 + @Override
666.141 + public void fileDataCreated(FileEvent fe) {
666.142 + if (CONFIG_FILE_NAME.equals(fe.getFile().getNameExt())) {
666.143 + resetCache();
666.144 + }
666.145 + }
666.146 + };
666.147 +
666.148 + savingTask = RP.create(new Runnable() {
666.149 + public @Override void run() {
666.150 + try {
666.151 + projectDirectory.getFileSystem().runAtomicAction(new AtomicAction() {
666.152 + public @Override void run() throws IOException {
666.153 + Document doc;
666.154 + synchronized (PythonAuxilaryConfig.this) {
666.155 + doc = scheduledDocument;
666.156 + if (doc == null) {
666.157 + return;
666.158 + }
666.159 + scheduledDocument = null;
666.160 + }
666.161 + synchronized (configIOLock) {
666.162 + FileObject config = projectDirectory.getFileObject(CONFIG_FILE_NAME);
666.163 + if (doc.getDocumentElement().getElementsByTagName("*").getLength() > 0) {
666.164 + OutputStream out = config == null ? projectDirectory.createAndOpen(CONFIG_FILE_NAME) : config.getOutputStream();
666.165 + LOG.log(Level.FINEST, "Write configuration file for {0}", projectDirectory);
666.166 + try {
666.167 + XMLUtil.write(doc, out, "UTF-8"); //NOI18N
666.168 + } finally {
666.169 + out.close();
666.170 + }
666.171 + } else if (config != null) {
666.172 + LOG.log(Level.FINEST, "Delete empty configuration file for {0}", projectDirectory);
666.173 + config.delete();
666.174 + }
666.175 + }
666.176 + }
666.177 + });
666.178 + } catch (IOException ex) {
666.179 + LOG.log(Level.INFO, "IO Error while saving " + projectDirectory.getFileObject(CONFIG_FILE_NAME), ex);
666.180 + }
666.181 + }
666.182 + });
666.183 + } else {
666.184 + fileChange = null;
666.185 + fileChangeSet.set(true);
666.186 + }
666.187 + }
666.188 +
666.189 + private synchronized void resetCache() {
666.190 + cachedDoc = null;
666.191 + }
666.192 +
666.193 +
666.194 + public ProjectProblemsProvider getProblemProvider() {
666.195 + return pp;
666.196 + }
666.197 +
666.198 + private Document loadConfig(FileObject config) throws IOException, SAXException {
666.199 + synchronized (configIOLock) {
666.200 + return XMLUtil.parse(new InputSource(config.toURL().toString()), false, true, null, null);
666.201 + }
666.202 + }
666.203 +
666.204 + public @Override Element getConfigurationFragment(String elementName, String namespace, boolean shared) {
666.205 + Element e = doGetConfigurationFragment(elementName, namespace, shared);
666.206 + return e != null ? cloneSafely(e) : null;
666.207 + }
666.208 + // Copied from AntProjectHelper.
666.209 + private static final DocumentBuilder db;
666.210 + static {
666.211 + try {
666.212 + db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
666.213 + } catch (ParserConfigurationException e) {
666.214 + throw new AssertionError(e);
666.215 + }
666.216 + }
666.217 + private static Element cloneSafely(Element el) { // #190845
666.218 + // #50198: for thread safety, use a separate document.
666.219 + // Using XMLUtil.createDocument is much too slow.
666.220 + synchronized (db) {
666.221 + Document dummy = db.newDocument();
666.222 + return (Element) dummy.importNode(el, true);
666.223 + }
666.224 + }
666.225 + @Messages({
666.226 + "TXT_Problem_Broken_Config=Broken nb-configuration.xml file.",
666.227 + "# {0} - parser error message",
666.228 + "DESC_Problem_Broken_Config=The $project_basedir/nb-configuration.xml file cannot be parsed. "
666.229 + + "The information contained in the file will be ignored until fixed. "
666.230 + + "This affects several features in the IDE that will not work properly as a result.\n\n "
666.231 + + "The parsing exception follows:\n{0}",
666.232 + "TXT_Problem_Broken_Config2=Duplicate entries found in nb-configuration.xml file.",
666.233 + "DESC_Problem_Broken_Config2=The $project_basedir/nb-configuration.xml file contains some elements multiple times. "
666.234 + + "That can happen when concurrent changes get merged by version control for example. The IDE however cannot decide which one to use. "
666.235 + + "So until the problem is resolved manually, the affected configuration will be ignored."
666.236 + })
666.237 + private synchronized Element doGetConfigurationFragment(final String elementName, final String namespace, boolean shared) {
666.238 + lazyAttachListener();
666.239 + if (shared) {
666.240 + //first check the document schedule for persistence
666.241 + if (scheduledDocument != null) {
666.242 + try {
666.243 + Element el = XMLUtil.findElement(scheduledDocument.getDocumentElement(), elementName, namespace);
666.244 + if (el != null) {
666.245 + el = (Element) el.cloneNode(true);
666.246 + }
666.247 + return el;
666.248 + } catch (IllegalArgumentException iae) {
666.249 + //thrown from XmlUtil.findElement when more than 1 equal elements are present.
666.250 + LOG.log(Level.INFO, iae.getMessage(), iae);
666.251 + }
666.252 + }
666.253 + if (cachedDoc == null) {
666.254 + final FileObject config = projectDirectory.getFileObject(CONFIG_FILE_NAME);
666.255 + if (config != null) {
666.256 + // we need to re-read the config file..
666.257 + try {
666.258 + Document doc = loadConfig(config);
666.259 + cachedDoc = doc;
666.260 + if (pp != null) {
666.261 + pp.setProblem(null);
666.262 + findDuplicateElements(doc.getDocumentElement(), pp, config);
666.263 + }
666.264 + return XMLUtil.findElement(doc.getDocumentElement(), elementName, namespace);
666.265 + } catch (final SAXException ex) {
666.266 + if (pp != null) {
666.267 + RP.post(new Runnable() {
666.268 + @Override
666.269 + public void run() {
666.270 + pp.setProblem(ProjectProblem.createWarning(
666.271 + TXT_Problem_Broken_Config(),
666.272 + DESC_Problem_Broken_Config(ex.getMessage())/*,
666.273 + new ProblemReporterImpl.MavenProblemResolver(ProblemReporterImpl.createOpenFileAction(config), BROKEN_NBCONFIG)*/));
666.274 + }
666.275 + });
666.276 + }
666.277 + LOG.log(Level.INFO, ex.getMessage(), ex);
666.278 + cachedDoc = BROKEN_DOCUMENT;
666.279 + } catch (IOException ex) {
666.280 + LOG.log(Level.INFO, "IO Error while loading " + config.getPath(), ex);
666.281 + cachedDoc = BROKEN_DOCUMENT;
666.282 + } catch (IllegalArgumentException iae) {
666.283 + //thrown from XmlUtil.findElement when more than 1 equal elements are present.
666.284 + LOG.log(Level.INFO, iae.getMessage(), iae);
666.285 + }
666.286 + return null;
666.287 + } else {
666.288 + // no file.. remove possible cache
666.289 + cachedDoc = DELETED_FILE_DOCUMENT;
666.290 + return null;
666.291 + }
666.292 + } else {
666.293 + if (cachedDoc == DELETED_FILE_DOCUMENT || cachedDoc == BROKEN_DOCUMENT) {
666.294 + return null;
666.295 + }
666.296 + //reuse cached value if available;
666.297 + try {
666.298 + return XMLUtil.findElement(cachedDoc.getDocumentElement(), elementName, namespace);
666.299 + } catch (IllegalArgumentException iae) {
666.300 + //thrown from XmlUtil.findElement when more than 1 equal elements are present.
666.301 + LOG.log(Level.INFO, iae.getMessage(), iae);
666.302 + }
666.303 + }
666.304 + return null;
666.305 + } else {
666.306 + String str = (String) projectDirectory.getAttribute(AUX_CONFIG);
666.307 + if (str != null) {
666.308 + Document doc;
666.309 + try {
666.310 + doc = XMLUtil.parse(new InputSource(new StringReader(str)), false, true, null, null);
666.311 + return XMLUtil.findElement(doc.getDocumentElement(), elementName, namespace);
666.312 + } catch (SAXException ex) {
666.313 + LOG.log(Level.FINE, "cannot parse", ex);
666.314 + } catch (IOException ex) {
666.315 + LOG.log(Level.FINE, "error reading private auxiliary configuration", ex);
666.316 + }
666.317 + }
666.318 + return null;
666.319 + }
666.320 + }
666.321 +
666.322 + private void lazyAttachListener() {
666.323 + if (fileChangeSet.compareAndSet(false, true)) {
666.324 + projectDirectory.addFileChangeListener(FileUtil.weakFileChangeListener(fileChange, projectDirectory));
666.325 + }
666.326 + }
666.327 +
666.328 + public @Override synchronized void putConfigurationFragment(final Element fragment, final boolean shared) throws IllegalArgumentException {
666.329 + lazyAttachListener();
666.330 + Document doc = null;
666.331 + if (shared) {
666.332 + if (scheduledDocument != null) {
666.333 + doc = scheduledDocument;
666.334 + } else {
666.335 + FileObject config = projectDirectory.getFileObject(CONFIG_FILE_NAME);
666.336 + if (config != null) {
666.337 + try {
666.338 + doc = loadConfig(config);
666.339 + } catch (SAXException ex) {
666.340 + LOG.log(Level.INFO, "Cannot parse file " + config.getPath(), ex);
666.341 + if (config.getSize() == 0) {
666.342 + //something got wrong in the past..
666.343 + doc = createNewSharedDocument();
666.344 + }
666.345 + } catch (IOException ex) {
666.346 + LOG.log(Level.INFO, "IO Error with " + config.getPath(), ex);
666.347 + }
666.348 + } else {
666.349 + doc = createNewSharedDocument();
666.350 + }
666.351 + }
666.352 + } else {
666.353 + String str = (String) projectDirectory.getAttribute(AUX_CONFIG);
666.354 + if (str != null) {
666.355 + try {
666.356 + doc = XMLUtil.parse(new InputSource(new StringReader(str)), false, true, null, null);
666.357 + } catch (SAXException ex) {
666.358 + LOG.log(Level.FINE, "cannot parse", ex);
666.359 + } catch (IOException ex) {
666.360 + LOG.log(Level.FINE, "error reading private auxiliary configuration", ex);
666.361 + }
666.362 + }
666.363 + if (doc == null) {
666.364 + String element = "project-private"; // NOI18N
666.365 + doc = XMLUtil.createDocument(element, null, null, null);
666.366 + }
666.367 + }
666.368 + if (doc != null) {
666.369 + Element el = XMLUtil.findElement(doc.getDocumentElement(), fragment.getNodeName(), fragment.getNamespaceURI());
666.370 + if (el != null) {
666.371 + doc.getDocumentElement().removeChild(el);
666.372 + }
666.373 + doc.getDocumentElement().appendChild(doc.importNode(fragment, true));
666.374 +
666.375 + if (shared) {
666.376 + if (scheduledDocument == null) {
666.377 + scheduledDocument = doc;
666.378 + }
666.379 + LOG.log(Level.FINEST, "Schedule saving of configuration fragment for " + projectDirectory, new Exception());
666.380 + savingTask.schedule(SAVING_DELAY);
666.381 + } else {
666.382 + try {
666.383 + ByteArrayOutputStream wr = new ByteArrayOutputStream();
666.384 + XMLUtil.write(doc, wr, "UTF-8"); //NOI18N
666.385 + projectDirectory.setAttribute(AUX_CONFIG, wr.toString("UTF-8"));
666.386 + } catch (IOException ex) {
666.387 + LOG.log(Level.FINE, "error writing private auxiliary configuration", ex);
666.388 + }
666.389 + }
666.390 + }
666.391 +
666.392 + }
666.393 +
666.394 + public @Override synchronized boolean removeConfigurationFragment(final String elementName, final String namespace, final boolean shared) throws IllegalArgumentException {
666.395 + lazyAttachListener();
666.396 + Document doc = null;
666.397 + FileObject config = projectDirectory.getFileObject(CONFIG_FILE_NAME);
666.398 + if (shared) {
666.399 + if (scheduledDocument != null) {
666.400 + doc = scheduledDocument;
666.401 + } else {
666.402 + if (config != null) {
666.403 + try {
666.404 + try {
666.405 + doc = loadConfig(config);
666.406 + } catch (SAXException ex) {
666.407 + LOG.log(Level.INFO, "Cannot parse file " + config.getPath(), ex);
666.408 + if (config.getSize() == 0) {
666.409 + //just delete the empty file, something got wrong a while back..
666.410 + config.delete();
666.411 + }
666.412 + return true;
666.413 + }
666.414 + } catch (IOException ex) {
666.415 + LOG.log(Level.INFO, "IO Error with " + config.getPath(), ex);
666.416 + }
666.417 + } else {
666.418 + return false;
666.419 + }
666.420 + }
666.421 + } else {
666.422 + String str = (String) projectDirectory.getAttribute(AUX_CONFIG);
666.423 + if (str != null) {
666.424 + try {
666.425 + doc = XMLUtil.parse(new InputSource(new StringReader(str)), false, true, null, null);
666.426 + } catch (SAXException ex) {
666.427 + Exceptions.printStackTrace(ex);
666.428 + } catch (IOException ex) {
666.429 + Exceptions.printStackTrace(ex);
666.430 + }
666.431 + } else {
666.432 + return false;
666.433 + }
666.434 + }
666.435 + if (doc != null) {
666.436 + Element el = XMLUtil.findElement(doc.getDocumentElement(), elementName, namespace);
666.437 + if (el != null) {
666.438 + doc.getDocumentElement().removeChild(el);
666.439 + }
666.440 + if (shared) {
666.441 + if (scheduledDocument == null) {
666.442 + scheduledDocument = doc;
666.443 + }
666.444 + LOG.log(Level.FINEST, "Schedule saving of configuration fragment for " + projectDirectory, new Exception());
666.445 + savingTask.schedule(SAVING_DELAY);
666.446 + } else {
666.447 + try {
666.448 + ByteArrayOutputStream wr = new ByteArrayOutputStream();
666.449 + XMLUtil.write(doc, wr, "UTF-8"); //NOI18N
666.450 + projectDirectory.setAttribute(AUX_CONFIG, wr.toString("UTF-8"));
666.451 + } catch (IOException ex) {
666.452 + Exceptions.printStackTrace(ex);
666.453 + }
666.454 + }
666.455 + }
666.456 + return true;
666.457 + }
666.458 +
666.459 + private Document createNewSharedDocument() throws DOMException {
666.460 + String element = "project-shared-configuration";
666.461 + Document doc = XMLUtil.createDocument(element, null, null, null);
666.462 + doc.getDocumentElement().appendChild(doc.createComment(
666.463 + "\nThis file contains additional configuration written by modules in the NetBeans IDE.\n" +
666.464 + "The configuration is intended to be shared among all the users of project and\n" +
666.465 + "therefore it is assumed to be part of version control checkout.\n" +
666.466 + "Without this configuration present, some functionality in the IDE may be limited or fail altogether.\n"));
666.467 + return doc;
666.468 + }
666.469 +
666.470 + static void findDuplicateElements(@NonNull Element parent, @NonNull ProblemProvider pp, FileObject config) {
666.471 + NodeList l = parent.getChildNodes();
666.472 + int nodeCount = l.getLength();
666.473 + Set<String> known = new HashSet<String>();
666.474 + for (int i = 0; i < nodeCount; i++) {
666.475 + if (l.item(i).getNodeType() == Node.ELEMENT_NODE) {
666.476 + Node node = l.item(i);
666.477 + String localName = node.getLocalName();
666.478 + localName = localName == null ? node.getNodeName() : localName;
666.479 + String id = localName + "|" + node.getNamespaceURI();
666.480 + if (!known.add(id)) {
666.481 + //we have a duplicate;
666.482 + pp.setProblem(ProjectProblem.createWarning(
666.483 + TXT_Problem_Broken_Config2(),
666.484 + DESC_Problem_Broken_Config2()/*,
666.485 + new ProblemReporterImpl.MavenProblemResolver(ProblemReporterImpl.createOpenFileAction(config), BROKEN_NBCONFIG)*/));
666.486 + }
666.487 + }
666.488 + }
666.489 + }
666.490 +
666.491 + private class ProblemProvider implements ProjectProblemsProvider {
666.492 +
666.493 + private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
666.494 + private ProjectProblem pp;
666.495 +
666.496 + public ProblemProvider() {
666.497 + }
666.498 +
666.499 + void setProblem(ProjectProblem pp) {
666.500 + this.pp = pp;
666.501 + if (pp == null && this.pp == null) {
666.502 + return; //ignore this case, dont' fire change..
666.503 + }
666.504 + pcs.firePropertyChange(ProjectProblemsProvider.PROP_PROBLEMS, null, null);
666.505 + }
666.506 +
666.507 + @Override
666.508 + public void addPropertyChangeListener(PropertyChangeListener listener) {
666.509 + pcs.addPropertyChangeListener(listener);
666.510 + }
666.511 +
666.512 + @Override
666.513 + public void removePropertyChangeListener(PropertyChangeListener listener) {
666.514 + pcs.removePropertyChangeListener(listener);
666.515 + }
666.516 +
666.517 + @Override
666.518 + public Collection<? extends ProjectProblem> getProblems() {
666.519 + if (pp != null) {
666.520 + return Collections.singleton(pp);
666.521 + } else {
666.522 + return Collections.emptyList();
666.523 + }
666.524 + }
666.525 +
666.526 + }
666.527 +}
667.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
667.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/PythonProject2.java Sat Feb 28 17:25:32 2015 -0800
667.3 @@ -0,0 +1,368 @@
667.4 +package org.netbeans.modules.python.project2;
667.5 +
667.6 +import java.beans.PropertyChangeListener;
667.7 +import java.beans.PropertyChangeSupport;
667.8 +import java.io.IOException;
667.9 +import java.util.Properties;
667.10 +import java.util.Scanner;
667.11 +import java.util.concurrent.ExecutionException;
667.12 +import java.util.concurrent.Future;
667.13 +import javax.swing.Icon;
667.14 +import javax.swing.ImageIcon;
667.15 +import org.netbeans.api.project.Project;
667.16 +import org.netbeans.api.project.ProjectInformation;
667.17 +import org.netbeans.api.project.ProjectManager;
667.18 +import org.netbeans.api.project.ProjectUtils;
667.19 +import org.netbeans.modules.python.api.PythonException;
667.20 +import org.netbeans.modules.python.api.PythonExecution;
667.21 +import org.netbeans.modules.python.api.PythonPlatform;
667.22 +import org.netbeans.modules.python.api.PythonPlatformManager;
667.23 +import org.netbeans.modules.python.editor.codecoverage.PythonCoverageProvider;
667.24 +import org.netbeans.modules.python.project2.classpath.ClassPathProviderImpl;
667.25 +import org.netbeans.modules.python.project2.ui.customizer.PythonCustomizerProvider;
667.26 +import org.netbeans.spi.project.AuxiliaryConfiguration;
667.27 +import org.netbeans.spi.project.ProjectState;
667.28 +import org.netbeans.spi.project.ui.LogicalViewProvider;
667.29 +import org.netbeans.spi.project.ui.ProjectOpenedHook;
667.30 +import org.openide.filesystems.FileAttributeEvent;
667.31 +import org.openide.filesystems.FileChangeListener;
667.32 +import org.openide.filesystems.FileEvent;
667.33 +import org.openide.filesystems.FileObject;
667.34 +import org.openide.filesystems.FileRenameEvent;
667.35 +import org.openide.filesystems.FileUtil;
667.36 +import org.openide.util.Exceptions;
667.37 +import org.openide.util.ImageUtilities;
667.38 +import org.openide.util.Lookup;
667.39 +import org.openide.util.Mutex;
667.40 +import org.openide.util.io.ReaderInputStream;
667.41 +import org.openide.util.lookup.Lookups;
667.42 +import org.openide.xml.XMLUtil;
667.43 +import org.w3c.dom.Element;
667.44 +import org.w3c.dom.Node;
667.45 +import org.w3c.dom.NodeList;
667.46 +import org.w3c.dom.Text;
667.47 +
667.48 +/**
667.49 + *
667.50 + * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
667.51 + */
667.52 +public class PythonProject2 implements Project {
667.53 +
667.54 + /**
667.55 + * the only property change fired by the class, means that the setup.py file
667.56 + * has changed.
667.57 + */
667.58 + public static final String PROP_PROJECT = "MavenProject"; //NOI18N
667.59 +
667.60 + private static final String NS_PYTHON_1 = "http://nbpython.dev.java.net/ns/php-project/1"; // NOI18N
667.61 + private static final String EL_PYTHON = "python-data"; // NOI18N
667.62 + private static final ImageIcon PROJECT_ICON = ImageUtilities.loadImageIcon("org/netbeans/modules/python/project/resources/py_25_16.png", false);
667.63 +
667.64 + private static final String MAIN_MODULE = "main.file"; //NOI18N
667.65 + private static final String APPLICATION_ARGS = "application.args"; //NOI18N
667.66 + private static final String ACTIVE_PLATFORM = "platform.active"; //NOI18N
667.67 + public static final String SOURCES_TYPE_PYTHON = "python"; //NOI18N
667.68 + static final String SETUPPY = "setup.py"; //NOI18N
667.69 +
667.70 + private final FileObject projectDirectory;
667.71 + protected Lookup lkp;
667.72 + protected AuxiliaryConfiguration aux;
667.73 + protected LogicalViewProvider logicalView;
667.74 + private final Info info;
667.75 + private final PropertyChangeSupport support;
667.76 + private final PythonSources sources;
667.77 +
667.78 + public PythonProject2(FileObject projectDirectory, ProjectState state) {
667.79 + support = new PropertyChangeSupport(this);
667.80 + this.logicalView = new Python2LogicalView(this);
667.81 + this.projectDirectory = projectDirectory;
667.82 + info = new PythonProject2.Info();
667.83 + aux = new PythonAuxilaryConfig(projectDirectory, true);
667.84 + sources = new PythonSources(this);
667.85 + this.lkp = createLookup(state);
667.86 + }
667.87 +
667.88 + @Override
667.89 + public FileObject getProjectDirectory() {
667.90 + return projectDirectory;
667.91 + }
667.92 +
667.93 + @Override
667.94 + public Lookup getLookup() {
667.95 + return lkp;
667.96 + }
667.97 +
667.98 + private Lookup createLookup(ProjectState state) {
667.99 + return Lookups.fixed(new Object[]{
667.100 + this, //project spec requires a project be in it's own lookup
667.101 + aux, //Auxiliary configuartion to store bookmarks and so on
667.102 + new PythonActionProvider(this), //Provides Standard like build and cleen
667.103 + info, // Project information Implementation
667.104 + logicalView, // Logical view if project implementation
667.105 + new PythonProject2.PythonOpenedHook(), //Called by project framework when project is opened (closed)
667.106 + sources, //Python source grops - used by package view, factories, refactoring, ...
667.107 + new ClassPathProviderImpl(this, sources),
667.108 +// new PythonProjectOperations(this), //move, rename, copy of project
667.109 +// new PythonProject.RecommendedTemplatesImpl(this.updateHelper), // Recommended Templates
667.110 + new PythonCustomizerProvider(this), //Project custmoizer
667.111 +// new PythonProjectFileEncodingQuery(getEvaluator()), //Provides encoding of the project - used by editor, runtime
667.112 +// new PythonSharabilityQuery(helper, getEvaluator(), getSourceRoots(), getTestRoots()), //Sharabilit info - used by VCS
667.113 +// helper.createCacheDirectoryProvider(), //Cache provider
667.114 +// helper.createAuxiliaryProperties(), // AuxiliaryConfiguraion provider - used by bookmarks, project Preferences, etc
667.115 +// new PythonPlatformProvider(getEvaluator()),
667.116 + new PythonCoverageProvider(this),
667.117 + new PythonProjectSourceLevelQuery(this),
667.118 + state
667.119 + });
667.120 + }
667.121 +
667.122 + public void addPropertyChangeListener(PropertyChangeListener propertyChangeListener) {
667.123 + support.addPropertyChangeListener(propertyChangeListener);
667.124 + }
667.125 +
667.126 + public void removePropertyChangeListener(PropertyChangeListener propertyChangeListener) {
667.127 + support.removePropertyChangeListener(propertyChangeListener);
667.128 + }
667.129 +
667.130 + public PythonPlatform getActivePlatform() {
667.131 + String pid = getProp(ProjectUtils.getAuxiliaryConfiguration(this), PythonProject2.APPLICATION_ARGS);
667.132 + final PythonPlatformManager manager = PythonPlatformManager.getInstance();
667.133 + if (pid == null) {
667.134 + pid = manager.getDefaultPlatform();
667.135 + }
667.136 + return manager.getPlatform(pid);
667.137 + }
667.138 +
667.139 + public void setActivePlatform(final PythonPlatform platform) {
667.140 + storeProp(ProjectUtils.getAuxiliaryConfiguration(this), PythonProject2.ACTIVE_PLATFORM, platform.getId());
667.141 + }
667.142 +
667.143 + public String getApplicationArgs() {
667.144 + return getProp(ProjectUtils.getAuxiliaryConfiguration(this), PythonProject2.APPLICATION_ARGS);
667.145 + }
667.146 +
667.147 + public void setApplicationArgs(final String args) {
667.148 + storeProp(ProjectUtils.getAuxiliaryConfiguration(this), PythonProject2.APPLICATION_ARGS, args);
667.149 + }
667.150 +
667.151 + public String getMainModule() {
667.152 + return getProp(ProjectUtils.getAuxiliaryConfiguration(this), PythonProject2.MAIN_MODULE);
667.153 + }
667.154 +
667.155 + public void setMainModule(final String main) {
667.156 + storeProp(ProjectUtils.getAuxiliaryConfiguration(this), PythonProject2.MAIN_MODULE, main);
667.157 + }
667.158 +
667.159 + private String getProp(final AuxiliaryConfiguration auxiliaryConfiguration, final String key) {
667.160 + return ProjectManager.mutex().readAccess(new Mutex.Action<String>() {
667.161 + @Override
667.162 + public String run() {
667.163 + Element data = auxiliaryConfiguration.getConfigurationFragment(PythonProject2.EL_PYTHON, PythonProject2.NS_PYTHON_1, true);
667.164 + if (data == null) {
667.165 + return null;
667.166 + }
667.167 + NodeList nl = data.getElementsByTagNameNS(PythonProject2.NS_PYTHON_1, key);
667.168 + if (nl.getLength() == 1) {
667.169 + nl = nl.item(0).getChildNodes();
667.170 + if (nl.getLength() == 1 && nl.item(0).getNodeType() == Node.TEXT_NODE) {
667.171 + return ((Text) nl.item(0)).getNodeValue();
667.172 + }
667.173 + }
667.174 + return null; // NOI18N
667.175 + }
667.176 + });
667.177 + }
667.178 +
667.179 + private void storeProp(final AuxiliaryConfiguration auxiliaryConfiguration, final String key, final String main) {
667.180 + ProjectManager.mutex().writeAccess(new Mutex.Action<Void>() {
667.181 + @Override
667.182 + public Void run() {
667.183 + Element data = auxiliaryConfiguration.getConfigurationFragment(PythonProject2.EL_PYTHON, PythonProject2.NS_PYTHON_1, true);
667.184 + if (data == null) {
667.185 + data = XMLUtil.createDocument(PythonProject2.EL_PYTHON, PythonProject2.NS_PYTHON_1, null, null).getDocumentElement();
667.186 + auxiliaryConfiguration.putConfigurationFragment(data, false);
667.187 + }
667.188 + NodeList nl = data.getElementsByTagNameNS(PythonProject2.NS_PYTHON_1, key);
667.189 + Element nameEl;
667.190 + if (nl.getLength() == 1) {
667.191 + nameEl = (Element) nl.item(0);
667.192 + NodeList deadKids = nameEl.getChildNodes();
667.193 + while (deadKids.getLength() > 0) {
667.194 + nameEl.removeChild(deadKids.item(0));
667.195 + }
667.196 + } else {
667.197 + nameEl = data.getOwnerDocument().createElementNS(PythonProject2.NS_PYTHON_1, key);
667.198 + data.insertBefore(nameEl, data.getChildNodes().item(0));
667.199 + }
667.200 + nameEl.appendChild(data.getOwnerDocument().createTextNode(main));
667.201 + auxiliaryConfiguration.putConfigurationFragment(data, true);
667.202 + return null;
667.203 + }
667.204 + });
667.205 + }
667.206 +
667.207 + private final class Info implements ProjectInformation, FileChangeListener {
667.208 +
667.209 + private static final String PROP_VERSION = "version";
667.210 +
667.211 + private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
667.212 + private final Properties properties;
667.213 +
667.214 + public Info() {
667.215 + properties = findProjectProperties();
667.216 + }
667.217 +
667.218 + @Override
667.219 + public void addPropertyChangeListener(PropertyChangeListener listener) {
667.220 + propertyChangeSupport.addPropertyChangeListener(listener);
667.221 + }
667.222 +
667.223 + @Override
667.224 + public void removePropertyChangeListener(PropertyChangeListener listener) {
667.225 + propertyChangeSupport.removePropertyChangeListener(listener);
667.226 + }
667.227 +
667.228 + public Properties getProperties() {
667.229 + return properties;
667.230 + }
667.231 +
667.232 + @Override
667.233 + public String getDisplayName() {
667.234 + return properties.getProperty(PROP_DISPLAY_NAME);
667.235 + }
667.236 +
667.237 + @Override
667.238 + public Icon getIcon() {
667.239 + return PROJECT_ICON;
667.240 + }
667.241 +
667.242 + @Override
667.243 + public String getName() {
667.244 + return projectDirectory.getName();
667.245 +// return name;
667.246 + }
667.247 +
667.248 + public String getVersion() {
667.249 + return properties.getProperty(PROP_VERSION);
667.250 +// return version;
667.251 + }
667.252 +
667.253 + @Override
667.254 + public Project getProject() {
667.255 + return PythonProject2.this;
667.256 + }
667.257 +
667.258 + public Properties findProjectProperties() {
667.259 + Properties props = new Properties();
667.260 + PythonPlatform platform = PythonPlatformManager.getInstance().getPlatforms().get(0);
667.261 + PythonExecution pye;
667.262 + try {
667.263 + pye = new PythonExecution();
667.264 + pye.setCommand(platform.getInterpreterCommand());
667.265 + pye.setDisplayName("Python Project Info");
667.266 + FileObject setuppy = projectDirectory.getFileObject(SETUPPY);
667.267 + setuppy.addFileChangeListener(this);
667.268 + pye.setScript(FileUtil.toFile(setuppy).getAbsolutePath());
667.269 + pye.setScriptArgs("--name --version"); //NOI18N
667.270 + pye.setShowControls(false);
667.271 + pye.setShowInput(false);
667.272 + pye.setShowWindow(false);
667.273 + pye.setShowProgress(false);
667.274 + pye.setShowSuspended(false);
667.275 + //pye.setWorkingDirectory(info.getAbsolutePath().substring(0, info.getAbsolutePath().lastIndexOf(File.separator)));
667.276 + pye.setWorkingDirectory(FileUtil.toFile(projectDirectory).getAbsolutePath());
667.277 + pye.attachOutputProcessor();
667.278 + Future<Integer> result = pye.run();
667.279 + Integer value = result.get();
667.280 + if (value.intValue() == 0) {
667.281 + // Problem with encoding?
667.282 +// prop.load(new ReaderInputStream(pye.getOutput()));
667.283 + try (Scanner sc = new Scanner(new ReaderInputStream(pye.getOutput()))) {
667.284 + String newName = sc.nextLine();
667.285 + props.setProperty(PROP_DISPLAY_NAME, newName);
667.286 + String newVersion = sc.nextLine();
667.287 + props.setProperty(PROP_VERSION, newVersion);
667.288 + }
667.289 + } else {
667.290 + throw new PythonException("Could not discover Python Project Info");
667.291 + }
667.292 + } catch (PythonException | InterruptedException | ExecutionException | IOException ex) {
667.293 + Exceptions.printStackTrace(ex);
667.294 + }
667.295 + return props;
667.296 + }
667.297 +
667.298 + @Override
667.299 + public void fileFolderCreated(FileEvent fe) {
667.300 + }
667.301 +
667.302 + @Override
667.303 + public void fileDataCreated(FileEvent fe) {
667.304 + }
667.305 +
667.306 + @Override
667.307 + public void fileChanged(FileEvent fe) {
667.308 + ProjectManager.mutex().writeAccess(new Mutex.Action<Void>() {
667.309 +
667.310 + @Override
667.311 + public Void run() {
667.312 + Properties newProps = findProjectProperties();
667.313 + for (String propName : newProps.stringPropertyNames()) {
667.314 + String value = newProps.getProperty(propName);
667.315 + Object oldValue = properties.setProperty(propName, value);
667.316 + if (!value.equals(oldValue)) {
667.317 + propertyChangeSupport.firePropertyChange(propName, oldValue, value);
667.318 + }
667.319 + }
667.320 + return null;
667.321 + }
667.322 + });
667.323 + }
667.324 +
667.325 + @Override
667.326 + public void fileDeleted(FileEvent fe) {
667.327 + //TODO: What when it is deleted?
667.328 + }
667.329 +
667.330 + @Override
667.331 + public void fileRenamed(FileRenameEvent fe) {
667.332 + //TODO: What when it is renamed?
667.333 + }
667.334 +
667.335 + @Override
667.336 + public void fileAttributeChanged(FileAttributeEvent fe) {
667.337 + }
667.338 + }
667.339 +
667.340 + public final class PythonOpenedHook extends ProjectOpenedHook {
667.341 +
667.342 + @Override
667.343 + protected void projectOpened() {
667.344 + // register project's classpaths to GlobalPathRegistry
667.345 +// final ClassPathProviderImpl cpProvider = getLookup().lookup(ClassPathProviderImpl.class);
667.346 +// assert cpProvider != null;
667.347 +// GlobalPathRegistry.getDefault().register(ClassPath.BOOT, cpProvider.getProjectClassPaths(ClassPath.BOOT));
667.348 +// GlobalPathRegistry.getDefault().register(ClassPath.SOURCE, cpProvider.getProjectClassPaths(ClassPath.SOURCE));
667.349 +
667.350 + // Ensure that code coverage is initialized in case it's enabled...
667.351 +// PythonCoverageProvider codeCoverage = getLookup().lookup(PythonCoverageProvider.class);
667.352 +// if (codeCoverage.isEnabled()) {
667.353 +// codeCoverage.notifyProjectOpened();
667.354 +// }
667.355 + }
667.356 +
667.357 + @Override
667.358 + protected void projectClosed() {
667.359 + // unregister project's classpaths to GlobalPathRegistry
667.360 +// final ClassPathProviderImpl cpProvider = getLookup().lookup(ClassPathProviderImpl.class);
667.361 +// assert cpProvider != null;
667.362 +// //GlobalPathRegistry.getDefault().unregister(ClassPath.BOOT, cpProvider.getProjectClassPaths(ClassPath.BOOT));
667.363 +// GlobalPathRegistry.getDefault().unregister(ClassPath.SOURCE, cpProvider.getProjectClassPaths(ClassPath.SOURCE));
667.364 +// try {
667.365 +// ProjectManager.getDefault().saveProject(PythonProject2.this);
667.366 +// } catch (IOException e) {
667.367 +// Exceptions.printStackTrace(e);
667.368 +// }
667.369 + }
667.370 + }
667.371 +}
668.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
668.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/PythonProjectFactory.java Sat Feb 28 17:25:32 2015 -0800
668.3 @@ -0,0 +1,39 @@
668.4 +/*
668.5 + * To change this license header, choose License Headers in Project Properties.
668.6 + * To change this template file, choose Tools | Templates
668.7 + * and open the template in the editor.
668.8 + */
668.9 +package org.netbeans.modules.python.project2;
668.10 +
668.11 +import java.io.IOException;
668.12 +import org.netbeans.api.project.Project;
668.13 +import org.netbeans.spi.project.ProjectFactory;
668.14 +import org.netbeans.spi.project.ProjectState;
668.15 +import org.openide.filesystems.FileObject;
668.16 +import org.openide.util.lookup.ServiceProvider;
668.17 +
668.18 +/**
668.19 + *
668.20 + * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
668.21 + */
668.22 +@ServiceProvider(service=ProjectFactory.class)
668.23 +public class PythonProjectFactory implements ProjectFactory {
668.24 +
668.25 +
668.26 + @Override
668.27 + public boolean isProject(FileObject projectDirectory) {
668.28 + return projectDirectory.getFileObject(PythonProject2.SETUPPY) != null;
668.29 + }
668.30 +
668.31 + //Specifies when the project will be opened, i.e., if the project exists:
668.32 + @Override
668.33 + public Project loadProject(FileObject dir, ProjectState state) throws IOException {
668.34 + return isProject(dir) ? new PythonProject2(dir, state) : null;
668.35 + }
668.36 +
668.37 + @Override
668.38 + public void saveProject(final Project project) throws IOException, ClassCastException {
668.39 + // leave unimplemented for the moment
668.40 + }
668.41 +
668.42 +}
669.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
669.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/PythonProjectSourceLevelQuery.java Sat Feb 28 17:25:32 2015 -0800
669.3 @@ -0,0 +1,88 @@
669.4 +package org.netbeans.modules.python.project2;
669.5 +
669.6 +import java.beans.PropertyChangeEvent;
669.7 +import java.beans.PropertyChangeListener;
669.8 +import javax.swing.event.ChangeListener;
669.9 +import org.netbeans.api.annotations.common.CheckForNull;
669.10 +import org.netbeans.api.annotations.common.NonNull;
669.11 +import org.netbeans.api.project.ProjectUtils;
669.12 +import org.netbeans.modules.python.api.PythonPlatform;
669.13 +import org.netbeans.modules.python.source.queries.SourceLevelQueryImplementation;
669.14 +import org.openide.filesystems.FileObject;
669.15 +import org.openide.util.ChangeSupport;
669.16 +import org.openide.util.WeakListeners;
669.17 +
669.18 +/**
669.19 + *
669.20 + * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
669.21 + */
669.22 +class PythonProjectSourceLevelQuery implements SourceLevelQueryImplementation {
669.23 +
669.24 + private final PythonProject2 project;
669.25 + private final Result result;
669.26 +
669.27 + PythonProjectSourceLevelQuery(@NonNull final PythonProject2 project) {
669.28 + assert project != null;
669.29 + this.project = project;
669.30 + this.result = new R(project);
669.31 + }
669.32 +
669.33 + @Override
669.34 + public Result getSourceLevel(FileObject javaFile) {
669.35 + return this.result;
669.36 + }
669.37 +
669.38 + @CheckForNull
669.39 + static String findSourceLevel (@NonNull final PythonProject2 project) {
669.40 + return findValue(project);
669.41 + }
669.42 +
669.43 + @CheckForNull
669.44 + private static String findValue(
669.45 + @NonNull final PythonProject2 project) {
669.46 + final PythonPlatform activePlatform = project.getActivePlatform();
669.47 + return activePlatform.getSourceLevel();
669.48 + }
669.49 +
669.50 + private class R implements Result, PropertyChangeListener {
669.51 +
669.52 + private final ChangeSupport cs = new ChangeSupport(this);
669.53 +
669.54 + @SuppressWarnings("LeakingThisInConstructor")
669.55 + private R(final PythonProject2 project) {
669.56 + project.addPropertyChangeListener(WeakListeners.propertyChange(this, project));
669.57 + }
669.58 +
669.59 + @Override
669.60 + public String getSourceLevel() {
669.61 + return findSourceLevel(project);
669.62 + }
669.63 +
669.64 + @Override
669.65 + public void addChangeListener(ChangeListener listener) {
669.66 + this.cs.addChangeListener(listener);
669.67 + }
669.68 +
669.69 + @Override
669.70 + public void removeChangeListener(ChangeListener listener) {
669.71 + this.cs.removeChangeListener(listener);
669.72 + }
669.73 +
669.74 + @Override
669.75 + public void propertyChange(PropertyChangeEvent evt) {
669.76 +// final String name = evt.getPropertyName();
669.77 +// if (name == null ||
669.78 +// PLATFORM_ACTIVE.equals(name)) {
669.79 + this.cs.fireChange();
669.80 +// }
669.81 + }
669.82 +
669.83 + @Override
669.84 + public String toString() {
669.85 + final String sl = getSourceLevel();
669.86 + return sl == null ? "" : sl; //NOI18M
669.87 + }
669.88 +
669.89 + }
669.90 +
669.91 +}
670.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
670.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/PythonSources.java Sat Feb 28 17:25:32 2015 -0800
670.3 @@ -0,0 +1,45 @@
670.4 +/*
670.5 + * To change this license header, choose License Headers in Project Properties.
670.6 + * To change this template file, choose Tools | Templates
670.7 + * and open the template in the editor.
670.8 + */
670.9 +package org.netbeans.modules.python.project2;
670.10 +
670.11 +import javax.swing.event.ChangeListener;
670.12 +import org.netbeans.api.project.SourceGroup;
670.13 +import org.netbeans.api.project.Sources;
670.14 +import org.netbeans.spi.project.support.GenericSources;
670.15 +import org.openide.filesystems.FileObject;
670.16 +
670.17 +/**
670.18 + *
670.19 + * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
670.20 + */
670.21 +public class PythonSources implements Sources {
670.22 + private final PythonProject2 project;
670.23 + private SourceGroup[] roots;
670.24 +
670.25 +
670.26 + public PythonSources(PythonProject2 project) {
670.27 + this.project = project;
670.28 + }
670.29 +
670.30 + @Override
670.31 + public SourceGroup[] getSourceGroups(String type) {
670.32 + synchronized(this) {
670.33 + if(roots == null) {
670.34 + FileObject fo = project.getProjectDirectory();
670.35 + roots = new SourceGroup[]{GenericSources.group(project, fo, fo.getPath(), "Source Packages", null, null)};
670.36 + }
670.37 + }
670.38 + return roots;
670.39 + }
670.40 +
670.41 + @Override
670.42 + public void addChangeListener(ChangeListener listener) {
670.43 + }
670.44 +
670.45 + @Override
670.46 + public void removeChangeListener(ChangeListener listener) {
670.47 + }
670.48 +}
671.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
671.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/classpath/BootClassPathImplementation.java Sat Feb 28 17:25:32 2015 -0800
671.3 @@ -0,0 +1,127 @@
671.4 +/*
671.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
671.6 + *
671.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
671.8 + *
671.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
671.10 + * Other names may be trademarks of their respective owners.
671.11 + *
671.12 + * The contents of this file are subject to the terms of either the GNU
671.13 + * General Public License Version 2 only ("GPL") or the Common
671.14 + * Development and Distribution License("CDDL") (collectively, the
671.15 + * "License"). You may not use this file except in compliance with the
671.16 + * License. You can obtain a copy of the License at
671.17 + * http://www.netbeans.org/cddl-gplv2.html
671.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
671.19 + * specific language governing permissions and limitations under the
671.20 + * License. When distributing the software, include this License Header
671.21 + * Notice in each file and include the License file at
671.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
671.23 + * particular file as subject to the "Classpath" exception as provided
671.24 + * by Oracle in the GPL Version 2 section of the License file that
671.25 + * accompanied this code. If applicable, add the following below the
671.26 + * License Header, with the fields enclosed by brackets [] replaced by
671.27 + * your own identifying information:
671.28 + * "Portions Copyrighted [year] [name of copyright owner]"
671.29 + *
671.30 + * Contributor(s):
671.31 + *
671.32 + * The Original Software is NetBeans. The Initial Developer of the Original
671.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
671.34 + * Microsystems, Inc. All Rights Reserved.
671.35 + *
671.36 + * If you wish your version of this file to be governed by only the CDDL
671.37 + * or only the GPL Version 2, indicate your decision by adding
671.38 + * "[Contributor] elects to include this software in this distribution
671.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
671.40 + * single choice of license, a recipient has the option to distribute
671.41 + * your version of this file under either the CDDL, the GPL Version 2 or
671.42 + * to extend the choice of license to its licensees as provided above.
671.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
671.44 + * Version 2 license, then the option applies only if the new code is
671.45 + * made subject to such option by the copyright holder.
671.46 + */
671.47 +package org.netbeans.modules.python.project2.classpath;
671.48 +
671.49 +import java.beans.PropertyChangeEvent;
671.50 +import java.beans.PropertyChangeListener;
671.51 +import java.beans.PropertyChangeSupport;
671.52 +import java.net.URL;
671.53 +import java.util.List;
671.54 +import java.util.ArrayList;
671.55 +import java.util.Collections;
671.56 +import org.netbeans.modules.python.api.PythonPlatform;
671.57 +import org.netbeans.modules.python.api.PythonPlatformManager;
671.58 +import org.netbeans.modules.python.project2.PythonProject2;
671.59 +import org.netbeans.spi.java.classpath.ClassPathImplementation;
671.60 +import org.netbeans.spi.java.classpath.PathResourceImplementation;
671.61 +import org.netbeans.spi.java.classpath.support.ClassPathSupport;
671.62 +import org.openide.util.Parameters;
671.63 +
671.64 +final class BootClassPathImplementation implements ClassPathImplementation, PropertyChangeListener {
671.65 + private List<PathResourceImplementation> resourcesCache;
671.66 + private final PropertyChangeSupport support = new PropertyChangeSupport(this);
671.67 + private final PythonProject2 project;
671.68 +
671.69 + public BootClassPathImplementation (final PythonProject2 project) {
671.70 + assert project != null;
671.71 + this.project = project;
671.72 +// this.eval.addPropertyChangeListener(WeakListeners.propertyChange(this, this.eval));
671.73 + }
671.74 +
671.75 + @Override
671.76 + public synchronized List<PathResourceImplementation> getResources() {
671.77 + if (this.resourcesCache == null) {
671.78 + List<URL> urls = getUrls(project);
671.79 + List<PathResourceImplementation> result = new ArrayList<>(1);
671.80 + for (URL url : urls) {
671.81 + result.add(ClassPathSupport.createResource(url));
671.82 + }
671.83 + resourcesCache = Collections.unmodifiableList(result);
671.84 + }
671.85 + return this.resourcesCache;
671.86 + }
671.87 +
671.88 + @Override
671.89 + public void addPropertyChangeListener(PropertyChangeListener listener) {
671.90 + Parameters.notNull("listener", listener);
671.91 + this.support.addPropertyChangeListener (listener);
671.92 + }
671.93 +
671.94 + @Override
671.95 + public void removePropertyChangeListener(PropertyChangeListener listener) {
671.96 + Parameters.notNull("listener", listener);
671.97 + this.support.removePropertyChangeListener (listener);
671.98 + }
671.99 +
671.100 + @Override
671.101 + public void propertyChange(final PropertyChangeEvent evt) {
671.102 +// if (evt.getSource() == this.eval &&
671.103 +// (evt.getPropertyName() == null || evt.getPropertyName().equals(PythonProjectProperties.ACTIVE_PLATFORM))) {
671.104 +// //Active platform was changed
671.105 +// RequestProcessor.getDefault().post(new Runnable() {
671.106 +// @Override
671.107 +// public void run() {
671.108 +// resetCache ();
671.109 +// }
671.110 +// }) ;
671.111 +// }
671.112 + }
671.113 +
671.114 + private void resetCache () {
671.115 + synchronized (this) {
671.116 + resourcesCache = null;
671.117 + }
671.118 + support.firePropertyChange(PROP_RESOURCES, null, null);
671.119 + }
671.120 +
671.121 + private List<URL> getUrls(PythonProject2 project) {
671.122 + PythonPlatform activePlatform = project.getActivePlatform();
671.123 + if (activePlatform == null) {
671.124 + final PythonPlatformManager manager = PythonPlatformManager.getInstance();
671.125 + final String platformName = manager.getDefaultPlatform();
671.126 + activePlatform = manager.getPlatform(platformName);
671.127 + }
671.128 + return activePlatform.getUrls();
671.129 + }
671.130 +}
672.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
672.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/classpath/ClassPathProviderImpl.java Sat Feb 28 17:25:32 2015 -0800
672.3 @@ -0,0 +1,205 @@
672.4 +/*
672.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
672.6 + *
672.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
672.8 + *
672.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
672.10 + * Other names may be trademarks of their respective owners.
672.11 + *
672.12 + * The contents of this file are subject to the terms of either the GNU
672.13 + * General Public License Version 2 only ("GPL") or the Common
672.14 + * Development and Distribution License("CDDL") (collectively, the
672.15 + * "License"). You may not use this file except in compliance with the
672.16 + * License. You can obtain a copy of the License at
672.17 + * http://www.netbeans.org/cddl-gplv2.html
672.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
672.19 + * specific language governing permissions and limitations under the
672.20 + * License. When distributing the software, include this License Header
672.21 + * Notice in each file and include the License file at
672.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
672.23 + * particular file as subject to the "Classpath" exception as provided
672.24 + * by Oracle in the GPL Version 2 section of the License file that
672.25 + * accompanied this code. If applicable, add the following below the
672.26 + * License Header, with the fields enclosed by brackets [] replaced by
672.27 + * your own identifying information:
672.28 + * "Portions Copyrighted [year] [name of copyright owner]"
672.29 + *
672.30 + * Contributor(s):
672.31 + *
672.32 + * The Original Software is NetBeans. The Initial Developer of the Original
672.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
672.34 + * Microsystems, Inc. All Rights Reserved.
672.35 + *
672.36 + * If you wish your version of this file to be governed by only the CDDL
672.37 + * or only the GPL Version 2, indicate your decision by adding
672.38 + * "[Contributor] elects to include this software in this distribution
672.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
672.40 + * single choice of license, a recipient has the option to distribute
672.41 + * your version of this file under either the CDDL, the GPL Version 2 or
672.42 + * to extend the choice of license to its licensees as provided above.
672.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
672.44 + * Version 2 license, then the option applies only if the new code is
672.45 + * made subject to such option by the copyright holder.
672.46 + */
672.47 +package org.netbeans.modules.python.project2.classpath;
672.48 +
672.49 +import java.util.HashMap;
672.50 +import java.util.Map;
672.51 +import org.netbeans.api.java.classpath.ClassPath;
672.52 +import org.netbeans.api.project.ProjectUtils;
672.53 +import org.netbeans.api.project.SourceGroup;
672.54 +import org.netbeans.api.project.Sources;
672.55 +import org.netbeans.modules.python.project2.PythonProject2;
672.56 +import org.netbeans.spi.java.classpath.ClassPathFactory;
672.57 +import org.netbeans.spi.java.classpath.ClassPathImplementation;
672.58 +import org.netbeans.spi.java.classpath.ClassPathProvider;
672.59 +import org.netbeans.spi.java.classpath.support.ClassPathSupport;
672.60 +import org.openide.filesystems.FileObject;
672.61 +import org.openide.filesystems.FileUtil;
672.62 +import org.openide.util.Pair;
672.63 +
672.64 +/**
672.65 + * Defines various paths for the Python Project.
672.66 + * Based on the Ruby project, in turn based on the J2SE project.
672.67 + * Greatly simplified at the moment since Python projects don't have a Sources object,
672.68 + * and there's no separate source/test folders.
672.69 + * @author Tor Norbye
672.70 + * @author Tomas Zezula
672.71 + */
672.72 +public final class ClassPathProviderImpl implements ClassPathProvider {
672.73 + private final PythonProject2 project;
672.74 + private final Sources sources;
672.75 + private final Map<Pair<String,Integer>,ClassPath> cache = new HashMap<>();
672.76 +
672.77 + public ClassPathProviderImpl(final PythonProject2 project, Sources sources) {
672.78 + assert project != null;
672.79 + this.project = project;
672.80 + this.sources = sources;
672.81 + assert this.sources != null;
672.82 + }
672.83 +
672.84 + private static final int MAX_TYPES = 3;
672.85 + /**
672.86 + * Find what a given file represents.
672.87 + * @param file a file in the project
672.88 + * @return one of: <dl>
672.89 + * <dt>0</dt> <dd>normal source</dd>
672.90 + * <dt>1</dt> <dd>test source</dd>
672.91 + * <dt>2</dt> <dd>the project root</dd>
672.92 + * <dt>-1</dt> <dd>something else</dd>
672.93 + * </dl>
672.94 + */
672.95 + private int getType(FileObject file) {
672.96 + if (file == project.getProjectDirectory()) {
672.97 + return 2;
672.98 + }
672.99 + for (SourceGroup sourceGroup : sources.getSourceGroups(PythonProject2.SOURCES_TYPE_PYTHON)) {
672.100 + FileObject root = sourceGroup.getRootFolder();
672.101 + if (root.equals(file) || FileUtil.isParentOf(root, file)) {
672.102 + return 0;
672.103 + }
672.104 + }
672.105 + return -1;
672.106 + }
672.107 +
672.108 + private synchronized ClassPath getSourcepath(FileObject file) {
672.109 + int type = getType(file);
672.110 + return this.getSourcepath(type);
672.111 + }
672.112 +
672.113 + private ClassPath getSourcepath(int type) {
672.114 + if (type < 0 || type > MAX_TYPES) {
672.115 + return null;
672.116 + }
672.117 + final Pair<String,Integer> key = Pair.of(ClassPath.SOURCE, type);
672.118 + ClassPath cp = cache.get(key);
672.119 + if (cp == null) {
672.120 + switch (type) {
672.121 + case 0:
672.122 + cp = ClassPathFactory.createClassPath(new SourcePathImplementation(sources));
672.123 + break;
672.124 +// case 1:
672.125 +// cp = ClassPathFactory.createClassPath(new SourcePathImplementation(tests));
672.126 +// break;
672.127 + case 2:
672.128 + // Classpath for the "whole project" - for now just use the sources
672.129 + // Used from the tasklist for example.
672.130 + cp = ClassPathFactory.createClassPath(new SourcePathImplementation(sources));
672.131 + break;
672.132 +
672.133 + default:
672.134 + throw new UnsupportedOperationException("Only sources are available in the Python project at this point");
672.135 + }
672.136 + cache.put (key,cp);
672.137 + }
672.138 + return cp;
672.139 + }
672.140 +
672.141 + private synchronized ClassPath getBootClassPath() {
672.142 + final Pair<String,Integer> key = Pair.of(ClassPath.BOOT, 0);
672.143 + ClassPath cp = cache.get(key);
672.144 + if (cp == null) {
672.145 + //todo: For now merge compile and platform class paths
672.146 + //under parsing api they should be separated
672.147 + final ClassPathImplementation boot = new BootClassPathImplementation(project);
672.148 + final ClassPathImplementation compile = new CompilePathImplementation(project);
672.149 + cp = ClassPathFactory.createClassPath(ClassPathSupport.createProxyClassPathImplementation(boot,compile));
672.150 + cache.put (key,cp);
672.151 + }
672.152 + return cp;
672.153 + }
672.154 +
672.155 +// private synchronized ClassPath getCompileClassPath() {
672.156 +// final Pair<String,Integer> key = Pair.of(ClassPath.COMPILE, 0);
672.157 +// ClassPath cp = cache.get(key);
672.158 +// if (cp == null) {
672.159 +// cp = ClassPathFactory.createClassPath(new CompilePathImplementation(this.project));
672.160 +// cache.put (key,cp);
672.161 +// }
672.162 +// return cp;
672.163 +// }
672.164 +
672.165 + @Override
672.166 + public ClassPath findClassPath(FileObject file, String type) {
672.167 + if (type.equals(ClassPath.SOURCE)) {
672.168 + return getSourcepath(file);
672.169 + } else if (type.equals(ClassPath.BOOT)) {
672.170 + return getBootClassPath();
672.171 + } else if (type.equals(ClassPath.COMPILE)) {
672.172 + // Bogus
672.173 + return getBootClassPath();
672.174 + } else {
672.175 + return null;
672.176 + }
672.177 + }
672.178 +
672.179 + /**
672.180 + * Returns array of all classpaths of the given type in the project.
672.181 + * The result is used for example for GlobalPathRegistry registrations.
672.182 + */
672.183 + public ClassPath[] getProjectClassPaths(String type) {
672.184 + if (ClassPath.BOOT.equals(type)) {
672.185 + return new ClassPath[]{getBootClassPath()};
672.186 + }
672.187 + if (ClassPath.SOURCE.equals(type)) {
672.188 + ClassPath[] l = new ClassPath[1];
672.189 + l[0] = getSourcepath(0);
672.190 + return l;
672.191 + }
672.192 + return null;
672.193 + }
672.194 +
672.195 + /**
672.196 + * Returns the given type of the classpath for the project sources
672.197 + * (i.e., excluding tests roots). Valid types are BOOT, SOURCE and COMPILE.
672.198 + */
672.199 + public ClassPath getProjectSourcesClassPath(String type) {
672.200 + if (ClassPath.BOOT.equals(type)) {
672.201 + return getBootClassPath();
672.202 + }
672.203 + if (ClassPath.SOURCE.equals(type)) {
672.204 + return getSourcepath(0);
672.205 + }
672.206 + return null;
672.207 + }
672.208 +}
673.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
673.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/classpath/CompilePathImplementation.java Sat Feb 28 17:25:32 2015 -0800
673.3 @@ -0,0 +1,147 @@
673.4 +/*
673.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
673.6 + *
673.7 + * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
673.8 + *
673.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
673.10 + * Other names may be trademarks of their respective owners.
673.11 + *
673.12 + * The contents of this file are subject to the terms of either the GNU
673.13 + * General Public License Version 2 only ("GPL") or the Common
673.14 + * Development and Distribution License("CDDL") (collectively, the
673.15 + * "License"). You may not use this file except in compliance with the
673.16 + * License. You can obtain a copy of the License at
673.17 + * http://www.netbeans.org/cddl-gplv2.html
673.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
673.19 + * specific language governing permissions and limitations under the
673.20 + * License. When distributing the software, include this License Header
673.21 + * Notice in each file and include the License file at
673.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
673.23 + * particular file as subject to the "Classpath" exception as provided
673.24 + * by Oracle in the GPL Version 2 section of the License file that
673.25 + * accompanied this code. If applicable, add the following below the
673.26 + * License Header, with the fields enclosed by brackets [] replaced by
673.27 + * your own identifying information:
673.28 + * "Portions Copyrighted [year] [name of copyright owner]"
673.29 + *
673.30 + * If you wish your version of this file to be governed by only the CDDL
673.31 + * or only the GPL Version 2, indicate your decision by adding
673.32 + * "[Contributor] elects to include this software in this distribution
673.33 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
673.34 + * single choice of license, a recipient has the option to distribute
673.35 + * your version of this file under either the CDDL, the GPL Version 2 or
673.36 + * to extend the choice of license to its licensees as provided above.
673.37 + * However, if you add GPL Version 2 code and therefore, elected the GPL
673.38 + * Version 2 license, then the option applies only if the new code is
673.39 + * made subject to such option by the copyright holder.
673.40 + *
673.41 + * Contributor(s):
673.42 + *
673.43 + * Portions Copyrighted 2008 Sun Microsystems, Inc.
673.44 + */
673.45 +package org.netbeans.modules.python.project2.classpath;
673.46 +
673.47 +import java.beans.PropertyChangeEvent;
673.48 +import java.beans.PropertyChangeListener;
673.49 +import java.beans.PropertyChangeSupport;
673.50 +import java.io.File;
673.51 +import java.util.ArrayList;
673.52 +import java.util.Collections;
673.53 +import java.util.List;
673.54 +import java.util.concurrent.atomic.AtomicBoolean;
673.55 +import org.netbeans.api.project.ProjectManager;
673.56 +import org.netbeans.modules.python.project2.PythonProject2;
673.57 +import org.netbeans.spi.java.classpath.ClassPathImplementation;
673.58 +import org.netbeans.spi.java.classpath.PathResourceImplementation;
673.59 +import org.openide.filesystems.FileObject;
673.60 +import org.openide.filesystems.FileUtil;
673.61 +import org.openide.util.Parameters;
673.62 +
673.63 +/**
673.64 + *
673.65 + * @author Tomas Zezula
673.66 + */
673.67 +public final class CompilePathImplementation implements ClassPathImplementation, PropertyChangeListener, Runnable {
673.68 +
673.69 + private final PropertyChangeSupport support = new PropertyChangeSupport(this);
673.70 + private final File projectFolder;
673.71 + private List<PathResourceImplementation> resources;
673.72 + private AtomicBoolean dirty = new AtomicBoolean();
673.73 +
673.74 + CompilePathImplementation(final PythonProject2 project) {
673.75 + assert project != null;
673.76 + FileObject fo = project.getProjectDirectory();;
673.77 + assert fo != null;
673.78 + this.projectFolder = FileUtil.toFile(fo);
673.79 + assert projectFolder != null;
673.80 + this.resources = this.getPath();
673.81 + }
673.82 +
673.83 + @Override
673.84 + public synchronized List<PathResourceImplementation> getResources() {
673.85 + assert this.resources != null;
673.86 + return this.resources;
673.87 + }
673.88 +
673.89 + @Override
673.90 + public void addPropertyChangeListener(final PropertyChangeListener listener) {
673.91 + Parameters.notNull("listener", listener);
673.92 + support.addPropertyChangeListener(listener);
673.93 + }
673.94 +
673.95 + @Override
673.96 + public void removePropertyChangeListener(PropertyChangeListener listener) {
673.97 + Parameters.notNull("listener", listener);
673.98 + support.removePropertyChangeListener(listener);
673.99 + }
673.100 +
673.101 + @Override
673.102 + public void propertyChange(final PropertyChangeEvent evt) {
673.103 + String prop = evt.getPropertyName();
673.104 +// if (prop != null && !PythonProjectProperties.PYTHON_LIB_PATH.equals(evt.getPropertyName())) {
673.105 +// // Not interesting to us.
673.106 +// return;
673.107 +// }
673.108 + // Coalesce changes; can come in fast after huge CP changes (#47910):
673.109 + if (!dirty.getAndSet(true)) {
673.110 + ProjectManager.mutex().postReadRequest(this);
673.111 + }
673.112 + }
673.113 +
673.114 + @Override
673.115 + public void run() {
673.116 + dirty.set(false);
673.117 + List<PathResourceImplementation> newRoots = getPath();
673.118 + boolean fire = false;
673.119 + synchronized (this) {
673.120 + if (!this.resources.equals(newRoots)) {
673.121 + this.resources = newRoots;
673.122 + fire = true;
673.123 + }
673.124 + }
673.125 + if (fire) {
673.126 + support.firePropertyChange(PROP_RESOURCES, null, null);
673.127 + }
673.128 + }
673.129 +
673.130 + private List<PathResourceImplementation> getPath() {
673.131 + List<PathResourceImplementation> result = new ArrayList<>();
673.132 +
673.133 +// String prop = evaluator.getProperty(PythonProjectProperties.PYTHON_LIB_PATH);
673.134 +// if (prop != null) {
673.135 +// //todo: Use PropertyUtil
673.136 +// final StringTokenizer tokenizer = new StringTokenizer(prop, "|"); //NOI18N
673.137 +// while (tokenizer.hasMoreTokens()) {
673.138 +// String piece = tokenizer.nextToken();
673.139 +// File f = PropertyUtils.resolveFile(this.projectFolder, piece);
673.140 +// URL entry = FileUtil.urlForArchiveOrDir(f);
673.141 +// if (entry != null) {
673.142 +// result.add(ClassPathSupport.createResource(entry));
673.143 +// } else {
673.144 +// Logger.getLogger(CompilePathImplementation.class.getName()).warning(f + " does not look like a valid archive file");
673.145 +// }
673.146 +// }
673.147 +// }
673.148 + return Collections.unmodifiableList(result);
673.149 + }
673.150 +}
674.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
674.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/classpath/SourcePathImplementation.java Sat Feb 28 17:25:32 2015 -0800
674.3 @@ -0,0 +1,109 @@
674.4 +/*
674.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
674.6 + *
674.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
674.8 + *
674.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
674.10 + * Other names may be trademarks of their respective owners.
674.11 + *
674.12 + * The contents of this file are subject to the terms of either the GNU
674.13 + * General Public License Version 2 only ("GPL") or the Common
674.14 + * Development and Distribution License("CDDL") (collectively, the
674.15 + * "License"). You may not use this file except in compliance with the
674.16 + * License. You can obtain a copy of the License at
674.17 + * http://www.netbeans.org/cddl-gplv2.html
674.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
674.19 + * specific language governing permissions and limitations under the
674.20 + * License. When distributing the software, include this License Header
674.21 + * Notice in each file and include the License file at
674.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
674.23 + * particular file as subject to the "Classpath" exception as provided
674.24 + * by Oracle in the GPL Version 2 section of the License file that
674.25 + * accompanied this code. If applicable, add the following below the
674.26 + * License Header, with the fields enclosed by brackets [] replaced by
674.27 + * your own identifying information:
674.28 + * "Portions Copyrighted [year] [name of copyright owner]"
674.29 + *
674.30 + * Contributor(s):
674.31 + *
674.32 + * The Original Software is NetBeans. The Initial Developer of the Original
674.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
674.34 + * Microsystems, Inc. All Rights Reserved.
674.35 + *
674.36 + * If you wish your version of this file to be governed by only the CDDL
674.37 + * or only the GPL Version 2, indicate your decision by adding
674.38 + * "[Contributor] elects to include this software in this distribution
674.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
674.40 + * single choice of license, a recipient has the option to distribute
674.41 + * your version of this file under either the CDDL, the GPL Version 2 or
674.42 + * to extend the choice of license to its licensees as provided above.
674.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
674.44 + * Version 2 license, then the option applies only if the new code is
674.45 + * made subject to such option by the copyright holder.
674.46 + */
674.47 +package org.netbeans.modules.python.project2.classpath;
674.48 +
674.49 +import java.beans.PropertyChangeEvent;
674.50 +import java.util.List;
674.51 +import java.util.ArrayList;
674.52 +import java.util.Collections;
674.53 +import java.beans.PropertyChangeListener;
674.54 +import java.beans.PropertyChangeSupport;
674.55 +import org.netbeans.api.project.SourceGroup;
674.56 +import org.netbeans.api.project.Sources;
674.57 +import org.netbeans.modules.python.project2.PythonProject2;
674.58 +import org.netbeans.spi.java.classpath.ClassPathImplementation;
674.59 +import org.netbeans.spi.java.classpath.PathResourceImplementation;
674.60 +import org.netbeans.spi.java.classpath.support.ClassPathSupport;
674.61 +
674.62 +/**
674.63 + * Source class path implementation
674.64 + * @author Tor Norbye
674.65 + * @author Tomas Zezula
674.66 + */
674.67 +final class SourcePathImplementation implements ClassPathImplementation, PropertyChangeListener {
674.68 + private final PropertyChangeSupport support = new PropertyChangeSupport(this);
674.69 + private List<PathResourceImplementation> resources;
674.70 + private final Sources src;
674.71 +
674.72 + public SourcePathImplementation(Sources sources) {
674.73 + assert sources != null;
674.74 + this.src = sources;
674.75 +// this.src.addPropertyChangeListener(WeakListeners.propertyChange(this, this.src));
674.76 + }
674.77 +
674.78 + @Override
674.79 + public List<PathResourceImplementation> getResources() {
674.80 + synchronized (this) {
674.81 + if (this.resources != null) {
674.82 + return this.resources;
674.83 + }
674.84 + }
674.85 + final SourceGroup[] urls = this.src.getSourceGroups(PythonProject2.SOURCES_TYPE_PYTHON);
674.86 + synchronized (this) {
674.87 + if (this.resources == null) {
674.88 + List<PathResourceImplementation> result = new ArrayList<>(urls.length);
674.89 + for (SourceGroup root : urls) {
674.90 + result.add(ClassPathSupport.createResource(root.getRootFolder().toURL()));
674.91 + }
674.92 + this.resources = Collections.unmodifiableList(result);
674.93 + }
674.94 + return this.resources;
674.95 + }
674.96 + }
674.97 +
674.98 + @Override
674.99 + public void addPropertyChangeListener(PropertyChangeListener listener) {
674.100 + support.addPropertyChangeListener (listener);
674.101 + }
674.102 +
674.103 + @Override
674.104 + public void removePropertyChangeListener(PropertyChangeListener listener) {
674.105 + support.removePropertyChangeListener (listener);
674.106 + }
674.107 +
674.108 + @Override
674.109 + public synchronized void propertyChange(PropertyChangeEvent evt) {
674.110 + this.resources = null;
674.111 + }
674.112 +}
675.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
675.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/layer.xml Sat Feb 28 17:25:32 2015 -0800
675.3 @@ -0,0 +1,39 @@
675.4 +<?xml version="1.0" encoding="UTF-8"?>
675.5 +<!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 1.2//EN" "http://www.netbeans.org/dtds/filesystem-1_2.dtd">
675.6 +<filesystem>
675.7 + <folder name="Projects">
675.8 + <folder name="Actions"/>
675.9 +
675.10 + <folder name="org-netbeans-modules-python-project2">
675.11 + <folder name="Nodes">
675.12 + <file name="org-netbeans-modules-python-project2-ui-SourceNodeFactory.instance">
675.13 + <attr name="position" intvalue="200"/>
675.14 + </file>
675.15 + </folder>
675.16 +
675.17 + <folder name="Customizer">
675.18 + <file name="PythonPath.instance">
675.19 + <attr name="instanceCreate" methodvalue="org.netbeans.modules.python.project2.ui.customizer.CompositePanelProviderImpl.createPythonPath"/>
675.20 + <attr name="position" intvalue="200"/>
675.21 + </file>
675.22 + <file name="Run.instance">
675.23 + <attr name="instanceCreate" methodvalue="org.netbeans.modules.python.project2.ui.customizer.CompositePanelProviderImpl.createRunConfig"/>
675.24 + <attr name="position" intvalue="300"/>
675.25 + </file>
675.26 + <file name="Formatting.instance">
675.27 + <attr name="instanceOf" stringvalue="org.netbeans.spi.project.ui.support.ProjectCustomizer$CompositeCategoryProvider"/>
675.28 + <attr name="instanceCreate" methodvalue="org.netbeans.modules.options.indentation.FormattingCustomizerPanel.createCategoryProvider"/>
675.29 + <attr name="allowedMimeTypes" stringvalue="text/x-python"/>
675.30 + <attr name="position" intvalue="1000"/>
675.31 + </file>
675.32 + </folder>
675.33 + </folder>
675.34 + </folder>
675.35 + <folder name="Templates">
675.36 + <folder name="Project">
675.37 + <folder name="Python">
675.38 + <attr name="position" intvalue="1412"/>
675.39 + </folder>
675.40 + </folder>
675.41 + </folder>
675.42 +</filesystem>
676.1 Binary file python.project2/src/org/netbeans/modules/python/project2/resources/brokenProjectBadge.gif has changed
677.1 Binary file python.project2/src/org/netbeans/modules/python/project2/resources/package.gif has changed
678.1 Binary file python.project2/src/org/netbeans/modules/python/project2/resources/packageBadge.gif has changed
679.1 Binary file python.project2/src/org/netbeans/modules/python/project2/resources/packageEmpty.gif has changed
680.1 Binary file python.project2/src/org/netbeans/modules/python/project2/resources/packagePrivate.gif has changed
681.1 Binary file python.project2/src/org/netbeans/modules/python/project2/resources/packagePublic.gif has changed
682.1 Binary file python.project2/src/org/netbeans/modules/python/project2/resources/py_25_16.png has changed
683.1 Binary file python.project2/src/org/netbeans/modules/python/project2/resources/sourceBadge.gif has changed
684.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
684.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/templates/Bundle.properties Sat Feb 28 17:25:32 2015 -0800
684.3 @@ -0,0 +1,57 @@
684.4 +# Python project wizards
684.5 +LBL_IteratorName={0} of {1}
684.6 +LBL_NewPythonProjectWizardIterator_WizardProgress_CreatingProject=Creating new project
684.7 +LBL_NewPythonProjectWizardIterator_WizardProgress_PreparingToOpen=Preparing new project to be opened
684.8 +TXT_PythonProject=Python Project
684.9 +TXT_ExistingPythonProject=Python Project with Existing Sources
684.10 +LBL_ProjectNameLocation=Name and Location
684.11 +LBL_ProjectSources=Existing Sources
684.12 +
684.13 +#PanelOptionsVisual
684.14 +TXT_MainFileName={0}.py
684.15 +ERROR_IllegalMainFileName=Illegal main file name.
684.16 +LBL_setAsMainCheckBox=Set as &Main Project
684.17 +ACSD_setAsMainCheckBox=N/A
684.18 +ACSN_setAsMainCheckBox=N/A
684.19 +ACSN_createMainCheckBox=Create Main Class
684.20 +ACSD_createMainCheckBox=Select checkbox to create main class in project.
684.21 +LBL_createMainCheckBox=&Create Main File
684.22 +ASCN_mainClassTextFiled=N/A
684.23 +ASCD_mainClassTextFiled=N/A
684.24 +ACSN_PanelOptionsVisual=N/A
684.25 +ACSD_PanelOptionsVisual=N/A
684.26 +
684.27 +#PanelConfigureProjectVisual
684.28 +TXT_NameAndLoc=Name and Location
684.29 +TXT_NewPythonApp=New Python Application
684.30 +ACSD_NewPythonApp=New Python Application
684.31 +ACSN_locationContainer=N/A
684.32 +ACSD_locationContainer=N/A
684.33 +ACSN_optionsContainer=N/A
684.34 +ACSD_optionsContainer=N/A
684.35 +TXT_PythonPlatform=&Python Platform:
684.36 +ERROR_IllegalPlatform=Wrong Python Platform
684.37 +TXT_ManagePlatfroms=&Manage...
684.38 +ACSD_ExistingPythonProject=N/A
684.39 +
684.40 +#PanelConfigureSourcesVisual
684.41 +LBL_SelectSources=Select Source Folder
684.42 +LBL_SelectTests=Select Test Folder
684.43 +
684.44 +ExistingPythonProjectPanelVisual.projectName.text=Project &Name:
684.45 +ExistingPythonProjectPanelVisual.projectFolder.text=Project &Folder:
684.46 +ExistingPythonProjectPanelVisual.browse.text=Br&owse
684.47 +LBL_SelectProjectFolder=Select project folder
684.48 +
684.49 +#Errors
684.50 +ERR_WrongName=Project Name is not a valid folder name.
684.51 +ERR_WrongProjectFolder=Project Folder is not a valid path.
684.52 +ERR_ReadOnlyProjectFolder=Project Folder cannot be created.
684.53 +ERR_AlreadyAnProject="There is already a NetBeans project in the project folder."
684.54 +PanelConfigureSourcesVisual.jLabel1.text=Specify the folders containing sources and tests.
684.55 +PanelConfigureSourcesVisual.jLabel2.text=&Source Root Folders
684.56 +PanelConfigureSourcesVisual.jLabel3.text=&Test Root Folders
684.57 +PanelConfigureSourcesVisual.addSource.text=&Add Folder...
684.58 +PanelConfigureSourcesVisual.removeSource.text=&Remove
684.59 +PanelConfigureSourcesVisual.addTest.text=Add F&older...
684.60 +PanelConfigureSourcesVisual.removeTest.text=Re&move
685.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
685.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/templates/EmptyPythonProjectDescription.html Sat Feb 28 17:25:32 2015 -0800
685.3 @@ -0,0 +1,12 @@
685.4 +<!--
685.5 +To change this template, choose Tools | Templates
685.6 +and open the template in the editor.
685.7 +-->
685.8 +<html>
685.9 + <head>
685.10 + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
685.11 + </head>
685.12 + <body>
685.13 + New Empty Python Project using setuptools
685.14 + </body>
685.15 +</html>
686.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
686.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/templates/EmptyPythonProjectPanelVisual.form Sat Feb 28 17:25:32 2015 -0800
686.3 @@ -0,0 +1,112 @@
686.4 +<?xml version="1.0" encoding="UTF-8" ?>
686.5 +
686.6 +<Form version="1.3" maxVersion="1.3" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
686.7 + <AuxValues>
686.8 + <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
686.9 + <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
686.10 + <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
686.11 + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
686.12 + <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
686.13 + <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
686.14 + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
686.15 + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
686.16 + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
686.17 + </AuxValues>
686.18 +
686.19 + <Layout>
686.20 + <DimensionLayout dim="0">
686.21 + <Group type="103" groupAlignment="0" attributes="0">
686.22 + <Group type="102" attributes="0">
686.23 + <Group type="103" groupAlignment="0" attributes="0">
686.24 + <Component id="projectLocationLabel" min="-2" max="-2" attributes="0"/>
686.25 + <Component id="createdFolderLabel" alignment="0" min="-2" max="-2" attributes="0"/>
686.26 + <Component id="projectNameLabel" min="-2" max="-2" attributes="0"/>
686.27 + </Group>
686.28 + <EmptySpace max="-2" attributes="0"/>
686.29 + <Group type="103" groupAlignment="0" attributes="0">
686.30 + <Group type="102" attributes="0">
686.31 + <Component id="projectLocationTextField" pref="238" max="32767" attributes="0"/>
686.32 + <EmptySpace max="-2" attributes="0"/>
686.33 + <Component id="browseButton" min="-2" max="-2" attributes="0"/>
686.34 + </Group>
686.35 + <Component id="projectNameTextField" pref="343" max="32767" attributes="0"/>
686.36 + <Component id="createdFolderTextField" alignment="0" pref="343" max="32767" attributes="0"/>
686.37 + </Group>
686.38 + </Group>
686.39 + </Group>
686.40 + </DimensionLayout>
686.41 + <DimensionLayout dim="1">
686.42 + <Group type="103" groupAlignment="0" attributes="0">
686.43 + <Group type="102" attributes="0">
686.44 + <EmptySpace min="-2" pref="20" max="-2" attributes="0"/>
686.45 + <Group type="103" groupAlignment="3" attributes="0">
686.46 + <Component id="projectNameLabel" alignment="3" min="-2" max="-2" attributes="0"/>
686.47 + <Component id="projectNameTextField" alignment="3" min="-2" max="-2" attributes="0"/>
686.48 + </Group>
686.49 + <EmptySpace min="-2" pref="8" max="-2" attributes="0"/>
686.50 + <Group type="103" groupAlignment="3" attributes="0">
686.51 + <Component id="projectLocationLabel" alignment="3" min="-2" max="-2" attributes="0"/>
686.52 + <Component id="browseButton" alignment="3" min="-2" max="-2" attributes="0"/>
686.53 + <Component id="projectLocationTextField" alignment="3" min="-2" max="-2" attributes="0"/>
686.54 + </Group>
686.55 + <EmptySpace max="-2" attributes="0"/>
686.56 + <Group type="103" groupAlignment="3" attributes="0">
686.57 + <Component id="createdFolderLabel" alignment="3" min="-2" max="-2" attributes="0"/>
686.58 + <Component id="createdFolderTextField" alignment="3" min="-2" max="-2" attributes="0"/>
686.59 + </Group>
686.60 + <EmptySpace pref="31" max="32767" attributes="0"/>
686.61 + </Group>
686.62 + </Group>
686.63 + </DimensionLayout>
686.64 + </Layout>
686.65 + <SubComponents>
686.66 + <Component class="javax.swing.JLabel" name="projectNameLabel">
686.67 + <Properties>
686.68 + <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
686.69 + <ComponentRef name="projectNameTextField"/>
686.70 + </Property>
686.71 + <Property name="text" type="java.lang.String" value="Project &Name:"/>
686.72 + </Properties>
686.73 + <AuxValues>
686.74 + <AuxValue name="generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
686.75 + </AuxValues>
686.76 + </Component>
686.77 + <Component class="javax.swing.JTextField" name="projectNameTextField">
686.78 + </Component>
686.79 + <Component class="javax.swing.JLabel" name="projectLocationLabel">
686.80 + <Properties>
686.81 + <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
686.82 + <ComponentRef name="projectLocationTextField"/>
686.83 + </Property>
686.84 + <Property name="text" type="java.lang.String" value="Project &Location:"/>
686.85 + </Properties>
686.86 + <AuxValues>
686.87 + <AuxValue name="generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
686.88 + </AuxValues>
686.89 + </Component>
686.90 + <Component class="javax.swing.JTextField" name="projectLocationTextField">
686.91 + </Component>
686.92 + <Component class="javax.swing.JButton" name="browseButton">
686.93 + <Properties>
686.94 + <Property name="text" type="java.lang.String" value="Br&owse..."/>
686.95 + <Property name="actionCommand" type="java.lang.String" value="BROWSE"/>
686.96 + </Properties>
686.97 + <Events>
686.98 + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="browseButtonActionPerformed"/>
686.99 + </Events>
686.100 + </Component>
686.101 + <Component class="javax.swing.JLabel" name="createdFolderLabel">
686.102 + <Properties>
686.103 + <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
686.104 + <ComponentRef name="createdFolderTextField"/>
686.105 + </Property>
686.106 + <Property name="text" type="java.lang.String" value="Project &Folder:"/>
686.107 + </Properties>
686.108 + </Component>
686.109 + <Component class="javax.swing.JTextField" name="createdFolderTextField">
686.110 + <Properties>
686.111 + <Property name="editable" type="boolean" value="false"/>
686.112 + </Properties>
686.113 + </Component>
686.114 + </SubComponents>
686.115 +</Form>
687.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
687.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/templates/EmptyPythonProjectPanelVisual.java Sat Feb 28 17:25:32 2015 -0800
687.3 @@ -0,0 +1,264 @@
687.4 +/*
687.5 + * To change this template, choose Tools | Templates
687.6 + * and open the template in the editor.
687.7 + */
687.8 +
687.9 +package org.netbeans.modules.python.project2.templates;
687.10 +
687.11 +import java.io.File;
687.12 +import javax.swing.JFileChooser;
687.13 +import javax.swing.event.DocumentEvent;
687.14 +import javax.swing.event.DocumentListener;
687.15 +import javax.swing.text.Document;
687.16 +import org.netbeans.spi.project.ui.support.ProjectChooser;
687.17 +import org.openide.WizardDescriptor;
687.18 +import org.openide.WizardValidationException;
687.19 +import org.openide.filesystems.FileUtil;
687.20 +
687.21 +public final class EmptyPythonProjectPanelVisual extends SettingsPanel implements DocumentListener {
687.22 +
687.23 +
687.24 + private final PanelConfigureProject panel;
687.25 +
687.26 + public EmptyPythonProjectPanelVisual(PanelConfigureProject panel) {
687.27 + initComponents();
687.28 + this.panel = panel;
687.29 + // Register listener on the textFields to make the automatic updates
687.30 + projectNameTextField.getDocument().addDocumentListener(this);
687.31 + projectLocationTextField.getDocument().addDocumentListener(this);
687.32 + }
687.33 +
687.34 + public String getProjectName() {
687.35 + return this.projectNameTextField.getText();
687.36 + }
687.37 +
687.38 + /** This method is called from within the constructor to
687.39 + * initialize the form.
687.40 + * WARNING: Do NOT modify this code. The content of this method is
687.41 + * always regenerated by the Form Editor.
687.42 + */
687.43 + // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
687.44 + private void initComponents() {
687.45 +
687.46 + projectNameLabel = new javax.swing.JLabel();
687.47 + projectNameTextField = new javax.swing.JTextField();
687.48 + projectLocationLabel = new javax.swing.JLabel();
687.49 + projectLocationTextField = new javax.swing.JTextField();
687.50 + browseButton = new javax.swing.JButton();
687.51 + createdFolderLabel = new javax.swing.JLabel();
687.52 + createdFolderTextField = new javax.swing.JTextField();
687.53 +
687.54 + projectNameLabel.setLabelFor(projectNameTextField);
687.55 + org.openide.awt.Mnemonics.setLocalizedText(projectNameLabel, "Project &Name:");
687.56 +
687.57 + projectLocationLabel.setLabelFor(projectLocationTextField);
687.58 + org.openide.awt.Mnemonics.setLocalizedText(projectLocationLabel, "Project &Location:");
687.59 +
687.60 + org.openide.awt.Mnemonics.setLocalizedText(browseButton, "Br&owse...");
687.61 + browseButton.setActionCommand("BROWSE");
687.62 + browseButton.addActionListener(new java.awt.event.ActionListener() {
687.63 + public void actionPerformed(java.awt.event.ActionEvent evt) {
687.64 + browseButtonActionPerformed(evt);
687.65 + }
687.66 + });
687.67 +
687.68 + createdFolderLabel.setLabelFor(createdFolderTextField);
687.69 + org.openide.awt.Mnemonics.setLocalizedText(createdFolderLabel, "Project &Folder:");
687.70 +
687.71 + createdFolderTextField.setEditable(false);
687.72 +
687.73 + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
687.74 + this.setLayout(layout);
687.75 + layout.setHorizontalGroup(
687.76 + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
687.77 + .addGroup(layout.createSequentialGroup()
687.78 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
687.79 + .addComponent(projectLocationLabel)
687.80 + .addComponent(createdFolderLabel)
687.81 + .addComponent(projectNameLabel))
687.82 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
687.83 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
687.84 + .addGroup(layout.createSequentialGroup()
687.85 + .addComponent(projectLocationTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE)
687.86 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
687.87 + .addComponent(browseButton))
687.88 + .addComponent(projectNameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
687.89 + .addComponent(createdFolderTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)))
687.90 + );
687.91 + layout.setVerticalGroup(
687.92 + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
687.93 + .addGroup(layout.createSequentialGroup()
687.94 + .addGap(20, 20, 20)
687.95 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
687.96 + .addComponent(projectNameLabel)
687.97 + .addComponent(projectNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
687.98 + .addGap(8, 8, 8)
687.99 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
687.100 + .addComponent(projectLocationLabel)
687.101 + .addComponent(browseButton)
687.102 + .addComponent(projectLocationTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
687.103 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
687.104 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
687.105 + .addComponent(createdFolderLabel)
687.106 + .addComponent(createdFolderTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
687.107 + .addContainerGap(31, Short.MAX_VALUE))
687.108 + );
687.109 + }// </editor-fold>//GEN-END:initComponents
687.110 +
687.111 + private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
687.112 + String command = evt.getActionCommand();
687.113 + if ("BROWSE".equals(command)) {
687.114 + JFileChooser chooser = new JFileChooser();
687.115 + chooser.setCurrentDirectory(null);
687.116 + chooser.setDialogTitle("Select Project Location");
687.117 + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
687.118 + String path = this.projectLocationTextField.getText();
687.119 + if (path.length() > 0) {
687.120 + File f = new File(path);
687.121 + if (f.exists()) {
687.122 + chooser.setSelectedFile(f);
687.123 + }
687.124 + }
687.125 + if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
687.126 + File projectDir = chooser.getSelectedFile();
687.127 + projectLocationTextField.setText(FileUtil.normalizeFile(projectDir).getAbsolutePath());
687.128 + }
687.129 + panel.fireChangeEvent();
687.130 + }
687.131 +
687.132 + }//GEN-LAST:event_browseButtonActionPerformed
687.133 + // Variables declaration - do not modify//GEN-BEGIN:variables
687.134 + private javax.swing.JButton browseButton;
687.135 + private javax.swing.JLabel createdFolderLabel;
687.136 + private javax.swing.JTextField createdFolderTextField;
687.137 + private javax.swing.JLabel projectLocationLabel;
687.138 + private javax.swing.JTextField projectLocationTextField;
687.139 + private javax.swing.JLabel projectNameLabel;
687.140 + private javax.swing.JTextField projectNameTextField;
687.141 + // End of variables declaration//GEN-END:variables
687.142 + @Override
687.143 + public void addNotify() {
687.144 + super.addNotify();
687.145 + //same problem as in 31086, initial focus on Cancel button
687.146 + projectNameTextField.requestFocus();
687.147 + }
687.148 +
687.149 + @Override
687.150 + boolean valid(WizardDescriptor wizardDescriptor) {
687.151 +
687.152 + if (projectNameTextField.getText().length() == 0) {
687.153 + wizardDescriptor.putProperty("WizardPanel_errorMessage",
687.154 + "Project Name is not a valid folder name.");
687.155 + return false; // Display name not specified
687.156 + }
687.157 + File f = FileUtil.normalizeFile(new File(projectLocationTextField.getText()).getAbsoluteFile());
687.158 + if (!f.isDirectory()) {
687.159 + String message = "Project Folder is not a valid path.";
687.160 + wizardDescriptor.putProperty("WizardPanel_errorMessage", message);
687.161 + return false;
687.162 + }
687.163 + final File destFolder = FileUtil.normalizeFile(new File(createdFolderTextField.getText()).getAbsoluteFile());
687.164 +
687.165 + File projLoc = destFolder;
687.166 + while (projLoc != null && !projLoc.exists()) {
687.167 + projLoc = projLoc.getParentFile();
687.168 + }
687.169 + if (projLoc == null || !projLoc.canWrite()) {
687.170 + wizardDescriptor.putProperty("WizardPanel_errorMessage",
687.171 + "Project Folder cannot be created.");
687.172 + return false;
687.173 + }
687.174 +
687.175 + if (FileUtil.toFileObject(projLoc) == null) {
687.176 + String message = "Project Folder is not a valid path.";
687.177 + wizardDescriptor.putProperty("WizardPanel_errorMessage", message);
687.178 + return false;
687.179 + }
687.180 +
687.181 + File[] kids = destFolder.listFiles();
687.182 + if (destFolder.exists() && kids != null && kids.length > 0) {
687.183 + // Folder exists and is not empty
687.184 + wizardDescriptor.putProperty("WizardPanel_errorMessage",
687.185 + "Project Folder already exists and is not empty.");
687.186 + return false;
687.187 + }
687.188 + wizardDescriptor.putProperty("WizardPanel_errorMessage", "");
687.189 + return true;
687.190 + }
687.191 +
687.192 + @Override
687.193 + void store(WizardDescriptor d) {
687.194 + String name = projectNameTextField.getText().trim();
687.195 + String folder = createdFolderTextField.getText().trim();
687.196 +
687.197 + d.putProperty(NewPythonProjectWizardIterator.PROP_PROJECT_LOCATION, new File(folder));
687.198 + d.putProperty(NewPythonProjectWizardIterator.PROP_PROJECT_NAME, name);
687.199 + }
687.200 +
687.201 + @Override
687.202 + void read(WizardDescriptor settings) {
687.203 + File projectLocation = (File) settings.getProperty(NewPythonProjectWizardIterator.PROP_PROJECT_LOCATION);
687.204 + if (projectLocation == null || projectLocation.getParentFile() == null || !projectLocation.getParentFile().isDirectory()) {
687.205 + projectLocation = ProjectChooser.getProjectsFolder();
687.206 + } else {
687.207 + projectLocation = projectLocation.getParentFile();
687.208 + }
687.209 + this.projectLocationTextField.setText(projectLocation.getAbsolutePath());
687.210 +
687.211 + String projectName = (String) settings.getProperty(NewPythonProjectWizardIterator.PROP_PROJECT_NAME);
687.212 + if (projectName == null) {
687.213 + projectName = NewPythonProjectWizardIterator.getFreeFolderName(projectLocation,"NewPythonProject"); //NOI18N
687.214 + }
687.215 + this.projectNameTextField.setText(projectName);
687.216 + this.projectNameTextField.selectAll();
687.217 + }
687.218 +
687.219 + @Override
687.220 + void validate(WizardDescriptor d) throws WizardValidationException {
687.221 + // nothing to validate
687.222 + }
687.223 +
687.224 + // Implementation of DocumentListener --------------------------------------
687.225 + @Override
687.226 + public void changedUpdate(DocumentEvent e) {
687.227 + updateTexts(e);
687.228 + if (this.projectNameTextField.getDocument() == e.getDocument()) {
687.229 + firePropertyChange(NewPythonProjectWizardIterator.PROP_PROJECT_NAME, null, this.projectNameTextField.getText());
687.230 + }
687.231 + }
687.232 +
687.233 + @Override
687.234 + public void insertUpdate(DocumentEvent e) {
687.235 + updateTexts(e);
687.236 + if (this.projectNameTextField.getDocument() == e.getDocument()) {
687.237 + firePropertyChange(NewPythonProjectWizardIterator.PROP_PROJECT_NAME, null, this.projectNameTextField.getText());
687.238 + }
687.239 + }
687.240 +
687.241 + @Override
687.242 + public void removeUpdate(DocumentEvent e) {
687.243 + updateTexts(e);
687.244 + if (this.projectNameTextField.getDocument() == e.getDocument()) {
687.245 + firePropertyChange(NewPythonProjectWizardIterator.PROP_PROJECT_NAME, null, this.projectNameTextField.getText());
687.246 + }
687.247 + }
687.248 +
687.249 + /** Handles changes in the Project name and project directory, */
687.250 + private void updateTexts(DocumentEvent e) {
687.251 +
687.252 + Document doc = e.getDocument();
687.253 +
687.254 + if (doc == projectNameTextField.getDocument() || doc == projectLocationTextField.getDocument()) {
687.255 + // Change in the project name
687.256 +
687.257 + String projectName = projectNameTextField.getText();
687.258 + String projectFolder = projectLocationTextField.getText();
687.259 +
687.260 + //if (projectFolder.trim().length() == 0 || projectFolder.equals(oldName)) {
687.261 + createdFolderTextField.setText(projectFolder + File.separatorChar + projectName);
687.262 + //}
687.263 +
687.264 + }
687.265 + panel.fireChangeEvent(); // Notify that the panel changed
687.266 + }
687.267 +}
688.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
688.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/templates/NewPythonProjectWizardIterator.java Sat Feb 28 17:25:32 2015 -0800
688.3 @@ -0,0 +1,273 @@
688.4 +package org.netbeans.modules.python.project2.templates;
688.5 +
688.6 +import java.io.File;
688.7 +import java.io.IOException;
688.8 +import java.util.HashMap;
688.9 +import java.util.HashSet;
688.10 +import java.util.Map;
688.11 +import java.util.NoSuchElementException;
688.12 +import java.util.Set;
688.13 +import javax.swing.event.ChangeListener;
688.14 +import org.netbeans.api.progress.ProgressHandle;
688.15 +import org.netbeans.api.project.Project;
688.16 +import org.netbeans.api.project.ProjectManager;
688.17 +import org.netbeans.api.templates.TemplateRegistration;
688.18 +import org.netbeans.modules.python.api.PythonPlatform;
688.19 +import org.netbeans.modules.python.api.PythonPlatformManager;
688.20 +import org.netbeans.modules.python.project2.PythonProject2;
688.21 +import org.netbeans.spi.project.ui.support.ProjectChooser;
688.22 +import org.openide.WizardDescriptor;
688.23 +import org.openide.filesystems.FileObject;
688.24 +import org.openide.filesystems.FileUtil;
688.25 +import org.openide.loaders.DataFolder;
688.26 +import org.openide.loaders.DataObject;
688.27 +import org.openide.util.Exceptions;
688.28 +import org.openide.util.Mutex;
688.29 +import org.openide.util.MutexException;
688.30 +import org.openide.util.NbBundle;
688.31 +
688.32 +public class NewPythonProjectWizardIterator implements WizardDescriptor.ProgressInstantiatingIterator {
688.33 +
688.34 + static final String PROP_MAIN_FILE = "mainFile"; //NOI18N
688.35 + static final String PROP_PROJECT_NAME = "projectName"; //NOI18N
688.36 + static final String PROP_PROJECT_LOCATION = "pojectLocation"; //NOI18N
688.37 + static final String PROP_PLATFORM_ID = "platform"; //NOI18N
688.38 +
688.39 + public static enum WizardType {
688.40 + APP
688.41 + }
688.42 +
688.43 + private final WizardType wizardType;
688.44 + private WizardDescriptor descriptor;
688.45 + private WizardDescriptor.Panel[] panels;
688.46 + private int index;
688.47 +
688.48 + public NewPythonProjectWizardIterator() {
688.49 + this(WizardType.APP);
688.50 + }
688.51 +
688.52 + private NewPythonProjectWizardIterator(WizardType wizardType) {
688.53 + this.wizardType = wizardType;
688.54 + }
688.55 +
688.56 + @TemplateRegistration(folder = "Project/Python", position = 148, displayName = "org.netbeans.modules.python.project2.Bundle#Templates/Project/Python/PythonProject2.xml", iconBase = "org/netbeans/modules/python/project2/resources/py_25_16.png", description = "/org/netbeans/modules/python/project2/templates/EmptyPythonProjectDescription.html")
688.57 + public static NewPythonProjectWizardIterator createApplication() {
688.58 + return new NewPythonProjectWizardIterator();
688.59 + }
688.60 +
688.61 + @Override
688.62 + public void initialize(WizardDescriptor wizard) {
688.63 + descriptor = wizard;
688.64 + index = 0;
688.65 + panels = createPanels();
688.66 + // normally we would do it in uninitialize but we have listener on ide options (=> NPE)
688.67 + initDescriptor(wizard);
688.68 + }
688.69 +
688.70 + @Override
688.71 + public void uninitialize(WizardDescriptor wizard) {
688.72 + panels = null;
688.73 + descriptor = null;
688.74 + }
688.75 +
688.76 + @Override
688.77 + public Set instantiate() throws IOException {
688.78 + assert false : "Cannot call this method if implements WizardDescriptor.ProgressInstantiatingIterator.";
688.79 + return null;
688.80 + }
688.81 +
688.82 + @Override
688.83 + public Set instantiate(ProgressHandle handle) throws IOException {
688.84 + final Set<FileObject> resultSet = new HashSet<>();
688.85 +
688.86 + handle.start(5);
688.87 +
688.88 + String msg = NbBundle.getMessage(
688.89 + NewPythonProjectWizardIterator.class, "LBL_NewPythonProjectWizardIterator_WizardProgress_CreatingProject");
688.90 + handle.progress(msg, 3);
688.91 + try {
688.92 + ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction<Void>() {
688.93 +
688.94 + @Override
688.95 + public Void run() throws MutexException {
688.96 + try {
688.97 + // project
688.98 + File projectDirectory = (File) descriptor.getProperty(PROP_PROJECT_LOCATION);
688.99 + ProjectChooser.setProjectsFolder(projectDirectory.getParentFile());
688.100 +
688.101 + final FileObject projectFO = FileUtil.createFolder(projectDirectory);
688.102 + String projectName = (String) descriptor.getProperty(PROP_PROJECT_NAME);
688.103 +
688.104 + Map<String, Object> params = new HashMap<>(2);
688.105 + /* org/netbeans/modules/python/editor/templates/setup.py
688.106 + * __author__="${user}"
688.107 + * __date__ ="$${date} ${time}$"
688.108 + *
688.109 + * from setuptools import setup,find_packages
688.110 + *
688.111 + * setup (
688.112 + * name = '${project_name}',
688.113 + * version = '0.1',
688.114 + * packages = find_packages(),
688.115 + *
688.116 + * # Declare your packages' dependencies here, for eg:
688.117 + * install_requires=[],
688.118 + *
688.119 + * # Fill in these to make your Egg ready for upload to
688.120 + * # PyPI
688.121 + * author = '${user}',
688.122 + * author_email = '',
688.123 + *
688.124 + * summary = 'Just another Python package for the cheese shop',
688.125 + * url = '',
688.126 + * license = '',
688.127 + * long_description= 'Long description of the package',
688.128 + *
688.129 + * # could also include long_description, download_url, classifiers, etc.
688.130 + * )
688.131 + */
688.132 + params.put("project_name", projectName); // NOI18N
688.133 + params.put("python3style", Boolean.TRUE);
688.134 + DataObject setuppy = createFromTemplate(FileUtil.getConfigFile("Templates/Python/_setup.py"), projectFO, "setup.py", params); // NOI18N
688.135 + // Do we want to open the setup.py?
688.136 +// resultSet.add(setuppy.getPrimaryFile());
688.137 + resultSet.add(projectFO);
688.138 +
688.139 + if (wizardType == WizardType.APP) {
688.140 + // package
688.141 + final String packageName = projectFO.getName().toLowerCase();
688.142 + FileObject packageFO = projectFO.createFolder(packageName);
688.143 + createFromTemplate(FileUtil.getConfigFile("Templates/Python/_init.py"), packageFO, "__init__.py", null); //NOI18N
688.144 + ProjectManager.getDefault().clearNonProjectCache();
688.145 + Project project = ProjectManager.getDefault().findProject(projectFO);
688.146 + // TODO: Change with provider in lookup cast is known to break
688.147 + PythonProject2 pyProj = (PythonProject2) project;
688.148 + final String platformId = (String) descriptor.getProperty(NewPythonProjectWizardIterator.PROP_PLATFORM_ID);
688.149 + PythonPlatform platform = PythonPlatformManager.getInstance().getPlatform(platformId);
688.150 + if(platform != null) {
688.151 + pyProj.setActivePlatform(platform);
688.152 + }
688.153 + // main file
688.154 + final String mainName = (String) descriptor.getProperty(NewPythonProjectWizardIterator.PROP_MAIN_FILE);
688.155 + if (mainName != null) {
688.156 + final FileObject mainFile = createFromTemplate(FileUtil.getConfigFile("Templates/Python/_module.py"), //NOI18N
688.157 + packageFO, mainName, params).getPrimaryFile();
688.158 + resultSet.add(mainFile);
688.159 + pyProj.setMainModule(FileUtil.getRelativePath(projectFO, mainFile));
688.160 + }
688.161 + ProjectManager.getDefault().saveProject(project);
688.162 + }
688.163 + } catch (IOException ex) {
688.164 + throw new MutexException(ex);
688.165 + }
688.166 + return null;
688.167 + }
688.168 + });
688.169 + } catch (MutexException ex) {
688.170 + Exceptions.printStackTrace(ex);
688.171 + }
688.172 +
688.173 + msg = NbBundle.getMessage(NewPythonProjectWizardIterator.class, "LBL_NewPythonProjectWizardIterator_WizardProgress_PreparingToOpen");
688.174 + handle.progress(msg, 5);
688.175 + return resultSet;
688.176 + }
688.177 +
688.178 + @Override
688.179 + public String name() {
688.180 + return NbBundle.getMessage(NewPythonProjectWizardIterator.class, "LBL_IteratorName", index + 1, panels.length);
688.181 + }
688.182 +
688.183 + @Override
688.184 + public boolean hasNext() {
688.185 + return index < panels.length - 1;
688.186 + }
688.187 +
688.188 + @Override
688.189 + public boolean hasPrevious() {
688.190 + return index > 0;
688.191 + }
688.192 +
688.193 + @Override
688.194 + public void nextPanel() {
688.195 + if (!hasNext()) {
688.196 + throw new NoSuchElementException();
688.197 + }
688.198 + index++;
688.199 + }
688.200 +
688.201 + @Override
688.202 + public void previousPanel() {
688.203 + if (!hasPrevious()) {
688.204 + throw new NoSuchElementException();
688.205 + }
688.206 + index--;
688.207 + }
688.208 +
688.209 + @Override
688.210 + public WizardDescriptor.Panel current() {
688.211 + // wizard title
688.212 + String title = NbBundle.getMessage(NewPythonProjectWizardIterator.class, wizardType == WizardType.APP ? "TXT_PythonProject" : "TXT_ExistingPythonProject");
688.213 + descriptor.putProperty(
688.214 + "NewProjectWizard_Title", title); // NOI18N
688.215 + return panels[index];
688.216 + }
688.217 +
688.218 + @Override
688.219 + public void addChangeListener(ChangeListener l) {
688.220 + }
688.221 +
688.222 + @Override
688.223 + public void removeChangeListener(ChangeListener l) {
688.224 + }
688.225 +
688.226 + static String getFreeFolderName(final File owner, final String proposal) {
688.227 + assert owner != null;
688.228 + assert proposal != null;
688.229 + String freeName = proposal;
688.230 + File f = new File(owner, freeName);
688.231 + int counter = 1;
688.232 + while (f.exists()) {
688.233 + counter++;
688.234 + freeName = proposal + counter;
688.235 + f = new File(owner, freeName);
688.236 + }
688.237 + return freeName;
688.238 +
688.239 + }
688.240 +
688.241 + private WizardDescriptor.Panel[] createPanels() {
688.242 + switch (wizardType) {
688.243 + case APP: {
688.244 + String[] steps = new String[]{
688.245 + NbBundle.getMessage(NewPythonProjectWizardIterator.class, "LBL_ProjectNameLocation"),};
688.246 +
688.247 + PanelConfigureProject configureProjectPanel = new PanelConfigureProject(wizardType, steps);
688.248 + return new WizardDescriptor.Panel[]{
688.249 + configureProjectPanel,};
688.250 + }
688.251 + default:
688.252 + throw new IllegalStateException(wizardType.toString());
688.253 + }
688.254 + }
688.255 +
688.256 + // prevent incorrect default values (empty project => back => existing project)
688.257 + private void initDescriptor(WizardDescriptor settings) {
688.258 + settings.putProperty(PROP_PROJECT_NAME, null);
688.259 + settings.putProperty(PROP_PROJECT_LOCATION, null);
688.260 + }
688.261 +
688.262 + private DataObject createFromTemplate(FileObject template, FileObject sourceDir, String name, Map<String, ? extends Object> parameters) throws IOException {
688.263 + DataFolder dataFolder = DataFolder.findFolder(sourceDir);
688.264 + DataObject dataTemplate = DataObject.find(template);
688.265 + //Strip extension when needed
688.266 + int dot = name.lastIndexOf('.');
688.267 + if (dot > 0 && dot < name.length() - 1 && "py".equalsIgnoreCase(name.substring(dot + 1))) { //NOI18N
688.268 + name = name.substring(0, dot);
688.269 + }
688.270 + if (parameters != null) {
688.271 + return dataTemplate.createFromTemplate(dataFolder, name, parameters);
688.272 + } else {
688.273 + return dataTemplate.createFromTemplate(dataFolder, name);
688.274 + }
688.275 + }
688.276 +}
689.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
689.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/templates/PanelConfigureProject.java Sat Feb 28 17:25:32 2015 -0800
689.3 @@ -0,0 +1,101 @@
689.4 +/*
689.5 + * To change this template, choose Tools | Templates
689.6 + * and open the template in the editor.
689.7 + */
689.8 +package org.netbeans.modules.python.project2.templates;
689.9 +
689.10 +import java.util.HashSet;
689.11 +import java.util.Set;
689.12 +import javax.swing.event.ChangeEvent;
689.13 +import javax.swing.event.ChangeListener;
689.14 +import org.openide.WizardDescriptor;
689.15 +import org.openide.WizardValidationException;
689.16 +import org.openide.util.HelpCtx;
689.17 +
689.18 +/**
689.19 + * Panel just asking for basic info.
689.20 + */
689.21 +public class PanelConfigureProject implements WizardDescriptor.Panel,
689.22 + WizardDescriptor.ValidatingPanel, WizardDescriptor.FinishablePanel {
689.23 +
689.24 + private WizardDescriptor wizardDescriptor;
689.25 + private PanelConfigureProjectVisual component;
689.26 + private final NewPythonProjectWizardIterator.WizardType type;
689.27 + private final String[] steps;
689.28 +
689.29 + public PanelConfigureProject (final NewPythonProjectWizardIterator.WizardType type, String[] steps) {
689.30 + assert type != null;
689.31 + assert steps != null;
689.32 + this.type = type;
689.33 + this.steps = steps;
689.34 + }
689.35 +
689.36 + @Override
689.37 + public PanelConfigureProjectVisual getComponent() {
689.38 + if (component == null) {
689.39 + component = new PanelConfigureProjectVisual(this, type);
689.40 + component.putClientProperty(WizardDescriptor.PROP_CONTENT_DATA, steps);
689.41 + }
689.42 + return component;
689.43 + }
689.44 +
689.45 + @Override
689.46 + public HelpCtx getHelp() {
689.47 + return new HelpCtx("org.netbeans.modules.python.project2.templates.PanelConfigureProject");
689.48 + }
689.49 +
689.50 + @Override
689.51 + public boolean isValid() {
689.52 + getComponent();
689.53 + return getComponent().valid(wizardDescriptor);
689.54 + }
689.55 + private final Set<ChangeListener> listeners = new HashSet<>(1); // or can use ChangeSupport in NB 6.0
689.56 +
689.57 + @Override
689.58 + public final void addChangeListener(ChangeListener l) {
689.59 + synchronized (listeners) {
689.60 + listeners.add(l);
689.61 + }
689.62 + }
689.63 +
689.64 + @Override
689.65 + public final void removeChangeListener(ChangeListener l) {
689.66 + synchronized (listeners) {
689.67 + listeners.remove(l);
689.68 + }
689.69 + }
689.70 +
689.71 + protected final void fireChangeEvent() {
689.72 + Set<ChangeListener> ls;
689.73 + synchronized (listeners) {
689.74 + ls = new HashSet<>(listeners);
689.75 + }
689.76 + ChangeEvent ev = new ChangeEvent(this);
689.77 + for (ChangeListener l : ls) {
689.78 + l.stateChanged(ev);
689.79 + }
689.80 + }
689.81 +
689.82 + @Override
689.83 + public void readSettings(Object settings) {
689.84 + wizardDescriptor = (WizardDescriptor) settings;
689.85 + getComponent().read(wizardDescriptor);
689.86 + }
689.87 +
689.88 + @Override
689.89 + public void storeSettings(Object settings) {
689.90 + WizardDescriptor d = (WizardDescriptor) settings;
689.91 + getComponent().store(d);
689.92 + }
689.93 +
689.94 + @Override
689.95 + public boolean isFinishPanel() {
689.96 + return true;
689.97 + }
689.98 +
689.99 + @Override
689.100 + public void validate() throws WizardValidationException {
689.101 + getComponent();
689.102 + getComponent().validate(wizardDescriptor);
689.103 + }
689.104 +}
690.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
690.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/templates/PanelConfigureProjectVisual.form Sat Feb 28 17:25:32 2015 -0800
690.3 @@ -0,0 +1,60 @@
690.4 +<?xml version="1.0" encoding="UTF-8" ?>
690.5 +
690.6 +<Form version="1.2" maxVersion="1.2" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
690.7 + <AuxValues>
690.8 + <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
690.9 + <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
690.10 + <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
690.11 + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
690.12 + <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
690.13 + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
690.14 + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
690.15 + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
690.16 + <AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,44,0,0,1,-112"/>
690.17 + </AuxValues>
690.18 +
690.19 + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/>
690.20 + <SubComponents>
690.21 + <Container class="javax.swing.JPanel" name="locationContainer">
690.22 + <AccessibilityProperties>
690.23 + <Property name="AccessibleContext.accessibleName" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
690.24 + <ResourceString bundle="org/netbeans/modules/python/project2/templates/Bundle.properties" key="ACSN_locationContainer" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
690.25 + </Property>
690.26 + <Property name="AccessibleContext.accessibleDescription" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
690.27 + <ResourceString bundle="org/netbeans/modules/python/project2/templates/Bundle.properties" key="ACSD_locationContainer" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
690.28 + </Property>
690.29 + </AccessibilityProperties>
690.30 + <Constraints>
690.31 + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
690.32 + <GridBagConstraints gridX="-1" gridY="-1" gridWidth="0" gridHeight="1" fill="1" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="1.0" weightY="0.0"/>
690.33 + </Constraint>
690.34 + </Constraints>
690.35 +
690.36 + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
690.37 + </Container>
690.38 + <Component class="javax.swing.JSeparator" name="jSeparator1">
690.39 + <Constraints>
690.40 + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
690.41 + <GridBagConstraints gridX="-1" gridY="-1" gridWidth="0" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="12" insetsLeft="0" insetsBottom="12" insetsRight="0" anchor="10" weightX="1.0" weightY="0.0"/>
690.42 + </Constraint>
690.43 + </Constraints>
690.44 + </Component>
690.45 + <Container class="javax.swing.JPanel" name="optionsContainer">
690.46 + <AccessibilityProperties>
690.47 + <Property name="AccessibleContext.accessibleName" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
690.48 + <ResourceString bundle="org/netbeans/modules/python/project2/templates/Bundle.properties" key="ACSN_optionsContainer" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
690.49 + </Property>
690.50 + <Property name="AccessibleContext.accessibleDescription" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
690.51 + <ResourceString bundle="org/netbeans/modules/python/project2/templates/Bundle.properties" key="ACSD_optionsContainer" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
690.52 + </Property>
690.53 + </AccessibilityProperties>
690.54 + <Constraints>
690.55 + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
690.56 + <GridBagConstraints gridX="-1" gridY="-1" gridWidth="0" gridHeight="0" fill="1" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="1.0" weightY="1.0"/>
690.57 + </Constraint>
690.58 + </Constraints>
690.59 +
690.60 + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
690.61 + </Container>
690.62 + </SubComponents>
690.63 +</Form>
691.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
691.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/templates/PanelConfigureProjectVisual.java Sat Feb 28 17:25:32 2015 -0800
691.3 @@ -0,0 +1,169 @@
691.4 +/*
691.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
691.6 + *
691.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
691.8 + *
691.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
691.10 + * Other names may be trademarks of their respective owners.
691.11 + *
691.12 + * The contents of this file are subject to the terms of either the GNU
691.13 + * General Public License Version 2 only ("GPL") or the Common
691.14 + * Development and Distribution License("CDDL") (collectively, the
691.15 + * "License"). You may not use this file except in compliance with the
691.16 + * License. You can obtain a copy of the License at
691.17 + * http://www.netbeans.org/cddl-gplv2.html
691.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
691.19 + * specific language governing permissions and limitations under the
691.20 + * License. When distributing the software, include this License Header
691.21 + * Notice in each file and include the License file at
691.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
691.23 + * particular file as subject to the "Classpath" exception as provided
691.24 + * by Oracle in the GPL Version 2 section of the License file that
691.25 + * accompanied this code. If applicable, add the following below the
691.26 + * License Header, with the fields enclosed by brackets [] replaced by
691.27 + * your own identifying information:
691.28 + * "Portions Copyrighted [year] [name of copyright owner]"
691.29 + *
691.30 + * Contributor(s):
691.31 + *
691.32 + * The Original Software is NetBeans. The Initial Developer of the Original
691.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
691.34 + * Microsystems, Inc. All Rights Reserved.
691.35 + *
691.36 + * If you wish your version of this file to be governed by only the CDDL
691.37 + * or only the GPL Version 2, indicate your decision by adding
691.38 + * "[Contributor] elects to include this software in this distribution
691.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
691.40 + * single choice of license, a recipient has the option to distribute
691.41 + * your version of this file under either the CDDL, the GPL Version 2 or
691.42 + * to extend the choice of license to its licensees as provided above.
691.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
691.44 + * Version 2 license, then the option applies only if the new code is
691.45 + * made subject to such option by the copyright holder.
691.46 + */
691.47 +
691.48 +package org.netbeans.modules.python.project2.templates;
691.49 +
691.50 +import javax.swing.JPanel;
691.51 +import org.openide.WizardDescriptor;
691.52 +import org.openide.WizardValidationException;
691.53 +import org.openide.util.NbBundle;
691.54 +
691.55 +/** First panel in the NewProject wizard. Used for filling in
691.56 + * name, and directory of the project.
691.57 + *
691.58 + * @author Tomas Zezula
691.59 + */
691.60 +public class PanelConfigureProjectVisual extends JPanel {
691.61 +
691.62 + private PanelConfigureProject panel;
691.63 +
691.64 + private SettingsPanel projectLocationPanel;
691.65 +
691.66 + private PanelOptionsVisual optionsPanel;
691.67 +
691.68 + private NewPythonProjectWizardIterator.WizardType type;
691.69 +
691.70 + public PanelConfigureProjectVisual(PanelConfigureProject panel, NewPythonProjectWizardIterator.WizardType type) {
691.71 + this.panel = panel;
691.72 + initComponents();
691.73 + this.type = type;
691.74 + setName(NbBundle.getMessage(PanelConfigureProjectVisual.class,"TXT_NameAndLoc")); // NOI18N
691.75 + switch (type) {
691.76 + case APP:
691.77 + projectLocationPanel = new EmptyPythonProjectPanelVisual(panel);
691.78 + putClientProperty ("NewProjectWizard_Title", NbBundle.getMessage(PanelConfigureProjectVisual.class,"TXT_NewPythonApp")); // NOI18N
691.79 + jSeparator1.setVisible(true);
691.80 + getAccessibleContext ().setAccessibleName (NbBundle.getMessage(PanelConfigureProjectVisual.class,"TXT_NewPythonApp")); // NOI18N
691.81 + getAccessibleContext ().setAccessibleDescription (NbBundle.getMessage(PanelConfigureProjectVisual.class,"ACSD_NewPythonApp")); // NOI18N
691.82 + break;
691.83 + default:
691.84 + throw new UnsupportedOperationException();
691.85 + }
691.86 + locationContainer.add( projectLocationPanel, java.awt.BorderLayout.CENTER );
691.87 + optionsPanel = new PanelOptionsVisual( panel, type );
691.88 + projectLocationPanel.addPropertyChangeListener(optionsPanel);
691.89 + optionsContainer.add( optionsPanel, java.awt.BorderLayout.CENTER );
691.90 + }
691.91 +
691.92 + boolean valid( WizardDescriptor wizardDescriptor ) {
691.93 + wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, ""); //NOI18N
691.94 + return projectLocationPanel.valid( wizardDescriptor ) && optionsPanel.valid(wizardDescriptor);
691.95 + }
691.96 +
691.97 + void read (WizardDescriptor d) {
691.98 + Object lastType = d.getProperty("wizard-type"); //NOI18N
691.99 + if (lastType == null || lastType != type) {
691.100 + //bugfix #46387 The type of project changed, reset values to defaults
691.101 + d.putProperty ("name", null);
691.102 + d.putProperty ("projdir",null);
691.103 + }
691.104 + projectLocationPanel.read (d);
691.105 + optionsPanel.read (d);
691.106 + }
691.107 +
691.108 + void store( WizardDescriptor d ) {
691.109 + d.putProperty("wizard-type", type); //NOI18N
691.110 + projectLocationPanel.store( d );
691.111 + optionsPanel.store( d );
691.112 + }
691.113 +
691.114 + void validate (WizardDescriptor d) throws WizardValidationException {
691.115 + projectLocationPanel.validate (d);
691.116 + }
691.117 +
691.118 +
691.119 + /** This method is called from within the constructor to
691.120 + * initialize the form.
691.121 + * WARNING: Do NOT modify this code. The content of this method is
691.122 + * always regenerated by the Form Editor.
691.123 + */
691.124 + // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
691.125 + private void initComponents() {
691.126 + java.awt.GridBagConstraints gridBagConstraints;
691.127 +
691.128 + locationContainer = new javax.swing.JPanel();
691.129 + jSeparator1 = new javax.swing.JSeparator();
691.130 + optionsContainer = new javax.swing.JPanel();
691.131 +
691.132 + setLayout(new java.awt.GridBagLayout());
691.133 +
691.134 + locationContainer.setLayout(new java.awt.BorderLayout());
691.135 + gridBagConstraints = new java.awt.GridBagConstraints();
691.136 + gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
691.137 + gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
691.138 + gridBagConstraints.weightx = 1.0;
691.139 + add(locationContainer, gridBagConstraints);
691.140 + locationContainer.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getBundle(PanelConfigureProjectVisual.class).getString("ACSN_locationContainer")); // NOI18N
691.141 + locationContainer.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(PanelConfigureProjectVisual.class).getString("ACSD_locationContainer")); // NOI18N
691.142 +
691.143 + gridBagConstraints = new java.awt.GridBagConstraints();
691.144 + gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
691.145 + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
691.146 + gridBagConstraints.weightx = 1.0;
691.147 + gridBagConstraints.insets = new java.awt.Insets(12, 0, 12, 0);
691.148 + add(jSeparator1, gridBagConstraints);
691.149 +
691.150 + optionsContainer.setLayout(new java.awt.BorderLayout());
691.151 + gridBagConstraints = new java.awt.GridBagConstraints();
691.152 + gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
691.153 + gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER;
691.154 + gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
691.155 + gridBagConstraints.weightx = 1.0;
691.156 + gridBagConstraints.weighty = 1.0;
691.157 + add(optionsContainer, gridBagConstraints);
691.158 + optionsContainer.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getBundle(PanelConfigureProjectVisual.class).getString("ACSN_optionsContainer")); // NOI18N
691.159 + optionsContainer.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(PanelConfigureProjectVisual.class).getString("ACSD_optionsContainer")); // NOI18N
691.160 + }// </editor-fold>//GEN-END:initComponents
691.161 +
691.162 + /** Currently only handles the "Browse..." button
691.163 + */
691.164 +
691.165 + // Variables declaration - do not modify//GEN-BEGIN:variables
691.166 + private javax.swing.JSeparator jSeparator1;
691.167 + private javax.swing.JPanel locationContainer;
691.168 + private javax.swing.JPanel optionsContainer;
691.169 + // End of variables declaration//GEN-END:variables
691.170 +
691.171 +
691.172 +}
692.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
692.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/templates/PanelOptionsVisual.form Sat Feb 28 17:25:32 2015 -0800
692.3 @@ -0,0 +1,125 @@
692.4 +<?xml version="1.0" encoding="UTF-8" ?>
692.5 +
692.6 +<Form version="1.2" maxVersion="1.2" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
692.7 + <AccessibilityProperties>
692.8 + <Property name="AccessibleContext.accessibleName" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
692.9 + <ResourceString bundle="org/netbeans/modules/python/project2/templates/Bundle.properties" key="ACSN_PanelOptionsVisual" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
692.10 + </Property>
692.11 + <Property name="AccessibleContext.accessibleDescription" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
692.12 + <ResourceString bundle="org/netbeans/modules/python/project2/templates/Bundle.properties" key="ACSD_PanelOptionsVisual" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
692.13 + </Property>
692.14 + </AccessibilityProperties>
692.15 + <AuxValues>
692.16 + <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
692.17 + <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
692.18 + <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
692.19 + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
692.20 + <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
692.21 + <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
692.22 + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
692.23 + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
692.24 + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
692.25 + </AuxValues>
692.26 +
692.27 + <Layout>
692.28 + <DimensionLayout dim="0">
692.29 + <Group type="103" groupAlignment="0" attributes="0">
692.30 + <Group type="102" alignment="0" attributes="0">
692.31 + <Group type="103" groupAlignment="0" attributes="0">
692.32 + <Component id="createMainCheckBox" alignment="0" min="-2" max="-2" attributes="0"/>
692.33 + <Component id="jLabel1" alignment="0" min="-2" max="-2" attributes="0"/>
692.34 + </Group>
692.35 + <EmptySpace type="separate" max="-2" attributes="0"/>
692.36 + <Group type="103" groupAlignment="0" attributes="0">
692.37 + <Group type="102" attributes="0">
692.38 + <Component id="platforms" min="-2" pref="233" max="-2" attributes="0"/>
692.39 + <EmptySpace type="unrelated" max="-2" attributes="0"/>
692.40 + <Component id="manage" min="-2" max="-2" attributes="0"/>
692.41 + <EmptySpace min="-2" pref="4" max="-2" attributes="0"/>
692.42 + </Group>
692.43 + <Component id="mainFileTextField" alignment="0" max="32767" attributes="0"/>
692.44 + </Group>
692.45 + </Group>
692.46 + </Group>
692.47 + </DimensionLayout>
692.48 + <DimensionLayout dim="1">
692.49 + <Group type="103" groupAlignment="0" attributes="0">
692.50 + <Group type="102" attributes="0">
692.51 + <EmptySpace max="-2" attributes="0"/>
692.52 + <Group type="103" groupAlignment="3" attributes="0">
692.53 + <Component id="createMainCheckBox" alignment="3" min="-2" max="-2" attributes="0"/>
692.54 + <Component id="mainFileTextField" alignment="3" min="-2" max="-2" attributes="0"/>
692.55 + </Group>
692.56 + <EmptySpace max="-2" attributes="0"/>
692.57 + <Group type="103" groupAlignment="0" attributes="0">
692.58 + <Group type="103" groupAlignment="3" attributes="0">
692.59 + <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
692.60 + <Component id="platforms" alignment="3" min="-2" max="-2" attributes="0"/>
692.61 + </Group>
692.62 + <Component id="manage" alignment="0" min="-2" max="-2" attributes="0"/>
692.63 + </Group>
692.64 + <EmptySpace max="32767" attributes="0"/>
692.65 + </Group>
692.66 + </Group>
692.67 + </DimensionLayout>
692.68 + </Layout>
692.69 + <SubComponents>
692.70 + <Component class="javax.swing.JCheckBox" name="createMainCheckBox">
692.71 + <Properties>
692.72 + <Property name="selected" type="boolean" value="true"/>
692.73 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
692.74 + <ResourceString bundle="org/netbeans/modules/python/project2/templates/Bundle.properties" key="LBL_createMainCheckBox" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
692.75 + </Property>
692.76 + </Properties>
692.77 + <AccessibilityProperties>
692.78 + <Property name="AccessibleContext.accessibleName" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
692.79 + <ResourceString bundle="org/netbeans/modules/python/project2/templates/Bundle.properties" key="ACSN_createMainCheckBox" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
692.80 + </Property>
692.81 + <Property name="AccessibleContext.accessibleDescription" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
692.82 + <ResourceString bundle="org/netbeans/modules/python/project2/templates/Bundle.properties" key="ACSD_createMainCheckBox" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
692.83 + </Property>
692.84 + </AccessibilityProperties>
692.85 + <AuxValues>
692.86 + <AuxValue name="generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
692.87 + </AuxValues>
692.88 + </Component>
692.89 + <Component class="javax.swing.JTextField" name="mainFileTextField">
692.90 + <Properties>
692.91 + <Property name="text" type="java.lang.String" value="main"/>
692.92 + </Properties>
692.93 + <AccessibilityProperties>
692.94 + <Property name="AccessibleContext.accessibleName" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
692.95 + <ResourceString bundle="org/netbeans/modules/python/project2/templates/Bundle.properties" key="ASCN_mainClassTextFiled" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
692.96 + </Property>
692.97 + <Property name="AccessibleContext.accessibleDescription" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
692.98 + <ResourceString bundle="org/netbeans/modules/python/project2/templates/Bundle.properties" key="ASCD_mainClassTextFiled" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
692.99 + </Property>
692.100 + </AccessibilityProperties>
692.101 + </Component>
692.102 + <Component class="javax.swing.JLabel" name="jLabel1">
692.103 + <Properties>
692.104 + <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
692.105 + <ComponentRef name="platforms"/>
692.106 + </Property>
692.107 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
692.108 + <ResourceString bundle="org/netbeans/modules/python/project2/templates/Bundle.properties" key="TXT_PythonPlatform" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
692.109 + </Property>
692.110 + </Properties>
692.111 + </Component>
692.112 + <Component class="javax.swing.JComboBox" name="platforms">
692.113 + <AuxValues>
692.114 + <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="org.netbeans.modules.python.api.PlatformComponentFactory.getPythonPlatformsComboxBox()"/>
692.115 + </AuxValues>
692.116 + </Component>
692.117 + <Component class="javax.swing.JButton" name="manage">
692.118 + <Properties>
692.119 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
692.120 + <ResourceString bundle="org/netbeans/modules/python/project2/templates/Bundle.properties" key="TXT_ManagePlatfroms" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
692.121 + </Property>
692.122 + </Properties>
692.123 + <Events>
692.124 + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="manageActionPerformed"/>
692.125 + </Events>
692.126 + </Component>
692.127 + </SubComponents>
692.128 +</Form>
693.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
693.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/templates/PanelOptionsVisual.java Sat Feb 28 17:25:32 2015 -0800
693.3 @@ -0,0 +1,349 @@
693.4 +/*
693.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
693.6 + *
693.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
693.8 + *
693.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
693.10 + * Other names may be trademarks of their respective owners.
693.11 + *
693.12 + * The contents of this file are subject to the terms of either the GNU
693.13 + * General Public License Version 2 only ("GPL") or the Common
693.14 + * Development and Distribution License("CDDL") (collectively, the
693.15 + * "License"). You may not use this file except in compliance with the
693.16 + * License. You can obtain a copy of the License at
693.17 + * http://www.netbeans.org/cddl-gplv2.html
693.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
693.19 + * specific language governing permissions and limitations under the
693.20 + * License. When distributing the software, include this License Header
693.21 + * Notice in each file and include the License file at
693.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
693.23 + * particular file as subject to the "Classpath" exception as provided
693.24 + * by Oracle in the GPL Version 2 section of the License file that
693.25 + * accompanied this code. If applicable, add the following below the
693.26 + * License Header, with the fields enclosed by brackets [] replaced by
693.27 + * your own identifying information:
693.28 + * "Portions Copyrighted [year] [name of copyright owner]"
693.29 + *
693.30 + * Contributor(s):
693.31 + *
693.32 + * The Original Software is NetBeans. The Initial Developer of the Original
693.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
693.34 + * Microsystems, Inc. All Rights Reserved.
693.35 + *
693.36 + * If you wish your version of this file to be governed by only the CDDL
693.37 + * or only the GPL Version 2, indicate your decision by adding
693.38 + * "[Contributor] elects to include this software in this distribution
693.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
693.40 + * single choice of license, a recipient has the option to distribute
693.41 + * your version of this file under either the CDDL, the GPL Version 2 or
693.42 + * to extend the choice of license to its licensees as provided above.
693.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
693.44 + * Version 2 license, then the option applies only if the new code is
693.45 + * made subject to such option by the copyright holder.
693.46 + */
693.47 +
693.48 +
693.49 +package org.netbeans.modules.python.project2.templates;
693.50 +
693.51 +import java.awt.event.ActionEvent;
693.52 +import java.awt.event.ActionListener;
693.53 +import java.beans.PropertyChangeEvent;
693.54 +import java.beans.PropertyChangeListener;
693.55 +import java.io.IOException;
693.56 +import java.util.StringTokenizer;
693.57 +import javax.swing.JComboBox;
693.58 +import javax.swing.event.DocumentListener;
693.59 +import javax.swing.event.DocumentEvent;
693.60 +import org.netbeans.modules.python.api.PlatformComponentFactory;
693.61 +import org.netbeans.modules.python.api.PythonPlatform;
693.62 +import org.netbeans.modules.python.api.PythonPlatformManager;
693.63 +import org.netbeans.modules.python.api.Util;
693.64 +import org.netbeans.modules.python.project2.ui.Utils;
693.65 +import org.openide.WizardDescriptor;
693.66 +import org.openide.WizardValidationException;
693.67 +import org.openide.filesystems.FileObject;
693.68 +import org.openide.filesystems.FileUtil;
693.69 +import org.openide.loaders.DataObject;
693.70 +import org.openide.loaders.InstanceDataObject;
693.71 +import org.openide.util.Exceptions;
693.72 +import org.openide.util.NbBundle;
693.73 +import org.openide.util.Utilities;
693.74 +import org.openide.util.actions.CallableSystemAction;
693.75 +
693.76 +/**
693.77 + * @author Tomas Zezula
693.78 + */
693.79 +public final class PanelOptionsVisual extends SettingsPanel implements ActionListener, PropertyChangeListener {
693.80 +
693.81 + private static boolean lastMainClassCheck = true; // XXX Store somewhere
693.82 +
693.83 + private PanelConfigureProject panel;
693.84 + private boolean valid;
693.85 + private String projectLocation;
693.86 +
693.87 + public PanelOptionsVisual(PanelConfigureProject panel, NewPythonProjectWizardIterator.WizardType type) {
693.88 + initComponents();
693.89 + this.panel = panel;
693.90 + PlatformComponentFactory.addPlatformChangeListener(platforms, new PlatformComponentFactory.PlatformChangeListener() {
693.91 + @Override
693.92 + public void platformChanged() {
693.93 + fireChangeEvent();
693.94 + }
693.95 + });
693.96 +
693.97 +
693.98 + switch (type) {
693.99 + case APP:
693.100 + createMainCheckBox.addActionListener( this );
693.101 + createMainCheckBox.setSelected( lastMainClassCheck );
693.102 + mainFileTextField.setEnabled( lastMainClassCheck );
693.103 + break;
693.104 + }
693.105 +
693.106 + this.mainFileTextField.getDocument().addDocumentListener( new DocumentListener () {
693.107 +
693.108 + @Override
693.109 + public void insertUpdate(DocumentEvent e) {
693.110 + mainFileChanged ();
693.111 + }
693.112 +
693.113 + @Override
693.114 + public void removeUpdate(DocumentEvent e) {
693.115 + mainFileChanged ();
693.116 + }
693.117 +
693.118 + @Override
693.119 + public void changedUpdate(DocumentEvent e) {
693.120 + mainFileChanged ();
693.121 + }
693.122 +
693.123 + });
693.124 +
693.125 + }
693.126 +
693.127 + @Override
693.128 + public void actionPerformed( ActionEvent e ) {
693.129 + if ( e.getSource() == createMainCheckBox ) {
693.130 + lastMainClassCheck = createMainCheckBox.isSelected();
693.131 + mainFileTextField.setEnabled( lastMainClassCheck );
693.132 + this.panel.fireChangeEvent();
693.133 + }
693.134 + }
693.135 +
693.136 + @Override
693.137 + public void propertyChange (PropertyChangeEvent event) {
693.138 + // The project name isn't very python'y
693.139 + if (NewPythonProjectWizardIterator.PROP_PROJECT_NAME.equals(event.getPropertyName())) {
693.140 + String newProjectName = (String) event.getNewValue();
693.141 + this.mainFileTextField.setText (NbBundle.getMessage(PanelOptionsVisual.class, "TXT_MainFileName",newProjectName.toLowerCase()));
693.142 + }
693.143 + if (NewPythonProjectWizardIterator.PROP_PROJECT_LOCATION.equals(event.getPropertyName())) {
693.144 + projectLocation = (String)event.getNewValue();
693.145 + }
693.146 + }
693.147 +
693.148 + /** This method is called from within the constructor to
693.149 + * initialize the form.
693.150 + * WARNING: Do NOT modify this code. The content of this method is
693.151 + * always regenerated by the Form Editor.
693.152 + */
693.153 + // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
693.154 + private void initComponents() {
693.155 +
693.156 + createMainCheckBox = new javax.swing.JCheckBox();
693.157 + mainFileTextField = new javax.swing.JTextField();
693.158 + jLabel1 = new javax.swing.JLabel();
693.159 + platforms = org.netbeans.modules.python.api.PlatformComponentFactory.getPythonPlatformsComboxBox();
693.160 + manage = new javax.swing.JButton();
693.161 +
693.162 + createMainCheckBox.setSelected(true);
693.163 + org.openide.awt.Mnemonics.setLocalizedText(createMainCheckBox, org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("LBL_createMainCheckBox")); // NOI18N
693.164 +
693.165 + mainFileTextField.setText("main");
693.166 +
693.167 + jLabel1.setLabelFor(platforms);
693.168 + org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(PanelOptionsVisual.class, "TXT_PythonPlatform")); // NOI18N
693.169 +
693.170 + org.openide.awt.Mnemonics.setLocalizedText(manage, org.openide.util.NbBundle.getMessage(PanelOptionsVisual.class, "TXT_ManagePlatfroms")); // NOI18N
693.171 + manage.addActionListener(new java.awt.event.ActionListener() {
693.172 + public void actionPerformed(java.awt.event.ActionEvent evt) {
693.173 + manageActionPerformed(evt);
693.174 + }
693.175 + });
693.176 +
693.177 + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
693.178 + this.setLayout(layout);
693.179 + layout.setHorizontalGroup(
693.180 + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
693.181 + .addGroup(layout.createSequentialGroup()
693.182 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
693.183 + .addComponent(createMainCheckBox)
693.184 + .addComponent(jLabel1))
693.185 + .addGap(18, 18, 18)
693.186 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
693.187 + .addGroup(layout.createSequentialGroup()
693.188 + .addComponent(platforms, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE)
693.189 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
693.190 + .addComponent(manage)
693.191 + .addGap(4, 4, 4))
693.192 + .addComponent(mainFileTextField)))
693.193 + );
693.194 + layout.setVerticalGroup(
693.195 + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
693.196 + .addGroup(layout.createSequentialGroup()
693.197 + .addContainerGap()
693.198 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
693.199 + .addComponent(createMainCheckBox)
693.200 + .addComponent(mainFileTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
693.201 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
693.202 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
693.203 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
693.204 + .addComponent(jLabel1)
693.205 + .addComponent(platforms, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
693.206 + .addComponent(manage))
693.207 + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
693.208 + );
693.209 +
693.210 + createMainCheckBox.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ACSN_createMainCheckBox")); // NOI18N
693.211 + createMainCheckBox.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ACSD_createMainCheckBox")); // NOI18N
693.212 + mainFileTextField.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ASCN_mainClassTextFiled")); // NOI18N
693.213 + mainFileTextField.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ASCD_mainClassTextFiled")); // NOI18N
693.214 +
693.215 + getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(PanelOptionsVisual.class, "ACSN_PanelOptionsVisual")); // NOI18N
693.216 + getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(PanelOptionsVisual.class, "ACSD_PanelOptionsVisual")); // NOI18N
693.217 + }// </editor-fold>//GEN-END:initComponents
693.218 +
693.219 +private void manageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_manageActionPerformed
693.220 +//Workaround, Needs an API to display platform customizer
693.221 + final FileObject fo = FileUtil.getConfigFile("Actions/Python/org-netbeans-modules-python-platform-PythonManagerAction.instance"); //NOI18N
693.222 + if (fo != null) {
693.223 + try {
693.224 + InstanceDataObject ido = (InstanceDataObject) DataObject.find(fo);
693.225 + CallableSystemAction action = (CallableSystemAction) ido.instanceCreate();
693.226 + action.performAction();
693.227 + platforms.setModel(Utils.createPlatformModel()); //Currentl the PythonManager doesn't fire events, we need to replace model.
693.228 + } catch (IOException | ClassNotFoundException ex) {
693.229 + Exceptions.printStackTrace(ex);
693.230 + }
693.231 + }
693.232 +}//GEN-LAST:event_manageActionPerformed
693.233 +
693.234 +
693.235 +
693.236 + @Override
693.237 + boolean valid(WizardDescriptor settings) {
693.238 + if (PlatformComponentFactory.getPlatform(platforms) == null) {
693.239 + // Only complain if there are no available platforms since most likely there's
693.240 + // no selection yet because it's busy auto-detecting
693.241 + if (PythonPlatformManager.getInstance().getPlatformList().isEmpty()) {
693.242 + settings.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE,
693.243 + NbBundle.getMessage(PanelOptionsVisual.class,"ERROR_IllegalPlatform"));
693.244 + }
693.245 + return false;
693.246 + }
693.247 + if (mainFileTextField.isVisible () && mainFileTextField.isEnabled ()) {
693.248 + if (!valid) {
693.249 + settings.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE,
693.250 + NbBundle.getMessage(PanelOptionsVisual.class,"ERROR_IllegalMainFileName")); //NOI18N
693.251 + }
693.252 + return this.valid;
693.253 + }
693.254 + else {
693.255 + return true;
693.256 + }
693.257 + }
693.258 +
693.259 + @Override
693.260 + void read (WizardDescriptor d) {
693.261 + final PythonPlatformManager manager = PythonPlatformManager.getInstance();
693.262 + String pid = (String) d.getProperty(NewPythonProjectWizardIterator.PROP_PLATFORM_ID);
693.263 + if (pid == null) {
693.264 + pid = Util.getPythonPreferences().get(LAST_PLATFORM_ID, null);
693.265 + if (pid == null) {
693.266 + pid = manager.getDefaultPlatform();
693.267 + }
693.268 + }
693.269 + final PythonPlatform activePlatform = manager.getPlatform(pid);
693.270 + if (activePlatform != null) {
693.271 + platforms.setSelectedItem(activePlatform);
693.272 + }
693.273 + }
693.274 +
693.275 + @Override
693.276 + void validate (WizardDescriptor d) throws WizardValidationException {
693.277 + // nothing to validate
693.278 + }
693.279 +
693.280 + @Override
693.281 + void store( WizardDescriptor d ) {
693.282 + d.putProperty(NewPythonProjectWizardIterator.PROP_MAIN_FILE, createMainCheckBox.isSelected() && createMainCheckBox.isVisible() ? mainFileTextField.getText() : null ); // NOI18N
693.283 + PythonPlatform platform = PlatformComponentFactory.getPlatform(platforms);
693.284 + if (platform != null) {
693.285 + d.putProperty(NewPythonProjectWizardIterator.PROP_PLATFORM_ID, platform.getId());
693.286 + }
693.287 + }
693.288 +
693.289 + // Variables declaration - do not modify//GEN-BEGIN:variables
693.290 + private javax.swing.JCheckBox createMainCheckBox;
693.291 + private javax.swing.JLabel jLabel1;
693.292 + private javax.swing.JTextField mainFileTextField;
693.293 + private javax.swing.JButton manage;
693.294 + private javax.swing.JComboBox platforms;
693.295 + // End of variables declaration//GEN-END:variables
693.296 +
693.297 + private void mainFileChanged () {
693.298 + String mainClassName = this.mainFileTextField.getText ();
693.299 + StringTokenizer tk = new StringTokenizer (mainClassName, "."); //NOI18N
693.300 + boolean isJavaIdentifier = true;
693.301 + while (tk.hasMoreTokens()) {
693.302 + String token = tk.nextToken();
693.303 + if (token.length() == 0 || !Utilities.isJavaIdentifier(token)) {
693.304 + isJavaIdentifier = false;
693.305 + break;
693.306 + }
693.307 + }
693.308 + this.valid = isJavaIdentifier;
693.309 + this.panel.fireChangeEvent();
693.310 + }
693.311 +
693.312 + public @Override void removeNotify() {
693.313 + storeWizardPlatform(platforms);
693.314 + super.removeNotify();
693.315 + }
693.316 +
693.317 + private void fireChangeEvent() {
693.318 + this.panel.fireChangeEvent();
693.319 + }
693.320 +
693.321 + private static final String LAST_PLATFORM_ID = "projectPanelLastPlatformID"; // NOI18N
693.322 +
693.323 + public static void preselectWizardPlatform(final JComboBox platforms) {
693.324 + preselectPlatform(platforms, LAST_PLATFORM_ID);
693.325 + }
693.326 +
693.327 + public static void preselectPlatform(final JComboBox platforms, final String preferencePlatformIDKey) {
693.328 + String lastPlatformID = Util.getPythonPreferences().get(preferencePlatformIDKey, null);
693.329 + if (lastPlatformID != null) {
693.330 + PythonPlatform platform = PythonPlatformManager.getInstance().getPlatform(lastPlatformID);
693.331 + if (platform != null) {
693.332 + platforms.setSelectedItem(platform);
693.333 + }
693.334 + }
693.335 + }
693.336 +
693.337 + public static void storeWizardPlatform(JComboBox platforms) {
693.338 + PythonPlatform selectedPlatform = PlatformComponentFactory.getPlatform(platforms);
693.339 + if (selectedPlatform != null) {
693.340 + Util.getPythonPreferences().put(LAST_PLATFORM_ID, selectedPlatform.getId());
693.341 + }
693.342 + }
693.343 +
693.344 +//
693.345 +// public static void storeWizardPlatform(JComboBox platforms) {
693.346 +// PythonPlatform selectedPlatform = PlatformComponentFactory.getPlatform(platforms);
693.347 +// if (selectedPlatform != null) {
693.348 +// RubyPreferences.getPreferences().put(LAST_PLATFORM_ID, selectedPlatform.getID());
693.349 +// }
693.350 +// }
693.351 +}
693.352 +
694.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
694.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/templates/SettingsPanel.java Sat Feb 28 17:25:32 2015 -0800
694.3 @@ -0,0 +1,64 @@
694.4 +/*
694.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
694.6 + *
694.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
694.8 + *
694.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
694.10 + * Other names may be trademarks of their respective owners.
694.11 + *
694.12 + * The contents of this file are subject to the terms of either the GNU
694.13 + * General Public License Version 2 only ("GPL") or the Common
694.14 + * Development and Distribution License("CDDL") (collectively, the
694.15 + * "License"). You may not use this file except in compliance with the
694.16 + * License. You can obtain a copy of the License at
694.17 + * http://www.netbeans.org/cddl-gplv2.html
694.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
694.19 + * specific language governing permissions and limitations under the
694.20 + * License. When distributing the software, include this License Header
694.21 + * Notice in each file and include the License file at
694.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
694.23 + * particular file as subject to the "Classpath" exception as provided
694.24 + * by Oracle in the GPL Version 2 section of the License file that
694.25 + * accompanied this code. If applicable, add the following below the
694.26 + * License Header, with the fields enclosed by brackets [] replaced by
694.27 + * your own identifying information:
694.28 + * "Portions Copyrighted [year] [name of copyright owner]"
694.29 + *
694.30 + * Contributor(s):
694.31 + *
694.32 + * The Original Software is NetBeans. The Initial Developer of the Original
694.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
694.34 + * Microsystems, Inc. All Rights Reserved.
694.35 + *
694.36 + * If you wish your version of this file to be governed by only the CDDL
694.37 + * or only the GPL Version 2, indicate your decision by adding
694.38 + * "[Contributor] elects to include this software in this distribution
694.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
694.40 + * single choice of license, a recipient has the option to distribute
694.41 + * your version of this file under either the CDDL, the GPL Version 2 or
694.42 + * to extend the choice of license to its licensees as provided above.
694.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
694.44 + * Version 2 license, then the option applies only if the new code is
694.45 + * made subject to such option by the copyright holder.
694.46 + */
694.47 +
694.48 +package org.netbeans.modules.python.project2.templates;
694.49 +
694.50 +import javax.swing.JPanel;
694.51 +import org.openide.WizardDescriptor;
694.52 +import org.openide.WizardValidationException;
694.53 +
694.54 +/**
694.55 + *
694.56 + * @author Tomas Zezula
694.57 + */
694.58 +abstract class SettingsPanel extends JPanel {
694.59 +
694.60 + abstract void store (WizardDescriptor settings);
694.61 +
694.62 + abstract void read (WizardDescriptor settings);
694.63 +
694.64 + abstract boolean valid (WizardDescriptor settings);
694.65 +
694.66 + abstract void validate (WizardDescriptor settings) throws WizardValidationException;
694.67 +}
695.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
695.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/Bundle.properties Sat Feb 28 17:25:32 2015 -0800
695.3 @@ -0,0 +1,5 @@
695.4 +# To change this license header, choose License Headers in Project Properties.
695.5 +# To change this template file, choose Tools | Templates
695.6 +# and open the template in the editor.
695.7 +
695.8 +MainModuleChooser.jLabel1.text=&Main Modules:
695.9 \ No newline at end of file
696.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
696.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/ChangePackageViewTypeAction.java Sat Feb 28 17:25:32 2015 -0800
696.3 @@ -0,0 +1,101 @@
696.4 +/*
696.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
696.6 + *
696.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
696.8 + *
696.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
696.10 + * Other names may be trademarks of their respective owners.
696.11 + *
696.12 + * The contents of this file are subject to the terms of either the GNU
696.13 + * General Public License Version 2 only ("GPL") or the Common
696.14 + * Development and Distribution License("CDDL") (collectively, the
696.15 + * "License"). You may not use this file except in compliance with the
696.16 + * License. You can obtain a copy of the License at
696.17 + * http://www.netbeans.org/cddl-gplv2.html
696.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
696.19 + * specific language governing permissions and limitations under the
696.20 + * License. When distributing the software, include this License Header
696.21 + * Notice in each file and include the License file at
696.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
696.23 + * particular file as subject to the "Classpath" exception as provided
696.24 + * by Oracle in the GPL Version 2 section of the License file that
696.25 + * accompanied this code. If applicable, add the following below the
696.26 + * License Header, with the fields enclosed by brackets [] replaced by
696.27 + * your own identifying information:
696.28 + * "Portions Copyrighted [year] [name of copyright owner]"
696.29 + *
696.30 + * Contributor(s):
696.31 + *
696.32 + * The Original Software is NetBeans. The Initial Developer of the Original
696.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
696.34 + * Microsystems, Inc. All Rights Reserved.
696.35 + *
696.36 + * If you wish your version of this file to be governed by only the CDDL
696.37 + * or only the GPL Version 2, indicate your decision by adding
696.38 + * "[Contributor] elects to include this software in this distribution
696.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
696.40 + * single choice of license, a recipient has the option to distribute
696.41 + * your version of this file under either the CDDL, the GPL Version 2 or
696.42 + * to extend the choice of license to its licensees as provided above.
696.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
696.44 + * Version 2 license, then the option applies only if the new code is
696.45 + * made subject to such option by the copyright holder.
696.46 + */
696.47 +
696.48 +package org.netbeans.modules.python.project2.ui;
696.49 +
696.50 +import java.awt.event.ActionEvent;
696.51 +import java.awt.event.ActionListener;
696.52 +import javax.swing.AbstractAction;
696.53 +import javax.swing.JMenu;
696.54 +import javax.swing.JMenuItem;
696.55 +import javax.swing.JRadioButtonMenuItem;
696.56 +import org.openide.awt.Mnemonics;
696.57 +import org.openide.util.NbBundle;
696.58 +import org.openide.util.actions.Presenter;
696.59 +import static org.netbeans.modules.python.project2.ui.Bundle.*;
696.60 +
696.61 +/**
696.62 + * Popup menu in Projects tab permitting you to change the package view type.
696.63 + *
696.64 + * <p>
696.65 + * <b>This is copied from the corresponding Java action in java.projects</b>
696.66 + * </p>
696.67 + *
696.68 + * @author Jesse Glick
696.69 + */
696.70 +@NbBundle.Messages({"LBL_change_package_type=&View Python Packages as",
696.71 + "ChangePackageViewTypeAction_list=&List",
696.72 + "ChangePackageViewTypeAction_tree=&Tree"})
696.73 +public final class ChangePackageViewTypeAction extends AbstractAction implements Presenter.Popup {
696.74 +
696.75 + public ChangePackageViewTypeAction() {}
696.76 +
696.77 + @Override
696.78 + public void actionPerformed(ActionEvent e) {
696.79 + assert false : e;
696.80 + }
696.81 +
696.82 + @Override
696.83 + public JMenuItem getPopupPresenter() {
696.84 + JMenu menu = new JMenu();
696.85 + Mnemonics.setLocalizedText(menu, LBL_change_package_type());
696.86 + menu.add(createChoice(PythonProjectSettings.TYPE_PACKAGE_VIEW, ChangePackageViewTypeAction_list()));
696.87 + menu.add(createChoice(PythonProjectSettings.TYPE_TREE, ChangePackageViewTypeAction_tree()));
696.88 + return menu;
696.89 + }
696.90 +
696.91 + private JMenuItem createChoice(final int type, String label) {
696.92 + JRadioButtonMenuItem item = new JRadioButtonMenuItem();
696.93 + Mnemonics.setLocalizedText(item, label);
696.94 + item.setSelected(PythonProjectSettings.getPackageViewType() == type);
696.95 + item.addActionListener(new ActionListener() {
696.96 + @Override
696.97 + public void actionPerformed(ActionEvent e) {
696.98 + PythonProjectSettings.setPackageViewType(type);
696.99 + }
696.100 + });
696.101 + return item;
696.102 + }
696.103 +
696.104 +}
697.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
697.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/MainModuleChooser.form Sat Feb 28 17:25:32 2015 -0800
697.3 @@ -0,0 +1,60 @@
697.4 +<?xml version="1.0" encoding="UTF-8" ?>
697.5 +
697.6 +<Form version="1.5" maxVersion="1.6" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
697.7 + <Properties>
697.8 + <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
697.9 + <Dimension value="[300, 300]"/>
697.10 + </Property>
697.11 + </Properties>
697.12 + <AuxValues>
697.13 + <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="1"/>
697.14 + <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
697.15 + <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
697.16 + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
697.17 + <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="true"/>
697.18 + <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
697.19 + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
697.20 + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
697.21 + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
697.22 + </AuxValues>
697.23 +
697.24 + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/>
697.25 + <SubComponents>
697.26 + <Component class="javax.swing.JLabel" name="jLabel1">
697.27 + <Properties>
697.28 + <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
697.29 + <ComponentRef name="mainModules"/>
697.30 + </Property>
697.31 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
697.32 + <ResourceString bundle="org/netbeans/modules/python/project2/ui/Bundle.properties" key="MainModuleChooser.jLabel1.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
697.33 + </Property>
697.34 + </Properties>
697.35 + <AuxValues>
697.36 + <AuxValue name="generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
697.37 + </AuxValues>
697.38 + <Constraints>
697.39 + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
697.40 + <GridBagConstraints gridX="-1" gridY="-1" gridWidth="0" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="12" insetsLeft="12" insetsBottom="0" insetsRight="12" anchor="18" weightX="1.0" weightY="0.0"/>
697.41 + </Constraint>
697.42 + </Constraints>
697.43 + </Component>
697.44 + <Container class="javax.swing.JScrollPane" name="jScrollPane1">
697.45 + <Constraints>
697.46 + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
697.47 + <GridBagConstraints gridX="-1" gridY="-1" gridWidth="0" gridHeight="0" fill="1" ipadX="0" ipadY="0" insetsTop="12" insetsLeft="12" insetsBottom="12" insetsRight="12" anchor="10" weightX="1.0" weightY="1.0"/>
697.48 + </Constraint>
697.49 + </Constraints>
697.50 +
697.51 + <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
697.52 + <SubComponents>
697.53 + <Component class="javax.swing.JList" name="mainModules">
697.54 + <Properties>
697.55 + <Property name="model" type="javax.swing.ListModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
697.56 + <Connection code="new DefaultListModel()" type="code"/>
697.57 + </Property>
697.58 + </Properties>
697.59 + </Component>
697.60 + </SubComponents>
697.61 + </Container>
697.62 + </SubComponents>
697.63 +</Form>
698.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
698.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/MainModuleChooser.java Sat Feb 28 17:25:32 2015 -0800
698.3 @@ -0,0 +1,137 @@
698.4 +/*
698.5 + * MainClassChooser.java
698.6 + *
698.7 + * Created on August 22, 2008, 6:07 PM
698.8 + */
698.9 +
698.10 +package org.netbeans.modules.python.project2.ui;
698.11 +
698.12 +import java.util.Enumeration;
698.13 +import java.util.LinkedList;
698.14 +import java.util.List;
698.15 +import javax.swing.DefaultListModel;
698.16 +import javax.swing.JButton;
698.17 +import javax.swing.SwingUtilities;
698.18 +import org.netbeans.api.project.ProjectUtils;
698.19 +import org.netbeans.api.project.SourceGroup;
698.20 +import org.netbeans.api.project.Sources;
698.21 +import org.netbeans.modules.python.api.PythonMIMEResolver;
698.22 +import org.netbeans.modules.python.project2.PythonProject2;
698.23 +import org.openide.filesystems.FileObject;
698.24 +import org.openide.filesystems.FileUtil;
698.25 +import org.openide.util.NbBundle;
698.26 +import org.openide.util.RequestProcessor;
698.27 +
698.28 +/**
698.29 + *
698.30 + * @author Tomas Zezula
698.31 + */
698.32 +@NbBundle.Messages({"TXT_PleaseWait=Please Wait..."})
698.33 +final class MainModuleChooser extends javax.swing.JPanel {
698.34 +
698.35 + private final PythonProject2 project;
698.36 + private final JButton okButton;
698.37 + private final static RequestProcessor RP = new RequestProcessor("MainModuleChooser"); //NOI18N
698.38 +
698.39 + /** Creates new form MainClassChooser */
698.40 + MainModuleChooser (final PythonProject2 project, final JButton okButton) {
698.41 + assert project != null;
698.42 + assert okButton != null;
698.43 + initComponents();
698.44 + this.project = project;
698.45 + this.okButton = okButton;
698.46 + this.okButton.setEnabled(false);
698.47 + ((DefaultListModel)this.mainModules.getModel()).addElement(NbBundle.getMessage(MainModuleChooser.class, "TXT_PleaseWait"));
698.48 + RP.post(new Runnable() {
698.49 + @Override
698.50 + public void run() {
698.51 + initData();
698.52 + }
698.53 + });
698.54 + }
698.55 +
698.56 + public String getMainModule () {
698.57 + return (String) mainModules.getSelectedValue();
698.58 + }
698.59 +
698.60 +
698.61 + private void initData () {
698.62 + final List<String> data = new LinkedList<>();
698.63 + Sources sources = ProjectUtils.getSources(project);
698.64 + for (SourceGroup sourceGroup : sources.getSourceGroups(PythonProject2.SOURCES_TYPE_PYTHON)) {
698.65 + final Enumeration<? extends FileObject> fos = sourceGroup.getRootFolder().getChildren(true);
698.66 + while (fos.hasMoreElements()) {
698.67 + final FileObject fo = fos.nextElement();
698.68 + if (isPython (fo)) {
698.69 + data.add(FileUtil.getRelativePath(sourceGroup.getRootFolder(), fo));
698.70 + }
698.71 + }
698.72 + }
698.73 + SwingUtilities.invokeLater(new Runnable() {
698.74 + @Override
698.75 + public void run() {
698.76 + DefaultListModel lm = (DefaultListModel)mainModules.getModel();
698.77 + lm.clear();
698.78 + for (String s : data) {
698.79 + lm.addElement(s);
698.80 + }
698.81 + okButton.setEnabled(true);
698.82 + }
698.83 + });
698.84 + }
698.85 +
698.86 + private static boolean isPython (final FileObject fo) {
698.87 + if (fo.isFolder() || !fo.isValid() || fo.isVirtual()) {
698.88 + return false;
698.89 + }
698.90 + return PythonMIMEResolver.PYTHON_MIME_TYPE.equals(FileUtil.getMIMEType(fo));
698.91 + }
698.92 +
698.93 + /** This method is called from within the constructor to
698.94 + * initialize the form.
698.95 + * WARNING: Do NOT modify this code. The content of this method is
698.96 + * always regenerated by the Form Editor.
698.97 + */
698.98 + @SuppressWarnings("unchecked")
698.99 + // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
698.100 + private void initComponents() {
698.101 + java.awt.GridBagConstraints gridBagConstraints;
698.102 +
698.103 + jLabel1 = new javax.swing.JLabel();
698.104 + jScrollPane1 = new javax.swing.JScrollPane();
698.105 + mainModules = new javax.swing.JList();
698.106 +
698.107 + setPreferredSize(new java.awt.Dimension(300, 300));
698.108 + setLayout(new java.awt.GridBagLayout());
698.109 +
698.110 + jLabel1.setLabelFor(mainModules);
698.111 + org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(MainModuleChooser.class, "MainModuleChooser.jLabel1.text")); // NOI18N
698.112 + gridBagConstraints = new java.awt.GridBagConstraints();
698.113 + gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
698.114 + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
698.115 + gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
698.116 + gridBagConstraints.weightx = 1.0;
698.117 + gridBagConstraints.insets = new java.awt.Insets(12, 12, 0, 12);
698.118 + add(jLabel1, gridBagConstraints);
698.119 +
698.120 + mainModules.setModel(new DefaultListModel());
698.121 + jScrollPane1.setViewportView(mainModules);
698.122 +
698.123 + gridBagConstraints = new java.awt.GridBagConstraints();
698.124 + gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
698.125 + gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER;
698.126 + gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
698.127 + gridBagConstraints.weightx = 1.0;
698.128 + gridBagConstraints.weighty = 1.0;
698.129 + gridBagConstraints.insets = new java.awt.Insets(12, 12, 12, 12);
698.130 + add(jScrollPane1, gridBagConstraints);
698.131 + }// </editor-fold>//GEN-END:initComponents
698.132 +
698.133 +
698.134 + // Variables declaration - do not modify//GEN-BEGIN:variables
698.135 + private javax.swing.JLabel jLabel1;
698.136 + private javax.swing.JScrollPane jScrollPane1;
698.137 + private javax.swing.JList mainModules;
698.138 + // End of variables declaration//GEN-END:variables
698.139 +
698.140 +}
699.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
699.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/PackageDisplayUtils.java Sat Feb 28 17:25:32 2015 -0800
699.3 @@ -0,0 +1,222 @@
699.4 +/*
699.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
699.6 + *
699.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
699.8 + *
699.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
699.10 + * Other names may be trademarks of their respective owners.
699.11 + *
699.12 + * The contents of this file are subject to the terms of either the GNU
699.13 + * General Public License Version 2 only ("GPL") or the Common
699.14 + * Development and Distribution License("CDDL") (collectively, the
699.15 + * "License"). You may not use this file except in compliance with the
699.16 + * License. You can obtain a copy of the License at
699.17 + * http://www.netbeans.org/cddl-gplv2.html
699.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
699.19 + * specific language governing permissions and limitations under the
699.20 + * License. When distributing the software, include this License Header
699.21 + * Notice in each file and include the License file at
699.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
699.23 + * particular file as subject to the "Classpath" exception as provided
699.24 + * by Oracle in the GPL Version 2 section of the License file that
699.25 + * accompanied this code. If applicable, add the following below the
699.26 + * License Header, with the fields enclosed by brackets [] replaced by
699.27 + * your own identifying information:
699.28 + * "Portions Copyrighted [year] [name of copyright owner]"
699.29 + *
699.30 + * Contributor(s):
699.31 + *
699.32 + * The Original Software is NetBeans. The Initial Developer of the Original
699.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
699.34 + * Microsystems, Inc. All Rights Reserved.
699.35 + *
699.36 + * If you wish your version of this file to be governed by only the CDDL
699.37 + * or only the GPL Version 2, indicate your decision by adding
699.38 + * "[Contributor] elects to include this software in this distribution
699.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
699.40 + * single choice of license, a recipient has the option to distribute
699.41 + * your version of this file under either the CDDL, the GPL Version 2 or
699.42 + * to extend the choice of license to its licensees as provided above.
699.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
699.44 + * Version 2 license, then the option applies only if the new code is
699.45 + * made subject to such option by the copyright holder.
699.46 + */
699.47 +
699.48 +package org.netbeans.modules.python.project2.ui;
699.49 +
699.50 +import java.awt.Image;
699.51 +//import org.netbeans.api.java.queries.AccessibilityQuery;
699.52 +import org.netbeans.api.queries.VisibilityQuery;
699.53 +import org.openide.filesystems.FileObject;
699.54 +import org.openide.util.ImageUtilities;
699.55 +import org.openide.util.NbBundle;
699.56 +
699.57 +// XXX needs unit test
699.58 +
699.59 +/**
699.60 + * Provides display name and icon utilities for
699.61 + * {@link PackageViewChildren.PackageNode} and {@link PackageListView.PackageItem}.
699.62 + *
699.63 + * <p>
699.64 + * <b>This is copied from the corresponding Java action in java.projects</b>
699.65 + * </p>
699.66 + *
699.67 + *
699.68 + * @author Jesse Glick
699.69 + */
699.70 +@NbBundle.Messages({"#LBL_DefaultPackage=<default package>",
699.71 + "LBL_DefaultPackage=<Top Level>",
699.72 + "# {0} - full package name",
699.73 + "LBL_package= PythonPackage ({0})",
699.74 + "# {0} - full package name",
699.75 + "LBL_public_package=Exported Python Source Package ({0})",
699.76 + "# {0} - full package name",
699.77 + "LBL_private_package=Private Python Source Package ({0})"})
699.78 +public final class PackageDisplayUtils {
699.79 +
699.80 + private PackageDisplayUtils() {}
699.81 +
699.82 + private static final Image PACKAGE = ImageUtilities.loadImage("org/netbeans/modules/python/project2/resources/package.gif"); // NOI18N
699.83 + private static final Image PACKAGE_EMPTY = ImageUtilities.loadImage("org/netbeans/modules/python/project2/resources/packageEmpty.gif"); // NOI18N
699.84 + private static final Image PACKAGE_PRIVATE = ImageUtilities.loadImage("org/netbeans/modules/python/project2/resources/packagePrivate.gif"); // NOI18N
699.85 + private static final Image PACKAGE_PUBLIC = ImageUtilities.loadImage("org/netbeans/modules/python/project2/resources/packagePublic.gif"); // NOI18N
699.86 +
699.87 + /**
699.88 + * Find the proper display label for a package.
699.89 + * @param pkg the actual folder
699.90 + * @param pkgname the dot-separated package name (<code>""</code> for default package)
699.91 + * @return an appropriate display label for it
699.92 + */
699.93 + public static String getDisplayLabel(String pkgname) {
699.94 + return computePackageName(pkgname);
699.95 + }
699.96 +
699.97 + /**
699.98 + * Find the proper tool tip for a package.
699.99 + * May have more info than the display label.
699.100 + * @param pkg the actual folder
699.101 + * @param pkgname the dot-separated package name (<code>""</code> for default package)
699.102 + * @return an appropriate display label for it
699.103 + */
699.104 + public static String getToolTip(FileObject pkg, String pkgname) {
699.105 + String pkglabel = computePackageName(pkgname);
699.106 +// Boolean b = AccessibilityQuery.isPubliclyAccessible(pkg);
699.107 +// if (b != null) {
699.108 +// if (b.booleanValue()) {
699.109 +// return NbBundle.getMessage(PackageDisplayUtils.class, "LBL_public_package", pkglabel);
699.110 +// } else {
699.111 +// return NbBundle.getMessage(PackageDisplayUtils.class, "LBL_private_package", pkglabel);
699.112 +// }
699.113 +// } else {
699.114 + return NbBundle.getMessage(PackageDisplayUtils.class, "LBL_package", pkglabel);
699.115 +// }
699.116 + }
699.117 +
699.118 + /**
699.119 + * Get package name.
699.120 + * Handles default package specially.
699.121 + */
699.122 + private static String computePackageName(String pkgname) {
699.123 + if (pkgname.length() == 0) {
699.124 + return NbBundle.getMessage(PackageDisplayUtils.class, "LBL_DefaultPackage"); // NOI18N
699.125 + } else {
699.126 + return pkgname;
699.127 + }
699.128 + }
699.129 +
699.130 +
699.131 +
699.132 + /**
699.133 + * Find the proper display icon for a package.
699.134 + * @param pkg the actual folder
699.135 + * @param pkgname the dot-separated package name (<code>""</code> for default package)
699.136 + * @return an appropriate display icon for it
699.137 + */
699.138 + public static Image getIcon(FileObject pkg, String pkgname) {
699.139 + return getIcon( pkg, pkgname, isEmpty(pkg) );
699.140 + }
699.141 +
699.142 + /** Performance optimization if the the isEmpty status is already known.
699.143 + *
699.144 + */
699.145 + public static Image getIcon(FileObject pkg, String pkgname, boolean empty ) {
699.146 + if ( empty ) {
699.147 + return PACKAGE_EMPTY;
699.148 + } else {
699.149 +// Boolean b = pkg.isValid() ? AccessibilityQuery.isPubliclyAccessible(pkg) : null;
699.150 +// if (b != null) {
699.151 +// if (b.booleanValue()) {
699.152 +// return PACKAGE_PUBLIC;
699.153 +// } else {
699.154 +// return PACKAGE_PRIVATE;
699.155 +// }
699.156 +// } else {
699.157 + return PACKAGE;
699.158 +// }
699.159 + }
699.160 + }
699.161 +
699.162 +
699.163 + /**
699.164 + * Check whether a package is empty (devoid of files except for subpackages).
699.165 + */
699.166 + public static boolean isEmpty( FileObject fo ) {
699.167 + return isEmpty (fo, true, false );
699.168 + }
699.169 +
699.170 + /**
699.171 + * Check whether a package is empty (devoid of files except for subpackages).
699.172 + * @param recurse specifies whether to check if subpackages are empty too.
699.173 + * @param initIsEmpty If true, don't consider __init__.py presence
699.174 + */
699.175 + public static boolean isEmpty( FileObject fo, boolean recurse, boolean initIsEmpty ) {
699.176 + FileObject[] kids = fo.getChildren();
699.177 + for( int i = 0; i < kids.length; i++ ) {
699.178 + final FileObject kid = kids[i];
699.179 + // Package init files don't count unless they have contents (or are pyc files)
699.180 + if (initIsEmpty && kid.getName().equals("__init__")) { // NOI18N
699.181 + if ("pyc".equals(kid.getExt()) || "pyo".equals(kid.getExt()) || kid.getSize() == 0) { // NOI18N
699.182 + continue;
699.183 + }
699.184 + }
699.185 + // XXX consider using group.contains() here
699.186 + if ( !kid.isFolder() && VisibilityQuery.getDefault().isVisible( kid) ) {
699.187 + return false;
699.188 + }
699.189 + else if (recurse && VisibilityQuery.getDefault().isVisible( kid) && !isEmpty(kid)) {
699.190 + return false;
699.191 + }
699.192 + }
699.193 + return true;
699.194 + }
699.195 +
699.196 + /**
699.197 + * Check whether a package should be displayed.
699.198 + * It should be displayed if {@link VisibilityQuery} says it should be,
699.199 + * and it is either completely empty, or contains files (as opposed to
699.200 + * containing some subpackages but no files).
699.201 + */
699.202 +// public static boolean isSignificant(FileObject pkg) throws IllegalArgumentException {
699.203 +// if (!pkg.isFolder()) {
699.204 +// throw new IllegalArgumentException("Not a folder"); // NOI18N
699.205 +// }
699.206 +// // XXX consider using group.contains() here
699.207 +// if (!VisibilityQuery.getDefault().isVisible(pkg)) {
699.208 +// return false;
699.209 +// }
699.210 +// FileObject[] kids = pkg.getChildren();
699.211 +// boolean subpackages = false;
699.212 +// for (int i = 0; i < kids.length; i++) {
699.213 +// if (!VisibilityQuery.getDefault().isVisible(kids[i])) {
699.214 +// continue;
699.215 +// }
699.216 +// if (kids[i].isData()) {
699.217 +// return true;
699.218 +// } else {
699.219 +// subpackages = true;
699.220 +// }
699.221 +// }
699.222 +// return !subpackages;
699.223 +// }
699.224 +
699.225 +}
700.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
700.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/PackageRootNode.java Sat Feb 28 17:25:32 2015 -0800
700.3 @@ -0,0 +1,447 @@
700.4 +/*
700.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
700.6 + *
700.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
700.8 + *
700.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
700.10 + * Other names may be trademarks of their respective owners.
700.11 + *
700.12 + * The contents of this file are subject to the terms of either the GNU
700.13 + * General Public License Version 2 only ("GPL") or the Common
700.14 + * Development and Distribution License("CDDL") (collectively, the
700.15 + * "License"). You may not use this file except in compliance with the
700.16 + * License. You can obtain a copy of the License at
700.17 + * http://www.netbeans.org/cddl-gplv2.html
700.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
700.19 + * specific language governing permissions and limitations under the
700.20 + * License. When distributing the software, include this License Header
700.21 + * Notice in each file and include the License file at
700.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
700.23 + * particular file as subject to the "Classpath" exception as provided
700.24 + * by Oracle in the GPL Version 2 section of the License file that
700.25 + * accompanied this code. If applicable, add the following below the
700.26 + * License Header, with the fields enclosed by brackets [] replaced by
700.27 + * your own identifying information:
700.28 + * "Portions Copyrighted [year] [name of copyright owner]"
700.29 + *
700.30 + * Contributor(s):
700.31 + *
700.32 + * The Original Software is NetBeans. The Initial Developer of the Original
700.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
700.34 + * Microsystems, Inc. All Rights Reserved.
700.35 + *
700.36 + * If you wish your version of this file to be governed by only the CDDL
700.37 + * or only the GPL Version 2, indicate your decision by adding
700.38 + * "[Contributor] elects to include this software in this distribution
700.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
700.40 + * single choice of license, a recipient has the option to distribute
700.41 + * your version of this file under either the CDDL, the GPL Version 2 or
700.42 + * to extend the choice of license to its licensees as provided above.
700.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
700.44 + * Version 2 license, then the option applies only if the new code is
700.45 + * made subject to such option by the copyright holder.
700.46 + */
700.47 +
700.48 +package org.netbeans.modules.python.project2.ui;
700.49 +
700.50 +import java.awt.Image;
700.51 +import java.awt.datatransfer.DataFlavor;
700.52 +import java.awt.datatransfer.Transferable;
700.53 +import java.awt.datatransfer.UnsupportedFlavorException;
700.54 +import java.io.IOException;
700.55 +import java.util.ArrayList;
700.56 +import java.util.Arrays;
700.57 +import java.util.Collections;
700.58 +import java.util.Iterator;
700.59 +import java.util.List;
700.60 +import java.util.Set;
700.61 +import javax.swing.Action;
700.62 +import javax.swing.Icon;
700.63 +import org.netbeans.api.project.SourceGroup;
700.64 +import org.netbeans.spi.project.ui.support.CommonProjectActions;
700.65 +import org.openide.ErrorManager;
700.66 +import org.openide.actions.FileSystemAction;
700.67 +import org.openide.actions.FindAction;
700.68 +import org.openide.actions.PasteAction;
700.69 +import org.openide.actions.ToolsAction;
700.70 +import org.openide.filesystems.FileObject;
700.71 +import org.openide.filesystems.FileStateInvalidException;
700.72 +import org.openide.filesystems.FileStatusEvent;
700.73 +import org.openide.filesystems.FileStatusListener;
700.74 +import org.openide.filesystems.FileSystem;
700.75 +import org.openide.filesystems.FileUtil;
700.76 +import org.openide.filesystems.StatusDecorator;
700.77 +import org.openide.loaders.DataFolder;
700.78 +import org.openide.loaders.DataObject;
700.79 +import org.openide.nodes.AbstractNode;
700.80 +import org.openide.nodes.Children;
700.81 +import org.openide.nodes.Node;
700.82 +import org.openide.nodes.Node.PropertySet;
700.83 +import org.openide.nodes.NodeNotFoundException;
700.84 +import org.openide.nodes.NodeOp;
700.85 +import org.openide.nodes.PropertySupport;
700.86 +import org.openide.nodes.Sheet;
700.87 +import org.openide.util.ImageUtilities;
700.88 +import org.openide.util.Lookup;
700.89 +import org.openide.util.NbBundle;
700.90 +import org.openide.util.RequestProcessor;
700.91 +import org.openide.util.actions.SystemAction;
700.92 +import org.openide.util.datatransfer.ExTransferable;
700.93 +import org.openide.util.datatransfer.MultiTransferObject;
700.94 +import org.openide.util.datatransfer.PasteType;
700.95 +import org.openide.util.lookup.AbstractLookup;
700.96 +import org.openide.util.lookup.InstanceContent;
700.97 +import org.openide.util.lookup.Lookups;
700.98 +import org.openide.util.lookup.ProxyLookup;
700.99 +//import org.openidex.search.SearchInfo;
700.100 +//import org.openidex.search.SearchInfoFactory;
700.101 +
700.102 +/** Node displaying a packages in given SourceGroup
700.103 + *
700.104 + * <p>
700.105 + * <b>This is copied from the corresponding Java action in java.projects</b>
700.106 + * </p>
700.107 + *
700.108 + * @author Petr Hrebejk
700.109 + */
700.110 +final class PackageRootNode extends AbstractNode implements Runnable, FileStatusListener {
700.111 +
700.112 + static Image PACKAGE_BADGE = ImageUtilities.loadImage("org/netbeans/modules/python/project2/resources/packageBadge.gif"); // NOI18N
700.113 +
700.114 + private static Action actions[];
700.115 +
700.116 + private SourceGroup group;
700.117 +
700.118 + private final FileObject file;
700.119 + private final Set<FileObject> files;
700.120 + private FileStatusListener fileSystemListener;
700.121 + private static final RequestProcessor RP = new RequestProcessor(PackageRootNode.class);
700.122 + private RequestProcessor.Task task;
700.123 + private volatile boolean iconChange;
700.124 + private volatile boolean nameChange;
700.125 +
700.126 + PackageRootNode( SourceGroup group ) {
700.127 + this( group, new InstanceContent() );
700.128 + }
700.129 +
700.130 + private PackageRootNode( SourceGroup group, InstanceContent ic ) {
700.131 + super( new PackageViewChildren(group),
700.132 + new ProxyLookup(createLookup(group), new AbstractLookup(ic)));
700.133 +// ic.add(alwaysSearchableSearchInfo(SearchInfoFactory.createSearchInfoBySubnodes(this)));
700.134 + this.group = group;
700.135 + file = group.getRootFolder();
700.136 + files = Collections.singleton(file);
700.137 + try {
700.138 + FileSystem fs = file.getFileSystem();
700.139 + fileSystemListener = FileUtil.weakFileStatusListener(this, fs);
700.140 + fs.addFileStatusListener(fileSystemListener);
700.141 + } catch (FileStateInvalidException e) {
700.142 + ErrorManager err = ErrorManager.getDefault();
700.143 + err.annotate(e, "Can not get " + file + " filesystem, ignoring..."); // NO18N
700.144 + err.notify(ErrorManager.INFORMATIONAL, e);
700.145 + }
700.146 + setName( group.getName() );
700.147 + setDisplayName( group.getDisplayName() );
700.148 + // setIconBase("org/netbeans/modules/java/j2seproject/ui/resources/packageRoot");
700.149 + }
700.150 +
700.151 + public @Override Image getIcon(int type) {
700.152 + return computeIcon( false, type );
700.153 + }
700.154 +
700.155 + public @Override Image getOpenedIcon(int type) {
700.156 + return computeIcon( true, type );
700.157 + }
700.158 +
700.159 + public @Override String getDisplayName() {
700.160 + String s = super.getDisplayName ();
700.161 +
700.162 + try {
700.163 + s = file.getFileSystem ().getDecorator ().annotateName (s, files);
700.164 + } catch (FileStateInvalidException e) {
700.165 + ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
700.166 + }
700.167 +
700.168 + return s;
700.169 + }
700.170 +
700.171 + public @Override String getHtmlDisplayName() {
700.172 + try {
700.173 + StatusDecorator stat = file.getFileSystem().getDecorator();
700.174 +
700.175 + String result = stat.annotateNameHtml (
700.176 + super.getDisplayName(), files);
700.177 +
700.178 + //Make sure the super string was really modified
700.179 + if (result != null && !super.getDisplayName().equals(result)) {
700.180 + return result;
700.181 + }
700.182 + } catch (FileStateInvalidException e) {
700.183 + ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
700.184 + }
700.185 + return super.getHtmlDisplayName();
700.186 + }
700.187 +
700.188 + @Override
700.189 + public void run() {
700.190 + if (iconChange) {
700.191 + fireIconChange();
700.192 + fireOpenedIconChange();
700.193 + iconChange = false;
700.194 + }
700.195 + if (nameChange) {
700.196 + fireDisplayNameChange(null, null);
700.197 + nameChange = false;
700.198 + }
700.199 + }
700.200 +
700.201 + @Override
700.202 + public void annotationChanged(FileStatusEvent event) {
700.203 + if (task == null) {
700.204 + task = RP.create(this);
700.205 + }
700.206 +
700.207 + if ((iconChange == false && event.isIconChange()) || (nameChange == false && event.isNameChange())) {
700.208 + if (event.hasChanged(file)) {
700.209 + iconChange |= event.isIconChange();
700.210 + nameChange |= event.isNameChange();
700.211 + }
700.212 + }
700.213 +
700.214 + task.schedule(50); // batch by 50 ms
700.215 + }
700.216 +
700.217 + public @Override Action[] getActions(boolean context) {
700.218 + if ( actions == null ) {
700.219 + actions = new Action[] {
700.220 + CommonProjectActions.newFileAction(),
700.221 + null,
700.222 + SystemAction.get( FileSystemAction.class ),
700.223 + null,
700.224 + SystemAction.get( FindAction.class ),
700.225 + null,
700.226 + SystemAction.get( PasteAction.class ),
700.227 + null,
700.228 + SystemAction.get( ToolsAction.class ),
700.229 + };
700.230 + }
700.231 + return actions;
700.232 + }
700.233 +
700.234 + // Show reasonable properties of the DataFolder,
700.235 + //it shows the sorting names as rw property, the name as ro property and the path to root as ro property
700.236 + public @Override PropertySet[] getPropertySets() {
700.237 + PropertySet[] properties = getDataFolderNodeDelegate().getPropertySets();
700.238 + for (int i=0; i< properties.length; i++) {
700.239 + if (Sheet.PROPERTIES.equals(properties[i].getName())) {
700.240 + //Replace the Sheet.PROPERTIES by the new one
700.241 + //having the ro name property and ro path property
700.242 + properties[i] = Sheet.createPropertiesSet();
700.243 + ((Sheet.Set) properties[i]).put(new PropertySupport.ReadOnly<String>(DataObject.PROP_NAME, String.class,
700.244 + NbBundle.getMessage(PackageRootNode.class,"PROP_name"), NbBundle.getMessage(PackageRootNode.class,"HINT_name")) {
700.245 + @Override
700.246 + public String getValue() {
700.247 + return PackageRootNode.this.getDisplayName();
700.248 + }
700.249 + });
700.250 + ((Sheet.Set) properties[i]).put(new PropertySupport.ReadOnly<String>("ROOT_PATH", String.class, //NOI18N
700.251 +NbBundle.getMessage(PackageRootNode.class,"PROP_rootpath"), NbBundle.getMessage(PackageRootNode.class,"HINT_rootpath")) {
700.252 + @Override
700.253 + public String getValue() {
700.254 + return FileUtil.getFileDisplayName(PackageRootNode.this.file);
700.255 + }
700.256 + });
700.257 + }
700.258 + }
700.259 + return properties;
700.260 + }
700.261 +
700.262 + // XXX Paste types - probably not very nice
700.263 + public @Override void createPasteTypes(Transferable t, List<PasteType> list) {
700.264 + if (t.isDataFlavorSupported(ExTransferable.multiFlavor)) {
700.265 + try {
700.266 + MultiTransferObject mto = (MultiTransferObject) t.getTransferData(ExTransferable.multiFlavor);
700.267 + List<PackageViewChildren.PackageNode> l = new ArrayList<>();
700.268 + boolean isPackageFlavor = false;
700.269 + boolean hasTheSameRoot = false;
700.270 + int op = -1;
700.271 + for (int i=0; i < mto.getCount(); i++) {
700.272 + Transferable pt = mto.getTransferableAt(i);
700.273 + DataFlavor[] flavors = mto.getTransferDataFlavors(i);
700.274 + for (int j=0; j< flavors.length; j++) {
700.275 + if (PackageViewChildren.SUBTYPE.equals(flavors[j].getSubType ()) &&
700.276 + PackageViewChildren.PRIMARY_TYPE.equals(flavors[j].getPrimaryType ())) {
700.277 + if (op == -1) {
700.278 + op = Integer.valueOf (flavors[j].getParameter (PackageViewChildren.MASK)).intValue ();
700.279 + }
700.280 + PackageViewChildren.PackageNode pkgNode = (PackageViewChildren.PackageNode) pt.getTransferData(flavors[j]);
700.281 + if ( !((PackageViewChildren)getChildren()).getRoot().equals( pkgNode.getRoot() ) ) {
700.282 + l.add(pkgNode);
700.283 + }
700.284 + else {
700.285 + hasTheSameRoot = true;
700.286 + }
700.287 + isPackageFlavor = true;
700.288 + }
700.289 + }
700.290 + }
700.291 + if (isPackageFlavor && !hasTheSameRoot) {
700.292 + list.add(new PackageViewChildren.PackagePasteType(this.group.getRootFolder(),
700.293 + l.toArray(new PackageViewChildren.PackageNode[l.size()]),
700.294 + op));
700.295 + }
700.296 + else if (!isPackageFlavor) {
700.297 + list.addAll( Arrays.asList( getDataFolderNodeDelegate().getPasteTypes( t ) ) );
700.298 + }
700.299 + } catch (UnsupportedFlavorException | IOException e) {
700.300 + ErrorManager.getDefault().notify(e);
700.301 + }
700.302 + }
700.303 + else {
700.304 + DataFlavor[] flavors = t.getTransferDataFlavors();
700.305 + FileObject root = this.group.getRootFolder();
700.306 + boolean isPackageFlavor = false;
700.307 + if (root!= null && root.canWrite()) {
700.308 + for (DataFlavor flavor : flavors) {
700.309 + if (PackageViewChildren.SUBTYPE.equals(flavor.getSubType ()) &&
700.310 + PackageViewChildren.PRIMARY_TYPE.equals(flavor.getPrimaryType ())) {
700.311 + isPackageFlavor = true;
700.312 + try {
700.313 + int op = Integer.parseInt(flavor.getParameter(PackageViewChildren.MASK));
700.314 + PackageViewChildren.PackageNode pkgNode = (PackageViewChildren.PackageNode) t.getTransferData(flavor);
700.315 + if ( !((PackageViewChildren)getChildren()).getRoot().equals( pkgNode.getRoot() ) ) {
700.316 + list.add(new PackageViewChildren.PackagePasteType (root, new PackageViewChildren.PackageNode[] {pkgNode}, op));
700.317 + }
700.318 + } catch (IOException | UnsupportedFlavorException ioe) {
700.319 + ErrorManager.getDefault().notify(ioe);
700.320 + }
700.321 + }
700.322 + }
700.323 + }
700.324 + if (!isPackageFlavor) {
700.325 + list.addAll( Arrays.asList( getDataFolderNodeDelegate().getPasteTypes( t ) ) );
700.326 + }
700.327 + }
700.328 + }
700.329 +
700.330 + @Override
700.331 + public PasteType getDropType(Transferable t, int action, int index) {
700.332 + PasteType pasteType = super.getDropType(t, action, index);
700.333 + //The pasteType can be:
700.334 + // 1) PackagePasteType - the t.flavor is package flavor
700.335 + // 2) null or DataPasteType - the t.flavor in not package flavor
700.336 + if (pasteType instanceof PackageViewChildren.PackagePasteType) {
700.337 + ((PackageViewChildren.PackagePasteType)pasteType).setOperation (action);
700.338 + }
700.339 + return pasteType;
700.340 + }
700.341 +
700.342 + // Private methods ---------------------------------------------------------
700.343 +
700.344 + private Node getDataFolderNodeDelegate() {
700.345 + DataFolder df = getLookup().lookup(DataFolder.class);
700.346 + try {
700.347 + if (df.isValid()) {
700.348 + return df.getNodeDelegate();
700.349 + }
700.350 + } catch (IllegalStateException e) {
700.351 + //The data systems API is not thread save,
700.352 + //the DataObject may become invalid after isValid call and before
700.353 + //getNodeDelegate call, we have to catch the ISE. When the DataObject
700.354 + //is valid - other cause rethrow it otherwise return leaf node.
700.355 + //todo: The DataObject.getNodedelegate should throw specialized exception type.
700.356 + if (df.isValid()) {
700.357 + throw e;
700.358 + }
700.359 + }
700.360 + return new AbstractNode(Children.LEAF);
700.361 + }
700.362 +
700.363 + private Image computeIcon( boolean opened, int type ) {
700.364 + Image image;
700.365 + Icon icon = group.getIcon( opened );
700.366 +
700.367 + if ( icon == null ) {
700.368 + image = opened ? getDataFolderNodeDelegate().getOpenedIcon( type ) :
700.369 + getDataFolderNodeDelegate().getIcon( type );
700.370 + image = ImageUtilities.mergeImages(image, PACKAGE_BADGE, 7, 7);
700.371 + }
700.372 + else {
700.373 + image = ImageUtilities.icon2Image(icon);
700.374 + }
700.375 +
700.376 + return image;
700.377 + }
700.378 +
700.379 + private static Lookup createLookup( SourceGroup group ) {
700.380 + // XXX Remove DataFolder when paste, find and refresh are reimplemented
700.381 + FileObject rootFolder = group.getRootFolder();
700.382 + DataFolder dataFolder = DataFolder.findFolder( rootFolder );
700.383 + return Lookups.fixed(dataFolder, new PathFinder(group));
700.384 + }
700.385 +
700.386 + /** If contained in the lookup can perform the search for a node
700.387 + */
700.388 + public static class PathFinder {
700.389 +
700.390 + private SourceGroup group;
700.391 +
700.392 + public PathFinder( SourceGroup group ) {
700.393 + this.group = group;
700.394 + }
700.395 +
700.396 + public Node findPath( Node root, Object object ) {
700.397 + FileObject fo;
700.398 + if (object instanceof FileObject) {
700.399 + fo = (FileObject) object;
700.400 + } else if (object instanceof DataObject) {
700.401 + fo = ((DataObject) object).getPrimaryFile();
700.402 + } else {
700.403 + return null;
700.404 + }
700.405 +
700.406 + FileObject groupRoot = group.getRootFolder();
700.407 + if ( FileUtil.isParentOf( groupRoot, fo ) /* && group.contains( fo ) */ ) {
700.408 + // The group contains the object
700.409 +
700.410 + String relPath = FileUtil.getRelativePath( groupRoot, fo.isFolder() ? fo : fo.getParent() );
700.411 +
700.412 + String[] path = new String[] { relPath.replace( '/', '.' ) };
700.413 + try {
700.414 + Node packageNode = NodeOp.findPath( root, path );
700.415 + if (fo.isFolder()) {
700.416 + return packageNode;
700.417 + } else {
700.418 + for (Node child : packageNode.getChildren().getNodes(true)) {
700.419 + DataObject dobj = child.getLookup().lookup(DataObject.class);
700.420 + if (dobj != null && dobj.getPrimaryFile().getNameExt().equals(fo.getNameExt())) {
700.421 + return child;
700.422 + }
700.423 + }
700.424 + }
700.425 + }
700.426 + catch ( NodeNotFoundException e ) {
700.427 + // did not manage to find it after all... why?
700.428 + return null;
700.429 + }
700.430 + }
700.431 + else if ( groupRoot.equals( fo ) ) {
700.432 + // First try to find default package
700.433 + try {
700.434 + return NodeOp.findPath( root, new String[] { "" } ); // NOI18N
700.435 + }
700.436 + catch ( NodeNotFoundException e ) {
700.437 + // If it does not exists return this node
700.438 + }
700.439 + return root;
700.440 + }
700.441 +
700.442 + return null;
700.443 + }
700.444 +
700.445 + public @Override String toString() {
700.446 + return "PathFinder[" + group + "]"; // NOI18N
700.447 + }
700.448 +
700.449 + }
700.450 +}
701.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
701.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/PackageView.java Sat Feb 28 17:25:32 2015 -0800
701.3 @@ -0,0 +1,403 @@
701.4 +/*
701.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
701.6 + *
701.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
701.8 + *
701.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
701.10 + * Other names may be trademarks of their respective owners.
701.11 + *
701.12 + * The contents of this file are subject to the terms of either the GNU
701.13 + * General Public License Version 2 only ("GPL") or the Common
701.14 + * Development and Distribution License("CDDL") (collectively, the
701.15 + * "License"). You may not use this file except in compliance with the
701.16 + * License. You can obtain a copy of the License at
701.17 + * http://www.netbeans.org/cddl-gplv2.html
701.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
701.19 + * specific language governing permissions and limitations under the
701.20 + * License. When distributing the software, include this License Header
701.21 + * Notice in each file and include the License file at
701.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
701.23 + * particular file as subject to the "Classpath" exception as provided
701.24 + * by Oracle in the GPL Version 2 section of the License file that
701.25 + * accompanied this code. If applicable, add the following below the
701.26 + * License Header, with the fields enclosed by brackets [] replaced by
701.27 + * your own identifying information:
701.28 + * "Portions Copyrighted [year] [name of copyright owner]"
701.29 + *
701.30 + * Contributor(s):
701.31 + *
701.32 + * The Original Software is NetBeans. The Initial Developer of the Original
701.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
701.34 + * Microsystems, Inc. All Rights Reserved.
701.35 + *
701.36 + * If you wish your version of this file to be governed by only the CDDL
701.37 + * or only the GPL Version 2, indicate your decision by adding
701.38 + * "[Contributor] elects to include this software in this distribution
701.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
701.40 + * single choice of license, a recipient has the option to distribute
701.41 + * your version of this file under either the CDDL, the GPL Version 2 or
701.42 + * to extend the choice of license to its licensees as provided above.
701.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
701.44 + * Version 2 license, then the option applies only if the new code is
701.45 + * made subject to such option by the copyright holder.
701.46 + */
701.47 +
701.48 +package org.netbeans.modules.python.project2.ui;
701.49 +
701.50 +import java.awt.Component;
701.51 +import java.awt.EventQueue;
701.52 +import java.awt.Image;
701.53 +import java.beans.PropertyChangeEvent;
701.54 +import java.beans.PropertyChangeListener;
701.55 +import java.util.ArrayList;
701.56 +import java.util.Collection;
701.57 +import java.util.IdentityHashMap;
701.58 +import java.util.List;
701.59 +import java.util.Map;
701.60 +import java.util.SortedSet;
701.61 +import java.util.TreeSet;
701.62 +import javax.swing.ComboBoxModel;
701.63 +import javax.swing.DefaultComboBoxModel;
701.64 +import javax.swing.Icon;
701.65 +import javax.swing.ImageIcon;
701.66 +import javax.swing.JLabel;
701.67 +import javax.swing.JList;
701.68 +import javax.swing.ListCellRenderer;
701.69 +import javax.swing.plaf.UIResource;
701.70 +import org.netbeans.api.progress.ProgressHandle;
701.71 +import org.netbeans.api.progress.ProgressHandleFactory;
701.72 +import org.netbeans.api.project.SourceGroup;
701.73 +import org.netbeans.api.queries.VisibilityQuery;
701.74 +import org.openide.filesystems.FileObject;
701.75 +import org.openide.filesystems.FileUtil;
701.76 +import org.openide.nodes.AbstractNode;
701.77 +import org.openide.nodes.FilterNode;
701.78 +import org.openide.nodes.Node;
701.79 +import org.openide.util.NbBundle;
701.80 +import org.openide.util.Parameters;
701.81 +import org.openide.util.WeakListeners;
701.82 +
701.83 +/**
701.84 + * Factory for package views.
701.85 + * @see org.netbeans.spi.project.ui.LogicalViewProvider
701.86 + * <p>
701.87 + * <b>This is copied from the corresponding Java action in java.projects</b>
701.88 + * </p>
701.89 + *
701.90 + * @author Jesse Glick
701.91 + */
701.92 +@NbBundle.Messages({"# {0} - Filename", "PackageView.find_packages_progress=Finding packages in {0}"})
701.93 +public class PackageView {
701.94 +
701.95 + private PackageView() {}
701.96 +
701.97 + /**
701.98 + * Create a node which will contain package-oriented view of a source group.
701.99 + * <p>
701.100 + * The precise structure of this node is <em>not</em> specified by the API
701.101 + * and is subject to arbitrary change (perhaps at user option).
701.102 + * Callers should not make assumptions about the nature of subnodes, the
701.103 + * code or display names of certain nodes, and so on. You may use cookies/lookup
701.104 + * to find if particular subnodes correspond to folders or files.
701.105 + * </p>
701.106 + * @param group a source group which should be represented
701.107 + * @return node which will display packages in given group
701.108 + */
701.109 + public static Node createPackageView( SourceGroup group ) {
701.110 + return new RootNode (group);
701.111 + }
701.112 +
701.113 + /**
701.114 + * Finds the node representing given object, if any.
701.115 + * The current implementation works only for {@link org.openide.filesystems.FileObject}s
701.116 + * and {@link org.openide.loaders.DataObject}s.
701.117 + * @param rootNode a node some descendant of which should contain the object
701.118 + * @param object object to find
701.119 + * @return a node representing the given object, or null if no such node was found
701.120 + */
701.121 + public static Node findPath(Node rootNode, Object object) {
701.122 +
701.123 + PackageRootNode.PathFinder pf = rootNode.getLookup().lookup(PackageRootNode.PathFinder.class);
701.124 +
701.125 + if ( pf != null ) {
701.126 + return pf.findPath( rootNode, object );
701.127 + } else {
701.128 + TreeRootNode.PathFinder pf2 = rootNode.getLookup().lookup(TreeRootNode.PathFinder.class);
701.129 + if (pf2 != null) {
701.130 + return pf2.findPath(rootNode, object);
701.131 + } else {
701.132 + return null;
701.133 + }
701.134 + }
701.135 + }
701.136 +
701.137 + /**
701.138 + * Create a list or combo box model suitable for {@link javax.swing.JList} from a source group
701.139 + * showing all Java packages in the source group.
701.140 + * To display it you will also need {@link #listRenderer}.
701.141 + * <p>No particular guarantees are made as to the nature of the model objects themselves,
701.142 + * except that {@link Object#toString} will give the fully-qualified package name
701.143 + * (or <code>""</code> for the default package), regardless of what the renderer
701.144 + * actually displays.</p>
701.145 + * @param group a Java-like source group
701.146 + * @return a model of its packages
701.147 + * @since org.netbeans.modules.java.project/1 1.3
701.148 + */
701.149 +
701.150 + public static ComboBoxModel createListView(SourceGroup group) {
701.151 + Parameters.notNull("group", group); //NOI18N
701.152 + SortedSet<PackageItem> data = new TreeSet<>();
701.153 + findNonExcludedPackages(null, data, group.getRootFolder(), group, false);
701.154 + return new DefaultComboBoxModel(data.toArray(new PackageItem[data.size()]));
701.155 + }
701.156 +
701.157 + /** Fills given collection with flattened packages under given folder
701.158 + *@param target The collection to be filled
701.159 + *@param fo The folder to be scanned
701.160 + * @param group the group to scan
701.161 + * @param createPackageItems if false the collection will be filled with file objects; if
701.162 + * true PackageItems will be created.
701.163 + * @param showProgress whether to show a progress handle or not
701.164 + */
701.165 + static void findNonExcludedPackages(PackageViewChildren children, Collection<PackageItem> target, FileObject fo, SourceGroup group, boolean showProgress) {
701.166 + if (showProgress) {
701.167 + ProgressHandle progress = ProgressHandleFactory.createHandle(NbBundle.getMessage(PackageView.class, "PackageView.find_packages_progress", FileUtil.getFileDisplayName(fo)));
701.168 + progress.start(1000);
701.169 + findNonExcludedPackages(children, target, fo, group, progress, 0, 1000);
701.170 + progress.finish();
701.171 + } else {
701.172 + findNonExcludedPackages(children, target, fo, group, null, 0, 0);
701.173 + }
701.174 + }
701.175 +
701.176 + private static void findNonExcludedPackages(PackageViewChildren children, Collection<PackageItem> target, FileObject fo, SourceGroup group, ProgressHandle progress, int start, int end) {
701.177 +
701.178 + assert fo.isFolder() : "Package view only accepts folders"; // NOI18N
701.179 +
701.180 + if (progress != null) {
701.181 + String path = FileUtil.getRelativePath(children.getRoot(), fo);
701.182 + assert path != null : fo + " in " + children.getRoot();
701.183 + progress.progress(path.replace('/', '.'), start);
701.184 + }
701.185 +
701.186 + if (!fo.isValid()) {
701.187 + return;
701.188 + }
701.189 +
701.190 + if ( !VisibilityQuery.getDefault().isVisible( fo ) ) {
701.191 + return; // Don't show hidden packages
701.192 + }
701.193 +
701.194 + boolean hasSubfolders = false;
701.195 + boolean hasFiles = false;
701.196 + List<FileObject> folders = new ArrayList<>();
701.197 + for (FileObject kid : fo.getChildren()) {
701.198 + if (kid.isValid() && VisibilityQuery.getDefault().isVisible(kid) && group.contains(kid)) {
701.199 + if (kid.isFolder()) {
701.200 + FileObject init = kid.getFileObject("__init__", "py"); //NOI18N
701.201 + if(init != null) {
701.202 + folders.add(kid);
701.203 + hasSubfolders = true;
701.204 + }
701.205 + }
701.206 + else {
701.207 + hasFiles = true;
701.208 + }
701.209 + }
701.210 + }
701.211 + if (hasFiles || !hasSubfolders) {
701.212 + if (target != null) {
701.213 + target.add( new PackageItem(group, fo, !hasFiles ) );
701.214 + }
701.215 + else {
701.216 + if (fo.isValid()) {
701.217 + children.add(fo, !hasFiles, false);
701.218 + }
701.219 + }
701.220 + }
701.221 + if (!folders.isEmpty()) {
701.222 + int diff = (end - start) / folders.size();
701.223 + int c = 0;
701.224 + for (FileObject kid : folders) {
701.225 + // Do this after adding the parent, so we get a pre-order traversal.
701.226 + // Also see PackageViewChildren.findChild: prefer to get root first.
701.227 + findNonExcludedPackages(children, target, kid, group, progress, start + c * diff, start + (c + 1) * diff);
701.228 + c++;
701.229 + }
701.230 + }
701.231 + }
701.232 +
701.233 +// public static ComboBoxModel createListView(SourceGroup group) {
701.234 +// DefaultListModel model = new DefaultListModel();
701.235 +// SortedSet/*<PackageItem>*/ items = new TreeSet();
701.236 +// FileObject root = group.getRootFolder();
701.237 +// if (PackageDisplayUtils.isSignificant(root)) {
701.238 +// items.add(new PackageItem(group, root));
701.239 +// }
701.240 +// Enumeration/*<FileObject>*/ files = root.getChildren(true);
701.241 +// while (files.hasMoreElements()) {
701.242 +// FileObject f = (FileObject) files.nextElement();
701.243 +// if (f.isFolder() && PackageDisplayUtils.isSignificant(f)) {
701.244 +// items.add(new PackageItem(group, f));
701.245 +// }
701.246 +// }
701.247 +// return new DefaultComboBoxModel(items.toArray(new PackageItem[items.size()]));
701.248 +// }
701.249 +
701.250 +
701.251 + /**
701.252 + * Create a renderer suited to rendering models created using {@link #createListView}.
701.253 + * The exact nature of the display is not specified.
701.254 + * Instances of String can also be rendered.
701.255 + * @return a suitable package renderer
701.256 + * @since org.netbeans.modules.java.project/1 1.3
701.257 + */
701.258 + public static ListCellRenderer listRenderer() {
701.259 + return new PackageListCellRenderer();
701.260 + }
701.261 +
701.262 + /**
701.263 + * FilterNode which listens on the PackageViewSettings and changes the view to
701.264 + * the package view or tree view
701.265 + *
701.266 + */
701.267 + private static final class RootNode extends FilterNode implements PropertyChangeListener {
701.268 +
701.269 + private final SourceGroup sourceGroup;
701.270 +
701.271 + @SuppressWarnings("LeakingThisInConstructor")
701.272 + private RootNode (SourceGroup group) {
701.273 + super(getOriginalNode(group));
701.274 + this.sourceGroup = group;
701.275 + PythonProjectSettings.addPropertyChangeListener(WeakListeners.propertyChange(this, PythonProjectSettings.class));
701.276 + group.addPropertyChangeListener(WeakListeners.propertyChange(this, group));
701.277 + }
701.278 +
701.279 + @Override
701.280 + public void propertyChange (PropertyChangeEvent event) {
701.281 + String prop = event.getPropertyName();
701.282 + if (PythonProjectSettings.PROP_PACKAGE_VIEW_TYPE.equals(prop) || SourceGroup.PROP_CONTAINERSHIP.equals(prop)) {
701.283 + EventQueue.invokeLater(new Runnable() {
701.284 + @Override
701.285 + public void run() {
701.286 + changeOriginal(getOriginalNode(sourceGroup), true);
701.287 + }
701.288 + });
701.289 + }
701.290 + }
701.291 +
701.292 + private static Node getOriginalNode(SourceGroup group) {
701.293 + FileObject root = group.getRootFolder();
701.294 + //Guard condition, if the project is (closed) and deleted but not yet gced
701.295 + // and the view is switched, the source group is not valid.
701.296 + if ( root == null || !root.isValid()) {
701.297 + return new AbstractNode (Children.LEAF);
701.298 + }
701.299 + switch (PythonProjectSettings.getPackageViewType()) {
701.300 + case PythonProjectSettings.TYPE_PACKAGE_VIEW:
701.301 + return new PackageRootNode(group);
701.302 + case PythonProjectSettings.TYPE_TREE:
701.303 + return new TreeRootNode(group);
701.304 + default:
701.305 + assert false : "Unknown PackageView Type"; //NOI18N
701.306 + return new PackageRootNode(group);
701.307 + }
701.308 + }
701.309 + }
701.310 +
701.311 + /**
701.312 + * Model item representing one package.
701.313 + */
701.314 + static final class PackageItem implements Comparable<PackageItem> {
701.315 +
701.316 + private static final Map<Image,Icon> image2icon = new IdentityHashMap<>();
701.317 +
701.318 + private final boolean empty;
701.319 + private final FileObject pkg;
701.320 + private final String pkgname;
701.321 + private Icon icon;
701.322 +
701.323 + public PackageItem(SourceGroup group, FileObject pkg, boolean empty) {
701.324 + this.pkg = pkg;
701.325 + this.empty = empty;
701.326 + String path = FileUtil.getRelativePath(group.getRootFolder(), pkg);
701.327 + assert path != null : "No " + pkg + " in " + group;
701.328 + pkgname = path.replace('/', '.');
701.329 + }
701.330 +
701.331 + @Override
701.332 + public String toString() {
701.333 + return pkgname;
701.334 + }
701.335 +
701.336 + public String getLabel() {
701.337 + return PackageDisplayUtils.getDisplayLabel(pkgname);
701.338 + }
701.339 +
701.340 + public Icon getIcon() {
701.341 + if ( icon == null ) {
701.342 + Image image = PackageDisplayUtils.getIcon(pkg, pkgname, empty);
701.343 + icon = image2icon.get(image);
701.344 + if ( icon == null ) {
701.345 + icon = new ImageIcon( image );
701.346 + image2icon.put( image, icon );
701.347 + }
701.348 + }
701.349 + return icon;
701.350 + }
701.351 +
701.352 + @Override
701.353 + public int compareTo(PackageItem p) {
701.354 + return pkgname.compareTo(p.pkgname);
701.355 + }
701.356 +
701.357 + }
701.358 +
701.359 + /**
701.360 + * The renderer which just displays {@link PackageItem#getLabel} and {@link PackageItem#getIcon}.
701.361 + */
701.362 + private static final class PackageListCellRenderer extends JLabel implements ListCellRenderer, UIResource {
701.363 +
701.364 + public PackageListCellRenderer() {
701.365 + setOpaque(true);
701.366 + }
701.367 +
701.368 + @Override
701.369 + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
701.370 + // #93658: GTK needs name to render cell renderer "natively"
701.371 + setName("ComboBox.listRenderer"); // NOI18N
701.372 +
701.373 + if (value instanceof PackageItem) {
701.374 + PackageItem pkgitem = (PackageItem) value;
701.375 + setText(pkgitem.getLabel());
701.376 + setIcon(pkgitem.getIcon());
701.377 + } else {
701.378 + // #49954: render a specially inserted package somehow.
701.379 + String pkgitem = (String) value;
701.380 + setText(pkgitem);
701.381 + setIcon(null);
701.382 + }
701.383 +
701.384 + if ( isSelected ) {
701.385 + setBackground(list.getSelectionBackground());
701.386 + setForeground(list.getSelectionForeground());
701.387 + }
701.388 + else {
701.389 + setBackground(list.getBackground());
701.390 + setForeground(list.getForeground());
701.391 + }
701.392 +
701.393 + return this;
701.394 + }
701.395 +
701.396 + // #93658: GTK needs name to render cell renderer "natively"
701.397 + @Override
701.398 + public String getName() {
701.399 + String name = super.getName();
701.400 + return name == null ? "ComboBox.renderer" : name; // NOI18N
701.401 + }
701.402 +
701.403 + }
701.404 +
701.405 +
701.406 +}
702.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
702.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/PackageViewChildren.java Sat Feb 28 17:25:32 2015 -0800
702.3 @@ -0,0 +1,1335 @@
702.4 +/*
702.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
702.6 + *
702.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
702.8 + *
702.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
702.10 + * Other names may be trademarks of their respective owners.
702.11 + *
702.12 + * The contents of this file are subject to the terms of either the GNU
702.13 + * General Public License Version 2 only ("GPL") or the Common
702.14 + * Development and Distribution License("CDDL") (collectively, the
702.15 + * "License"). You may not use this file except in compliance with the
702.16 + * License. You can obtain a copy of the License at
702.17 + * http://www.netbeans.org/cddl-gplv2.html
702.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
702.19 + * specific language governing permissions and limitations under the
702.20 + * License. When distributing the software, include this License Header
702.21 + * Notice in each file and include the License file at
702.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
702.23 + * particular file as subject to the "Classpath" exception as provided
702.24 + * by Oracle in the GPL Version 2 section of the License file that
702.25 + * accompanied this code. If applicable, add the following below the
702.26 + * License Header, with the fields enclosed by brackets [] replaced by
702.27 + * your own identifying information:
702.28 + * "Portions Copyrighted [year] [name of copyright owner]"
702.29 + *
702.30 + * Contributor(s):
702.31 + *
702.32 + * The Original Software is NetBeans. The Initial Developer of the Original
702.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
702.34 + * Microsystems, Inc. All Rights Reserved.
702.35 + *
702.36 + * If you wish your version of this file to be governed by only the CDDL
702.37 + * or only the GPL Version 2, indicate your decision by adding
702.38 + * "[Contributor] elects to include this software in this distribution
702.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
702.40 + * single choice of license, a recipient has the option to distribute
702.41 + * your version of this file under either the CDDL, the GPL Version 2 or
702.42 + * to extend the choice of license to its licensees as provided above.
702.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
702.44 + * Version 2 license, then the option applies only if the new code is
702.45 + * made subject to such option by the copyright holder.
702.46 + */
702.47 +
702.48 +package org.netbeans.modules.python.project2.ui;
702.49 +
702.50 +import java.awt.EventQueue;
702.51 +import java.awt.Image;
702.52 +import java.awt.datatransfer.DataFlavor;
702.53 +import java.awt.datatransfer.Transferable;
702.54 +import java.awt.datatransfer.UnsupportedFlavorException;
702.55 +import java.awt.dnd.DnDConstants;
702.56 +import java.beans.PropertyChangeEvent;
702.57 +import java.beans.PropertyChangeListener;
702.58 +import java.beans.PropertyChangeSupport;
702.59 +import java.io.IOException;
702.60 +import java.lang.reflect.InvocationTargetException;
702.61 +import java.text.MessageFormat;
702.62 +import java.util.ArrayList;
702.63 +import java.util.Collections;
702.64 +import java.util.HashSet;
702.65 +import java.util.Iterator;
702.66 +import java.util.List;
702.67 +import java.util.Set;
702.68 +import java.util.StringTokenizer;
702.69 +import java.util.TreeMap;
702.70 +import java.util.TreeSet;
702.71 +import javax.swing.Action;
702.72 +import javax.swing.SwingUtilities;
702.73 +import javax.swing.event.ChangeEvent;
702.74 +import javax.swing.event.ChangeListener;
702.75 +import org.netbeans.api.fileinfo.NonRecursiveFolder;
702.76 +import org.netbeans.api.project.SourceGroup;
702.77 +import org.netbeans.api.queries.VisibilityQuery;
702.78 +import org.netbeans.spi.project.ActionProvider;
702.79 +import org.netbeans.spi.project.ui.support.FileSensitiveActions;
702.80 +import org.openide.DialogDisplayer;
702.81 +import org.openide.ErrorManager;
702.82 +import org.openide.NotifyDescriptor;
702.83 +import org.openide.actions.FileSystemAction;
702.84 +import org.openide.actions.PropertiesAction;
702.85 +import org.openide.filesystems.FileAttributeEvent;
702.86 +import org.openide.filesystems.FileChangeListener;
702.87 +import org.openide.filesystems.FileEvent;
702.88 +import org.openide.filesystems.FileObject;
702.89 +import org.openide.filesystems.FileRenameEvent;
702.90 +import org.openide.filesystems.FileStateInvalidException;
702.91 +import org.openide.filesystems.FileSystem;
702.92 +import org.openide.filesystems.FileUIUtils;
702.93 +import org.openide.filesystems.FileUtil;
702.94 +import org.openide.filesystems.StatusDecorator;
702.95 +import org.openide.loaders.ChangeableDataFilter;
702.96 +import org.openide.loaders.DataFilter;
702.97 +import org.openide.loaders.DataFolder;
702.98 +import org.openide.loaders.DataObject;
702.99 +import org.openide.nodes.Children;
702.100 +import org.openide.nodes.FilterNode;
702.101 +import org.openide.nodes.Node;
702.102 +import org.openide.nodes.PropertySupport;
702.103 +import org.openide.nodes.Sheet;
702.104 +import org.openide.util.ChangeSupport;
702.105 +import org.openide.util.Exceptions;
702.106 +import org.openide.util.ImageUtilities;
702.107 +import org.openide.util.NbBundle;
702.108 +import org.openide.util.RequestProcessor;
702.109 +import org.openide.util.WeakListeners;
702.110 +import org.openide.util.datatransfer.ExTransferable;
702.111 +import org.openide.util.datatransfer.MultiTransferObject;
702.112 +import org.openide.util.datatransfer.PasteType;
702.113 +import org.openide.util.lookup.Lookups;
702.114 +import org.openide.util.lookup.ProxyLookup;
702.115 +
702.116 +/**
702.117 + * Display of Java sources in a package structure rather than folder structure.
702.118 + *
702.119 + * <p>
702.120 + * <b>This is copied from the corresponding Java action in java.projects</b>
702.121 + * </p>
702.122 + *
702.123 + * @author Adam Sotona, Jesse Glick, Petr Hrebejk, Tomas Zezula
702.124 + */
702.125 +@NbBundle.Messages({"TXT_PastePackage=Paste Package",
702.126 + "MSG_InvalidPackageName=Name is not a valid Java package.",
702.127 + "LBL_CompilePackage_Action=Compile Package",
702.128 + "PROP_name=Name",
702.129 + "HINT_name=Package Name"})
702.130 +final class PackageViewChildren extends Children.Keys<String> implements FileChangeListener, ChangeListener, Runnable {
702.131 +
702.132 + private static final String NODE_NOT_CREATED = "NNC"; // NOI18N
702.133 + private static final String NODE_NOT_CREATED_EMPTY = "NNC_E"; //NOI18N
702.134 +
702.135 + private static final MessageFormat PACKAGE_FLAVOR = new MessageFormat("application/x-python-org-netbeans-modules-python-project-packagenodednd; class=org.netbeans.spi.java.project.support.ui.PackageViewChildren$PackageNode; mask={0}"); //NOI18N
702.136 +
702.137 + static final String PRIMARY_TYPE = "application"; //NOI18N
702.138 + static final String SUBTYPE = "x-python-org-netbeans-modules-python-project-packagenodednd"; //NOI18N
702.139 + static final String MASK = "mask"; //NOI18N
702.140 +
702.141 + private java.util.Map<String,Object/*NODE_NOT_CREATED|NODE_NOT_CREATED_EMPTY|PackageNode*/> names2nodes;
702.142 + private final FileObject root;
702.143 + private final SourceGroup group;
702.144 + private FileChangeListener wfcl; // Weak listener on the system filesystem
702.145 + private ChangeListener wvqcl; // Weak listener on the VisibilityQuery
702.146 +
702.147 + /**
702.148 + * Creates children based on a single source root.
702.149 + * @param root the folder where sources start (must be a package root)
702.150 + */
702.151 + public PackageViewChildren(SourceGroup group) {
702.152 +
702.153 + // Sem mas dat cache a bude to uplne nejrychlejsi na svete
702.154 +
702.155 + this.root = group.getRootFolder();
702.156 + this.group = group;
702.157 + }
702.158 +
702.159 + FileObject getRoot() {
702.160 + return root; // Used from PackageRootNode
702.161 + }
702.162 +
702.163 + @Override
702.164 + protected Node[] createNodes(String path) {
702.165 + FileObject fo = root.getFileObject(path);
702.166 + if ( fo != null && fo.isValid()) {
702.167 + Object o = names2nodes.get(path);
702.168 + PackageNode n;
702.169 + DataFolder folder = DataFolder.findFolder(fo);
702.170 + if (folder.isValid()) {
702.171 + if ( o == NODE_NOT_CREATED ) {
702.172 + n = new PackageNode(root, folder, false);
702.173 + } else { // NODE_NOT_CREATED_EMPTY, PackageNode
702.174 + n = new PackageNode(root, folder);
702.175 + }
702.176 + names2nodes.put(path, n);
702.177 + return new Node[] {n};
702.178 + }
702.179 + }
702.180 + return new Node[0];
702.181 + }
702.182 +
702.183 + RequestProcessor.Task task = RequestProcessor.getDefault().create( this );
702.184 +
702.185 + @Override
702.186 + protected void addNotify() {
702.187 + // System.out.println("ADD NOTIFY" + root + " : " + this );
702.188 + super.addNotify();
702.189 + task.schedule( 0 );
702.190 + }
702.191 +
702.192 + @Override
702.193 + public Node[] getNodes( boolean optimal ) {
702.194 + if ( optimal ) {
702.195 + Node[] garbage = super.getNodes( false );
702.196 + task.waitFinished();
702.197 + }
702.198 + return super.getNodes( false );
702.199 + }
702.200 +
702.201 + @Override
702.202 + public Node findChild (String name) {
702.203 + while (true) {
702.204 + Node n = super.findChild(name);
702.205 + if (n != null) {
702.206 + // If already there, get it quickly.
702.207 + return n;
702.208 + }
702.209 + // In case a project is made on a large existing source root,
702.210 + // which happens to have a file in the root dir (so package node
702.211 + // should exist), try to select the root package node soon; no need
702.212 + // to wait for whole tree.
702.213 + try {
702.214 + if (task.waitFinished(5000)) {
702.215 + return super.findChild(name);
702.216 + }
702.217 + // refreshKeysAsync won't run since we are blocking EQ!
702.218 + refreshKeys();
702.219 + } catch (InterruptedException x) {
702.220 + Exceptions.printStackTrace(x);
702.221 + }
702.222 + }
702.223 + }
702.224 +
702.225 + @Override
702.226 + public void run() {
702.227 + computeKeys();
702.228 + refreshKeys();
702.229 + try {
702.230 + FileSystem fs = root.getFileSystem();
702.231 + wfcl = FileUtil.weakFileChangeListener(this, fs);
702.232 + fs.addFileChangeListener( wfcl );
702.233 + }
702.234 + catch ( FileStateInvalidException e ) {
702.235 + ErrorManager.getDefault().notify( ErrorManager.INFORMATIONAL, e );
702.236 + }
702.237 + wvqcl = WeakListeners.change( this, VisibilityQuery.getDefault() );
702.238 + VisibilityQuery.getDefault().addChangeListener( wvqcl );
702.239 + }
702.240 +
702.241 + @Override
702.242 + protected void removeNotify() {
702.243 + // System.out.println("REMOVE NOTIFY" + root + " : " + this );
702.244 + VisibilityQuery.getDefault().removeChangeListener( wvqcl );
702.245 + try {
702.246 + root.getFileSystem().removeFileChangeListener( wfcl );
702.247 + }
702.248 + catch ( FileStateInvalidException e ) {
702.249 + ErrorManager.getDefault().notify( ErrorManager.INFORMATIONAL, e );
702.250 + }
702.251 + setKeys(new String[0]);
702.252 + names2nodes.clear();
702.253 + super.removeNotify();
702.254 + }
702.255 +
702.256 + // Private methods ---------------------------------------------------------
702.257 +
702.258 + private void refreshKeys() {
702.259 + Set<String> keys;
702.260 + synchronized (names2nodes) {
702.261 + keys = new TreeSet<>(names2nodes.keySet());
702.262 + }
702.263 + setKeys(keys);
702.264 + }
702.265 +
702.266 + /* #70097: workaround of a javacore deadlock
702.267 + * See related issue: #61027
702.268 + */
702.269 + private void refreshKeysAsync () {
702.270 + EventQueue.invokeLater(new Runnable() {
702.271 + @Override
702.272 + public void run () {
702.273 + refreshKeys();
702.274 + }
702.275 + });
702.276 + }
702.277 +
702.278 + private void computeKeys() {
702.279 + // XXX this is not going to perform too well for a huge source root...
702.280 + // However we have to go through the whole hierarchy in order to find
702.281 + // all packages (Hrebejk)
702.282 + names2nodes = Collections.synchronizedMap(new TreeMap<String,Object>());
702.283 + findNonExcludedPackages( root );
702.284 + }
702.285 +
702.286 + /**
702.287 + * Collect all recursive subfolders, except those which have subfolders
702.288 + * but no files.
702.289 + */
702.290 + private void findNonExcludedPackages( FileObject fo ) {
702.291 + PackageView.findNonExcludedPackages(this, null, fo, group, true);
702.292 + }
702.293 +
702.294 +
702.295 + /** Finds all empty parents of given package and deletes them
702.296 + */
702.297 + private void cleanEmptyKeys( FileObject fo ) {
702.298 + FileObject parent = fo.getParent();
702.299 +
702.300 + // Special case for default package
702.301 + if ( root.equals( parent ) ) {
702.302 + PackageNode n = get( parent );
702.303 + // the default package is considered empty if it only contains folders,
702.304 + // regardless of the contents of these folders (empty or not)
702.305 + if ( n != null && PackageDisplayUtils.isEmpty( root, false, false ) ) {
702.306 + remove( root );
702.307 + }
702.308 + return;
702.309 + }
702.310 +
702.311 + while ( FileUtil.isParentOf( root, parent ) ) {
702.312 + PackageNode n = get( parent );
702.313 + if ( n != null && n.isLeaf() ) {
702.314 + // System.out.println("Cleaning " + parent);
702.315 + remove( parent );
702.316 + }
702.317 + parent = parent.getParent();
702.318 + }
702.319 + }
702.320 +
702.321 + // Non private only to be able to have the findNonExcludedPackages impl
702.322 + // in on place (PackageView)
702.323 + void add(FileObject fo, boolean empty, boolean refreshImmediately) {
702.324 + String path = FileUtil.getRelativePath( root, fo );
702.325 + assert path != null : "Adding wrong folder " + fo +"(valid="+fo.isValid()+")"+ "under root" + this.root + "(valid="+this.root.isValid()+")";
702.326 + if ( get( fo ) == null ) {
702.327 + names2nodes.put( path, empty ? NODE_NOT_CREATED_EMPTY : NODE_NOT_CREATED );
702.328 + if (refreshImmediately) {
702.329 + refreshKeysAsync();
702.330 + } else {
702.331 + synchronized (this) {
702.332 + if (refreshLazilyTask == null) {
702.333 + refreshLazilyTask = RequestProcessor.getDefault().post(new Runnable() {
702.334 + @Override
702.335 + public void run() {
702.336 + synchronized (PackageViewChildren.this) {
702.337 + refreshLazilyTask = null;
702.338 + refreshKeysAsync();
702.339 + }
702.340 + }
702.341 + }, 2500);
702.342 + }
702.343 + }
702.344 + }
702.345 + }
702.346 + }
702.347 + private RequestProcessor.Task refreshLazilyTask;
702.348 +
702.349 + private void remove( FileObject fo ) {
702.350 + String path = FileUtil.getRelativePath( root, fo );
702.351 + assert path != null : "Removing wrong folder" + fo;
702.352 + names2nodes.remove( path );
702.353 + }
702.354 +
702.355 + private void removeSubTree (FileObject fo) {
702.356 + String path = FileUtil.getRelativePath( root, fo );
702.357 + assert path != null : "Removing wrong folder" + fo;
702.358 + synchronized (names2nodes) {
702.359 + Set<String> keys = names2nodes.keySet();
702.360 + keys.remove(path);
702.361 + path = path + '/'; //NOI18N
702.362 + Iterator<String> it = keys.iterator();
702.363 + while (it.hasNext()) {
702.364 + if (it.next().startsWith(path)) {
702.365 + it.remove();
702.366 + }
702.367 + }
702.368 + }
702.369 + }
702.370 +
702.371 + private PackageNode get( FileObject fo ) {
702.372 + String path = FileUtil.getRelativePath( root, fo );
702.373 + assert path != null : "Asking for wrong folder" + fo;
702.374 + Object o = names2nodes.get( path );
702.375 + return !isNodeCreated( o ) ? null : (PackageNode)o;
702.376 + }
702.377 +
702.378 + private boolean contains( FileObject fo ) {
702.379 + String path = FileUtil.getRelativePath( root, fo );
702.380 + assert path != null : "Asking for wrong folder" + fo;
702.381 + Object o = names2nodes.get( path );
702.382 + return o != null;
702.383 + }
702.384 +
702.385 + private boolean exists( FileObject fo ) {
702.386 + String path = FileUtil.getRelativePath( root, fo );
702.387 + return names2nodes.get( path ) != null;
702.388 + }
702.389 +
702.390 + private boolean isNodeCreated( Object o ) {
702.391 + return o instanceof Node;
702.392 + }
702.393 +
702.394 + private PackageNode updatePath( String oldPath, String newPath ) {
702.395 + assert newPath != null;
702.396 + Object o = names2nodes.get( oldPath );
702.397 + if ( o == null ) {
702.398 + return null;
702.399 + }
702.400 + names2nodes.remove( oldPath );
702.401 + names2nodes.put( newPath, o );
702.402 + return !isNodeCreated( o ) ? null : (PackageNode)o;
702.403 + }
702.404 +
702.405 + // Implementation of FileChangeListener ------------------------------------
702.406 +
702.407 + @Override
702.408 + public void fileAttributeChanged( FileAttributeEvent fe ) {}
702.409 +
702.410 + @Override
702.411 + public void fileChanged( FileEvent fe ) {}
702.412 +
702.413 + @Override
702.414 + public void fileFolderCreated( FileEvent fe ) {
702.415 + FileObject fo = fe.getFile();
702.416 + if ( FileUtil.isParentOf( root, fo ) && isVisible( root, fo ) ) {
702.417 + cleanEmptyKeys( fo );
702.418 +// add( fo, false);
702.419 + findNonExcludedPackages( fo );
702.420 + refreshKeys();
702.421 + }
702.422 + }
702.423 +
702.424 + @Override
702.425 + public void fileDataCreated( FileEvent fe ) {
702.426 + FileObject fo = fe.getFile();
702.427 + if ( FileUtil.isParentOf( root, fo ) && isVisible( root, fo ) ) {
702.428 + FileObject parent = fo.getParent();
702.429 + // XXX consider using group.contains() here
702.430 + if ( !VisibilityQuery.getDefault().isVisible( parent ) ) {
702.431 + return; // Adding file into ignored directory
702.432 + }
702.433 + PackageNode n = get( parent );
702.434 + if ( n == null && !contains( parent ) ) {
702.435 + add(parent, false, true);
702.436 + refreshKeys();
702.437 + }
702.438 + else if ( n != null ) {
702.439 + n.updateChildren();
702.440 + }
702.441 + }
702.442 + }
702.443 +
702.444 + @Override
702.445 + public void fileDeleted( FileEvent fe ) {
702.446 + FileObject fo = fe.getFile();
702.447 +
702.448 + // System.out.println("FILE DELETED " + FileUtil.getRelativePath( root, fo ) );
702.449 +
702.450 + if ( FileUtil.isParentOf( root, fo ) && isVisible( root, fo ) ) {
702.451 +
702.452 + // System.out.println("IS FOLDER? " + fo + " : " + fo.isFolder() );
702.453 + /* Hack for MasterFS see #42464 */
702.454 + if ( fo.isFolder() || get( fo ) != null ) {
702.455 + // System.out.println("REMOVING FODER " + fo );
702.456 + removeSubTree( fo );
702.457 + // Now add the parent if necessary
702.458 + FileObject parent = fo.getParent();
702.459 + if ( ( FileUtil.isParentOf( root, parent ) || root.equals( parent ) ) && get( parent ) == null && parent.isValid() ) {
702.460 + // Candidate for adding
702.461 + if ( !toBeRemoved( parent ) ) {
702.462 + // System.out.println("ADDING PARENT " + parent );
702.463 + add(parent, true, true);
702.464 + }
702.465 + }
702.466 + refreshKeysAsync();
702.467 + }
702.468 + else {
702.469 + FileObject parent = fo.getParent();
702.470 + final PackageNode n = get( parent );
702.471 + if ( n != null ) {
702.472 + //#61027: workaround to a deadlock when the package is being changed from non-leaf to leaf:
702.473 + boolean leaf = n.isLeaf();
702.474 + DataFolder df = n.getDataFolder();
702.475 + boolean empty = isEmpty(df);
702.476 +
702.477 + if (leaf != empty) {
702.478 + SwingUtilities.invokeLater(new Runnable() {
702.479 + @Override
702.480 + public void run() {
702.481 + n.updateChildren();
702.482 + }
702.483 + });
702.484 + } else {
702.485 + n.updateChildren();
702.486 + }
702.487 + }
702.488 + // If the parent folder only contains folders remove it
702.489 + if ( toBeRemoved( parent ) ) {
702.490 + remove( parent );
702.491 + refreshKeysAsync();
702.492 + }
702.493 +
702.494 + }
702.495 + }
702.496 + // else {
702.497 + // System.out.println("NOT A PARENT " + fo );
702.498 + // }
702.499 + }
702.500 +
702.501 + /** Returns true if the folder should be removed from the view
702.502 + * i.e. it has some unignored children and the children are folders only
702.503 + */
702.504 + private boolean toBeRemoved( FileObject folder ) {
702.505 + boolean ignoredOnly = true;
702.506 + boolean foldersOnly = true;
702.507 + for (FileObject kid : folder.getChildren()) {
702.508 + // XXX consider using group.contains() here
702.509 + if (VisibilityQuery.getDefault().isVisible(kid)) {
702.510 + ignoredOnly = false;
702.511 + if (!kid.isFolder()) {
702.512 + foldersOnly = false;
702.513 + break;
702.514 + }
702.515 + }
702.516 + }
702.517 + if ( ignoredOnly ) {
702.518 + return false; // It is either empty or it only contains ignored files
702.519 + // thus is leaf and it means package
702.520 + }
702.521 + else {
702.522 + return foldersOnly;
702.523 + }
702.524 + }
702.525 +
702.526 +
702.527 + @Override
702.528 + public void fileRenamed( FileRenameEvent fe ) {
702.529 + FileObject fo = fe.getFile();
702.530 + if ( FileUtil.isParentOf( root, fo ) && fo.isFolder() ) {
702.531 + String rp = FileUtil.getRelativePath( root, fo.getParent() );
702.532 + String oldPath = rp + ( rp.length() == 0 ? "" : "/" ) + fe.getName() + fe.getExt(); // NOI18N
702.533 +
702.534 + // XXX consider using group.contains() here
702.535 + boolean visible = VisibilityQuery.getDefault().isVisible( fo );
702.536 + boolean doUpdate = false;
702.537 +
702.538 + // Find all entries which have to be updated
702.539 + List<String> needsUpdate = new ArrayList<>();
702.540 + synchronized (names2nodes) {
702.541 + for (Iterator<String> it = names2nodes.keySet().iterator(); it.hasNext(); ) {
702.542 + String p = it.next();
702.543 + if ( p.startsWith( oldPath ) ) {
702.544 + if ( visible ) {
702.545 + needsUpdate.add( p );
702.546 + } else {
702.547 + it.remove();
702.548 + doUpdate = true;
702.549 + }
702.550 + }
702.551 + }
702.552 + }
702.553 +
702.554 + // If the node does not exists then there might have been update
702.555 + // from ignored to non ignored
702.556 + if ( get( fo ) == null && visible ) {
702.557 + cleanEmptyKeys( fo );
702.558 + findNonExcludedPackages( fo );
702.559 + doUpdate = true; // force refresh
702.560 + }
702.561 +
702.562 + int oldPathLen = oldPath.length();
702.563 + String newPath = FileUtil.getRelativePath( root, fo );
702.564 + for (String p : needsUpdate) {
702.565 + StringBuilder np = new StringBuilder(p);
702.566 + np.replace( 0, oldPathLen, newPath );
702.567 + PackageNode n = updatePath( p, np.toString() ); // Replace entries in cache
702.568 + if ( n != null ) {
702.569 + n.updateDisplayName(); // Update nodes
702.570 + }
702.571 + }
702.572 +
702.573 + if ( needsUpdate.size() > 1 || doUpdate ) {
702.574 + // Sorting might change
702.575 + refreshKeys();
702.576 + }
702.577 + }
702.578 + /*
702.579 + else if ( FileUtil.isParentOf( root, fo ) && fo.isFolder() ) {
702.580 + FileObject parent = fo.getParent();
702.581 + PackageNode n = get( parent );
702.582 + if ( n != null && VisibilityQuery.getDefault().isVisible( parent ) ) {
702.583 + n.updateChildren();
702.584 + }
702.585 +
702.586 + }
702.587 + */
702.588 +
702.589 + }
702.590 +
702.591 + /** Test whether file and all it's parent up to parent paremeter
702.592 + * are visible
702.593 + */
702.594 + private boolean isVisible( FileObject parent, FileObject file ) {
702.595 +
702.596 + do {
702.597 + // XXX consider using group.contains() here
702.598 + if ( !VisibilityQuery.getDefault().isVisible( file ) ) {
702.599 + return false;
702.600 + }
702.601 + file = file.getParent();
702.602 + }
702.603 + while ( file != null && file != parent );
702.604 +
702.605 + return true;
702.606 + }
702.607 +
702.608 +
702.609 + // Implementation of ChangeListener ------------------------------------
702.610 +
702.611 + @Override
702.612 + public void stateChanged( ChangeEvent e ) {
702.613 + computeKeys();
702.614 + refreshKeys();
702.615 + }
702.616 +
702.617 +
702.618 + /*
702.619 + private void debugKeySet() {
702.620 + for( Iterator it = names2nodes.keySet().iterator(); it.hasNext(); ) {
702.621 + String k = (String)it.next();
702.622 + System.out.println( " " + k + " -> " + names2nodes.get( k ) );
702.623 + }
702.624 + }
702.625 + */
702.626 +
702.627 + private final DataFilter NO_FOLDERS_FILTER = new NoFoldersDataFilter();
702.628 +
702.629 + private static boolean isEmpty(DataFolder dataFolder) {
702.630 + if ( dataFolder == null ) {
702.631 + return true;
702.632 + }
702.633 + return PackageDisplayUtils.isEmpty( dataFolder.getPrimaryFile() );
702.634 + }
702.635 +
702.636 + final class PackageNode extends FilterNode {
702.637 +
702.638 + private Action actions[];
702.639 +
702.640 + private final FileObject root;
702.641 + private DataFolder dataFolder;
702.642 + private boolean isDefaultPackage;
702.643 +
702.644 + public PackageNode( FileObject root, DataFolder dataFolder ) {
702.645 + this( root, dataFolder, isEmpty( dataFolder ) );
702.646 + }
702.647 +
702.648 + public PackageNode( FileObject root, DataFolder dataFolder, boolean empty ) {
702.649 + super( dataFolder.getNodeDelegate(),
702.650 + empty ? Children.LEAF : dataFolder.createNodeChildren( NO_FOLDERS_FILTER ),
702.651 + new ProxyLookup(
702.652 + Lookups.singleton(new NoFoldersContainer (dataFolder)),
702.653 + dataFolder.getNodeDelegate().getLookup()
702.654 +// Lookups.singleton(PackageRootNode.alwaysSearchableSearchInfo(SearchInfoFactory.createSearchInfo(
702.655 +// dataFolder.getPrimaryFile(),
702.656 +// false, //not recursive
702.657 +// new FileObjectFilter[] {
702.658 +// SearchInfoFactory.VISIBILITY_FILTER})
702.659 + ));
702.660 + this.root = root;
702.661 + this.dataFolder = dataFolder;
702.662 + this.isDefaultPackage = root.equals( dataFolder.getPrimaryFile() );
702.663 + }
702.664 +
702.665 + FileObject getRoot() {
702.666 + return root; // Used from PackageRootNode
702.667 + }
702.668 +
702.669 +
702.670 + @Override
702.671 + public String getName() {
702.672 + String relativePath = FileUtil.getRelativePath(root, dataFolder.getPrimaryFile());
702.673 + return relativePath == null ? null : relativePath.replace('/', '.'); // NOI18N
702.674 + }
702.675 +
702.676 + @Override
702.677 + public Action[] getActions( boolean context ) {
702.678 +
702.679 + if ( !context ) {
702.680 + if ( actions == null ) {
702.681 + // Copy actions and leave out the PropertiesAction and FileSystemAction.
702.682 + Action superActions[] = super.getActions( context );
702.683 + List<Action> actionList = new ArrayList<>(superActions.length);
702.684 +
702.685 + for( int i = 0; i < superActions.length; i++ ) {
702.686 +
702.687 + if ( (i <= superActions.length - 2) && superActions[ i ] == null && superActions[i + 1] instanceof PropertiesAction ) {
702.688 + i ++;
702.689 + continue;
702.690 + }
702.691 + else if ( superActions[i] instanceof PropertiesAction ) {
702.692 + continue;
702.693 + }
702.694 + else if ( superActions[i] instanceof FileSystemAction ) {
702.695 + actionList.add (null); // insert separator and new action
702.696 + actionList.add (FileSensitiveActions.fileCommandAction(ActionProvider.COMMAND_COMPILE_SINGLE,
702.697 + NbBundle.getMessage( PackageViewChildren.class, "LBL_CompilePackage_Action" ), // NOI18N
702.698 + null ));
702.699 + }
702.700 +
702.701 + actionList.add( superActions[i] );
702.702 + }
702.703 +
702.704 + actions = new Action[ actionList.size() ];
702.705 + actionList.toArray( actions );
702.706 + }
702.707 + return actions;
702.708 + }
702.709 + else {
702.710 + return super.getActions( context );
702.711 + }
702.712 + }
702.713 +
702.714 + @Override
702.715 + public boolean canRename() {
702.716 + return !isDefaultPackage;
702.717 + }
702.718 +
702.719 + @Override
702.720 + public boolean canCut () {
702.721 + return !isDefaultPackage;
702.722 + }
702.723 +
702.724 + /**
702.725 + * Copy handling
702.726 + */
702.727 + @Override
702.728 + public Transferable clipboardCopy () throws IOException {
702.729 + try {
702.730 + return new PackageTransferable (this, DnDConstants.ACTION_COPY);
702.731 + } catch (ClassNotFoundException e) {
702.732 + throw new AssertionError(e);
702.733 + }
702.734 + }
702.735 +
702.736 + @Override
702.737 + public Transferable clipboardCut () throws IOException {
702.738 + try {
702.739 + return new PackageTransferable (this, DnDConstants.ACTION_MOVE);
702.740 + } catch (ClassNotFoundException e) {
702.741 + throw new AssertionError(e);
702.742 + }
702.743 + }
702.744 +
702.745 + @Override
702.746 + public /*@Override*/ Transferable drag () throws IOException {
702.747 + try {
702.748 + return new PackageTransferable (this, DnDConstants.ACTION_NONE);
702.749 + } catch (ClassNotFoundException e) {
702.750 + throw new AssertionError(e);
702.751 + }
702.752 + }
702.753 +
702.754 + @Override
702.755 + public PasteType[] getPasteTypes(Transferable t) {
702.756 + if (t.isDataFlavorSupported(ExTransferable.multiFlavor)) {
702.757 + try {
702.758 + MultiTransferObject mto = (MultiTransferObject) t.getTransferData (ExTransferable.multiFlavor);
702.759 + boolean hasPackageFlavor = false;
702.760 + for (int i=0; i < mto.getCount(); i++) {
702.761 + DataFlavor[] flavors = mto.getTransferDataFlavors(i);
702.762 + if (isPackageFlavor(flavors)) {
702.763 + hasPackageFlavor = true;
702.764 + }
702.765 + }
702.766 + return hasPackageFlavor ? new PasteType[0] : super.getPasteTypes (t);
702.767 + } catch (UnsupportedFlavorException | IOException e) {
702.768 + ErrorManager.getDefault().notify(e);
702.769 + return new PasteType[0];
702.770 + }
702.771 + }
702.772 + else {
702.773 + DataFlavor[] flavors = t.getTransferDataFlavors();
702.774 + if (isPackageFlavor(flavors)) {
702.775 + return new PasteType[0];
702.776 + }
702.777 + else {
702.778 + return super.getPasteTypes(t);
702.779 + }
702.780 + }
702.781 + }
702.782 +
702.783 + @Override
702.784 + public /*@Override*/ PasteType getDropType (Transferable t, int action, int index) {
702.785 + if (t.isDataFlavorSupported(ExTransferable.multiFlavor)) {
702.786 + try {
702.787 + MultiTransferObject mto = (MultiTransferObject) t.getTransferData (ExTransferable.multiFlavor);
702.788 + boolean hasPackageFlavor = false;
702.789 + for (int i=0; i < mto.getCount(); i++) {
702.790 + DataFlavor[] flavors = mto.getTransferDataFlavors(i);
702.791 + if (isPackageFlavor(flavors)) {
702.792 + hasPackageFlavor = true;
702.793 + }
702.794 + }
702.795 + return hasPackageFlavor ? null : super.getDropType (t, action, index);
702.796 + } catch (UnsupportedFlavorException | IOException e) {
702.797 + ErrorManager.getDefault().notify(e);
702.798 + return null;
702.799 + }
702.800 + }
702.801 + else {
702.802 + DataFlavor[] flavors = t.getTransferDataFlavors();
702.803 + if (isPackageFlavor(flavors)) {
702.804 + return null;
702.805 + }
702.806 + else {
702.807 + return super.getDropType (t, action, index);
702.808 + }
702.809 + }
702.810 + }
702.811 +
702.812 +
702.813 + private boolean isPackageFlavor (DataFlavor[] flavors) {
702.814 + for (int i=0; i<flavors.length; i++) {
702.815 + if (SUBTYPE.equals(flavors[i].getSubType ()) && PRIMARY_TYPE.equals(flavors[i].getPrimaryType ())) {
702.816 + //Disable pasting into package, only paste into root is allowed
702.817 + return true;
702.818 + }
702.819 + }
702.820 + return false;
702.821 + }
702.822 +
702.823 +// TOR
702.824 +// private synchronized PackageRenameHandler getRenameHandler() {
702.825 +// Collection<? extends PackageRenameHandler> handlers = Lookup.getDefault().lookupAll(PackageRenameHandler.class);
702.826 +// if (handlers.size()==0)
702.827 +// return null;
702.828 +// if (handlers.size()>1)
702.829 +// ErrorManager.getDefault().log(ErrorManager.WARNING, "Multiple instances of PackageRenameHandler found in Lookup; only using first one: " + handlers); //NOI18N
702.830 +// return handlers.iterator().next();
702.831 +// }
702.832 +
702.833 + @Override
702.834 + public void setName(String name) {
702.835 +// PackageRenameHandler handler = getRenameHandler();
702.836 +// if (handler!=null) {
702.837 +// handler.handleRename(this, name);
702.838 +// return;
702.839 +// }
702.840 +
702.841 + if (isDefaultPackage) {
702.842 + return;
702.843 + }
702.844 + String oldName = getName();
702.845 + if (oldName.equals(name)) {
702.846 + return;
702.847 + }
702.848 + if (!isValidPackageName (name)) {
702.849 + DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message (
702.850 + NbBundle.getMessage(PackageViewChildren.class,"MSG_InvalidPackageName"), NotifyDescriptor.INFORMATION_MESSAGE));
702.851 + return;
702.852 + }
702.853 + name = name.replace('.','/')+'/'; //NOI18N
702.854 + oldName = oldName.replace('.','/')+'/'; //NOI18N
702.855 + int i;
702.856 + for (i=0; i<oldName.length() && i< name.length(); i++) {
702.857 + if (oldName.charAt(i) != name.charAt(i)) {
702.858 + break;
702.859 + }
702.860 + }
702.861 + i--;
702.862 + int index = oldName.lastIndexOf('/',i); //NOI18N
702.863 + String commonPrefix = index == -1 ? null : oldName.substring(0,index);
702.864 + String toCreate = (index+1 == name.length()) ? "" : name.substring(index+1); //NOI18N
702.865 + try {
702.866 + FileObject commonFolder = commonPrefix == null ? this.root : this.root.getFileObject(commonPrefix);
702.867 + FileObject destination = commonFolder;
702.868 + StringTokenizer dtk = new StringTokenizer(toCreate,"/"); //NOI18N
702.869 + while (dtk.hasMoreTokens()) {
702.870 + String pathElement = dtk.nextToken();
702.871 + FileObject tmp = destination.getFileObject(pathElement);
702.872 + if (tmp == null) {
702.873 + tmp = destination.createFolder (pathElement);
702.874 + }
702.875 + destination = tmp;
702.876 + }
702.877 + FileObject source = this.dataFolder.getPrimaryFile();
702.878 + DataFolder sourceFolder = DataFolder.findFolder (source);
702.879 + DataFolder destinationFolder = DataFolder.findFolder (destination);
702.880 + DataObject[] children = sourceFolder.getChildren();
702.881 + for (int j=0; j<children.length; j++) {
702.882 + if (children[j].getPrimaryFile().isData()) {
702.883 + children[j].move(destinationFolder);
702.884 + }
702.885 + }
702.886 + while (!commonFolder.equals(source)) {
702.887 + if (source.getChildren().length==0) {
702.888 + FileObject tmp = source;
702.889 + source = source.getParent();
702.890 + tmp.delete();
702.891 + }
702.892 + else {
702.893 + break;
702.894 + }
702.895 + }
702.896 + } catch (IOException ioe) {
702.897 + ErrorManager.getDefault().notify (ioe);
702.898 + }
702.899 + }
702.900 +
702.901 +
702.902 +
702.903 + @Override
702.904 + public boolean canDestroy() {
702.905 + if ( isDefaultPackage ) {
702.906 + return false;
702.907 + }
702.908 + else {
702.909 + return true;
702.910 + }
702.911 + }
702.912 +
702.913 + @Override
702.914 + public void destroy() throws IOException {
702.915 + FileObject parent = dataFolder.getPrimaryFile().getParent();
702.916 + // First; delete all files except packages
702.917 + DataObject ch[] = dataFolder.getChildren();
702.918 + boolean empty = true;
702.919 + for( int i = 0; ch != null && i < ch.length; i++ ) {
702.920 + if ( !ch[i].getPrimaryFile().isFolder() ) {
702.921 + ch[i].delete();
702.922 + }
702.923 + else {
702.924 + empty = false;
702.925 + }
702.926 + }
702.927 +
702.928 + // If empty delete itself
702.929 + if ( empty ) {
702.930 + super.destroy();
702.931 + }
702.932 +
702.933 +
702.934 + // Second; delete empty super packages
702.935 + while( !parent.equals( root ) && parent.getChildren().length == 0 ) {
702.936 + FileObject newParent = parent.getParent();
702.937 + parent.delete();
702.938 + parent = newParent;
702.939 + }
702.940 + }
702.941 +
702.942 + /**
702.943 + * Initially overridden to support CVS status labels in package nodes.
702.944 + *
702.945 + * @return annotated display name
702.946 + */
702.947 + @Override
702.948 + public String getHtmlDisplayName() {
702.949 + String name = getDisplayName();
702.950 + try {
702.951 + FileObject fo = dataFolder.getPrimaryFile();
702.952 + Set<FileObject> set = new NonRecursiveFolderSet(fo);
702.953 + StatusDecorator status = fo.getFileSystem().getDecorator();
702.954 + String htmlName = status.annotateNameHtml(name, set);
702.955 + if (htmlName != null) {
702.956 + name = htmlName;
702.957 + } else {
702.958 + // #89138: return null if the name starts with '<' and status is not HtmlStatus
702.959 + if (name.startsWith("<")) {
702.960 + name = null;
702.961 + } else {
702.962 + name = status.annotateName(name, set);
702.963 + }
702.964 + }
702.965 + } catch (FileStateInvalidException e) {
702.966 + // no fs, do nothing
702.967 + }
702.968 + return name;
702.969 + }
702.970 +
702.971 + @Override
702.972 + public String getDisplayName() {
702.973 + FileObject folder = dataFolder.getPrimaryFile();
702.974 + String path = FileUtil.getRelativePath(root, folder);
702.975 + if (path == null) {
702.976 + // ???
702.977 + return "";
702.978 + }
702.979 + return PackageDisplayUtils.getDisplayLabel( path.replace('/', '.'));
702.980 + }
702.981 +
702.982 + @Override
702.983 + public String getShortDescription() {
702.984 + FileObject folder = dataFolder.getPrimaryFile();
702.985 + String path = FileUtil.getRelativePath(root, folder);
702.986 + if (path == null) {
702.987 + // ???
702.988 + return "";
702.989 + }
702.990 + return PackageDisplayUtils.getToolTip(folder, path.replace('/', '.'));
702.991 + }
702.992 +
702.993 + @Override
702.994 + public Image getIcon (int type) {
702.995 + Image img = getMyIcon (type);
702.996 +
702.997 + try {
702.998 + FileObject fo = dataFolder.getPrimaryFile();
702.999 + Set<FileObject> set = new NonRecursiveFolderSet(fo);
702.1000 + img = FileUIUtils.getImageDecorator(fo.getFileSystem ()).annotateIcon (img, type, set);
702.1001 + } catch (FileStateInvalidException e) {
702.1002 + // no fs, do nothing
702.1003 + }
702.1004 +
702.1005 + return img;
702.1006 + }
702.1007 +
702.1008 + @Override
702.1009 + public Image getOpenedIcon (int type) {
702.1010 + Image img = getMyOpenedIcon(type);
702.1011 +
702.1012 + try {
702.1013 + FileObject fo = dataFolder.getPrimaryFile();
702.1014 + Set<FileObject> set = new NonRecursiveFolderSet(fo);
702.1015 + img = FileUIUtils.getImageDecorator(fo.getFileSystem ()).annotateIcon (img, type, set);
702.1016 + } catch (FileStateInvalidException e) {
702.1017 + // no fs, do nothing
702.1018 + }
702.1019 +
702.1020 + return img;
702.1021 + }
702.1022 +
702.1023 +
702.1024 + private Image getMyIcon(int type) {
702.1025 + FileObject folder = dataFolder.getPrimaryFile();
702.1026 + String path = FileUtil.getRelativePath(root, folder);
702.1027 + if (path == null) {
702.1028 + // ??? - #103711: null cannot be returned because the icon
702.1029 + // must be annotated; general package icon is returned instead
702.1030 + return ImageUtilities.loadImage("org/netbeans/modules/python/project/resources/package.gif"); // NOI18N
702.1031 + }
702.1032 + //return PackageDisplayUtils.getIcon(folder, path.replace('/', '.'), isLeaf() );
702.1033 + return PackageDisplayUtils.getIcon(folder, path.replace('/', '.'),
702.1034 + PackageDisplayUtils.isEmpty(dataFolder.getPrimaryFile(), false, true));
702.1035 + }
702.1036 +
702.1037 + private Image getMyOpenedIcon(int type) {
702.1038 + return getMyIcon(type);
702.1039 + }
702.1040 +
702.1041 + public void update() {
702.1042 + fireIconChange();
702.1043 + fireOpenedIconChange();
702.1044 + }
702.1045 +
702.1046 + public void updateDisplayName() {
702.1047 + fireNameChange(null, null);
702.1048 + fireDisplayNameChange(null, null);
702.1049 + fireShortDescriptionChange(null, null);
702.1050 + }
702.1051 +
702.1052 + public void updateChildren() {
702.1053 + boolean leaf = isLeaf();
702.1054 + DataFolder df = getDataFolder();
702.1055 + boolean empty = isEmpty( df );
702.1056 + if ( leaf != empty ) {
702.1057 + setChildren( empty ? Children.LEAF: df.createNodeChildren( NO_FOLDERS_FILTER ) );
702.1058 + update();
702.1059 + }
702.1060 + }
702.1061 +
702.1062 + @Override
702.1063 + public Node.PropertySet[] getPropertySets () {
702.1064 + Node.PropertySet[] properties = super.getPropertySets ();
702.1065 + for (int i=0; i< properties.length; i++) {
702.1066 + if (Sheet.PROPERTIES.equals(properties[i].getName())) {
702.1067 + //Replace the Sheet.PROPERTIES by the new one
702.1068 + //having only the name property which does refactoring
702.1069 + properties[i] = Sheet.createPropertiesSet();
702.1070 + ((Sheet.Set) properties[i]).put(new PropertySupport.ReadWrite<String>(DataObject.PROP_NAME, String.class,
702.1071 + NbBundle.getMessage(PackageViewChildren.class,"PROP_name"), NbBundle.getMessage(PackageViewChildren.class,"HINT_name")) {
702.1072 + @Override
702.1073 + public String getValue() {
702.1074 + return PackageViewChildren.PackageNode.this.getName();
702.1075 + }
702.1076 + @Override
702.1077 + public void setValue(String n) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
702.1078 + if (!canRename()) {
702.1079 + throw new IllegalAccessException();
702.1080 + }
702.1081 + PackageViewChildren.PackageNode.this.setName(n);
702.1082 + }
702.1083 + @Override
702.1084 + public boolean canWrite() {
702.1085 + return PackageViewChildren.PackageNode.this.canRename();
702.1086 + }
702.1087 + });
702.1088 + }
702.1089 + }
702.1090 + return properties;
702.1091 + }
702.1092 +
702.1093 + private DataFolder getDataFolder() {
702.1094 + return getCookie(DataFolder.class);
702.1095 + }
702.1096 +
702.1097 + private boolean isValidPackageName(String name) {
702.1098 + if (name.length() == 0) {
702.1099 + //Fast check of default pkg
702.1100 + return true;
702.1101 + }
702.1102 + StringTokenizer tk = new StringTokenizer(name,".",true); //NOI18N
702.1103 + boolean delimExpected = false;
702.1104 + while (tk.hasMoreTokens()) {
702.1105 + String namePart = tk.nextToken();
702.1106 + if (!delimExpected) {
702.1107 + if (namePart.equals(".")) { //NOI18N
702.1108 + return false;
702.1109 + }
702.1110 + for (int i=0; i< namePart.length(); i++) {
702.1111 + char c = namePart.charAt(i);
702.1112 + if (i == 0) {
702.1113 + if (!Character.isJavaIdentifierStart (c)) {
702.1114 + return false;
702.1115 + }
702.1116 + }
702.1117 + else {
702.1118 + if (!Character.isJavaIdentifierPart(c)) {
702.1119 + return false;
702.1120 + }
702.1121 + }
702.1122 + }
702.1123 + }
702.1124 + else {
702.1125 + if (!namePart.equals(".")) { //NOI18N
702.1126 + return false;
702.1127 + }
702.1128 + }
702.1129 + delimExpected = !delimExpected;
702.1130 + }
702.1131 + return delimExpected;
702.1132 + }
702.1133 + }
702.1134 +
702.1135 + private static final class NoFoldersContainer
702.1136 + implements DataObject.Container, PropertyChangeListener,
702.1137 + NonRecursiveFolder {
702.1138 + private DataFolder folder;
702.1139 + private PropertyChangeSupport prop = new PropertyChangeSupport (this);
702.1140 +
702.1141 + public NoFoldersContainer (DataFolder folder) {
702.1142 + this.folder = folder;
702.1143 + }
702.1144 +
702.1145 + @Override
702.1146 + public FileObject getFolder() {
702.1147 + return folder.getPrimaryFile();
702.1148 + }
702.1149 +
702.1150 + @Override
702.1151 + public DataObject[] getChildren () {
702.1152 + DataObject[] arr = folder.getChildren ();
702.1153 + List<DataObject> list = new ArrayList<>(arr.length);
702.1154 + for (int i = 0; i < arr.length; i++) {
702.1155 + if (arr[i] instanceof DataFolder) continue;
702.1156 +
702.1157 + list.add (arr[i]);
702.1158 + }
702.1159 + return list.size() == arr.length ? arr : list.toArray(new DataObject[0]);
702.1160 + }
702.1161 +
702.1162 + @Override
702.1163 + public void addPropertyChangeListener(PropertyChangeListener l) {
702.1164 + prop.addPropertyChangeListener (l);
702.1165 + }
702.1166 +
702.1167 + @Override
702.1168 + public void removePropertyChangeListener(PropertyChangeListener l) {
702.1169 + prop.removePropertyChangeListener (l);
702.1170 + }
702.1171 +
702.1172 + @Override
702.1173 + public void propertyChange(PropertyChangeEvent evt) {
702.1174 + if (DataObject.Container.PROP_CHILDREN.equals (evt.getPropertyName ())) {
702.1175 + prop.firePropertyChange (PROP_CHILDREN, null, null);
702.1176 + }
702.1177 + }
702.1178 + }
702.1179 +
702.1180 + private final class NoFoldersDataFilter implements ChangeListener, ChangeableDataFilter, DataFilter.FileBased {
702.1181 +
702.1182 + private final ChangeSupport cs = new ChangeSupport(this);
702.1183 +
702.1184 + public NoFoldersDataFilter() {
702.1185 + VisibilityQuery.getDefault().addChangeListener(WeakListeners.change(this, VisibilityQuery.getDefault()));
702.1186 + }
702.1187 +
702.1188 + @Override
702.1189 + public boolean acceptDataObject(DataObject obj) {
702.1190 + // Filter out .pyc or .pyo files!
702.1191 + String ext = obj.getPrimaryFile().getExt();
702.1192 + if ("pyc".equals(ext) || "pyo".equals(ext)) { // NOI18N
702.1193 + return false;
702.1194 + }
702.1195 + return acceptFileObject(obj.getPrimaryFile());
702.1196 + }
702.1197 +
702.1198 + @Override
702.1199 + public void stateChanged( ChangeEvent e) {
702.1200 + cs.fireChange();
702.1201 + }
702.1202 +
702.1203 + @Override
702.1204 + public void addChangeListener( ChangeListener listener ) {
702.1205 + cs.addChangeListener(listener);
702.1206 + }
702.1207 +
702.1208 + @Override
702.1209 + public void removeChangeListener( ChangeListener listener ) {
702.1210 + cs.removeChangeListener(listener);
702.1211 + }
702.1212 +
702.1213 + @Override
702.1214 + public boolean acceptFileObject(FileObject fo) {
702.1215 + return fo.isValid() && VisibilityQuery.getDefault().isVisible(fo) && fo.isData() && group.contains(fo);
702.1216 + }
702.1217 +
702.1218 + }
702.1219 +
702.1220 + static class PackageTransferable extends ExTransferable.Single {
702.1221 +
702.1222 + private PackageNode node;
702.1223 +
702.1224 + public PackageTransferable (PackageNode node, int operation) throws ClassNotFoundException {
702.1225 + super(new DataFlavor(PACKAGE_FLAVOR.format(new Object[] {new Integer(operation)}), null, PackageNode.class.getClassLoader()));
702.1226 + this.node = node;
702.1227 + }
702.1228 +
702.1229 + @Override
702.1230 + protected Object getData() throws IOException, UnsupportedFlavorException {
702.1231 + return this.node;
702.1232 + }
702.1233 + }
702.1234 +
702.1235 +
702.1236 + static class PackagePasteType extends PasteType {
702.1237 +
702.1238 + private int op;
702.1239 + private PackageNode[] nodes;
702.1240 + private FileObject srcRoot;
702.1241 +
702.1242 + public PackagePasteType (FileObject srcRoot, PackageNode[] node, int op) {
702.1243 + assert op == DnDConstants.ACTION_COPY || op == DnDConstants.ACTION_MOVE || op == DnDConstants.ACTION_NONE : "Invalid DnD operation"; //NOI18N
702.1244 + this.nodes = node;
702.1245 + this.op = op;
702.1246 + this.srcRoot = srcRoot;
702.1247 + }
702.1248 +
702.1249 + public void setOperation (int op) {
702.1250 + this.op = op;
702.1251 + }
702.1252 +
702.1253 + @Override
702.1254 + public Transferable paste() throws IOException {
702.1255 + assert this.op != DnDConstants.ACTION_NONE;
702.1256 + for (int ni=0; ni< nodes.length; ni++) {
702.1257 + FileObject fo = srcRoot;
702.1258 + if (!nodes[ni].isDefaultPackage) {
702.1259 + String pkgName = nodes[ni].getName();
702.1260 + StringTokenizer tk = new StringTokenizer(pkgName,"."); //NOI18N
702.1261 + while (tk.hasMoreTokens()) {
702.1262 + String name = tk.nextToken();
702.1263 + FileObject tmp = fo.getFileObject(name,null);
702.1264 + if (tmp == null) {
702.1265 + tmp = fo.createFolder(name);
702.1266 + }
702.1267 + fo = tmp;
702.1268 + }
702.1269 + }
702.1270 + DataFolder dest = DataFolder.findFolder(fo);
702.1271 + DataObject[] children = nodes[ni].dataFolder.getChildren();
702.1272 + boolean cantDelete = false;
702.1273 + for (int i=0; i< children.length; i++) {
702.1274 + if (children[i].getPrimaryFile().isData()
702.1275 + && VisibilityQuery.getDefault().isVisible (children[i].getPrimaryFile())) {
702.1276 + //Copy only the package level
702.1277 + if (this.op == DnDConstants.ACTION_MOVE) {
702.1278 + children[i].move(dest);
702.1279 + }
702.1280 + else {
702.1281 + children[i].copy (dest);
702.1282 + }
702.1283 + }
702.1284 + else {
702.1285 + cantDelete = true;
702.1286 + }
702.1287 + }
702.1288 + if (this.op == DnDConstants.ACTION_MOVE && !cantDelete) {
702.1289 + try {
702.1290 + FileObject tmpFo = nodes[ni].dataFolder.getPrimaryFile();
702.1291 + FileObject originalRoot = nodes[ni].root;
702.1292 + assert tmpFo != null && originalRoot != null;
702.1293 + while (!tmpFo.equals(originalRoot)) {
702.1294 + if (tmpFo.getChildren().length == 0) {
702.1295 + FileObject tmpFoParent = tmpFo.getParent();
702.1296 + tmpFo.delete ();
702.1297 + tmpFo = tmpFoParent;
702.1298 + }
702.1299 + else {
702.1300 + break;
702.1301 + }
702.1302 + }
702.1303 + } catch (IOException ioe) {
702.1304 + //Not important
702.1305 + }
702.1306 + }
702.1307 + }
702.1308 + return ExTransferable.EMPTY;
702.1309 + }
702.1310 +
702.1311 + @Override
702.1312 + public String getName() {
702.1313 + return NbBundle.getMessage(PackageViewChildren.class,"TXT_PastePackage");
702.1314 + }
702.1315 + }
702.1316 +
702.1317 + /**
702.1318 + * FileObject set that represents package. It means
702.1319 + * that it's content must not be processed recursively.
702.1320 + */
702.1321 + private static class NonRecursiveFolderSet extends HashSet<FileObject> implements NonRecursiveFolder {
702.1322 +
702.1323 + private final FileObject folder;
702.1324 +
702.1325 + /**
702.1326 + * Creates set with one element, the folder.
702.1327 + */
702.1328 + public NonRecursiveFolderSet(FileObject folder) {
702.1329 + this.folder = folder;
702.1330 + add(folder);
702.1331 + }
702.1332 +
702.1333 + @Override
702.1334 + public FileObject getFolder() {
702.1335 + return folder;
702.1336 + }
702.1337 + }
702.1338 +}
703.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
703.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/PythonProjectSettings.java Sat Feb 28 17:25:32 2015 -0800
703.3 @@ -0,0 +1,119 @@
703.4 +/*
703.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
703.6 + *
703.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
703.8 + *
703.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
703.10 + * Other names may be trademarks of their respective owners.
703.11 + *
703.12 + * The contents of this file are subject to the terms of either the GNU
703.13 + * General Public License Version 2 only ("GPL") or the Common
703.14 + * Development and Distribution License("CDDL") (collectively, the
703.15 + * "License"). You may not use this file except in compliance with the
703.16 + * License. You can obtain a copy of the License at
703.17 + * http://www.netbeans.org/cddl-gplv2.html
703.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
703.19 + * specific language governing permissions and limitations under the
703.20 + * License. When distributing the software, include this License Header
703.21 + * Notice in each file and include the License file at
703.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
703.23 + * particular file as subject to the "Classpath" exception as provided
703.24 + * by Oracle in the GPL Version 2 section of the License file that
703.25 + * accompanied this code. If applicable, add the following below the
703.26 + * License Header, with the fields enclosed by brackets [] replaced by
703.27 + * your own identifying information:
703.28 + * "Portions Copyrighted [year] [name of copyright owner]"
703.29 + *
703.30 + * Contributor(s):
703.31 + *
703.32 + * The Original Software is NetBeans. The Initial Developer of the Original
703.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
703.34 + * Microsystems, Inc. All Rights Reserved.
703.35 + *
703.36 + * If you wish your version of this file to be governed by only the CDDL
703.37 + * or only the GPL Version 2, indicate your decision by adding
703.38 + * "[Contributor] elects to include this software in this distribution
703.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
703.40 + * single choice of license, a recipient has the option to distribute
703.41 + * your version of this file under either the CDDL, the GPL Version 2 or
703.42 + * to extend the choice of license to its licensees as provided above.
703.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
703.44 + * Version 2 license, then the option applies only if the new code is
703.45 + * made subject to such option by the copyright holder.
703.46 + */
703.47 +
703.48 +package org.netbeans.modules.python.project2.ui;
703.49 +
703.50 +import java.beans.PropertyChangeListener;
703.51 +import java.beans.PropertyChangeSupport;
703.52 +import java.util.prefs.Preferences;
703.53 +import org.openide.util.NbPreferences;
703.54 +
703.55 +/**
703.56 + * Preferences for the module.
703.57 + * <p>
703.58 + * <b>This is copied from the corresponding Java action in java.projects (JavaProjectSettings)</b>
703.59 + * </p>
703.60 + *
703.61 + * @author Tomas Zezula, Jesse Glick
703.62 + */
703.63 +public class PythonProjectSettings {
703.64 +
703.65 + private PythonProjectSettings() {}
703.66 +
703.67 + private static final PropertyChangeSupport pcs = new PropertyChangeSupport(PythonProjectSettings.class);
703.68 +
703.69 + /**
703.70 + * The package view should be displayed as a list of packages.
703.71 + */
703.72 + public static final int TYPE_PACKAGE_VIEW = 0;
703.73 +
703.74 + /**
703.75 + * The package view should be displayed as a tree of folders.
703.76 + */
703.77 + public static final int TYPE_TREE = 1;
703.78 +
703.79 + public static final String PROP_PACKAGE_VIEW_TYPE = "packageViewType"; //NOI18N
703.80 +// private static final String PROP_SHOW_AGAIN_BROKEN_REF_ALERT = "showAgainBrokenRefAlert"; //NOI18N
703.81 +
703.82 + private static Preferences prefs() {
703.83 + return NbPreferences.forModule(PythonProjectSettings.class);
703.84 + }
703.85 +
703.86 + /**
703.87 + * Returns how the package view should be displayed.
703.88 + * @return {@link #TYPE_PACKAGE_VIEW} or {@link #TYPE_TREE}
703.89 + */
703.90 + public static int getPackageViewType() {
703.91 + return prefs().getInt(PROP_PACKAGE_VIEW_TYPE, TYPE_PACKAGE_VIEW);
703.92 + }
703.93 +
703.94 + /**
703.95 + * Sets how the package view should be displayed.
703.96 + * @param type either {@link #TYPE_PACKAGE_VIEW} or {@link #TYPE_TREE}
703.97 + */
703.98 + public static void setPackageViewType(int type) {
703.99 + int currentType = getPackageViewType();
703.100 + if (currentType != type) {
703.101 + prefs().putInt(PROP_PACKAGE_VIEW_TYPE, type);
703.102 + pcs.firePropertyChange(PROP_PACKAGE_VIEW_TYPE, currentType, type);
703.103 + }
703.104 + }
703.105 +
703.106 +// public static boolean isShowAgainBrokenRefAlert() {
703.107 +// return prefs().getBoolean(PROP_SHOW_AGAIN_BROKEN_REF_ALERT, true);
703.108 +// }
703.109 +//
703.110 +// public static void setShowAgainBrokenRefAlert(boolean again) {
703.111 +// prefs().putBoolean(PROP_SHOW_AGAIN_BROKEN_REF_ALERT, again);
703.112 +// }
703.113 +
703.114 + public static void addPropertyChangeListener(PropertyChangeListener l) {
703.115 + pcs.addPropertyChangeListener(l);
703.116 + }
703.117 +
703.118 + public static void removePropertyChangeListener(PropertyChangeListener l) {
703.119 + pcs.removePropertyChangeListener(l);
703.120 + }
703.121 +
703.122 +}
704.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
704.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/SourceNodeFactory.java Sat Feb 28 17:25:32 2015 -0800
704.3 @@ -0,0 +1,257 @@
704.4 +/*
704.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
704.6 + *
704.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
704.8 + *
704.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
704.10 + * Other names may be trademarks of their respective owners.
704.11 + *
704.12 + * The contents of this file are subject to the terms of either the GNU
704.13 + * General Public License Version 2 only ("GPL") or the Common
704.14 + * Development and Distribution License("CDDL") (collectively, the
704.15 + * "License"). You may not use this file except in compliance with the
704.16 + * License. You can obtain a copy of the License at
704.17 + * http://www.netbeans.org/cddl-gplv2.html
704.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
704.19 + * specific language governing permissions and limitations under the
704.20 + * License. When distributing the software, include this License Header
704.21 + * Notice in each file and include the License file at
704.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
704.23 + * particular file as subject to the "Classpath" exception as provided
704.24 + * by Oracle in the GPL Version 2 section of the License file that
704.25 + * accompanied this code. If applicable, add the following below the
704.26 + * License Header, with the fields enclosed by brackets [] replaced by
704.27 + * your own identifying information:
704.28 + * "Portions Copyrighted [year] [name of copyright owner]"
704.29 + *
704.30 + * Contributor(s):
704.31 + *
704.32 + * The Original Software is NetBeans. The Initial Developer of the Original
704.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
704.34 + * Microsystems, Inc. All Rights Reserved.
704.35 + *
704.36 + * If you wish your version of this file to be governed by only the CDDL
704.37 + * or only the GPL Version 2, indicate your decision by adding
704.38 + * "[Contributor] elects to include this software in this distribution
704.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
704.40 + * single choice of license, a recipient has the option to distribute
704.41 + * your version of this file under either the CDDL, the GPL Version 2 or
704.42 + * to extend the choice of license to its licensees as provided above.
704.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
704.44 + * Version 2 license, then the option applies only if the new code is
704.45 + * made subject to such option by the copyright holder.
704.46 + */
704.47 +
704.48 +package org.netbeans.modules.python.project2.ui;
704.49 +
704.50 +import java.awt.event.ActionEvent;
704.51 +import java.util.ArrayList;
704.52 +import java.util.Collections;
704.53 +import java.util.List;
704.54 +import javax.swing.AbstractAction;
704.55 +import javax.swing.Action;
704.56 +import javax.swing.SwingUtilities;
704.57 +import javax.swing.event.ChangeEvent;
704.58 +import javax.swing.event.ChangeListener;
704.59 +import org.netbeans.modules.python.project2.PythonProject2;
704.60 +import org.netbeans.api.project.Project;
704.61 +import org.netbeans.api.project.ProjectUtils;
704.62 +import org.netbeans.api.project.SourceGroup;
704.63 +import org.netbeans.api.project.Sources;
704.64 +import org.netbeans.spi.project.ui.support.NodeFactory;
704.65 +import org.netbeans.spi.project.ui.support.NodeList;
704.66 +import org.openide.filesystems.FileObject;
704.67 +import org.openide.nodes.FilterNode;
704.68 +import org.openide.nodes.Node;
704.69 +import org.openide.util.ChangeSupport;
704.70 +import org.openide.util.NbBundle;
704.71 +
704.72 +/**
704.73 + * Source roots view
704.74 + * @author Tomas Zezula
704.75 + */
704.76 +@NbBundle.Messages({"LBL_Properties_Action=Properties"})
704.77 +public final class SourceNodeFactory implements NodeFactory {
704.78 + public SourceNodeFactory() {
704.79 + }
704.80 +
704.81 + @Override
704.82 + public NodeList createNodes(Project p) {
704.83 + PythonProject2 project = (PythonProject2)p.getLookup().lookup(PythonProject2.class);
704.84 + assert project != null;
704.85 + return new SourcesNodeList(project);
704.86 + }
704.87 +
704.88 + private static class SourcesNodeList implements NodeList<SourceGroupKey>, ChangeListener {
704.89 +
704.90 + private PythonProject2 project;
704.91 +
704.92 + private final ChangeSupport changeSupport = new ChangeSupport(this);
704.93 +
704.94 + public SourcesNodeList(PythonProject2 proj) {
704.95 + project = proj;
704.96 + }
704.97 +
704.98 + @Override
704.99 + public List<SourceGroupKey> keys() {
704.100 + if (this.project.getProjectDirectory() == null || !this.project.getProjectDirectory().isValid()) {
704.101 + return Collections.EMPTY_LIST;
704.102 + }
704.103 + Sources sources = getSources();
704.104 + SourceGroup[] groups = sources.getSourceGroups(PythonProject2.SOURCES_TYPE_PYTHON);
704.105 +
704.106 + List result = new ArrayList(groups.length);
704.107 + for (SourceGroup group : groups) {
704.108 + result.add(new SourceGroupKey(group));
704.109 + }
704.110 + return result;
704.111 + }
704.112 +
704.113 + @Override
704.114 + public void addChangeListener(ChangeListener l) {
704.115 + changeSupport.addChangeListener(l);
704.116 + }
704.117 +
704.118 + @Override
704.119 + public void removeChangeListener(ChangeListener l) {
704.120 + changeSupport.removeChangeListener(l);
704.121 + }
704.122 +
704.123 + @Override
704.124 + public Node node(SourceGroupKey key) {
704.125 + return new PackageViewFilterNode(key.group, project);
704.126 + }
704.127 +
704.128 + @Override
704.129 + public void addNotify() {
704.130 + getSources().addChangeListener(this);
704.131 + }
704.132 +
704.133 + @Override
704.134 + public void removeNotify() {
704.135 + getSources().removeChangeListener(this);
704.136 + }
704.137 +
704.138 + @Override
704.139 + public void stateChanged(ChangeEvent e) {
704.140 + // setKeys(getKeys());
704.141 + // The caller holds ProjectManager.mutex() read lock
704.142 + SwingUtilities.invokeLater(new Runnable() {
704.143 + @Override
704.144 + public void run() {
704.145 + changeSupport.fireChange();
704.146 + }
704.147 + });
704.148 + }
704.149 +
704.150 + private Sources getSources() {
704.151 + return ProjectUtils.getSources(project);
704.152 + }
704.153 +
704.154 + }
704.155 +
704.156 + private static class SourceGroupKey {
704.157 +
704.158 + public final SourceGroup group;
704.159 + public final FileObject fileObject;
704.160 +
704.161 + SourceGroupKey(SourceGroup group) {
704.162 + this.group = group;
704.163 + this.fileObject = group.getRootFolder();
704.164 + }
704.165 +
704.166 + @Override
704.167 + public int hashCode() {
704.168 + int hash = 5;
704.169 + String disp = this.group.getDisplayName();
704.170 + hash = 79 * hash + (fileObject != null ? fileObject.hashCode() : 0);
704.171 + hash = 79 * hash + (disp != null ? disp.hashCode() : 0);
704.172 + return hash;
704.173 + }
704.174 +
704.175 + @Override
704.176 + public boolean equals(Object obj) {
704.177 + if (!(obj instanceof SourceGroupKey)) {
704.178 + return false;
704.179 + } else {
704.180 + SourceGroupKey otherKey = (SourceGroupKey) obj;
704.181 +
704.182 + if (fileObject != otherKey.fileObject && (fileObject == null || !fileObject.equals(otherKey.fileObject))) {
704.183 + return false;
704.184 + }
704.185 + String thisDisplayName = this.group.getDisplayName();
704.186 + String otherDisplayName = otherKey.group.getDisplayName();
704.187 + boolean oneNull = thisDisplayName == null;
704.188 + boolean twoNull = otherDisplayName == null;
704.189 + return !(oneNull != twoNull || !thisDisplayName.equals(otherDisplayName));
704.190 + }
704.191 + }
704.192 +
704.193 +
704.194 + }
704.195 +
704.196 + /** Yet another cool filter node just to add properties action
704.197 + */
704.198 + private static class PackageViewFilterNode extends FilterNode {
704.199 +
704.200 + private String nodeName;
704.201 + private Project project;
704.202 +
704.203 + Action[] actions;
704.204 +
704.205 + public PackageViewFilterNode(SourceGroup sourceGroup, Project project) {
704.206 + super(PackageView.createPackageView(sourceGroup));
704.207 + this.project = project;
704.208 + this.nodeName = "Sources"; //NOI18N
704.209 + }
704.210 +
704.211 + @Override
704.212 + public Action[] getActions(boolean context) {
704.213 + if (!context) {
704.214 + if (actions == null) {
704.215 + Action superActions[] = super.getActions(context);
704.216 + actions = new Action[superActions.length + 2];
704.217 + System.arraycopy(superActions, 0, actions, 0, superActions.length);
704.218 + actions[superActions.length] = null;
704.219 + actions[superActions.length + 1] = new PreselectPropertiesAction(project, nodeName);
704.220 + }
704.221 + return actions;
704.222 + } else {
704.223 + return super.getActions(context);
704.224 + }
704.225 + }
704.226 +
704.227 + }
704.228 +
704.229 +
704.230 + /** The special properties action
704.231 + */
704.232 + static class PreselectPropertiesAction extends AbstractAction {
704.233 +
704.234 + private final Project project;
704.235 + private final String nodeName;
704.236 + private final String panelName;
704.237 +
704.238 + public PreselectPropertiesAction(Project project, String nodeName) {
704.239 + this(project, nodeName, null);
704.240 + }
704.241 +
704.242 + public PreselectPropertiesAction(Project project, String nodeName, String panelName) {
704.243 + super(NbBundle.getMessage(SourceNodeFactory.class, "LBL_Properties_Action"));
704.244 + this.project = project;
704.245 + this.nodeName = nodeName;
704.246 + this.panelName = panelName;
704.247 + }
704.248 +
704.249 + @Override
704.250 + public void actionPerformed(ActionEvent e) {
704.251 +//todo: Add customizer
704.252 +// CustomizerProviderImpl cp = (CustomizerProviderImpl) project.getLookup().lookup(CustomizerProviderImpl.class);
704.253 +// if (cp != null) {
704.254 +// cp.showCustomizer(nodeName, panelName);
704.255 +// }
704.256 +
704.257 + }
704.258 + }
704.259 +
704.260 +}
705.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
705.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/TreeRootNode.java Sat Feb 28 17:25:32 2015 -0800
705.3 @@ -0,0 +1,312 @@
705.4 +/*
705.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
705.6 + *
705.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
705.8 + *
705.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
705.10 + * Other names may be trademarks of their respective owners.
705.11 + *
705.12 + * The contents of this file are subject to the terms of either the GNU
705.13 + * General Public License Version 2 only ("GPL") or the Common
705.14 + * Development and Distribution License("CDDL") (collectively, the
705.15 + * "License"). You may not use this file except in compliance with the
705.16 + * License. You can obtain a copy of the License at
705.17 + * http://www.netbeans.org/cddl-gplv2.html
705.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
705.19 + * specific language governing permissions and limitations under the
705.20 + * License. When distributing the software, include this License Header
705.21 + * Notice in each file and include the License file at
705.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
705.23 + * particular file as subject to the "Classpath" exception as provided
705.24 + * by Oracle in the GPL Version 2 section of the License file that
705.25 + * accompanied this code. If applicable, add the following below the
705.26 + * License Header, with the fields enclosed by brackets [] replaced by
705.27 + * your own identifying information:
705.28 + * "Portions Copyrighted [year] [name of copyright owner]"
705.29 + *
705.30 + * Contributor(s):
705.31 + *
705.32 + * The Original Software is NetBeans. The Initial Developer of the Original
705.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
705.34 + * Microsystems, Inc. All Rights Reserved.
705.35 + *
705.36 + * If you wish your version of this file to be governed by only the CDDL
705.37 + * or only the GPL Version 2, indicate your decision by adding
705.38 + * "[Contributor] elects to include this software in this distribution
705.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
705.40 + * single choice of license, a recipient has the option to distribute
705.41 + * your version of this file under either the CDDL, the GPL Version 2 or
705.42 + * to extend the choice of license to its licensees as provided above.
705.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
705.44 + * Version 2 license, then the option applies only if the new code is
705.45 + * made subject to such option by the copyright holder.
705.46 + */
705.47 +package org.netbeans.modules.python.project2.ui;
705.48 +
705.49 +import java.awt.EventQueue;
705.50 +import java.awt.Image;
705.51 +import java.beans.PropertyChangeEvent;
705.52 +import java.beans.PropertyChangeListener;
705.53 +import java.util.ArrayList;
705.54 +import java.util.Collections;
705.55 +import java.util.List;
705.56 +import java.util.StringTokenizer;
705.57 +import java.util.logging.Level;
705.58 +import java.util.logging.Logger;
705.59 +import javax.swing.Icon;
705.60 +import javax.swing.event.ChangeEvent;
705.61 +import javax.swing.event.ChangeListener;
705.62 +import javax.swing.event.EventListenerList;
705.63 +import org.netbeans.api.project.SourceGroup;
705.64 +import org.netbeans.api.queries.VisibilityQuery;
705.65 +import org.openide.DialogDisplayer;
705.66 +import org.openide.NotifyDescriptor;
705.67 +import org.openide.filesystems.FileObject;
705.68 +import org.openide.filesystems.FileUtil;
705.69 +import org.openide.loaders.ChangeableDataFilter;
705.70 +import org.openide.loaders.DataFolder;
705.71 +import org.openide.loaders.DataObject;
705.72 +import org.openide.nodes.FilterNode;
705.73 +import org.openide.nodes.Node;
705.74 +import org.openide.nodes.NodeNotFoundException;
705.75 +import org.openide.nodes.NodeOp;
705.76 +import org.openide.util.ImageUtilities;
705.77 +import org.openide.util.NbBundle;
705.78 +import org.openide.util.Utilities;
705.79 +import org.openide.util.WeakListeners;
705.80 +import org.openide.util.lookup.Lookups;
705.81 +import org.openide.util.lookup.ProxyLookup;
705.82 +
705.83 +/**
705.84 + * Copied from java.project API module, the same copy is in ruby project, rails project, etc.
705.85 + * Unlike PackageViewChildren this class definitelly requires more generic API module, probably projectui.
705.86 + * Displays a package root in a tree.
705.87 + * @see "#42151"
705.88 + * @author Jesse Glick
705.89 + */
705.90 +public final class TreeRootNode extends FilterNode implements PropertyChangeListener {
705.91 +
705.92 + private final static Image SOURCE_ROOT_BADGE = ImageUtilities.loadImage("org/netbeans/modules/python/project2/resources/sourceBadge.gif"); // NOI18N
705.93 + private final SourceGroup g;
705.94 +
705.95 + public TreeRootNode(SourceGroup g) {
705.96 + this(DataFolder.findFolder(g.getRootFolder()), g);
705.97 + }
705.98 +
705.99 + private TreeRootNode(DataFolder folder, SourceGroup g) {
705.100 + this(new FilterNode(folder.getNodeDelegate(), folder.createNodeChildren(new VisibilityQueryDataFilter(g))), g);
705.101 + }
705.102 +
705.103 + @SuppressWarnings("LeakingThisInConstructor")
705.104 + private TreeRootNode(Node originalNode, SourceGroup g) {
705.105 + super(originalNode, new PackageFilterChildren(originalNode),
705.106 + new ProxyLookup(
705.107 + originalNode.getLookup(),
705.108 + Lookups.singleton(new PathFinder(g)) // no need for explicit search info
705.109 + ));
705.110 + this.g = g;
705.111 + g.addPropertyChangeListener(WeakListeners.propertyChange(this, g));
705.112 + }
705.113 +
705.114 + /** Copied from PackageRootNode with modifications. */
705.115 + private Image computeIcon(boolean opened, int type) {
705.116 + Icon icon = g.getIcon(opened);
705.117 + if (icon == null) {
705.118 + Image image = opened ? super.getOpenedIcon(type) : super.getIcon(type);
705.119 + return ImageUtilities.mergeImages(image, SOURCE_ROOT_BADGE, 7, 7);
705.120 + } else {
705.121 + return ImageUtilities.icon2Image(icon);
705.122 + }
705.123 + }
705.124 +
705.125 + @Override
705.126 + public Image getIcon(int type) {
705.127 + return computeIcon(false, type);
705.128 + }
705.129 +
705.130 + @Override
705.131 + public Image getOpenedIcon(int type) {
705.132 + return computeIcon(true, type);
705.133 + }
705.134 +
705.135 + @Override
705.136 + public String getName() {
705.137 + return g.getName();
705.138 + }
705.139 +
705.140 + @Override
705.141 + public String getDisplayName() {
705.142 + return g.getDisplayName();
705.143 + }
705.144 +
705.145 + @Override
705.146 + public boolean canRename() {
705.147 + return false;
705.148 + }
705.149 +
705.150 + @Override
705.151 + public boolean canDestroy() {
705.152 + return false;
705.153 + }
705.154 +
705.155 + @Override
705.156 + public boolean canCut() {
705.157 + return false;
705.158 + }
705.159 +
705.160 + @Override
705.161 + public void propertyChange(PropertyChangeEvent ev) {
705.162 + // XXX handle SourceGroup.rootFolder change too
705.163 + EventQueue.invokeLater(new Runnable() {
705.164 +
705.165 + @Override
705.166 + public void run() {
705.167 + fireNameChange(null, null);
705.168 + fireDisplayNameChange(null, null);
705.169 + fireIconChange();
705.170 + fireOpenedIconChange();
705.171 + }
705.172 + });
705.173 + }
705.174 +
705.175 + /** Copied from PhysicalView and PackageRootNode. */
705.176 + public static final class PathFinder {
705.177 +
705.178 + private final SourceGroup g;
705.179 +
705.180 + PathFinder(SourceGroup g) {
705.181 + this.g = g;
705.182 + }
705.183 +
705.184 + public Node findPath(Node rootNode, Object o) {
705.185 + FileObject fo;
705.186 + if (o instanceof FileObject) {
705.187 + fo = (FileObject) o;
705.188 + } else if (o instanceof DataObject) {
705.189 + fo = ((DataObject) o).getPrimaryFile();
705.190 + } else {
705.191 + return null;
705.192 + }
705.193 + FileObject groupRoot = g.getRootFolder();
705.194 + if (FileUtil.isParentOf(groupRoot, fo) /* && group.contains(fo) */) {
705.195 + FileObject folder = fo.isFolder() ? fo : fo.getParent();
705.196 + String relPath = FileUtil.getRelativePath(groupRoot, folder);
705.197 + List<String> path = new ArrayList<>();
705.198 + StringTokenizer strtok = new StringTokenizer(relPath, "/"); // NOI18N
705.199 + while (strtok.hasMoreTokens()) {
705.200 + String token = strtok.nextToken();
705.201 + path.add(token);
705.202 + }
705.203 + try {
705.204 + Node folderNode = folder.equals(groupRoot) ? rootNode : NodeOp.findPath(rootNode, Collections.enumeration(path));
705.205 + if (fo.isFolder()) {
705.206 + return folderNode;
705.207 + } else {
705.208 + Node[] childs = folderNode.getChildren().getNodes(true);
705.209 + for (Node child : childs) {
705.210 + DataObject dobj = child.getLookup().lookup(DataObject.class);
705.211 + if (dobj != null && dobj.getPrimaryFile().getNameExt().equals(fo.getNameExt())) {
705.212 + return child;
705.213 + }
705.214 + }
705.215 + }
705.216 + } catch (NodeNotFoundException e) {
705.217 + LOG.log(Level.WARNING, "TreeRootNode.findPath", e);
705.218 + }
705.219 + } else if (groupRoot.equals(fo)) {
705.220 + return rootNode;
705.221 + }
705.222 + return null;
705.223 + }
705.224 + private static final Logger LOG = Logger.getLogger(PathFinder.class.getName());
705.225 + }
705.226 +
705.227 + private static final class VisibilityQueryDataFilter implements ChangeListener, PropertyChangeListener, ChangeableDataFilter {
705.228 +
705.229 + private static final long serialVersionUID = 1L; // in case a DataFolder.ClonedFilterHandle saves me
705.230 + private final EventListenerList ell = new EventListenerList();
705.231 + private final SourceGroup g;
705.232 +
705.233 + @SuppressWarnings("LeakingThisInConstructor")
705.234 + public VisibilityQueryDataFilter(SourceGroup g) {
705.235 + this.g = g;
705.236 + VisibilityQuery.getDefault().addChangeListener(WeakListeners.change(this, VisibilityQuery.getDefault()));
705.237 + g.addPropertyChangeListener(WeakListeners.propertyChange(this, g));
705.238 + }
705.239 +
705.240 + @Override
705.241 + public boolean acceptDataObject(DataObject obj) {
705.242 + FileObject fo = obj.getPrimaryFile();
705.243 + if (fo.getExt().equalsIgnoreCase("pyc") || fo.getExt().equalsIgnoreCase("pyo") | fo.getExt().equalsIgnoreCase("egg-info") || fo.getName().equalsIgnoreCase("build") || fo.getName().equalsIgnoreCase("dist")) {
705.244 + return false;
705.245 + }
705.246 + return g.contains(fo) &&
705.247 + VisibilityQuery.getDefault().isVisible(fo);
705.248 + }
705.249 +
705.250 + @Override
705.251 + public void stateChanged(ChangeEvent e) {
705.252 + fireChange();
705.253 + }
705.254 +
705.255 + @Override
705.256 + public void propertyChange(PropertyChangeEvent e) {
705.257 + if (SourceGroup.PROP_CONTAINERSHIP.equals(e.getPropertyName())) {
705.258 + fireChange();
705.259 + }
705.260 + }
705.261 +
705.262 + private void fireChange() {
705.263 + Object[] listeners = ell.getListenerList();
705.264 + ChangeEvent event = null;
705.265 + for (int i = listeners.length - 2; i >= 0; i -= 2) {
705.266 + if (listeners[i] == ChangeListener.class) {
705.267 + if (event == null) {
705.268 + event = new ChangeEvent(this);
705.269 + }
705.270 + ((ChangeListener) listeners[i + 1]).stateChanged(event);
705.271 + }
705.272 + }
705.273 + }
705.274 +
705.275 + @Override
705.276 + public void addChangeListener(ChangeListener listener) {
705.277 + ell.add(ChangeListener.class, listener);
705.278 + }
705.279 +
705.280 + @Override
705.281 + public void removeChangeListener(ChangeListener listener) {
705.282 + ell.remove(ChangeListener.class, listener);
705.283 + }
705.284 + }
705.285 +
705.286 + private static final class PackageFilterChildren extends FilterNode.Children {
705.287 +
705.288 + public PackageFilterChildren(final Node originalNode) {
705.289 + super(originalNode);
705.290 + }
705.291 +
705.292 + @Override
705.293 + protected Node copyNode(final Node originalNode) {
705.294 + DataObject dobj = originalNode.getLookup().lookup(DataObject.class);
705.295 + return (dobj instanceof DataFolder) ? new PackageFilterNode(originalNode) : super.copyNode(originalNode);
705.296 + }
705.297 + }
705.298 +
705.299 + private static final class PackageFilterNode extends FilterNode {
705.300 +
705.301 + public PackageFilterNode(final Node origNode) {
705.302 + super(origNode, new PackageFilterChildren(origNode));
705.303 + }
705.304 +
705.305 + @Override
705.306 + public void setName(final String name) {
705.307 + if (Utilities.isJavaIdentifier(name)) {
705.308 + super.setName(name);
705.309 + } else {
705.310 + DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
705.311 + NbBundle.getMessage(TreeRootNode.class, "MSG_InvalidPackageName"), NotifyDescriptor.INFORMATION_MESSAGE));
705.312 + }
705.313 + }
705.314 + }
705.315 +}
706.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
706.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/Utils.java Sat Feb 28 17:25:32 2015 -0800
706.3 @@ -0,0 +1,166 @@
706.4 +package org.netbeans.modules.python.project2.ui;
706.5 +
706.6 +import java.awt.Component;
706.7 +import java.io.File;
706.8 +import java.util.Iterator;
706.9 +import java.util.List;
706.10 +import javax.swing.ComboBoxModel;
706.11 +import javax.swing.DefaultComboBoxModel;
706.12 +import javax.swing.JButton;
706.13 +import javax.swing.JComponent;
706.14 +import javax.swing.JFileChooser;
706.15 +import javax.swing.JList;
706.16 +import javax.swing.JTable;
706.17 +import javax.swing.ListCellRenderer;
706.18 +import javax.swing.table.DefaultTableCellRenderer;
706.19 +import javax.swing.table.DefaultTableModel;
706.20 +import javax.swing.table.TableModel;
706.21 +import org.netbeans.modules.python.api.PythonPlatform;
706.22 +import org.netbeans.modules.python.api.PythonPlatformManager;
706.23 +import org.netbeans.modules.python.project2.PythonProject2;
706.24 +import org.openide.DialogDescriptor;
706.25 +import org.openide.DialogDisplayer;
706.26 +import org.openide.awt.HtmlRenderer;
706.27 +import org.openide.filesystems.FileObject;
706.28 +import org.openide.filesystems.FileUtil;
706.29 +import org.openide.util.HelpCtx;
706.30 +import org.openide.util.NbBundle;
706.31 +import org.openide.util.Pair;
706.32 +
706.33 +/**
706.34 + *
706.35 + * @author Tomas Zezula
706.36 + */
706.37 +public class Utils {
706.38 +
706.39 + @NbBundle.Messages({"LBL_SelectMainModule=Select Main Module", "LBL_BrowseMainModules=Browse Main Modules"})
706.40 + public static String chooseMainModule (PythonProject2 project) {
706.41 + final JButton okButton = new JButton (NbBundle.getMessage(Utils.class, "LBL_SelectMainModule"));
706.42 + final MainModuleChooser mcc = new MainModuleChooser(project, okButton);
706.43 + final Object[] options = new Object[] {okButton, DialogDescriptor.CANCEL_OPTION};
706.44 + final DialogDescriptor dd = new DialogDescriptor (mcc, NbBundle.getMessage(Utils.class, "LBL_BrowseMainModules"), true, options,
706.45 + okButton,DialogDescriptor.RIGHT_ALIGN,HelpCtx.DEFAULT_HELP,null);
706.46 + dd.setClosingOptions(options);
706.47 + if (DialogDisplayer.getDefault().notify(dd) == okButton) {
706.48 + return mcc.getMainModule();
706.49 + }
706.50 + return null;
706.51 + }
706.52 +
706.53 + public static interface SourceRootsMediator {
706.54 + public void setRelatedEditMediator(SourceRootsMediator rem);
706.55 + }
706.56 +
706.57 + public static ComboBoxModel createPlatformModel () {
706.58 + return new PlatformModel ();
706.59 + }
706.60 +
706.61 + public static ListCellRenderer createPlatformRenderer () {
706.62 + return new PlatformRenderer();
706.63 + }
706.64 +
706.65 + private static class PlatformModel extends DefaultComboBoxModel {
706.66 +
706.67 + private final PythonPlatformManager manager;
706.68 +
706.69 + public PlatformModel () {
706.70 + manager = PythonPlatformManager.getInstance();
706.71 + init ();
706.72 + }
706.73 +
706.74 + private void init () {
706.75 + this.removeAllElements(); //init will be used also in case of chnge of installed plaforms
706.76 + final List<String> ids = manager.getPlatformList();
706.77 + for (String id : ids) {
706.78 + PythonPlatform platform = manager.getPlatform(id);
706.79 + this.addElement(platform);
706.80 + }
706.81 + }
706.82 + }
706.83 +
706.84 + private static class PlatformRenderer implements ListCellRenderer {
706.85 +
706.86 + private final ListCellRenderer delegate;
706.87 +
706.88 + public PlatformRenderer () {
706.89 + delegate = HtmlRenderer.createRenderer();
706.90 + }
706.91 +
706.92 + @Override
706.93 + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
706.94 + String name;
706.95 + if (value instanceof PythonPlatform) {
706.96 + PythonPlatform key = (PythonPlatform) value;
706.97 + name = key.getName();
706.98 + }
706.99 + else if (value instanceof String) {
706.100 + //hndles broken platform for customizer
706.101 + name = "<html><font color=\"#A40000\">" //NOI18N
706.102 + + NbBundle.getMessage(
706.103 + Utils.class, "TXT_BrokenPlatformFmt", (String)value);
706.104 + }
706.105 + else {
706.106 + name = "";
706.107 + }
706.108 + return delegate.getListCellRendererComponent(list, name, index, isSelected, cellHasFocus);
706.109 + }
706.110 +
706.111 + }
706.112 +
706.113 + private static class SourceRootsModel extends DefaultTableModel {
706.114 +
706.115 + public SourceRootsModel (Object[][] data) {
706.116 + super (data,new Object[]{"location","label"});//NOI18N
706.117 + }
706.118 +
706.119 + @Override
706.120 + public boolean isCellEditable(int row, int column) {
706.121 + return column == 1;
706.122 + }
706.123 +
706.124 + @Override
706.125 + public Class getColumnClass(int columnIndex) {
706.126 + switch (columnIndex) {
706.127 + case 0:
706.128 + return File.class;
706.129 + case 1:
706.130 + return String.class;
706.131 + default:
706.132 + return super.getColumnClass (columnIndex);
706.133 + }
706.134 + }
706.135 + }
706.136 +
706.137 + private static class FileRenderer extends DefaultTableCellRenderer {
706.138 +
706.139 + private File projectFolder;
706.140 +
706.141 + public FileRenderer (File projectFolder) {
706.142 + this.projectFolder = projectFolder;
706.143 + }
706.144 +
706.145 + @Override
706.146 + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,int row, int column) {
706.147 + String displayName;
706.148 + if (value instanceof File) {
706.149 + File root = (File) value;
706.150 + String pfPath = projectFolder.getAbsolutePath() + File.separatorChar;
706.151 + String srPath = root.getAbsolutePath();
706.152 + if (srPath.startsWith(pfPath)) {
706.153 + displayName = srPath.substring(pfPath.length());
706.154 + }
706.155 + else {
706.156 + displayName = srPath;
706.157 + }
706.158 + }
706.159 + else {
706.160 + displayName = null;
706.161 + }
706.162 + Component c = super.getTableCellRendererComponent(table, displayName, isSelected, hasFocus, row, column);
706.163 + if (c instanceof JComponent) {
706.164 + ((JComponent) c).setToolTipText (displayName);
706.165 + }
706.166 + return c;
706.167 + }
706.168 + }
706.169 +}
707.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
707.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/actions/Command.java Sat Feb 28 17:25:32 2015 -0800
707.3 @@ -0,0 +1,116 @@
707.4 +/*
707.5 + * To change this template, choose Tools | Templates
707.6 + * and open the template in the editor.
707.7 + */
707.8 +package org.netbeans.modules.python.project2.ui.actions;
707.9 +
707.10 +import java.io.File;
707.11 +import java.util.ArrayList;
707.12 +import javax.swing.JOptionPane;
707.13 +import org.netbeans.api.project.ProjectUtils;
707.14 +import org.netbeans.api.project.SourceGroup;
707.15 +import org.netbeans.api.project.Sources;
707.16 +import org.netbeans.modules.python.api.PythonPlatform;
707.17 +import org.netbeans.modules.python.api.PythonPlatformManager;
707.18 +import org.netbeans.modules.python.project2.PythonProject2;
707.19 +import org.openide.filesystems.FileUtil;
707.20 +import org.openide.nodes.Node;
707.21 +import org.openide.util.Lookup;
707.22 +import org.openide.windows.TopComponent;
707.23 +
707.24 +/**
707.25 + * @author Radek Matous
707.26 + * @author Tomas Zezula
707.27 + */
707.28 +public abstract class Command {
707.29 +
707.30 + private final PythonProject2 project;
707.31 +
707.32 + public Command(PythonProject2 project) {
707.33 + this.project = project;
707.34 + assert project != null;
707.35 + }
707.36 +
707.37 + public abstract String getCommandId();
707.38 +
707.39 + public abstract void invokeAction(Lookup context) throws IllegalArgumentException;
707.40 +
707.41 + public abstract boolean isActionEnabled(Lookup context) throws IllegalArgumentException;
707.42 +
707.43 + public boolean asyncCallRequired() {
707.44 + return true;
707.45 + }
707.46 +
707.47 + public boolean saveRequired() {
707.48 + return true;
707.49 + }
707.50 +
707.51 + public final PythonProject2 getProject() {
707.52 + return project;
707.53 + }
707.54 +
707.55 + public Node[] getSelectedNodes() {
707.56 + return TopComponent.getRegistry().getCurrentNodes();
707.57 + }
707.58 +
707.59 + protected void showLaunchError(String message) {
707.60 + JOptionPane.showMessageDialog(null, message, "Python Launch Error", JOptionPane.ERROR_MESSAGE);
707.61 +
707.62 + }
707.63 +
707.64 + /**
707.65 + * used by children to handle sever launched errors
707.66 + *
707.67 + * @param errMessage
707.68 + */
707.69 + protected PythonPlatform checkProjectPythonPlatform(PythonProject2 pyProject) {
707.70 +// PythonPlatform platform = PythonProject2Util.getActivePlatform(pyProject);
707.71 +// if ( platform == null ) {
707.72 +// // Better to inform the user than try to use a default unsuited
707.73 +// String platformId = pyProject.getEvaluator().getProperty(PythonProject2Properties.ACTIVE_PLATFORM);
707.74 +// showLaunchError( "selected project has broken python platform : " +
707.75 +// platformId +
707.76 +// " => bind to an existing python platform in project's properties "
707.77 +// );
707.78 +// }
707.79 + PythonPlatform platform = PythonPlatformManager.getInstance().getPlatforms().get(0);
707.80 + return platform;
707.81 + }
707.82 +
707.83 + /**
707.84 + *
707.85 + * provide a reasonable common Build of PYTHONPATH for Run or Debug commands
707.86 + *
707.87 + * @param platform current platform
707.88 + * @param project current project
707.89 + * @return PythonPath FileList
707.90 + */
707.91 + protected ArrayList<String> buildPythonPath(PythonPlatform platform, PythonProject2 project) {
707.92 + final ArrayList<String> pythonPath = new ArrayList<String>();
707.93 + // start with platform
707.94 + pythonPath.addAll(platform.getPythonPath());
707.95 + Sources sources = ProjectUtils.getSources(project);
707.96 + for (SourceGroup fo : sources.getSourceGroups(PythonProject2.SOURCES_TYPE_PYTHON)) {
707.97 + File f = FileUtil.toFile(fo.getRootFolder());
707.98 + pythonPath.add(f.getAbsolutePath());
707.99 + }
707.100 + return pythonPath;
707.101 + }
707.102 +
707.103 + /**
707.104 + *
707.105 + * provide a reasonable common Build of JAVAPATH for Run or Debug Jython
707.106 + * commands
707.107 + *
707.108 + * @param platform current platform
707.109 + * @param project current project
707.110 + * @return JavaPath fileList for jython CLASSPATH command
707.111 + */
707.112 +// protected ArrayList<String> buildJavaPath( PythonPlatform platform , PythonProject2 project ) {
707.113 +// final ArrayList<String> javaPath = new ArrayList<String>() ;
707.114 +// // start with platform
707.115 +// javaPath.addAll(platform.getJavaPath());
707.116 +// javaPath.addAll(getProperties().getJavaPath());
707.117 +// return javaPath ;
707.118 +// }
707.119 +}
708.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
708.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/actions/RunCommand.java Sat Feb 28 17:25:32 2015 -0800
708.3 @@ -0,0 +1,137 @@
708.4 +package org.netbeans.modules.python.project2.ui.actions;
708.5 +
708.6 +import org.netbeans.modules.python.api.PythonExecution;
708.7 +import org.netbeans.modules.python.api.PythonPlatform;
708.8 +import org.netbeans.modules.python.project2.PythonProject2;
708.9 +import org.netbeans.api.project.ProjectUtils;
708.10 +import org.netbeans.api.project.SourceGroup;
708.11 +import org.netbeans.api.project.Sources;
708.12 +import org.netbeans.modules.python.project2.ui.Utils;
708.13 +import org.netbeans.spi.project.ActionProvider;
708.14 +import org.openide.filesystems.FileObject;
708.15 +import org.openide.filesystems.FileUtil;
708.16 +import org.openide.util.Lookup;
708.17 +
708.18 +/**
708.19 + *
708.20 + * @author alley
708.21 + */
708.22 +public class RunCommand extends Command {
708.23 +
708.24 + protected final boolean isTest;
708.25 +
708.26 + public RunCommand(PythonProject2 project, boolean isTest) {
708.27 + super(project);
708.28 + this.isTest = isTest;
708.29 + }
708.30 +
708.31 + @Override
708.32 + public String getCommandId() {
708.33 + return isTest ? ActionProvider.COMMAND_TEST : ActionProvider.COMMAND_RUN;
708.34 + }
708.35 +
708.36 + @Override
708.37 + public void invokeAction(Lookup context) throws IllegalArgumentException {
708.38 +// if (isTest) {
708.39 +// TestRunner testRunner = PythonActionProvider.getTestRunner(TestRunner.TestType.PY_UNIT);
708.40 +// //boolean testTaskExist = RakeSupport.getRakeTask(project, TEST_TASK_NAME) != null;
708.41 +// //if (testTaskExist) {
708.42 +// // File pwd = FileUtil.toFile(project.getProjectDirectory());
708.43 +// // RakeRunner runner = new RakeRunner(project);
708.44 +// // runner.setPWD(pwd);
708.45 +// // runner.setFileLocator(new RubyFileLocator(context, project));
708.46 +// // runner.showWarnings(true);
708.47 +// // runner.setDebug(COMMAND_DEBUG_SINGLE.equals(command));
708.48 +// // runner.run(TEST_TASK_NAME);
708.49 +// //} else if (testRunner != null) {
708.50 +// testRunner.getInstance().runAllTests(getProject(), false);
708.51 +// //}
708.52 +// return;
708.53 +// }
708.54 +
708.55 + final PythonProject2 pyProject = getProject();
708.56 + final PythonPlatform platform = checkProjectPythonPlatform(pyProject);
708.57 + if (platform == null) {
708.58 + return; // invalid platform user has been warn in check so safe to return
708.59 + }
708.60 +
708.61 + String main = pyProject.getMainModule();
708.62 + if (main == null || main.isEmpty()) {
708.63 + main = Utils.chooseMainModule(pyProject);
708.64 + pyProject.setMainModule(main);
708.65 + }
708.66 + //System.out.println("main module " + getProperties().getMainModule());
708.67 + FileObject script = findMainFile(pyProject, main);
708.68 + //assert script != null;
708.69 + if (script == null) {
708.70 + main = Utils.chooseMainModule(pyProject);
708.71 + pyProject.setMainModule(main);
708.72 + script = findMainFile(pyProject, main);
708.73 + }
708.74 + if(script == null) {
708.75 + return;
708.76 + }
708.77 + final FileObject parent = script.getParent();
708.78 + PythonExecution pyexec = new PythonExecution();
708.79 + pyexec.setDisplayName(ProjectUtils.getInformation(pyProject).getDisplayName());
708.80 + //Set work dir - probably we need a property to store work dir
708.81 + String path = FileUtil.toFile(parent).getAbsolutePath();
708.82 + pyexec.setWorkingDirectory(path);
708.83 + pyexec.setCommand(platform.getInterpreterCommand());
708.84 + //Set python script
708.85 + path = FileUtil.toFile(script).getAbsolutePath();
708.86 + pyexec.setScript(path);
708.87 + pyexec.setCommandArgs(platform.getInterpreterArgs());
708.88 + pyexec.setScriptArgs(pyProject.getApplicationArgs());
708.89 + //build path & set
708.90 + //build path & set
708.91 + pyexec.setPath(PythonPlatform.buildPath(super.buildPythonPath(platform, pyProject)));
708.92 +// pyexec.setJavaPath(PythonPlatform.buildPath(super.buildJavaPath(platform, pyProject)));
708.93 + pyexec.setShowControls(true);
708.94 + pyexec.setShowInput(true);
708.95 + pyexec.setShowWindow(true);
708.96 + pyexec.addStandardRecognizers();
708.97 +
708.98 +// PythonCoverageProvider coverageProvider = PythonCoverageProvider.get(pyProject);
708.99 +// if (coverageProvider != null && coverageProvider.isEnabled()) {
708.100 +// pyexec = coverageProvider.wrapWithCoverage(pyexec);
708.101 +// }
708.102 +
708.103 + pyexec.run();
708.104 + }
708.105 +
708.106 +
708.107 + @Override
708.108 + public boolean isActionEnabled(Lookup context) throws IllegalArgumentException {
708.109 +// final PythonProject2 pyProject = getProject();
708.110 +// PythonPlatform platform = PythonProject2Util.getActivePlatform(pyProject);
708.111 +// if (platform == null) {
708.112 +// return false;
708.113 +// }
708.114 +// else{
708.115 +// return true;
708.116 +// }
708.117 +// final FileObject fo = findMainFile (pyProject);
708.118 +// if (fo == null) {
708.119 +// return false;
708.120 +// }
708.121 +// return PythonMIMEResolver.PYTHON_MIME_TYPE.equals(fo.getMIMEType());
708.122 + return true;
708.123 + }
708.124 +
708.125 + protected static FileObject findMainFile(final PythonProject2 pyProject, final String mainFile) {
708.126 + if (mainFile == null) {
708.127 + return null;
708.128 + }
708.129 + final Sources sources = ProjectUtils.getSources(pyProject);
708.130 + FileObject fo = null;
708.131 + for (SourceGroup root : sources.getSourceGroups(PythonProject2.SOURCES_TYPE_PYTHON)) {
708.132 + fo = root.getRootFolder().getFileObject(mainFile);
708.133 + if (fo != null) {
708.134 + break;
708.135 + }
708.136 + }
708.137 + return fo;
708.138 + }
708.139 +
708.140 +}
709.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
709.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/actions/RunSingleCommand.java Sat Feb 28 17:25:32 2015 -0800
709.3 @@ -0,0 +1,127 @@
709.4 +package org.netbeans.modules.python.project2.ui.actions;
709.5 +
709.6 +import javax.swing.JOptionPane;
709.7 +import org.netbeans.modules.python.api.PythonExecution;
709.8 +import org.netbeans.modules.python.api.PythonMIMEResolver;
709.9 +import org.netbeans.modules.python.api.PythonOptions;
709.10 +import org.netbeans.modules.python.api.PythonPlatform;
709.11 +import org.netbeans.modules.python.api.PythonPlatformManager;
709.12 +import org.netbeans.modules.python.editor.codecoverage.PythonCoverageProvider;
709.13 +import org.netbeans.modules.python.project2.PythonProject2;
709.14 +import org.netbeans.spi.project.ActionProvider;
709.15 +import org.openide.filesystems.FileObject;
709.16 +import org.openide.filesystems.FileUtil;
709.17 +import org.openide.loaders.DataObject;
709.18 +import org.openide.nodes.Node;
709.19 +import org.openide.util.Lookup;
709.20 +
709.21 +/**
709.22 + *
709.23 + * @author alley
709.24 + */
709.25 +public class RunSingleCommand extends Command {
709.26 +
709.27 + PythonPlatformManager manager = PythonPlatformManager.getInstance();
709.28 + protected boolean isTest;
709.29 +
709.30 + public RunSingleCommand(PythonProject2 project, boolean isTest) {
709.31 + super(project);
709.32 + this.isTest = isTest;
709.33 + }
709.34 +
709.35 + @Override
709.36 + public String getCommandId() {
709.37 + return isTest ? ActionProvider.COMMAND_TEST_SINGLE : ActionProvider.COMMAND_RUN_SINGLE;
709.38 + }
709.39 +
709.40 + @Override
709.41 + public void invokeAction(Lookup context) throws IllegalArgumentException {
709.42 + Node[] activatedNodes = getSelectedNodes();
709.43 + DataObject gdo = activatedNodes[0].getLookup().lookup(DataObject.class);
709.44 + FileObject file = gdo.getPrimaryFile();
709.45 + if (file.getMIMEType().equals(PythonMIMEResolver.PYTHON_MIME_TYPE)) {
709.46 + String path = FileUtil.toFile(file.getParent()).getAbsolutePath();
709.47 + // String workingdir = FileUtil.toFile(getProject().getSrcFolder()).getAbsolutePath();
709.48 + //int pos = path.lastIndexOf("/");
709.49 + //path = path.substring(0, pos);
709.50 + String script = FileUtil.toFile(file).getAbsolutePath();
709.51 + //System.out.println("Folder " + path);
709.52 + //System.out.println("File " + script);
709.53 +
709.54 + final PythonProject2 pyProject = getProject();
709.55 +
709.56 + //String target = FileUtil.getRelativePath(getRoot(project.getSourceRoots().getRoots(),file), file);
709.57 +// if (isTest || file.getName().endsWith("_test")) { // NOI18N
709.58 +//
709.59 +// // See if this looks like a test file; if not, see if we can find its corresponding
709.60 +// // test
709.61 +// boolean isTestFile = (file.getName().endsWith("_test"));
709.62 +// if (!isTestFile) {
709.63 +// for (FileObject testRoot : pyProject.getTestSourceRootFiles()) {
709.64 +// if (FileUtil.isParentOf(testRoot, file)) {
709.65 +// isTestFile = true;
709.66 +// break;
709.67 +// }
709.68 +// }
709.69 +// }
709.70 +// if (!isTestFile) {
709.71 +// // Try to find the matching test
709.72 +// LocationResult result = new GotoTest().findTest(file, -1);
709.73 +// if (result != null && result.getFileObject() != null) {
709.74 +// file = result.getFileObject();
709.75 +// }
709.76 +// }
709.77 +//
709.78 +// // Run test normally - don't pop up browser
709.79 +// TestRunner testRunner = PythonActionProvider.getTestRunner(TestRunner.TestType.PY_UNIT);
709.80 +// if (testRunner != null) {
709.81 +// testRunner.getInstance().runTest(file, false);
709.82 +// return;
709.83 +// }
709.84 +// }
709.85 + PythonExecution pyexec = new PythonExecution();
709.86 + pyexec.setDisplayName(gdo.getName());
709.87 + pyexec.setWorkingDirectory(path);
709.88 + if (PythonOptions.getInstance().getPromptForArgs()) {
709.89 + String args = JOptionPane.showInputDialog("Enter the args for this script.", "");
709.90 + pyexec.setScriptArgs(args);
709.91 +
709.92 + }
709.93 + final PythonPlatform platform = checkProjectPythonPlatform(pyProject);
709.94 + if (platform == null) {
709.95 + return; // invalid platform user has been warn in check so safe to return
709.96 + }
709.97 + pyexec.setCommand(platform.getInterpreterCommand());
709.98 + pyexec.setScript(script);
709.99 + pyexec.setCommandArgs(platform.getInterpreterArgs());
709.100 + pyexec.setPath(PythonPlatform.buildPath(super.buildPythonPath(platform, pyProject)));
709.101 +// pyexec.setJavaPath(PythonPlatform.buildPath(super.buildJavaPath(platform, pyProject)));
709.102 + pyexec.setShowControls(true);
709.103 + pyexec.setShowInput(true);
709.104 + pyexec.setShowWindow(true);
709.105 + pyexec.addStandardRecognizers();
709.106 +
709.107 +// PythonCoverageProvider coverageProvider = PythonCoverageProvider.get(pyProject);
709.108 +// if (coverageProvider != null && coverageProvider.isEnabled()) {
709.109 +// pyexec = coverageProvider.wrapWithCoverage(pyexec);
709.110 +// }
709.111 +
709.112 + pyexec.run();
709.113 + }
709.114 + }
709.115 +
709.116 + @Override
709.117 + public boolean isActionEnabled(Lookup context) throws IllegalArgumentException {
709.118 + boolean results = false; //super.enable(activatedNodes);
709.119 + Node[] activatedNodes = getSelectedNodes();
709.120 + if (activatedNodes != null && activatedNodes.length > 0) {
709.121 + DataObject gdo = activatedNodes[0].getLookup().lookup(DataObject.class);
709.122 + if (gdo != null && gdo.getPrimaryFile() != null) {
709.123 + results = gdo.getPrimaryFile().getMIMEType().equals(
709.124 + PythonMIMEResolver.PYTHON_MIME_TYPE);
709.125 + }
709.126 + }
709.127 + return results;
709.128 + }
709.129 +
709.130 +}
710.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
710.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/customizer/Bundle.properties Sat Feb 28 17:25:32 2015 -0800
710.3 @@ -0,0 +1,64 @@
710.4 +# To change this template, choose Tools | Templates
710.5 +# and open the template in the editor.
710.6 +
710.7 +#PythonProjectProperties
710.8 +LBL_Customizer_Title=Project Properties - {0}
710.9 +
710.10 +#CompositePanelProviderImpl
710.11 +LBL_Config_RunConfig=Run
710.12 +LBL_Config_PhpIncludePath=Python
710.13 +
710.14 +#Customizer Sources
710.15 +CTL_ProjectFolder=Project Folder\:
710.16 +MNE_ProjectFolder=F
710.17 +CTL_SourceRoots=Source Root Folders\:
710.18 +MNE_SourceRoots=S
710.19 +CTL_TestRoots=Test Root Folders:
710.20 +MNE_TestRoots=T
710.21 +TXT_Encoding=&Encoding\:
710.22 +CTL_AddSourceRoot=Add Folder...
710.23 +MNE_AddSourceRoot=A
710.24 +CTL_RemoveSourceRoot=Remove
710.25 +MNE_RemoveSourceRoot=R
710.26 +CTL_UpSourceRoot=Move Up
710.27 +MNE_UpSourceRoot=U
710.28 +CTL_DownSourceRoot=Move Down
710.29 +MNE_DownSourceRoot=D
710.30 +CTL_AddTestRoot=Add Folder...
710.31 +MNE_AddTestRoot=o
710.32 +CTL_RemoveTestRoot=Remove
710.33 +MNE_RemoveTestRoot=m
710.34 +CTL_UpTestRoot=Move Up
710.35 +MNE_UpTestRoot=p
710.36 +CTL_DownTestRoot=Move Down
710.37 +MNE_DownTestRoot=w
710.38 +AD_CustomizerSources_addSourceRoot=N/A
710.39 +AD_CustomizerSources_testRoots=N/A
710.40 +AD_CustomizerSources_sourceRoots=N/A
710.41 +AD_CustomizerSources_downTestRoot=N/A
710.42 +AD_CustomizerSources_upTestRoot=N/A
710.43 +AD_CustomizerSources_removeTestRoot=N/A
710.44 +AD_CustomizerSources_addTestRoot=N/A
710.45 +AD_CustomizerSources_downSourceRoot=N/A
710.46 +AD_CustomizerSources_upSourceRoot=N/A
710.47 +AD_CustomizerSources_removeSourceRoot=N/A
710.48 +AD_CustomizerSources_projectLocation=N/A
710.49 +AD_CustomizerSources_Encoding=N/A
710.50 +MSG_EncodingWarning=Changing project encoding might result in some characters in existing files not being read and written correctly.
710.51 +CustomizerRun.mainModule.text=&Main Module:
710.52 +CustomizerRun.mainModule.ad=N/A
710.53 +CustomizerRun.appArgs.text=&Application Arguments:
710.54 +CustomizerRun.appArgs.ad=N/A
710.55 +CustomizerRun.browseMain.text=&Browse...
710.56 +CustomizerRun.browseMain.ad=N/A
710.57 +CustomizerPythonPath.addPythonPath.text=Add...
710.58 +CustomizerPythonPath.moveDownPythonPath.text=Move Down
710.59 +CustomizerPythonPath.moveUpPythonPath.text=Move Up
710.60 +CustomizerPythonPath.removePythonPath.text=Remove
710.61 +CustomizerPythonPath.addPythonPath.text_1=Add...
710.62 +CustomizerPythonPath.moveDownPythonPath.text_1=Move Down
710.63 +CustomizerPythonPath.moveUpPythonPath.text_1=Move Up
710.64 +CustomizerPythonPath.removePythonPath.text_1=Remove
710.65 +CustomizerPythonPath.manage.text=Manage...
710.66 +CustomizerPythonPath.jLabel1.text=Python Platform:
710.67 +CustomizerPythonPath.jLabel2.text=Python Path:
711.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
711.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/customizer/CompositePanelProviderImpl.java Sat Feb 28 17:25:32 2015 -0800
711.3 @@ -0,0 +1,67 @@
711.4 +package org.netbeans.modules.python.project2.ui.customizer;
711.5 +
711.6 +import javax.swing.JComponent;
711.7 +import javax.swing.JPanel;
711.8 +import org.netbeans.modules.python.project2.PythonProject2;
711.9 +import org.netbeans.spi.project.ui.support.ProjectCustomizer;
711.10 +import org.netbeans.spi.project.ui.support.ProjectCustomizer.CompositeCategoryProvider;
711.11 +import org.openide.util.Lookup;
711.12 +import org.openide.util.NbBundle;
711.13 +
711.14 +/**
711.15 + *
711.16 + * @author Tomas Zezula
711.17 + */
711.18 +public class CompositePanelProviderImpl implements CompositeCategoryProvider {
711.19 +
711.20 + private static final String PYTHON_PATH = "PythonPath"; //NOI18N
711.21 + private static final String RUN = "Run"; // NOI18N
711.22 +
711.23 + private final String name;
711.24 +
711.25 + public CompositePanelProviderImpl(String name) {
711.26 + this.name = name;
711.27 + }
711.28 +
711.29 + @Override
711.30 + public ProjectCustomizer.Category createCategory(Lookup context) {
711.31 + ProjectCustomizer.Category toReturn = null;
711.32 + final ProjectCustomizer.Category[] categories = null;
711.33 + if (RUN.equals(name)) {
711.34 + toReturn = ProjectCustomizer.Category.create(
711.35 + RUN,
711.36 + NbBundle.getMessage(CompositePanelProviderImpl.class, "LBL_Config_RunConfig"),
711.37 + null,
711.38 + categories);
711.39 + } else if (PYTHON_PATH.equals(name)) {
711.40 + toReturn = ProjectCustomizer.Category.create(
711.41 + PYTHON_PATH,
711.42 + NbBundle.getMessage(CompositePanelProviderImpl.class, "LBL_Config_PhpIncludePath"),
711.43 + null,
711.44 + categories);
711.45 + }
711.46 + assert toReturn != null : "No category for name: " + name;
711.47 + return toReturn;
711.48 + }
711.49 +
711.50 + @Override
711.51 + public JComponent createComponent(ProjectCustomizer.Category category, Lookup context) {
711.52 + String nm = category.getName();
711.53 + PythonProject2 project = context.lookup(PythonProject2.class);
711.54 + if (RUN.equals(nm)) {
711.55 + return new CustomizerRun(project);
711.56 + } else if (PYTHON_PATH.equals(nm)) {
711.57 + return new CustomizerPythonPath(project);
711.58 + }
711.59 + return new JPanel();
711.60 + }
711.61 +
711.62 + public static CompositePanelProviderImpl createRunConfig() {
711.63 + return new CompositePanelProviderImpl(RUN);
711.64 + }
711.65 +
711.66 + public static CompositePanelProviderImpl createPythonPath() {
711.67 + return new CompositePanelProviderImpl(PYTHON_PATH);
711.68 + }
711.69 +
711.70 +}
712.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
712.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/customizer/CustomizerPythonPath.form Sat Feb 28 17:25:32 2015 -0800
712.3 @@ -0,0 +1,168 @@
712.4 +<?xml version="1.0" encoding="UTF-8" ?>
712.5 +
712.6 +<Form version="1.5" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
712.7 + <AuxValues>
712.8 + <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="1"/>
712.9 + <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
712.10 + <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
712.11 + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
712.12 + <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="true"/>
712.13 + <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
712.14 + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
712.15 + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
712.16 + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
712.17 + </AuxValues>
712.18 +
712.19 + <Layout>
712.20 + <DimensionLayout dim="0">
712.21 + <Group type="103" groupAlignment="0" attributes="0">
712.22 + <Group type="102" attributes="0">
712.23 + <EmptySpace max="-2" attributes="0"/>
712.24 + <Group type="103" groupAlignment="0" attributes="0">
712.25 + <Group type="102" alignment="0" attributes="0">
712.26 + <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
712.27 + <EmptySpace max="-2" attributes="0"/>
712.28 + <Component id="platforms" pref="205" max="32767" attributes="0"/>
712.29 + <EmptySpace min="-2" max="-2" attributes="0"/>
712.30 + <Component id="manage" min="-2" max="-2" attributes="0"/>
712.31 + <EmptySpace min="30" pref="30" max="30" attributes="0"/>
712.32 + </Group>
712.33 + <Group type="102" alignment="1" attributes="0">
712.34 + <Component id="jScrollPane2" pref="0" max="32767" attributes="0"/>
712.35 + <EmptySpace max="-2" attributes="0"/>
712.36 + <Group type="103" groupAlignment="0" attributes="0">
712.37 + <Component id="moveDownPythonPath" linkSize="1" alignment="0" min="-2" max="-2" attributes="0"/>
712.38 + <Component id="moveUpPythonPath" linkSize="1" alignment="0" min="-2" max="-2" attributes="1"/>
712.39 + <Component id="removePythonPath" linkSize="1" alignment="0" min="-2" max="-2" attributes="1"/>
712.40 + <Component id="addPythonPath" linkSize="1" alignment="0" min="-2" max="-2" attributes="1"/>
712.41 + </Group>
712.42 + </Group>
712.43 + <Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
712.44 + </Group>
712.45 + <EmptySpace min="-2" max="-2" attributes="0"/>
712.46 + </Group>
712.47 + </Group>
712.48 + </DimensionLayout>
712.49 + <DimensionLayout dim="1">
712.50 + <Group type="103" groupAlignment="0" attributes="0">
712.51 + <Group type="102" alignment="0" attributes="0">
712.52 + <EmptySpace min="-2" max="-2" attributes="0"/>
712.53 + <Group type="103" groupAlignment="0" max="-2" attributes="0">
712.54 + <Group type="103" alignment="0" groupAlignment="3" attributes="0">
712.55 + <Component id="platforms" alignment="3" min="-2" max="-2" attributes="0"/>
712.56 + <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
712.57 + </Group>
712.58 + <Component id="manage" alignment="0" min="-2" max="-2" attributes="0"/>
712.59 + </Group>
712.60 + <EmptySpace min="-2" max="-2" attributes="0"/>
712.61 + <Component id="jLabel2" min="-2" pref="16" max="-2" attributes="0"/>
712.62 + <EmptySpace min="-2" pref="8" max="-2" attributes="0"/>
712.63 + <Group type="103" groupAlignment="0" attributes="0">
712.64 + <Group type="102" attributes="0">
712.65 + <Component id="addPythonPath" min="-2" max="-2" attributes="0"/>
712.66 + <EmptySpace max="-2" attributes="0"/>
712.67 + <Component id="removePythonPath" min="-2" max="-2" attributes="0"/>
712.68 + <EmptySpace max="-2" attributes="0"/>
712.69 + <Component id="moveUpPythonPath" min="-2" max="-2" attributes="0"/>
712.70 + <EmptySpace max="-2" attributes="0"/>
712.71 + <Component id="moveDownPythonPath" min="-2" max="-2" attributes="0"/>
712.72 + </Group>
712.73 + <Component id="jScrollPane2" pref="214" max="32767" attributes="0"/>
712.74 + </Group>
712.75 + <EmptySpace min="-2" pref="19" max="-2" attributes="0"/>
712.76 + </Group>
712.77 + </Group>
712.78 + </DimensionLayout>
712.79 + </Layout>
712.80 + <SubComponents>
712.81 + <Container class="javax.swing.JScrollPane" name="jScrollPane2">
712.82 + <AuxValues>
712.83 + <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
712.84 + </AuxValues>
712.85 +
712.86 + <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
712.87 + <SubComponents>
712.88 + <Component class="javax.swing.JList" name="pythonPath">
712.89 + <Properties>
712.90 + <Property name="model" type="javax.swing.ListModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
712.91 + <Connection code="pythonPathModel" type="code"/>
712.92 + </Property>
712.93 + <Property name="selectionMode" type="int" value="0"/>
712.94 + </Properties>
712.95 + </Component>
712.96 + </SubComponents>
712.97 + </Container>
712.98 + <Component class="javax.swing.JButton" name="addPythonPath">
712.99 + <Properties>
712.100 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
712.101 + <ResourceString bundle="org/netbeans/modules/python/project2/ui/customizer/Bundle.properties" key="CustomizerPythonPath.addPythonPath.text_1" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
712.102 + </Property>
712.103 + </Properties>
712.104 + <Events>
712.105 + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="addPythonPathActionPerformed"/>
712.106 + </Events>
712.107 + </Component>
712.108 + <Component class="javax.swing.JButton" name="removePythonPath">
712.109 + <Properties>
712.110 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
712.111 + <ResourceString bundle="org/netbeans/modules/python/project2/ui/customizer/Bundle.properties" key="CustomizerPythonPath.removePythonPath.text_1" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
712.112 + </Property>
712.113 + </Properties>
712.114 + <Events>
712.115 + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="removePythonPathActionPerformed"/>
712.116 + </Events>
712.117 + </Component>
712.118 + <Component class="javax.swing.JButton" name="moveUpPythonPath">
712.119 + <Properties>
712.120 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
712.121 + <ResourceString bundle="org/netbeans/modules/python/project2/ui/customizer/Bundle.properties" key="CustomizerPythonPath.moveUpPythonPath.text_1" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
712.122 + </Property>
712.123 + </Properties>
712.124 + <Events>
712.125 + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="moveUpPythonPathActionPerformed"/>
712.126 + </Events>
712.127 + </Component>
712.128 + <Component class="javax.swing.JButton" name="moveDownPythonPath">
712.129 + <Properties>
712.130 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
712.131 + <ResourceString bundle="org/netbeans/modules/python/project2/ui/customizer/Bundle.properties" key="CustomizerPythonPath.moveDownPythonPath.text_1" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
712.132 + </Property>
712.133 + </Properties>
712.134 + <Events>
712.135 + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="moveDownPythonPathActionPerformed"/>
712.136 + </Events>
712.137 + </Component>
712.138 + <Component class="javax.swing.JButton" name="manage">
712.139 + <Properties>
712.140 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
712.141 + <ResourceString bundle="org/netbeans/modules/python/project2/ui/customizer/Bundle.properties" key="CustomizerPythonPath.manage.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
712.142 + </Property>
712.143 + </Properties>
712.144 + <Events>
712.145 + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="manageActionPerformed"/>
712.146 + </Events>
712.147 + </Component>
712.148 + <Component class="javax.swing.JComboBox" name="platforms">
712.149 + <Events>
712.150 + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="platformsActionPerformed"/>
712.151 + </Events>
712.152 + <AuxValues>
712.153 + <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="org.netbeans.modules.python.api.PlatformComponentFactory.getPythonPlatformsComboxBox()"/>
712.154 + </AuxValues>
712.155 + </Component>
712.156 + <Component class="javax.swing.JLabel" name="jLabel1">
712.157 + <Properties>
712.158 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
712.159 + <ResourceString bundle="org/netbeans/modules/python/project2/ui/customizer/Bundle.properties" key="CustomizerPythonPath.jLabel1.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
712.160 + </Property>
712.161 + </Properties>
712.162 + </Component>
712.163 + <Component class="javax.swing.JLabel" name="jLabel2">
712.164 + <Properties>
712.165 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
712.166 + <ResourceString bundle="org/netbeans/modules/python/project2/ui/customizer/Bundle.properties" key="CustomizerPythonPath.jLabel2.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
712.167 + </Property>
712.168 + </Properties>
712.169 + </Component>
712.170 + </SubComponents>
712.171 +</Form>
713.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
713.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/customizer/CustomizerPythonPath.java Sat Feb 28 17:25:32 2015 -0800
713.3 @@ -0,0 +1,271 @@
713.4 +/*
713.5 + * To change this template, choose Tools | Templates
713.6 + * and open the template in the editor.
713.7 + */
713.8 +
713.9 +/*
713.10 + * CustomizerPythonPath.java
713.11 + *
713.12 + * Created on Sep 7, 2008, 6:56:16 PM
713.13 + */
713.14 +package org.netbeans.modules.python.project2.ui.customizer;
713.15 +
713.16 +import java.io.File;
713.17 +import java.io.IOException;
713.18 +import javax.swing.JFileChooser;
713.19 +
713.20 +import org.netbeans.modules.python.api.PlatformComponentFactory;
713.21 +import org.netbeans.modules.python.api.PythonPlatform;
713.22 +import org.netbeans.modules.python.core.ui.models.PathListModel;
713.23 +import org.netbeans.modules.python.project2.PythonProject2;
713.24 +import org.netbeans.modules.python.project2.ui.Utils;
713.25 +
713.26 +import org.openide.filesystems.FileObject;
713.27 +import org.openide.filesystems.FileUtil;
713.28 +import org.openide.loaders.DataObject;
713.29 +import org.openide.loaders.InstanceDataObject;
713.30 +import org.openide.util.Exceptions;
713.31 +import org.openide.util.actions.CallableSystemAction;
713.32 +
713.33 +/**
713.34 + *
713.35 + * @author alley
713.36 + */
713.37 +public class CustomizerPythonPath extends javax.swing.JPanel {
713.38 +
713.39 + private final PythonProject2 project;
713.40 + private PlatformComponentFactory.PlatformChangeListener platformListener;
713.41 + private final PathListModel pythonPathModel = new PathListModel();
713.42 +
713.43 + /**
713.44 + * Creates new form CustomizerPythonPath
713.45 + */
713.46 + public CustomizerPythonPath(PythonProject2 properties) {
713.47 + this.project = properties;
713.48 + initComponents();
713.49 +// pythonPathModel.setModel(project.getPythonPath());
713.50 +
713.51 + final PythonPlatform activePlatform = project.getActivePlatform();
713.52 + if (activePlatform != null) {
713.53 + platforms.setSelectedItem(activePlatform);
713.54 + }
713.55 + }
713.56 +
713.57 + public @Override
713.58 + void addNotify() {
713.59 + super.addNotify();
713.60 + platformListener = new PlatformComponentFactory.PlatformChangeListener() {
713.61 + @Override
713.62 + public void platformChanged() {
713.63 + PythonPlatform platform = (PythonPlatform) platforms.getSelectedItem();
713.64 + if (platform != null) {
713.65 + project.setActivePlatform(platform);
713.66 + // When we support configurations:
713.67 + //configs.get(getSelectedConfig()).put(PythonProjectProperties.ACTIVE_PLATFORM, platform.getName());
713.68 + }
713.69 + }
713.70 + };
713.71 + PlatformComponentFactory.addPlatformChangeListener(platforms, platformListener);
713.72 + }
713.73 +
713.74 + public @Override
713.75 + void removeNotify() {
713.76 + PlatformComponentFactory.removePlatformChangeListener(platforms, platformListener);
713.77 + super.removeNotify();
713.78 + }
713.79 +
713.80 + /**
713.81 + * This method is called from within the constructor to initialize the form.
713.82 + * WARNING: Do NOT modify this code. The content of this method is always
713.83 + * regenerated by the Form Editor.
713.84 + */
713.85 + @SuppressWarnings("unchecked")
713.86 + // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
713.87 + private void initComponents() {
713.88 +
713.89 + jScrollPane2 = new javax.swing.JScrollPane();
713.90 + pythonPath = new javax.swing.JList();
713.91 + addPythonPath = new javax.swing.JButton();
713.92 + removePythonPath = new javax.swing.JButton();
713.93 + moveUpPythonPath = new javax.swing.JButton();
713.94 + moveDownPythonPath = new javax.swing.JButton();
713.95 + manage = new javax.swing.JButton();
713.96 + platforms = org.netbeans.modules.python.api.PlatformComponentFactory.getPythonPlatformsComboxBox();
713.97 + jLabel1 = new javax.swing.JLabel();
713.98 + jLabel2 = new javax.swing.JLabel();
713.99 +
713.100 + pythonPath.setModel(pythonPathModel);
713.101 + pythonPath.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
713.102 + jScrollPane2.setViewportView(pythonPath);
713.103 +
713.104 + addPythonPath.setText(org.openide.util.NbBundle.getMessage(CustomizerPythonPath.class, "CustomizerPythonPath.addPythonPath.text_1")); // NOI18N
713.105 + addPythonPath.addActionListener(new java.awt.event.ActionListener() {
713.106 + public void actionPerformed(java.awt.event.ActionEvent evt) {
713.107 + addPythonPathActionPerformed(evt);
713.108 + }
713.109 + });
713.110 +
713.111 + removePythonPath.setText(org.openide.util.NbBundle.getMessage(CustomizerPythonPath.class, "CustomizerPythonPath.removePythonPath.text_1")); // NOI18N
713.112 + removePythonPath.addActionListener(new java.awt.event.ActionListener() {
713.113 + public void actionPerformed(java.awt.event.ActionEvent evt) {
713.114 + removePythonPathActionPerformed(evt);
713.115 + }
713.116 + });
713.117 +
713.118 + moveUpPythonPath.setText(org.openide.util.NbBundle.getMessage(CustomizerPythonPath.class, "CustomizerPythonPath.moveUpPythonPath.text_1")); // NOI18N
713.119 + moveUpPythonPath.addActionListener(new java.awt.event.ActionListener() {
713.120 + public void actionPerformed(java.awt.event.ActionEvent evt) {
713.121 + moveUpPythonPathActionPerformed(evt);
713.122 + }
713.123 + });
713.124 +
713.125 + moveDownPythonPath.setText(org.openide.util.NbBundle.getMessage(CustomizerPythonPath.class, "CustomizerPythonPath.moveDownPythonPath.text_1")); // NOI18N
713.126 + moveDownPythonPath.addActionListener(new java.awt.event.ActionListener() {
713.127 + public void actionPerformed(java.awt.event.ActionEvent evt) {
713.128 + moveDownPythonPathActionPerformed(evt);
713.129 + }
713.130 + });
713.131 +
713.132 + manage.setText(org.openide.util.NbBundle.getMessage(CustomizerPythonPath.class, "CustomizerPythonPath.manage.text")); // NOI18N
713.133 + manage.addActionListener(new java.awt.event.ActionListener() {
713.134 + public void actionPerformed(java.awt.event.ActionEvent evt) {
713.135 + manageActionPerformed(evt);
713.136 + }
713.137 + });
713.138 +
713.139 + platforms.addActionListener(new java.awt.event.ActionListener() {
713.140 + public void actionPerformed(java.awt.event.ActionEvent evt) {
713.141 + platformsActionPerformed(evt);
713.142 + }
713.143 + });
713.144 +
713.145 + jLabel1.setText(org.openide.util.NbBundle.getMessage(CustomizerPythonPath.class, "CustomizerPythonPath.jLabel1.text")); // NOI18N
713.146 +
713.147 + jLabel2.setText(org.openide.util.NbBundle.getMessage(CustomizerPythonPath.class, "CustomizerPythonPath.jLabel2.text")); // NOI18N
713.148 +
713.149 + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
713.150 + this.setLayout(layout);
713.151 + layout.setHorizontalGroup(
713.152 + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
713.153 + .addGroup(layout.createSequentialGroup()
713.154 + .addContainerGap()
713.155 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
713.156 + .addGroup(layout.createSequentialGroup()
713.157 + .addComponent(jLabel1)
713.158 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
713.159 + .addComponent(platforms, 0, 205, Short.MAX_VALUE)
713.160 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
713.161 + .addComponent(manage)
713.162 + .addGap(30, 30, 30))
713.163 + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
713.164 + .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
713.165 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
713.166 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
713.167 + .addComponent(moveDownPythonPath)
713.168 + .addComponent(moveUpPythonPath)
713.169 + .addComponent(removePythonPath)
713.170 + .addComponent(addPythonPath)))
713.171 + .addComponent(jLabel2))
713.172 + .addContainerGap())
713.173 + );
713.174 +
713.175 + layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {addPythonPath, moveDownPythonPath, moveUpPythonPath, removePythonPath});
713.176 +
713.177 + layout.setVerticalGroup(
713.178 + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
713.179 + .addGroup(layout.createSequentialGroup()
713.180 + .addContainerGap()
713.181 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
713.182 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
713.183 + .addComponent(platforms, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
713.184 + .addComponent(jLabel1))
713.185 + .addComponent(manage))
713.186 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
713.187 + .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
713.188 + .addGap(8, 8, 8)
713.189 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
713.190 + .addGroup(layout.createSequentialGroup()
713.191 + .addComponent(addPythonPath)
713.192 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
713.193 + .addComponent(removePythonPath)
713.194 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
713.195 + .addComponent(moveUpPythonPath)
713.196 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
713.197 + .addComponent(moveDownPythonPath))
713.198 + .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE))
713.199 + .addGap(19, 19, 19))
713.200 + );
713.201 + }// </editor-fold>//GEN-END:initComponents
713.202 +
713.203 + private void addPythonPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addPythonPathActionPerformed
713.204 + final JFileChooser fc = new JFileChooser();
713.205 + fc.setFileHidingEnabled(false);
713.206 + fc.setDialogTitle("Select Python Egg or Python Lib Directory");
713.207 + fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
713.208 + /* jean-Yves for practical reasons @@@ ENHANCE to have multiple selection enabled here */
713.209 + fc.setMultiSelectionEnabled(true);
713.210 + int returnVal = fc.showOpenDialog(this);
713.211 + if (returnVal == JFileChooser.APPROVE_OPTION) {
713.212 + File[] files = fc.getSelectedFiles();
713.213 + for (File file : files) {
713.214 + String cmd = file.getAbsolutePath();
713.215 + pythonPathModel.add(cmd);
713.216 + }
713.217 + }
713.218 +
713.219 +}//GEN-LAST:event_addPythonPathActionPerformed
713.220 +
713.221 + private void removePythonPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removePythonPathActionPerformed
713.222 + int selectedIndex = pythonPath.getSelectedIndex();
713.223 + if (selectedIndex != -1) {
713.224 + pythonPathModel.remove(selectedIndex);
713.225 + }
713.226 +}//GEN-LAST:event_removePythonPathActionPerformed
713.227 +
713.228 + private void moveUpPythonPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveUpPythonPathActionPerformed
713.229 + int selectedIndex = pythonPath.getSelectedIndex();
713.230 + if (selectedIndex != -1) {
713.231 + pythonPathModel.moveUp(selectedIndex);
713.232 + }
713.233 +}//GEN-LAST:event_moveUpPythonPathActionPerformed
713.234 +
713.235 + private void moveDownPythonPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveDownPythonPathActionPerformed
713.236 + pythonPathModel.moveDown(pythonPath.getSelectedIndex());
713.237 +}//GEN-LAST:event_moveDownPythonPathActionPerformed
713.238 +
713.239 + private void manageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_manageActionPerformed
713.240 + //Workaround, Needs an API to display platform customizer
713.241 + final FileObject fo = FileUtil.getConfigFile("Actions/Python/org-netbeans-modules-python-platform-PythonManagerAction.instance"); //NOI18N
713.242 + if (fo != null) {
713.243 + try {
713.244 + InstanceDataObject ido = (InstanceDataObject) DataObject.find(fo);
713.245 + CallableSystemAction action = (CallableSystemAction) ido.instanceCreate();
713.246 + action.performAction();
713.247 + platforms.setModel(Utils.createPlatformModel()); //Currentl the PythonManager doesn't fire events, we need to replace model.
713.248 + } catch (IOException | ClassNotFoundException ex) {
713.249 + Exceptions.printStackTrace(ex);
713.250 + }
713.251 + }
713.252 +}//GEN-LAST:event_manageActionPerformed
713.253 +
713.254 + private void platformsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_platformsActionPerformed
713.255 + PythonPlatform selectedPlatform = (PythonPlatform) platforms.getSelectedItem();
713.256 + if (selectedPlatform != null) {
713.257 + project.setActivePlatform(selectedPlatform);
713.258 + }
713.259 + }//GEN-LAST:event_platformsActionPerformed
713.260 +
713.261 + // Variables declaration - do not modify//GEN-BEGIN:variables
713.262 + private javax.swing.JButton addPythonPath;
713.263 + private javax.swing.JLabel jLabel1;
713.264 + private javax.swing.JLabel jLabel2;
713.265 + private javax.swing.JScrollPane jScrollPane2;
713.266 + private javax.swing.JButton manage;
713.267 + private javax.swing.JButton moveDownPythonPath;
713.268 + private javax.swing.JButton moveUpPythonPath;
713.269 + private javax.swing.JComboBox platforms;
713.270 + private javax.swing.JList pythonPath;
713.271 + private javax.swing.JButton removePythonPath;
713.272 + // End of variables declaration//GEN-END:variables
713.273 +
713.274 +}
714.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
714.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/customizer/CustomizerRun.form Sat Feb 28 17:25:32 2015 -0800
714.3 @@ -0,0 +1,113 @@
714.4 +<?xml version="1.0" encoding="UTF-8" ?>
714.5 +
714.6 +<Form version="1.5" maxVersion="1.6" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
714.7 + <AuxValues>
714.8 + <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="1"/>
714.9 + <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
714.10 + <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
714.11 + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
714.12 + <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="true"/>
714.13 + <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
714.14 + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
714.15 + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
714.16 + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
714.17 + </AuxValues>
714.18 +
714.19 + <Layout>
714.20 + <DimensionLayout dim="0">
714.21 + <Group type="103" groupAlignment="0" attributes="0">
714.22 + <Group type="102" attributes="0">
714.23 + <Group type="103" groupAlignment="0" attributes="0">
714.24 + <Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
714.25 + <Component id="jLabel1" alignment="0" min="-2" max="-2" attributes="0"/>
714.26 + </Group>
714.27 + <EmptySpace max="-2" attributes="0"/>
714.28 + <Group type="103" groupAlignment="0" attributes="0">
714.29 + <Component id="mainModule" alignment="0" pref="364" max="32767" attributes="0"/>
714.30 + <Component id="appArgs" alignment="0" pref="364" max="32767" attributes="0"/>
714.31 + </Group>
714.32 + <EmptySpace type="unrelated" max="-2" attributes="0"/>
714.33 + <Component id="jButton1" min="-2" max="-2" attributes="0"/>
714.34 + <EmptySpace max="-2" attributes="0"/>
714.35 + </Group>
714.36 + </Group>
714.37 + </DimensionLayout>
714.38 + <DimensionLayout dim="1">
714.39 + <Group type="103" groupAlignment="0" attributes="0">
714.40 + <Group type="102" alignment="0" attributes="0">
714.41 + <Group type="103" groupAlignment="3" attributes="0">
714.42 + <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
714.43 + <Component id="jButton1" alignment="3" min="-2" max="-2" attributes="0"/>
714.44 + <Component id="mainModule" alignment="3" min="-2" max="-2" attributes="0"/>
714.45 + </Group>
714.46 + <EmptySpace max="-2" attributes="0"/>
714.47 + <Group type="103" groupAlignment="3" attributes="0">
714.48 + <Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
714.49 + <Component id="appArgs" alignment="3" min="-2" max="-2" attributes="0"/>
714.50 + </Group>
714.51 + <EmptySpace pref="234" max="32767" attributes="0"/>
714.52 + </Group>
714.53 + </Group>
714.54 + </DimensionLayout>
714.55 + </Layout>
714.56 + <SubComponents>
714.57 + <Component class="javax.swing.JLabel" name="jLabel1">
714.58 + <Properties>
714.59 + <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
714.60 + <ComponentRef name="mainModule"/>
714.61 + </Property>
714.62 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
714.63 + <ResourceString bundle="org/netbeans/modules/python/project2/ui/customizer/Bundle.properties" key="CustomizerRun.mainModule.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
714.64 + </Property>
714.65 + </Properties>
714.66 + <AuxValues>
714.67 + <AuxValue name="generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
714.68 + </AuxValues>
714.69 + </Component>
714.70 + <Component class="javax.swing.JTextField" name="mainModule">
714.71 + <AccessibilityProperties>
714.72 + <Property name="AccessibleContext.accessibleDescription" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
714.73 + <ResourceString bundle="org/netbeans/modules/python/project/ui/customizer/Bundle.properties" key="CustomizerRun.mainModule.ad" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
714.74 + </Property>
714.75 + </AccessibilityProperties>
714.76 + </Component>
714.77 + <Component class="javax.swing.JButton" name="jButton1">
714.78 + <Properties>
714.79 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
714.80 + <ResourceString bundle="org/netbeans/modules/python/project2/ui/customizer/Bundle.properties" key="CustomizerRun.browseMain.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
714.81 + </Property>
714.82 + </Properties>
714.83 + <AccessibilityProperties>
714.84 + <Property name="AccessibleContext.accessibleDescription" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
714.85 + <ResourceString bundle="org/netbeans/modules/python/project/ui/customizer/Bundle.properties" key="CustomizerRun.browseMain.ad" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
714.86 + </Property>
714.87 + </AccessibilityProperties>
714.88 + <Events>
714.89 + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton1ActionPerformed"/>
714.90 + </Events>
714.91 + <AuxValues>
714.92 + <AuxValue name="generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
714.93 + </AuxValues>
714.94 + </Component>
714.95 + <Component class="javax.swing.JLabel" name="jLabel2">
714.96 + <Properties>
714.97 + <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
714.98 + <ComponentRef name="appArgs"/>
714.99 + </Property>
714.100 + <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
714.101 + <ResourceString bundle="org/netbeans/modules/python/project2/ui/customizer/Bundle.properties" key="CustomizerRun.appArgs.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
714.102 + </Property>
714.103 + </Properties>
714.104 + <AuxValues>
714.105 + <AuxValue name="generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
714.106 + </AuxValues>
714.107 + </Component>
714.108 + <Component class="javax.swing.JTextField" name="appArgs">
714.109 + <AccessibilityProperties>
714.110 + <Property name="AccessibleContext.accessibleDescription" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
714.111 + <ResourceString bundle="org/netbeans/modules/python/project/ui/customizer/Bundle.properties" key="CustomizerRun.appArgs.ad" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, "{key}")"/>
714.112 + </Property>
714.113 + </AccessibilityProperties>
714.114 + </Component>
714.115 + </SubComponents>
714.116 +</Form>
715.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
715.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/customizer/CustomizerRun.java Sat Feb 28 17:25:32 2015 -0800
715.3 @@ -0,0 +1,152 @@
715.4 +/*
715.5 + * CustomizerRun.java
715.6 + *
715.7 + * Created on August 22, 2008, 4:52 PM
715.8 + */
715.9 +
715.10 +package org.netbeans.modules.python.project2.ui.customizer;
715.11 +
715.12 +import javax.swing.event.DocumentEvent;
715.13 +import javax.swing.event.DocumentListener;
715.14 +import javax.swing.text.Document;
715.15 +import org.netbeans.modules.python.project2.PythonProject2;
715.16 +import org.netbeans.modules.python.project2.ui.Utils;
715.17 +
715.18 +/**
715.19 + *
715.20 + * @author Tomas Zezula
715.21 + */
715.22 +public class CustomizerRun extends javax.swing.JPanel {
715.23 +
715.24 + private final PythonProject2 project;
715.25 + private final DocListener listener;
715.26 +
715.27 + /** Creates new form CustomizerRun */
715.28 + public CustomizerRun(final PythonProject2 project) {
715.29 + assert project != null;
715.30 + this.project = project;
715.31 + initComponents();
715.32 + String mainModule = project.getMainModule();
715.33 + if (mainModule != null) {
715.34 + this.mainModule.setText(mainModule);
715.35 + }
715.36 + String appArgs = project.getApplicationArgs();
715.37 + if (appArgs != null) {
715.38 + this.appArgs.setText(appArgs);
715.39 + }
715.40 + this.listener = new DocListener ();
715.41 + this.mainModule.getDocument().addDocumentListener(listener);
715.42 + this.appArgs.getDocument().addDocumentListener(listener);
715.43 + }
715.44 +
715.45 + /** This method is called from within the constructor to
715.46 + * initialize the form.
715.47 + * WARNING: Do NOT modify this code. The content of this method is
715.48 + * always regenerated by the Form Editor.
715.49 + */
715.50 + @SuppressWarnings("unchecked")
715.51 + // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
715.52 + private void initComponents() {
715.53 +
715.54 + jLabel1 = new javax.swing.JLabel();
715.55 + mainModule = new javax.swing.JTextField();
715.56 + jButton1 = new javax.swing.JButton();
715.57 + jLabel2 = new javax.swing.JLabel();
715.58 + appArgs = new javax.swing.JTextField();
715.59 +
715.60 + jLabel1.setLabelFor(mainModule);
715.61 + org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.mainModule.text")); // NOI18N
715.62 +
715.63 + org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.browseMain.text")); // NOI18N
715.64 + jButton1.addActionListener(new java.awt.event.ActionListener() {
715.65 + public void actionPerformed(java.awt.event.ActionEvent evt) {
715.66 + jButton1ActionPerformed(evt);
715.67 + }
715.68 + });
715.69 +
715.70 + jLabel2.setLabelFor(appArgs);
715.71 + org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.appArgs.text")); // NOI18N
715.72 +
715.73 + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
715.74 + this.setLayout(layout);
715.75 + layout.setHorizontalGroup(
715.76 + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
715.77 + .addGroup(layout.createSequentialGroup()
715.78 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
715.79 + .addComponent(jLabel2)
715.80 + .addComponent(jLabel1))
715.81 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
715.82 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
715.83 + .addComponent(mainModule, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
715.84 + .addComponent(appArgs, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE))
715.85 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
715.86 + .addComponent(jButton1)
715.87 + .addContainerGap())
715.88 + );
715.89 + layout.setVerticalGroup(
715.90 + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
715.91 + .addGroup(layout.createSequentialGroup()
715.92 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
715.93 + .addComponent(jLabel1)
715.94 + .addComponent(jButton1)
715.95 + .addComponent(mainModule, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
715.96 + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
715.97 + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
715.98 + .addComponent(jLabel2)
715.99 + .addComponent(appArgs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
715.100 + .addContainerGap(234, Short.MAX_VALUE))
715.101 + );
715.102 +
715.103 + mainModule.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.mainModule.ad")); // NOI18N
715.104 + jButton1.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.browseMain.ad")); // NOI18N
715.105 + appArgs.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.appArgs.ad")); // NOI18N
715.106 + }// </editor-fold>//GEN-END:initComponents
715.107 +
715.108 +private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
715.109 + String main = Utils.chooseMainModule(project);
715.110 + if (main != null) {
715.111 + mainModule.setText(main);
715.112 + }
715.113 +}//GEN-LAST:event_jButton1ActionPerformed
715.114 +
715.115 +
715.116 + // Variables declaration - do not modify//GEN-BEGIN:variables
715.117 + private javax.swing.JTextField appArgs;
715.118 + private javax.swing.JButton jButton1;
715.119 + private javax.swing.JLabel jLabel1;
715.120 + private javax.swing.JLabel jLabel2;
715.121 + private javax.swing.JTextField mainModule;
715.122 + // End of variables declaration//GEN-END:variables
715.123 +
715.124 +
715.125 + private class DocListener implements DocumentListener {
715.126 +
715.127 + @Override
715.128 + public void insertUpdate(DocumentEvent e) {
715.129 + handleDocEvent (e);
715.130 + }
715.131 +
715.132 + @Override
715.133 + public void removeUpdate(DocumentEvent e) {
715.134 + handleDocEvent(e);
715.135 + }
715.136 +
715.137 + @Override
715.138 + public void changedUpdate(DocumentEvent e) {
715.139 + handleDocEvent(e);
715.140 + }
715.141 +
715.142 + private void handleDocEvent (final DocumentEvent e) {
715.143 + final Document doc = e.getDocument();
715.144 + if (doc == mainModule.getDocument()) {
715.145 + //System.out.println("Updating main Module to " + mainModule.getText() );
715.146 +
715.147 + project.setMainModule(mainModule.getText());
715.148 + }
715.149 + else if (doc == appArgs.getDocument()) {
715.150 + project.setApplicationArgs(appArgs.getText());
715.151 + }
715.152 + }
715.153 +
715.154 + }
715.155 +}
716.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
716.2 +++ b/python.project2/src/org/netbeans/modules/python/project2/ui/customizer/PythonCustomizerProvider.java Sat Feb 28 17:25:32 2015 -0800
716.3 @@ -0,0 +1,118 @@
716.4 +/*
716.5 + * To change this template, choose Tools | Templates
716.6 + * and open the template in the editor.
716.7 + */
716.8 +package org.netbeans.modules.python.project2.ui.customizer;
716.9 +
716.10 +import java.awt.Dialog;
716.11 +import java.awt.event.ActionEvent;
716.12 +import java.awt.event.ActionListener;
716.13 +import java.awt.event.WindowAdapter;
716.14 +import java.awt.event.WindowEvent;
716.15 +import java.text.MessageFormat;
716.16 +import java.util.HashMap;
716.17 +import java.util.Map;
716.18 +import org.netbeans.modules.python.project2.PythonProject2;
716.19 +import org.netbeans.api.project.Project;
716.20 +import org.netbeans.api.project.ProjectUtils;
716.21 +import org.netbeans.spi.project.ui.CustomizerProvider;
716.22 +import org.netbeans.spi.project.ui.support.ProjectCustomizer;
716.23 +import org.openide.util.Lookup;
716.24 +import org.openide.util.NbBundle;
716.25 +import org.openide.util.lookup.Lookups;
716.26 +
716.27 +/**
716.28 + *
716.29 + * @author Tomas Zezula
716.30 + */
716.31 +public class PythonCustomizerProvider implements CustomizerProvider {
716.32 +
716.33 + private static final String CUSTOMIZER_FOLDER_PATH = "Projects/org-netbeans-modules-python-project2//Customizer"; //NO18N
716.34 +
716.35 + private static final Map<Project, Dialog> PROJECT_2_DIALOG = new HashMap<>();
716.36 +
716.37 + private final PythonProject2 project;
716.38 +
716.39 + public PythonCustomizerProvider(final PythonProject2 project) {
716.40 + assert project != null;
716.41 + this.project = project;
716.42 + }
716.43 +
716.44 + @Override
716.45 + public void showCustomizer() {
716.46 + showCustomizer(null);
716.47 + }
716.48 +
716.49 + public void showCustomizer(String preselectedCategory) {
716.50 + Dialog dialog = PROJECT_2_DIALOG.get(project);
716.51 + if (dialog != null) {
716.52 + dialog.setVisible(true);
716.53 + return;
716.54 + }
716.55 +
716.56 + final Lookup context = Lookups.fixed(project);
716.57 + final OptionListener optionListener = new OptionListener(project);
716.58 + final StoreListener storeListener = new StoreListener(project);
716.59 + dialog = ProjectCustomizer.createCustomizerDialog(CUSTOMIZER_FOLDER_PATH, context, preselectedCategory,
716.60 + optionListener, storeListener, null);
716.61 + dialog.addWindowListener(optionListener);
716.62 + dialog.setTitle(MessageFormat.format(
716.63 + NbBundle.getMessage(PythonCustomizerProvider.class, "LBL_Customizer_Title"),
716.64 + ProjectUtils.getInformation(project).getDisplayName()));
716.65 +
716.66 + PROJECT_2_DIALOG.put(project, dialog);
716.67 + dialog.setVisible(true);
716.68 + }
716.69 +
716.70 + private class StoreListener implements ActionListener {
716.71 +
716.72 + private final PythonProject2 uiProperties;
716.73 +
716.74 + StoreListener(PythonProject2 uiProperties) {
716.75 + this.uiProperties = uiProperties;
716.76 + }
716.77 +
716.78 + @Override
716.79 + public void actionPerformed(ActionEvent e) {
716.80 +// uiProperties.save();
716.81 + }
716.82 + }
716.83 +
716.84 + private static class OptionListener extends WindowAdapter implements ActionListener {
716.85 +
716.86 + private final Project project;
716.87 +
716.88 + OptionListener(Project project) {
716.89 + this.project = project;
716.90 + }
716.91 +
716.92 + // Listening to OK button ----------------------------------------------
716.93 + @Override
716.94 + public void actionPerformed(ActionEvent e) {
716.95 + // Close & dispose the the dialog
716.96 + Dialog dialog = PROJECT_2_DIALOG.get(project);
716.97 + if (dialog != null) {
716.98 + dialog.setVisible(false);
716.99 + dialog.dispose();
716.100 + }
716.101 + }
716.102 +
716.103 + // Listening to window events ------------------------------------------
716.104 + @Override
716.105 + public void windowClosed(WindowEvent e) {
716.106 + PROJECT_2_DIALOG.remove(project);
716.107 + }
716.108 +
716.109 + @Override
716.110 + public void windowClosing(WindowEvent e) {
716.111 + //Dispose the dialog otherwsie the {@link WindowAdapter#windowClosed}
716.112 + //may not be called
716.113 + Dialog dialog = PROJECT_2_DIALOG.get(project);
716.114 + if (dialog != null) {
716.115 + dialog.setVisible(false);
716.116 + dialog.dispose();
716.117 + }
716.118 + }
716.119 + }
716.120 +
716.121 +}
717.1 --- a/python.qshell/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
717.2 +++ b/python.qshell/nbproject/project.xml Sat Feb 28 17:25:32 2015 -0800
717.3 @@ -48,6 +48,14 @@
717.4 </run-dependency>
717.5 </dependency>
717.6 <dependency>
717.7 + <code-name-base>org.openide.util</code-name-base>
717.8 + <build-prerequisite/>
717.9 + <compile-dependency/>
717.10 + <run-dependency>
717.11 + <specification-version>9.3</specification-version>
717.12 + </run-dependency>
717.13 + </dependency>
717.14 + <dependency>
717.15 <code-name-base>org.openide.util.ui</code-name-base>
717.16 <build-prerequisite/>
717.17 <compile-dependency/>
718.1 --- a/python.qshell/src/org/netbeans/modules/python/qshell/TermExecutor.java Sun Jan 04 13:11:53 2015 -0600
718.2 +++ b/python.qshell/src/org/netbeans/modules/python/qshell/TermExecutor.java Sat Feb 28 17:25:32 2015 -0800
718.3 @@ -101,6 +101,16 @@
718.4 pixels.height, pixels.width);
718.5 }
718.6 }
718.7 +
718.8 + @Override
718.9 + public void titleChanged(String string) {
718.10 + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
718.11 + }
718.12 +
718.13 + @Override
718.14 + public void cwdChanged(String cwd) {
718.15 + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
718.16 + }
718.17 }
718.18
718.19 private static void error(String fmt, Object...args) {
719.1 --- a/python.qshell/src/org/netbeans/modules/python/qshell/richexecution/PtyLibrary.java Sun Jan 04 13:11:53 2015 -0600
719.2 +++ b/python.qshell/src/org/netbeans/modules/python/qshell/richexecution/PtyLibrary.java Sat Feb 28 17:25:32 2015 -0800
719.3 @@ -47,6 +47,7 @@
719.4 import com.sun.jna.Library;
719.5 import com.sun.jna.Native;
719.6 import com.sun.jna.Structure;
719.7 +import java.util.List;
719.8
719.9 public interface PtyLibrary extends Library {
719.10
719.11 @@ -64,6 +65,11 @@
719.12 this.ws_xpixel = (short) width;
719.13 this.ws_ypixel = (short) height;
719.14 }
719.15 +
719.16 + @Override
719.17 + protected List getFieldOrder() {
719.18 + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
719.19 + }
719.20 }
719.21
719.22 // struct termios
719.23 @@ -80,6 +86,11 @@
719.24 public Termios() {
719.25 c_cc = new byte[NCCS];
719.26 }
719.27 +
719.28 + @Override
719.29 + protected List getFieldOrder() {
719.30 + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
719.31 + }
719.32 }
719.33
719.34 public PtyLibrary INSTANCE = (PtyLibrary) Native.loadLibrary("c", PtyLibrary.class);
720.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
720.2 +++ b/python.source/build.xml Sat Feb 28 17:25:32 2015 -0800
720.3 @@ -0,0 +1,8 @@
720.4 +<?xml version="1.0" encoding="UTF-8"?>
720.5 +<!-- You may freely edit this file. See harness/README in the NetBeans platform -->
720.6 +<!-- for some information on what you could do (e.g. targets to override). -->
720.7 +<!-- If you delete this file and reopen the project it will be recreated. -->
720.8 +<project name="contrib/python.source" default="netbeans" basedir=".">
720.9 + <description>Builds, tests, and runs the project org.netbeans.modules.python.source.</description>
720.10 + <import file="../../nbbuild/templates/projectized.xml"/>
720.11 +</project>
721.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
721.2 +++ b/python.source/manifest.mf Sat Feb 28 17:25:32 2015 -0800
721.3 @@ -0,0 +1,5 @@
721.4 +Manifest-Version: 1.0
721.5 +OpenIDE-Module: org.netbeans.modules.python.source
721.6 +OpenIDE-Module-Localizing-Bundle: org/netbeans/modules/python/source/Bundle.properties
721.7 +OpenIDE-Module-Specification-Version: 1.0
721.8 +AutoUpdate-Show-In-Client: false
722.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
722.2 +++ b/python.source/nbproject/project.properties Sat Feb 28 17:25:32 2015 -0800
722.3 @@ -0,0 +1,2 @@
722.4 +javac.source=1.6
722.5 +javac.compilerargs=-Xlint -Xlint:-serial
723.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
723.2 +++ b/python.source/nbproject/project.xml Sat Feb 28 17:25:32 2015 -0800
723.3 @@ -0,0 +1,57 @@
723.4 +<?xml version="1.0" encoding="UTF-8"?>
723.5 +<project xmlns="http://www.netbeans.org/ns/project/1">
723.6 + <type>org.netbeans.modules.apisupport.project</type>
723.7 + <configuration>
723.8 + <data xmlns="http://www.netbeans.org/ns/nb-module-project/3">
723.9 + <code-name-base>org.netbeans.modules.python.source</code-name-base>
723.10 + <!--<suite-component/>-->
723.11 + <module-dependencies>
723.12 + <dependency>
723.13 + <code-name-base>org.netbeans.api.annotations.common</code-name-base>
723.14 + <build-prerequisite/>
723.15 + <compile-dependency/>
723.16 + <run-dependency>
723.17 + <release-version>1</release-version>
723.18 + <specification-version>1.24.1</specification-version>
723.19 + </run-dependency>
723.20 + </dependency>
723.21 + <dependency>
723.22 + <code-name-base>org.netbeans.modules.projectapi</code-name-base>
723.23 + <build-prerequisite/>
723.24 + <compile-dependency/>
723.25 + <run-dependency>
723.26 + <release-version>1</release-version>
723.27 + <specification-version>1.60.2</specification-version>
723.28 + </run-dependency>
723.29 + </dependency>
723.30 + <dependency>
723.31 + <code-name-base>org.openide.filesystems</code-name-base>
723.32 + <build-prerequisite/>
723.33 + <compile-dependency/>
723.34 + <run-dependency>
723.35 + <specification-version>8.12.1</specification-version>
723.36 + </run-dependency>
723.37 + </dependency>
723.38 + <dependency>
723.39 + <code-name-base>org.openide.util</code-name-base>
723.40 + <build-prerequisite/>
723.41 + <compile-dependency/>
723.42 + <run-dependency>
723.43 + <specification-version>8.39.1</specification-version>
723.44 + </run-dependency>
723.45 + </dependency>
723.46 + <dependency>
723.47 + <code-name-base>org.openide.util.lookup</code-name-base>
723.48 + <build-prerequisite/>
723.49 + <compile-dependency/>
723.50 + <run-dependency>
723.51 + <specification-version>8.25.1</specification-version>
723.52 + </run-dependency>
723.53 + </dependency>
723.54 + </module-dependencies>
723.55 + <public-packages>
723.56 + <package>org.netbeans.modules.python.source.queries</package>
723.57 + </public-packages>
723.58 + </data>
723.59 + </configuration>
723.60 +</project>
724.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
724.2 +++ b/python.source/src/org/netbeans/modules/python/source/Bundle.properties Sat Feb 28 17:25:32 2015 -0800
724.3 @@ -0,0 +1,1 @@
724.4 +OpenIDE-Module-Name=Python Source
725.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
725.2 +++ b/python.source/src/org/netbeans/modules/python/source/PythonProjectSourceLevelQuery.java Sat Feb 28 17:25:32 2015 -0800
725.3 @@ -0,0 +1,29 @@
725.4 +/*
725.5 + * To change this license header, choose License Headers in Project Properties.
725.6 + * To change this template file, choose Tools | Templates
725.7 + * and open the template in the editor.
725.8 + */
725.9 +package org.netbeans.modules.python.source;
725.10 +
725.11 +import org.netbeans.modules.python.source.queries.SourceLevelQueryImplementation;
725.12 +import org.netbeans.api.project.FileOwnerQuery;
725.13 +import org.netbeans.api.project.Project;
725.14 +import org.openide.filesystems.FileObject;
725.15 +import org.openide.util.lookup.ServiceProvider;
725.16 +
725.17 +@ServiceProvider(service = SourceLevelQueryImplementation.class, position = 400)
725.18 +public class PythonProjectSourceLevelQuery implements SourceLevelQueryImplementation {
725.19 +
725.20 + @Override
725.21 + public Result getSourceLevel(FileObject pythonFile) {
725.22 + final Project project = FileOwnerQuery.getOwner(pythonFile);
725.23 + if (project != null) {
725.24 + SourceLevelQueryImplementation impl = project.getLookup().lookup(SourceLevelQueryImplementation.class);
725.25 + if (impl != null) {
725.26 + return impl.getSourceLevel(pythonFile);
725.27 + }
725.28 + }
725.29 + return null;
725.30 + }
725.31 +
725.32 +}
726.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
726.2 +++ b/python.source/src/org/netbeans/modules/python/source/queries/SourceLevelQuery.java Sat Feb 28 17:25:32 2015 -0800
726.3 @@ -0,0 +1,240 @@
726.4 +/*
726.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
726.6 + *
726.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
726.8 + *
726.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
726.10 + * Other names may be trademarks of their respective owners.
726.11 + *
726.12 + * The contents of this file are subject to the terms of either the GNU
726.13 + * General Public License Version 2 only ("GPL") or the Common
726.14 + * Development and Distribution License("CDDL") (collectively, the
726.15 + * "License"). You may not use this file except in compliance with the
726.16 + * License. You can obtain a copy of the License at
726.17 + * http://www.netbeans.org/cddl-gplv2.html
726.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
726.19 + * specific language governing permissions and limitations under the
726.20 + * License. When distributing the software, include this License Header
726.21 + * Notice in each file and include the License file at
726.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
726.23 + * particular file as subject to the "Classpath" exception as provided
726.24 + * by Oracle in the GPL Version 2 section of the License file that
726.25 + * accompanied this code. If applicable, add the following below the
726.26 + * License Header, with the fields enclosed by brackets [] replaced by
726.27 + * your own identifying information:
726.28 + * "Portions Copyrighted [year] [name of copyright owner]"
726.29 + *
726.30 + * Contributor(s):
726.31 + *
726.32 + * The Original Software is NetBeans. The Initial Developer of the Original
726.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
726.34 + * Microsystems, Inc. All Rights Reserved.
726.35 + *
726.36 + * If you wish your version of this file to be governed by only the CDDL
726.37 + * or only the GPL Version 2, indicate your decision by adding
726.38 + * "[Contributor] elects to include this software in this distribution
726.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
726.40 + * single choice of license, a recipient has the option to distribute
726.41 + * your version of this file under either the CDDL, the GPL Version 2 or
726.42 + * to extend the choice of license to its licensees as provided above.
726.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
726.44 + * Version 2 license, then the option applies only if the new code is
726.45 + * made subject to such option by the copyright holder.
726.46 + */
726.47 +
726.48 +package org.netbeans.modules.python.source.queries;
726.49 +
726.50 +import java.text.MessageFormat;
726.51 +import java.util.logging.Level;
726.52 +import java.util.logging.Logger;
726.53 +import java.util.regex.Matcher;
726.54 +import java.util.regex.Pattern;
726.55 +import javax.swing.event.ChangeEvent;
726.56 +import javax.swing.event.ChangeListener;
726.57 +import org.netbeans.api.annotations.common.CheckForNull;
726.58 +import org.netbeans.api.annotations.common.NonNull;
726.59 +import org.netbeans.api.annotations.common.NullAllowed;
726.60 +import org.openide.filesystems.FileObject;
726.61 +import org.openide.util.ChangeSupport;
726.62 +import org.openide.util.Lookup;
726.63 +import org.openide.util.Parameters;
726.64 +import org.openide.util.Union2;
726.65 +import org.openide.util.WeakListeners;
726.66 +
726.67 +/**
726.68 + * Returns source level of the given Python file if it is known.
726.69 + * @author David Konecny
726.70 + * @author Tomas Zezula
726.71 + * @author Ralph Benjamin Ruijs
726.72 + */
726.73 +public final class SourceLevelQuery {
726.74 +
726.75 + private static final Logger LOGGER = Logger.getLogger(SourceLevelQuery.class.getName());
726.76 +
726.77 + private static final Pattern SOURCE_LEVEL = Pattern.compile("Python.(\\d+\\.\\d+)\\.\\d+"); //NOI18N
726.78 + private static final Pattern SYNONYM = Pattern.compile("\\d+");//NOI18N
726.79 +
726.80 + private static final Lookup.Result<? extends SourceLevelQueryImplementation> impls =
726.81 + Lookup.getDefault().lookupResult (SourceLevelQueryImplementation.class);
726.82 +
726.83 + private SourceLevelQuery() {
726.84 + }
726.85 +
726.86 + /**
726.87 + * Returns a source level of the given Python file, Python package or source folder.
726.88 + * @param pythonFile Python source file, Python package or source folder in question
726.89 + * @return a {@link Result} object encapsulating the source level of the Python file. Results created for source
726.90 + * levels provided by the {@link SourceLevelQueryImplementation} do not support listening. Use {@link Result#supportsChanges()}
726.91 + * to check if the result supports listening.
726.92 + */
726.93 + @SuppressWarnings("deprecation")
726.94 + public static @NonNull Result getSourceLevelResult(final @NonNull FileObject pythonFile) {
726.95 + for (SourceLevelQueryImplementation sqi : impls.allInstances()) {
726.96 + final SourceLevelQueryImplementation.Result result = sqi.getSourceLevel(pythonFile);
726.97 + if (result != null) {
726.98 + if (LOGGER.isLoggable(Level.FINE)) {
726.99 + LOGGER.log(Level.FINE, "Found source level {0} for {1} from {2}", new Object[] {result, pythonFile, sqi}); //NOI18N
726.100 + }
726.101 + return new Result(result);
726.102 + }
726.103 + }
726.104 + LOGGER.log(Level.FINE, "No source level found for {0}", pythonFile);
726.105 + return new Result(pythonFile);
726.106 + }
726.107 +
726.108 + public static String getSourceLevel(FileObject javaFile) {
726.109 + for (SourceLevelQueryImplementation sqi : impls.allInstances()) {
726.110 + final SourceLevelQueryImplementation.Result result = sqi.getSourceLevel(javaFile);
726.111 + if (result != null) {
726.112 + final String s = normalize(result.getSourceLevel());
726.113 + if (s != null) {
726.114 + Matcher matcher = SOURCE_LEVEL.matcher(s);
726.115 + if (!matcher.matches()) {
726.116 + LOGGER.log(Level.WARNING, "#83994: Ignoring bogus source level {0} for {1} from {2}", new Object[] {s, javaFile, sqi}); //NOI18N
726.117 + continue;
726.118 + }
726.119 + if (LOGGER.isLoggable(Level.FINE)) {
726.120 + LOGGER.log(Level.FINE, "Found source level {0} for {1} from {2}", new Object[] {s, javaFile, sqi}); //NOI18N
726.121 + }
726.122 + return matcher.group(1);
726.123 + }
726.124 + }
726.125 + }
726.126 + LOGGER.log(Level.FINE, "No source level found for {0}", javaFile);
726.127 + return null;
726.128 + }
726.129 +
726.130 + /**
726.131 + * Result of finding source level, encapsulating the answer as well as the
726.132 + * ability to listen to it.
726.133 + */
726.134 + public static final class Result {
726.135 +
726.136 + private final @NonNull Union2<SourceLevelQueryImplementation.Result,FileObject> delegate;
726.137 + private final ChangeSupport cs = new ChangeSupport(this);
726.138 + private /**@GuardedBy("this")*/ ChangeListener spiListener;
726.139 +
726.140 + private Result(@NonNull final SourceLevelQueryImplementation.Result delegate) {
726.141 + Parameters.notNull("delegate", delegate); //NOI18N
726.142 + this.delegate = Union2.<SourceLevelQueryImplementation.Result,FileObject>createFirst(delegate);
726.143 + }
726.144 +
726.145 + private Result(@NonNull final FileObject javaFile) {
726.146 + Parameters.notNull("sourceLevel", javaFile);
726.147 + this.delegate = Union2.<SourceLevelQueryImplementation.Result,FileObject>createSecond(javaFile);
726.148 + }
726.149 +
726.150 + /**
726.151 + * Get the source level.
726.152 + * @return a source level of the Python file, e.g. "2.7", "3.0", "3.1"
726.153 + * or null if the source level is unknown. Even it is allowed for a SPI implementation to return
726.154 + * a source level synonym e.g. "3" for "3.0+" the returned value is always normalized.
726.155 + */
726.156 + public @CheckForNull String getSourceLevel() {
726.157 + if (delegate.hasFirst()) {
726.158 + String sourceLevel = normalize(delegate.first().getSourceLevel());
726.159 + Matcher matcher = SOURCE_LEVEL.matcher(sourceLevel);
726.160 + if (sourceLevel != null && !matcher.matches()) {
726.161 + LOGGER.log(
726.162 + Level.WARNING,
726.163 + "#83994: Ignoring bogus source level {0} from {2}", //NOI18N
726.164 + new Object[] {
726.165 + sourceLevel,
726.166 + delegate.first()
726.167 + });
726.168 + sourceLevel = null;
726.169 + }
726.170 + return matcher.group(1);
726.171 + } else {
726.172 + return SourceLevelQuery.getSourceLevel(delegate.second());
726.173 + }
726.174 + }
726.175 +
726.176 +
726.177 + /**
726.178 + * Add a listener to changes of source level.
726.179 + * If {@link #supportsChanges} is false, the listener will never be notified
726.180 + * although {@link #getSourceLevel} may change from call to call.
726.181 + * @param listener a listener to add
726.182 + */
726.183 + public void addChangeListener(@NonNull ChangeListener listener) {
726.184 + Parameters.notNull("listener", listener); //NOI18N
726.185 + final SourceLevelQueryImplementation.Result _delegate = getDelegate();
726.186 + if (_delegate == null) {
726.187 + return;
726.188 + }
726.189 + cs.addChangeListener(listener);
726.190 + synchronized (this) {
726.191 + if (spiListener == null) {
726.192 + spiListener = new ChangeListener() {
726.193 + @Override
726.194 + public void stateChanged(ChangeEvent e) {
726.195 + cs.fireChange();
726.196 + }
726.197 + };
726.198 + _delegate.addChangeListener(WeakListeners.change(spiListener, _delegate));
726.199 + }
726.200 + }
726.201 +
726.202 + }
726.203 +
726.204 + /**
726.205 + * Remove a listener to changes of source level.
726.206 + * @param listener a listener to add
726.207 + */
726.208 + public void removeChangeListener(@NonNull ChangeListener listener) {
726.209 + Parameters.notNull("listener", listener); //NOI18N
726.210 + final SourceLevelQueryImplementation.Result _delegate = getDelegate();
726.211 + if (_delegate == null) {
726.212 + return;
726.213 + }
726.214 + cs.removeChangeListener(listener);
726.215 + }
726.216 +
726.217 + /**
726.218 + * Returns true if the result support updates and client may
726.219 + * listen on it. If false client should always ask again to
726.220 + * obtain current value. The results created for values returned
726.221 + * by the {@link SourceLevelQueryImplementation} do not support
726.222 + * listening.
726.223 + * @return true if the result supports changes and listening
726.224 + */
726.225 + public boolean supportsChanges() {
726.226 + return getDelegate() != null;
726.227 + }
726.228 +
726.229 + private SourceLevelQueryImplementation.Result getDelegate() {
726.230 + return delegate.hasFirst() ? delegate.first() : null;
726.231 + }
726.232 + }
726.233 +
726.234 + @CheckForNull
726.235 + private static String normalize(@NullAllowed String sourceLevel) {
726.236 + if (sourceLevel != null && SYNONYM.matcher(sourceLevel).matches()) {
726.237 + sourceLevel = MessageFormat.format("1.{0}", sourceLevel); //NOI18N
726.238 + }
726.239 + return sourceLevel;
726.240 + }
726.241 +
726.242 +}
726.243 +
727.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
727.2 +++ b/python.source/src/org/netbeans/modules/python/source/queries/SourceLevelQueryImplementation.java Sat Feb 28 17:25:32 2015 -0800
727.3 @@ -0,0 +1,103 @@
727.4 +/*
727.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
727.6 + *
727.7 + * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
727.8 + *
727.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
727.10 + * Other names may be trademarks of their respective owners.
727.11 + *
727.12 + * The contents of this file are subject to the terms of either the GNU
727.13 + * General Public License Version 2 only ("GPL") or the Common
727.14 + * Development and Distribution License("CDDL") (collectively, the
727.15 + * "License"). You may not use this file except in compliance with the
727.16 + * License. You can obtain a copy of the License at
727.17 + * http://www.netbeans.org/cddl-gplv2.html
727.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
727.19 + * specific language governing permissions and limitations under the
727.20 + * License. When distributing the software, include this License Header
727.21 + * Notice in each file and include the License file at
727.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
727.23 + * particular file as subject to the "Classpath" exception as provided
727.24 + * by Oracle in the GPL Version 2 section of the License file that
727.25 + * accompanied this code. If applicable, add the following below the
727.26 + * License Header, with the fields enclosed by brackets [] replaced by
727.27 + * your own identifying information:
727.28 + * "Portions Copyrighted [year] [name of copyright owner]"
727.29 + *
727.30 + * If you wish your version of this file to be governed by only the CDDL
727.31 + * or only the GPL Version 2, indicate your decision by adding
727.32 + * "[Contributor] elects to include this software in this distribution
727.33 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
727.34 + * single choice of license, a recipient has the option to distribute
727.35 + * your version of this file under either the CDDL, the GPL Version 2 or
727.36 + * to extend the choice of license to its licensees as provided above.
727.37 + * However, if you add GPL Version 2 code and therefore, elected the GPL
727.38 + * Version 2 license, then the option applies only if the new code is
727.39 + * made subject to such option by the copyright holder.
727.40 + *
727.41 + * Contributor(s):
727.42 + *
727.43 + * Portions Copyrighted 2010 Sun Microsystems, Inc.
727.44 + */
727.45 +
727.46 +package org.netbeans.modules.python.source.queries;
727.47 +
727.48 +import javax.swing.event.ChangeListener;
727.49 +import org.netbeans.api.annotations.common.CheckForNull;
727.50 +import org.netbeans.api.annotations.common.NonNull;
727.51 +import org.openide.filesystems.FileObject;
727.52 +
727.53 +/**
727.54 + *
727.55 + * Permits providers to return specification source level of Java source file.
727.56 + * <p>
727.57 + * A default implementation is registered by the
727.58 + * <code>org.netbeans.modules.python.project</code> module which looks up the
727.59 + * project corresponding to the file (if any) and checks whether that
727.60 + * project has an implementation of this interface in its lookup. If so, it
727.61 + * delegates to that implementation. Therefore it is not generally necessary
727.62 + * for a project type provider to register its own global implementation of
727.63 + * this query, if it depends on the Python Project module and uses this style.
727.64 + * </p>
727.65 + * @see org.netbeans.modules.python.source.queries.SourceLevelQuery
727.66 + * @author Tomas Zezula
727.67 + * @author Ralph Benjamin Ruijs
727.68 + */
727.69 +public interface SourceLevelQueryImplementation {
727.70 +
727.71 + /**
727.72 + * Returns source level of the given Python file.
727.73 + * @param pythonFile Python source file in question
727.74 + * @return source level of the Python file encapsulated as {@link Result}, or
727.75 + * null if the file is not handled by this provider.
727.76 + */
727.77 + Result getSourceLevel(FileObject pythonFile);
727.78 +
727.79 + /**
727.80 + * Result of finding source level, encapsulating the answer as well as the
727.81 + * ability to listen to it.
727.82 + */
727.83 + interface Result {
727.84 +
727.85 + /**
727.86 + * Get the source level.
727.87 + * @return a source level of the Python file, e.g. "2.6", "3.0", "3.1"
727.88 + * or null if the source level is unknown. It is allowed to return source level synonyms
727.89 + * e.g. "3" for "Python 3". These synonyms are always normalized by
727.90 + * {@link SourceLevelQuery#getSourceLevel}.
727.91 + */
727.92 + @CheckForNull String getSourceLevel();
727.93 +
727.94 + /**
727.95 + * Add a listener to changes of source level.
727.96 + * @param listener a listener to add
727.97 + */
727.98 + void addChangeListener(@NonNull ChangeListener listener);
727.99 +
727.100 + /**
727.101 + * Remove a listener to changes of source level.
727.102 + * @param listener a listener to add
727.103 + */
727.104 + void removeChangeListener(@NonNull ChangeListener listener);
727.105 + }
727.106 +}
728.1 --- a/python.testrunner/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
728.2 +++ b/python.testrunner/nbproject/project.xml Sat Feb 28 17:25:32 2015 -0800
728.3 @@ -41,15 +41,6 @@
728.4 </run-dependency>
728.5 </dependency>
728.6 <dependency>
728.7 - <code-name-base>org.netbeans.modules.gsf.api</code-name-base>
728.8 - <build-prerequisite/>
728.9 - <compile-dependency/>
728.10 - <run-dependency>
728.11 - <release-version>2</release-version>
728.12 - <specification-version>1.8.0</specification-version>
728.13 - </run-dependency>
728.14 - </dependency>
728.15 - <dependency>
728.16 <code-name-base>org.netbeans.modules.gsf.testrunner</code-name-base>
728.17 <build-prerequisite/>
728.18 <compile-dependency/>
728.19 @@ -97,7 +88,10 @@
728.20 <code-name-base>org.netbeans.modules.projectuiapi</code-name-base>
728.21 <build-prerequisite/>
728.22 <compile-dependency/>
728.23 - <run-dependency><release-version>1</release-version><specification-version>1.78</specification-version></run-dependency>
728.24 + <run-dependency>
728.25 + <release-version>1</release-version>
728.26 + <specification-version>1.78</specification-version>
728.27 + </run-dependency>
728.28 </dependency>
728.29 <dependency>
728.30 <code-name-base>org.netbeans.modules.projectuiapi.base</code-name-base>
728.31 @@ -236,20 +230,6 @@
728.32 </run-dependency>
728.33 </dependency>
728.34 </module-dependencies>
728.35 - <test-dependencies>
728.36 - <test-type>
728.37 - <name>unit</name>
728.38 - <test-dependency>
728.39 - <code-name-base>org.netbeans.libs.junit4</code-name-base>
728.40 - <compile-dependency/>
728.41 - </test-dependency>
728.42 - <test-dependency>
728.43 - <code-name-base>org.netbeans.modules.nbjunit</code-name-base>
728.44 - <recursive/>
728.45 - <compile-dependency/>
728.46 - </test-dependency>
728.47 - </test-type>
728.48 - </test-dependencies>
728.49 <public-packages/>
728.50 </data>
728.51 </configuration>
729.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
729.2 +++ b/python.testrunner/src/org/netbeans/modules/python/testrunner/Bundle.properties Sat Feb 28 17:25:32 2015 -0800
729.3 @@ -1,14 +1,1 @@
729.4 -OpenIDE-Module-Name=Python Test Runner
729.5 -OpenIDE-Module-Display-Category=Python
729.6 -OpenIDE-Module-Short-Description=Python Test Runner
729.7 -OpenIDE-Module-Long-Description=\
729.8 - Provides support for running and displaying Test/Unit and RSpec tests.
729.9 -
729.10 -# {0} - project name
729.11 -AutoTest=AutoTest ({0})
729.12 -MSG_SpecOptsWarning = [Using {0}; create {1} to set options used under the IDE. \
729.13 - Suppress this warning message by adding \
729.14 - -J-D{2}=false to the flags in etc/netbeans.conf]
729.15 -
729.16 -# RspecRunner
729.17 -MSG_SpecNotFound = Could not find the 'spec' executable. Make sure it is on the path.
729.18 +OpenIDE-Module-Name=Python Testrunner
730.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/PyUnitRunner.java Sun Jan 04 13:11:53 2015 -0600
730.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
730.3 @@ -1,341 +0,0 @@
730.4 -/*
730.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
730.6 - *
730.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
730.8 - *
730.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
730.10 - * Other names may be trademarks of their respective owners.
730.11 - *
730.12 - * The contents of this file are subject to the terms of either the GNU
730.13 - * General Public License Version 2 only ("GPL") or the Common
730.14 - * Development and Distribution License("CDDL") (collectively, the
730.15 - * "License"). You may not use this file except in compliance with the
730.16 - * License. You can obtain a copy of the License at
730.17 - * http://www.netbeans.org/cddl-gplv2.html
730.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
730.19 - * specific language governing permissions and limitations under the
730.20 - * License. When distributing the software, include this License Header
730.21 - * Notice in each file and include the License file at
730.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
730.23 - * particular file as subject to the "Classpath" exception as provided
730.24 - * by Oracle in the GPL Version 2 section of the License file that
730.25 - * accompanied this code. If applicable, add the following below the
730.26 - * License Header, with the fields enclosed by brackets [] replaced by
730.27 - * your own identifying information:
730.28 - * "Portions Copyrighted [year] [name of copyright owner]"
730.29 - *
730.30 - * If you wish your version of this file to be governed by only the CDDL
730.31 - * or only the GPL Version 2, indicate your decision by adding
730.32 - * "[Contributor] elects to include this software in this distribution
730.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
730.34 - * single choice of license, a recipient has the option to distribute
730.35 - * your version of this file under either the CDDL, the GPL Version 2 or
730.36 - * to extend the choice of license to its licensees as provided above.
730.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
730.38 - * Version 2 license, then the option applies only if the new code is
730.39 - * made subject to such option by the copyright holder.
730.40 - *
730.41 - * Contributor(s):
730.42 - *
730.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
730.44 - */
730.45 -package org.netbeans.modules.python.testrunner;
730.46 -
730.47 -import java.io.File;
730.48 -import java.util.ArrayList;
730.49 -import java.util.List;
730.50 -import java.util.Map;
730.51 -import java.util.logging.Level;
730.52 -import java.util.logging.Logger;
730.53 -import org.netbeans.api.project.FileOwnerQuery;
730.54 -import org.netbeans.api.project.Project;
730.55 -import org.netbeans.api.project.ProjectUtils;
730.56 -import org.netbeans.modules.gsf.testrunner.api.TestSession;
730.57 -import org.netbeans.modules.gsf.testrunner.api.TestSession.SessionType;
730.58 -import org.netbeans.modules.gsf.testrunner.ui.api.Manager;
730.59 -import org.netbeans.modules.python.api.PythonExecution;
730.60 -import org.netbeans.modules.python.api.PythonPlatform;
730.61 -import org.netbeans.modules.python.editor.codecoverage.PythonCoverageProvider;
730.62 -import org.netbeans.modules.python.project.PythonProject;
730.63 -import org.netbeans.modules.python.project.spi.TestRunner;
730.64 -import org.netbeans.modules.python.project.ui.customizer.PythonProjectProperties;
730.65 -import org.netbeans.modules.python.testrunner.ui.PyUnitHandlerFactory;
730.66 -import org.openide.filesystems.FileObject;
730.67 -import org.openide.filesystems.FileUtil;
730.68 -import org.openide.modules.InstalledFileLocator;
730.69 -import org.openide.util.BaseUtilities;
730.70 -
730.71 -/**
730.72 - * Test runner implmentation for running PyUnit tests
730.73 - *
730.74 - * @author Erno Mononen
730.75 - */
730.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)})
730.77 -public final class PyUnitRunner implements TestRunner/*, RakeTaskCustomizer*/ {
730.78 -
730.79 - private static final Logger LOGGER = Logger.getLogger(PyUnitRunner.class.getName());
730.80 - private static final String NB_TEST_RUNNER = "NB_TEST_RUNNER"; //NOI18N
730.81 - //public static final String MEDIATOR_SCRIPT_NAME = "nb_test_mediator.py"; //NOI18N
730.82 - public static final String RUNNER_SCRIPT_NAME = "nb_test_runner.py"; //NOI18N
730.83 - private static final TestRunner INSTANCE = new PyUnitRunner();
730.84 -
730.85 - static {
730.86 - // this env variable is referenced from nb_test_runner.py, where it
730.87 - // gets appended to the rake require path
730.88 - System.setProperty(NB_TEST_RUNNER, getScript(RUNNER_SCRIPT_NAME).getAbsolutePath());
730.89 - }
730.90 -
730.91 - public TestRunner getInstance() {
730.92 - return INSTANCE;
730.93 - }
730.94 -
730.95 - public void runSingleTest(FileObject testFile, String className, String testMethod, boolean debug) {
730.96 - List<String> additionalArgs = getTestFileArgs(testFile);
730.97 - additionalArgs.add("-m"); // NOI18N
730.98 - String methodRef;
730.99 - String file = additionalArgs.get(1);
730.100 - if (className.startsWith(file+".")) { // NOI18N
730.101 - className = className.substring(file.length()+1);
730.102 - }
730.103 - methodRef = className + "." + testMethod; // NOI18N
730.104 - additionalArgs.add(methodRef);
730.105 - run(FileOwnerQuery.getOwner(testFile), additionalArgs, testMethod, debug);
730.106 - }
730.107 -
730.108 - public void runTest(FileObject testFile, boolean debug) {
730.109 - Project project = FileOwnerQuery.getOwner(testFile);
730.110 - if (!testFile.isFolder()) {
730.111 - run(project, getTestFileArgs(testFile), testFile.getName(), debug);
730.112 - } else {
730.113 - List<String> additionalArgs = new ArrayList<String>();
730.114 - additionalArgs.add("-d"); //NOI18N
730.115 - additionalArgs.add(FileUtil.toFile(testFile).getAbsolutePath());
730.116 - String name = ProjectUtils.getInformation(project).getDisplayName();
730.117 - run(project, additionalArgs, name, debug);
730.118 - }
730.119 - }
730.120 -
730.121 - private List<String> getTestFileArgs(FileObject testFile) {
730.122 - Project project = FileOwnerQuery.getOwner(testFile);
730.123 - String testFilePath = FileUtil.toFile(testFile).getAbsolutePath();
730.124 - if (project instanceof PythonProject) {
730.125 - PythonProject pythonPrj = (PythonProject)project;
730.126 - FileObject root = null;
730.127 - for (FileObject r : pythonPrj.getSourceRootFiles()) {
730.128 - if (FileUtil.isParentOf(r, testFile)) {
730.129 - root = r;
730.130 - break;
730.131 - }
730.132 - }
730.133 - if (root == null) {
730.134 - for (FileObject r : pythonPrj.getTestSourceRootFiles()) {
730.135 - if (FileUtil.isParentOf(r, testFile)) {
730.136 - root = r;
730.137 - break;
730.138 - }
730.139 - }
730.140 - }
730.141 -
730.142 - if (root != null) {
730.143 - String rootPath = FileUtil.toFile(root).getAbsolutePath();
730.144 - if (testFilePath.startsWith(rootPath)) {
730.145 - testFilePath = testFilePath.substring(rootPath.length());
730.146 - if (testFilePath.startsWith("/") || testFilePath.startsWith("\\")) { // NOI18N
730.147 - testFilePath = testFilePath.substring(1);
730.148 - }
730.149 -
730.150 - testFilePath = testFilePath.replace("\\", ".");
730.151 - testFilePath = testFilePath.replace("/", ".");
730.152 -
730.153 - if (testFilePath.endsWith(".py")) {
730.154 - testFilePath = testFilePath.substring(0, testFilePath.length()-3);
730.155 - }
730.156 - }
730.157 - }
730.158 - }
730.159 - List<String> additionalArgs = new ArrayList<String>();
730.160 - additionalArgs.add("-f"); //NOI18N
730.161 - additionalArgs.add(testFilePath);
730.162 - return additionalArgs;
730.163 - }
730.164 -
730.165 - private static File getScript(String name) {
730.166 - File script = InstalledFileLocator.getDefault().locate(
730.167 - name, "org.netbeans.modules.python.testrunner", false); // NOI18N
730.168 -
730.169 - if (script == null) {
730.170 - throw new IllegalStateException("Could not locate " + name); // NOI18N
730.171 -
730.172 - }
730.173 - return script;
730.174 -
730.175 - }
730.176 -
730.177 - static void addPyUnitRunnerToEnv(Map<String, String> env) {
730.178 - env.put(NB_TEST_RUNNER, getScript(RUNNER_SCRIPT_NAME).getAbsolutePath());
730.179 - }
730.180 -
730.181 - public void runAllTests(Project project, boolean debug) {
730.182 - List<String> additionalArgs = new ArrayList<String>();
730.183 - PythonProject baseProject = project.getLookup().lookup(PythonProject.class);
730.184 - boolean haveTestFolders = false;
730.185 - for (FileObject testDir : baseProject.getTestSourceRootFiles()) {
730.186 - additionalArgs.add("-d"); //NOI18N
730.187 - additionalArgs.add(FileUtil.toFile(testDir).getAbsolutePath());
730.188 - haveTestFolders = true;
730.189 - }
730.190 - if (!haveTestFolders) {
730.191 - for (FileObject testDir : baseProject.getSourceRootFiles()) {
730.192 - additionalArgs.add("-d"); //NOI18N
730.193 - additionalArgs.add(FileUtil.toFile(testDir).getAbsolutePath());
730.194 - }
730.195 - }
730.196 -
730.197 - String name = ProjectUtils.getInformation(project).getDisplayName();
730.198 -
730.199 - run(project, additionalArgs, name, debug);
730.200 - }
730.201 -
730.202 - protected ArrayList<String> buildPythonPath( PythonPlatform platform , PythonProject project ) {
730.203 - final ArrayList<String> pythonPath = new ArrayList<String>() ;
730.204 - // start with platform
730.205 - pythonPath.addAll(platform.getPythonPath());
730.206 - for (FileObject fo : project.getSourceRoots().getRoots()) {
730.207 - File f = FileUtil.toFile(fo);
730.208 - pythonPath.add(f.getAbsolutePath());
730.209 - }
730.210 - for (FileObject fo : project.getTestRoots().getRoots()) {
730.211 - File f = FileUtil.toFile(fo);
730.212 - pythonPath.add(f.getAbsolutePath());
730.213 - }
730.214 - PythonProjectProperties properties = new PythonProjectProperties(project);
730.215 - pythonPath.addAll(properties.getPythonPath());
730.216 - return pythonPath ;
730.217 - }
730.218 -
730.219 - /**
730.220 - *
730.221 - * provide a reasonable common Build of JAVAPATH for Run or Debug Jython commands
730.222 - * @param platform current platform
730.223 - * @param project current project
730.224 - * @return JavaPath fileList for jython CLASSPATH command
730.225 - */
730.226 - protected ArrayList<String> buildJavaPath( PythonPlatform platform , PythonProject project ) {
730.227 - final ArrayList<String> javaPath = new ArrayList<String>() ;
730.228 - // start with platform
730.229 - javaPath.addAll(platform.getJavaPath());
730.230 - PythonProjectProperties properties = new PythonProjectProperties(project);
730.231 - javaPath.addAll(properties.getJavaPath());
730.232 - return javaPath ;
730.233 - }
730.234 -
730.235 - private void run(Project project, List<String> additionalArgs, String name, boolean debug) {
730.236 - PythonPlatform platform = PythonPlatform.platformFor(project);
730.237 -
730.238 - //String targetPath = getScript(MEDIATOR_SCRIPT_NAME).getAbsolutePath();
730.239 - PythonExecution desc = null;
730.240 - desc = new PythonExecution();
730.241 -
730.242 - // TODO: Handle debugging...
730.243 - // Requires some coordination between the test infrastructure (which wants to own it through
730.244 - // its TestExecutionManager.start call) and debugging (which wants to own it through its
730.245 - // DebugPythonSource.startDebugging call
730.246 -
730.247 - // TODO - handle passing arguments to the script.
730.248 - // The PythonExecution descriptor needs work.
730.249 -
730.250 - //String charsetName = null;
730.251 - //FileLocator locator = project.getLookup().lookup(FileLocator.class);
730.252 -// desc.additionalArgs(additionalArgs.toArray(new String[additionalArgs.size()]));
730.253 -// desc.initialArgs(PythonProjectUtil.getLoadPath(project)); //NOI18N
730.254 -//
730.255 -// desc.debug(debug);
730.256 -// desc.allowInput();
730.257 -// desc.fileLocator(locator);
730.258 -
730.259 - File pwd = FileUtil.toFile(project.getProjectDirectory());
730.260 -
730.261 - desc.setDisplayName(name);
730.262 - desc.setScriptArgs(BaseUtilities.escapeParameters(additionalArgs.toArray(new String[additionalArgs.size()])));
730.263 - desc.setWorkingDirectory(pwd.getAbsolutePath());
730.264 - desc.setCommand(platform.getInterpreterCommand());
730.265 - desc.setScript(getScript(RUNNER_SCRIPT_NAME).getAbsolutePath());
730.266 - desc.setCommandArgs(platform.getInterpreterArgs());
730.267 - if (project instanceof PythonProject) {
730.268 - PythonProject pythonProject = (PythonProject)project;
730.269 - desc.setPath(PythonPlatform.buildPath(buildPythonPath(platform, pythonProject)));
730.270 - desc.setJavaPath(PythonPlatform.buildPath(buildJavaPath(platform, pythonProject)));
730.271 - }
730.272 - desc.setShowControls(true);
730.273 - desc.setShowInput(true);
730.274 - desc.setShowWindow(true);
730.275 - desc.addStandardRecognizers();
730.276 -
730.277 - PythonCoverageProvider coverageProvider = PythonCoverageProvider.get(project);
730.278 - if (coverageProvider != null && coverageProvider.isEnabled()) {
730.279 - desc = coverageProvider.wrapWithCoverage(desc);
730.280 - }
730.281 -
730.282 - if (LOGGER.isLoggable(Level.INFO)) {
730.283 - LOGGER.log(Level.INFO, "Running Python Unit Test with the following descriptor: command={0} " +
730.284 - "commandArgs={1} displayName={2} javaPath={3} path={4} script={5} scriptArgs={6}" +
730.285 - " workingDirectory={7}", new Object[]{desc.getCommand(), desc.getCommandArgs(),
730.286 - desc.getDisplayName(), desc.getJavaPath(), desc.getPath(), desc.getScript(),
730.287 - desc.getScriptArgs(), desc.getWorkingDirectory()});
730.288 - }
730.289 - Manager.getInstance().setNodeFactory(new PythonTestRunnerNodeFactory());
730.290 - final TestSession session = new TestSession(name,
730.291 - project,
730.292 - debug ? SessionType.DEBUG : SessionType.TEST);
730.293 -
730.294 - TestExecutionManager.getInstance().start(desc, new PyUnitHandlerFactory(), session);
730.295 - }
730.296 -
730.297 - public boolean supports(TestType type) {
730.298 - return type == TestType.PY_UNIT;
730.299 - }
730.300 -
730.301 -// public void customize(Project project, RakeTask task, final PythonExecution taskDescriptor, boolean debug) {
730.302 -// boolean useRunner = TestRunnerUtilities.useTestRunner(project, SharedPythonProjectProperties.TEST_TASKS, task, new DefaultTaskEvaluator() {
730.303 -//
730.304 -// public boolean isDefault(RakeTask task) {
730.305 -// return "test".equals(task.getTask()) || task.getTask().startsWith("test:"); //NOI18N
730.306 -// }
730.307 -// });
730.308 -//
730.309 -// if (!useRunner) {
730.310 -// return;
730.311 -// }
730.312 -//
730.313 -// TestExecutionManager.getInstance().reset();
730.314 -// // this takes care of loading our custom TestTask, which in turn passes
730.315 -// // the custom test runner as an option for the task. This is needed since
730.316 -// // the test run is forked to a different process (by Rake::TestTask) than rake itself
730.317 -// task.addRakeParameters("-r \"" + getScript(RUNNER_SCRIPT_NAME).getAbsolutePath() + "\""); //NOI18N
730.318 -// TestSession session = new TestSession(task.getDisplayName(),
730.319 -// project,
730.320 -// debug ? SessionType.DEBUG : SessionType.TEST,
730.321 -// new PythonTestRunnerNodeFactory());
730.322 -//
730.323 -// Map<String, String> env = new HashMap<String, String>(1);
730.324 -// addPyUnitRunnerToEnv(env);
730.325 -// taskDescriptor.addAdditionalEnv(env);
730.326 -// Manager manager = Manager.getInstance();
730.327 -// final TestRunnerLineConvertor testConvertor = new TestRunnerLineConvertor(manager, session, new PyUnitHandlerFactory());
730.328 -// taskDescriptor.addStandardRecognizers();
730.329 -// taskDescriptor.addOutConvertor(testConvertor);
730.330 -// taskDescriptor.addErrConvertor(testConvertor);
730.331 -// taskDescriptor.lineBased(true);
730.332 -// taskDescriptor.setOutProcessorFactory(new TestRunnerInputProcessorFactory(manager, session, true));
730.333 -// taskDescriptor.setErrProcessorFactory(new TestRunnerInputProcessorFactory(manager, session, false));
730.334 -// taskDescriptor.postBuild(new Runnable() {
730.335 -//
730.336 -// public void run() {
730.337 -// TestExecutionManager.getInstance().finish();
730.338 -// testConvertor.refreshSession();
730.339 -// }
730.340 -// });
730.341 -// TestExecutionManager.getInstance().init(taskDescriptor);
730.342 -// }
730.343 -
730.344 -}
731.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/PythonTestRunnerNodeFactory.java Sun Jan 04 13:11:53 2015 -0600
731.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
731.3 @@ -1,75 +0,0 @@
731.4 -/*
731.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
731.6 - *
731.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
731.8 - *
731.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
731.10 - * Other names may be trademarks of their respective owners.
731.11 - *
731.12 - * The contents of this file are subject to the terms of either the GNU
731.13 - * General Public License Version 2 only ("GPL") or the Common
731.14 - * Development and Distribution License("CDDL") (collectively, the
731.15 - * "License"). You may not use this file except in compliance with the
731.16 - * License. You can obtain a copy of the License at
731.17 - * http://www.netbeans.org/cddl-gplv2.html
731.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
731.19 - * specific language governing permissions and limitations under the
731.20 - * License. When distributing the software, include this License Header
731.21 - * Notice in each file and include the License file at
731.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
731.23 - * particular file as subject to the "Classpath" exception as provided
731.24 - * by Oracle in the GPL Version 2 section of the License file that
731.25 - * accompanied this code. If applicable, add the following below the
731.26 - * License Header, with the fields enclosed by brackets [] replaced by
731.27 - * your own identifying information:
731.28 - * "Portions Copyrighted [year] [name of copyright owner]"
731.29 - *
731.30 - * If you wish your version of this file to be governed by only the CDDL
731.31 - * or only the GPL Version 2, indicate your decision by adding
731.32 - * "[Contributor] elects to include this software in this distribution
731.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
731.34 - * single choice of license, a recipient has the option to distribute
731.35 - * your version of this file under either the CDDL, the GPL Version 2 or
731.36 - * to extend the choice of license to its licensees as provided above.
731.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
731.38 - * Version 2 license, then the option applies only if the new code is
731.39 - * made subject to such option by the copyright holder.
731.40 - *
731.41 - * Contributor(s):
731.42 - *
731.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
731.44 - */
731.45 -
731.46 -package org.netbeans.modules.python.testrunner;
731.47 -
731.48 -import org.netbeans.api.project.Project;
731.49 -import org.netbeans.modules.gsf.testrunner.ui.api.TestRunnerNodeFactory;
731.50 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
731.51 -import org.netbeans.modules.gsf.testrunner.ui.api.TestsuiteNode;
731.52 -import org.netbeans.modules.python.testrunner.ui.PythonCallstackFrameNode;
731.53 -import org.netbeans.modules.python.testrunner.ui.PythonTestMethodNode;
731.54 -import org.netbeans.modules.python.testrunner.ui.PythonTestsuiteNode;
731.55 -import org.openide.nodes.Node;
731.56 -
731.57 -/**
731.58 - *
731.59 - * @author Erno Mononen
731.60 - */
731.61 -public class PythonTestRunnerNodeFactory extends TestRunnerNodeFactory {
731.62 -
731.63 - @Override
731.64 - public Node createTestMethodNode(Testcase testcase, Project project) {
731.65 - return new PythonTestMethodNode(testcase, project);
731.66 - }
731.67 -
731.68 - @Override
731.69 - public Node createCallstackFrameNode(String frameInfo, String dispayName) {
731.70 - return new PythonCallstackFrameNode(frameInfo, dispayName);
731.71 - }
731.72 -
731.73 - @Override
731.74 - public TestsuiteNode createTestSuiteNode(String suiteName, boolean filtered) {
731.75 - return new PythonTestsuiteNode(suiteName, filtered);
731.76 - }
731.77 -
731.78 -}
732.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/TestExecutionManager.java Sun Jan 04 13:11:53 2015 -0600
732.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
732.3 @@ -1,243 +0,0 @@
732.4 -/*
732.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
732.6 - *
732.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
732.8 - *
732.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
732.10 - * Other names may be trademarks of their respective owners.
732.11 - *
732.12 - * The contents of this file are subject to the terms of either the GNU
732.13 - * General Public License Version 2 only ("GPL") or the Common
732.14 - * Development and Distribution License("CDDL") (collectively, the
732.15 - * "License"). You may not use this file except in compliance with the
732.16 - * License. You can obtain a copy of the License at
732.17 - * http://www.netbeans.org/cddl-gplv2.html
732.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
732.19 - * specific language governing permissions and limitations under the
732.20 - * License. When distributing the software, include this License Header
732.21 - * Notice in each file and include the License file at
732.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
732.23 - * particular file as subject to the "Classpath" exception as provided
732.24 - * by Oracle in the GPL Version 2 section of the License file that
732.25 - * accompanied this code. If applicable, add the following below the
732.26 - * License Header, with the fields enclosed by brackets [] replaced by
732.27 - * your own identifying information:
732.28 - * "Portions Copyrighted [year] [name of copyright owner]"
732.29 - *
732.30 - * If you wish your version of this file to be governed by only the CDDL
732.31 - * or only the GPL Version 2, indicate your decision by adding
732.32 - * "[Contributor] elects to include this software in this distribution
732.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
732.34 - * single choice of license, a recipient has the option to distribute
732.35 - * your version of this file under either the CDDL, the GPL Version 2 or
732.36 - * to extend the choice of license to its licensees as provided above.
732.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
732.38 - * Version 2 license, then the option applies only if the new code is
732.39 - * made subject to such option by the copyright holder.
732.40 - *
732.41 - * Contributor(s):
732.42 - *
732.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
732.44 - */
732.45 -
732.46 -package org.netbeans.modules.python.testrunner;
732.47 -
732.48 -import java.io.IOException;
732.49 -import java.util.Set;
732.50 -import java.util.concurrent.Callable;
732.51 -import java.util.concurrent.CancellationException;
732.52 -import java.util.concurrent.ExecutionException;
732.53 -import java.util.concurrent.Future;
732.54 -import java.util.logging.Level;
732.55 -import java.util.logging.Logger;
732.56 -import javax.swing.event.ChangeListener;
732.57 -import org.netbeans.api.extexecution.ExecutionDescriptor;
732.58 -import org.netbeans.api.extexecution.ExecutionService;
732.59 -import org.netbeans.modules.gsf.testrunner.ui.api.Manager;
732.60 -import org.netbeans.modules.gsf.testrunner.api.RerunHandler;
732.61 -import org.netbeans.modules.gsf.testrunner.api.RerunType;
732.62 -import org.netbeans.modules.gsf.testrunner.api.TestSession;
732.63 -//import org.netbeans.modules.python.testrunner.ui.Manager;
732.64 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
732.65 -import org.netbeans.modules.python.api.PythonExecution;
732.66 -import org.netbeans.modules.python.testrunner.ui.TestHandlerFactory;
732.67 -import org.netbeans.modules.python.testrunner.ui.TestRunnerInputProcessorFactory;
732.68 -import org.netbeans.modules.python.testrunner.ui.TestRunnerLineConvertor;
732.69 -//import org.netbeans.modules.python.testrunner.ui.TestSession;
732.70 -import org.openide.LifecycleManager;
732.71 -import org.openide.util.ChangeSupport;
732.72 -import org.openide.util.Exceptions;
732.73 -import org.openide.util.RequestProcessor;
732.74 -
732.75 -/**
732.76 - * Handles running and re-running of test executions.
732.77 - *
732.78 - * <i>This class will probably not be needed after migrating to the new Execution API</i>
732.79 - *
732.80 - * @author Erno Mononen
732.81 - */
732.82 -public final class TestExecutionManager implements RerunHandler {
732.83 -
732.84 - private final static Logger LOGGER = Logger.getLogger(TestExecutionManager.class.getName());
732.85 -
732.86 - /**
732.87 - * The current execution.
732.88 - */
732.89 - private ExecutionService execution;
732.90 - private Future<Integer> result;
732.91 - /**
732.92 - * Indicates whether the current execution has finished.
732.93 - */
732.94 - private boolean finished;
732.95 - private TestRunnerLineConvertor outConvertor;
732.96 - private TestRunnerLineConvertor errConvertor;
732.97 - private final ChangeSupport changeSupport = new ChangeSupport(this);
732.98 - private final RequestProcessor testExecutionProcessor = new RequestProcessor("Python Test Execution Processor"); //NOI18N
732.99 -
732.100 - private static final TestExecutionManager INSTANCE = new TestExecutionManager();
732.101 -
732.102 - private TestExecutionManager() {
732.103 - }
732.104 -
732.105 - public static TestExecutionManager getInstance() {
732.106 - return INSTANCE;
732.107 - }
732.108 -
732.109 - synchronized void finish() {
732.110 - setFinished(true);
732.111 - }
732.112 -
732.113 - synchronized void reset() {
732.114 - this.finished = false;
732.115 - }
732.116 - /**
732.117 - * Inits our TestExecutionManager with the given PythonExecution. Does not
732.118 - * run the execution.
732.119 - *
732.120 - * @param pythonDescriptor
732.121 - */
732.122 - synchronized void init(PythonExecution pythonDescriptor) {
732.123 - try {
732.124 - Callable<Process> rpc = pythonDescriptor.buildProcess();
732.125 -//
732.126 - ExecutionDescriptor descriptor = pythonDescriptor.toExecutionDescriptor();
732.127 - execution = ExecutionService.newService(rpc, descriptor, pythonDescriptor.getDisplayName());
732.128 - } catch (IOException ex) {
732.129 - Exceptions.printStackTrace(ex);
732.130 - }
732.131 - }
732.132 - /**
732.133 - * Starts a PythonExecution with the given executionDescriptor and testRecognizer.
732.134 - *
732.135 - * @param executionDescriptor
732.136 - * @param testRecognizer
732.137 - */
732.138 - synchronized void start(PythonExecution pythonDescriptor,
732.139 - TestHandlerFactory handlerFactory, TestSession session) {
732.140 -
732.141 - setFinished(false);
732.142 - session.setRerunHandler(this);
732.143 - final Manager manager = Manager.getInstance();
732.144 - outConvertor = new TestRunnerLineConvertor(manager, session, handlerFactory);
732.145 - errConvertor = new TestRunnerLineConvertor(manager, session, handlerFactory);
732.146 - pythonDescriptor.addOutConvertor(outConvertor);
732.147 - pythonDescriptor.addErrConvertor(errConvertor);
732.148 - pythonDescriptor.setOutProcessorFactory(new TestRunnerInputProcessorFactory(manager, session, handlerFactory.printSummary()));
732.149 - pythonDescriptor.setErrProcessorFactory(new TestRunnerInputProcessorFactory(manager, session, false));
732.150 - pythonDescriptor.lineBased(true);
732.151 -
732.152 -
732.153 - try {
732.154 - Callable<Process> rpc = pythonDescriptor.buildProcess();
732.155 -
732.156 - final Runnable oldPostExecutionHook = pythonDescriptor.getPostExecutionHook();
732.157 - ExecutionDescriptor descriptor = pythonDescriptor.toExecutionDescriptor()
732.158 - .postExecution(new Runnable() {
732.159 -
732.160 - public void run() {
732.161 - refresh();
732.162 - if (oldPostExecutionHook != null) {
732.163 - oldPostExecutionHook.run();
732.164 - }
732.165 - }
732.166 - });
732.167 - execution = ExecutionService.newService(rpc, descriptor, pythonDescriptor.getDisplayName());
732.168 - runExecution();
732.169 - } catch (IOException ex) {
732.170 - Exceptions.printStackTrace(ex);
732.171 - }
732.172 - }
732.173 -
732.174 - private void runExecution() {
732.175 - result = execution.run();
732.176 - testExecutionProcessor.post(new Runnable() {
732.177 - public void run() {
732.178 - try {
732.179 - result.get();
732.180 - } catch (InterruptedException ex) {
732.181 - Exceptions.printStackTrace(ex);
732.182 - } catch (ExecutionException ex) {
732.183 - Exceptions.printStackTrace(ex);
732.184 - } catch (CancellationException ex) {
732.185 - // ignore
732.186 - }
732.187 - setFinished(result.isDone());
732.188 - }
732.189 - });
732.190 - }
732.191 -
732.192 - /**
732.193 - * Checks whether the current execution is finished.
732.194 - *
732.195 - * @return true if the current execution has finished,
732.196 - * false otherwise.
732.197 - */
732.198 - @Override
732.199 - public boolean enabled(RerunType type) {
732.200 - return RerunType.ALL.equals(type) && (finished || (result != null && result.isDone()));
732.201 - }
732.202 -
732.203 - private void setFinished(boolean finished) {
732.204 - this.finished = finished;
732.205 - changeSupport.fireChange();
732.206 - }
732.207 - /**
732.208 - * Re-runs the last run test execution.
732.209 - */
732.210 - public synchronized void rerun() {
732.211 - assert enabled(RerunType.ALL);
732.212 - if (LOGGER.isLoggable(Level.FINE)) {
732.213 - LOGGER.log(Level.FINE, "Re-running: " + execution);
732.214 - }
732.215 - refresh();
732.216 - setFinished(false);
732.217 - LifecycleManager.getDefault().saveAll();
732.218 - runExecution();
732.219 - }
732.220 -
732.221 - @Override
732.222 - public void rerun(Set<Testcase> tests) {
732.223 - //not implemented yet
732.224 - }
732.225 -
732.226 - public void addChangeListener(ChangeListener listener) {
732.227 - changeSupport.addChangeListener(listener);
732.228 - }
732.229 -
732.230 - public void removeChangeListener(ChangeListener listener) {
732.231 - changeSupport.removeChangeListener(listener);
732.232 - }
732.233 -
732.234 - /**
732.235 - * Refreshes the current session, i.e. clears all currently
732.236 - * computed test statuses.
732.237 - */
732.238 - public synchronized void refresh() {
732.239 - if (outConvertor != null) {
732.240 - outConvertor.refreshSession();
732.241 - }
732.242 - if (errConvertor != null) {
732.243 - errConvertor.refreshSession();
732.244 - }
732.245 - }
732.246 -}
733.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/TestRunnerUtilities.java Sun Jan 04 13:11:53 2015 -0600
733.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
733.3 @@ -1,93 +0,0 @@
733.4 -/*
733.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
733.6 - *
733.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
733.8 - *
733.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
733.10 - * Other names may be trademarks of their respective owners.
733.11 - *
733.12 - * The contents of this file are subject to the terms of either the GNU
733.13 - * General Public License Version 2 only ("GPL") or the Common
733.14 - * Development and Distribution License("CDDL") (collectively, the
733.15 - * "License"). You may not use this file except in compliance with the
733.16 - * License. You can obtain a copy of the License at
733.17 - * http://www.netbeans.org/cddl-gplv2.html
733.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
733.19 - * specific language governing permissions and limitations under the
733.20 - * License. When distributing the software, include this License Header
733.21 - * Notice in each file and include the License file at
733.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
733.23 - * particular file as subject to the "Classpath" exception as provided
733.24 - * by Oracle in the GPL Version 2 section of the License file that
733.25 - * accompanied this code. If applicable, add the following below the
733.26 - * License Header, with the fields enclosed by brackets [] replaced by
733.27 - * your own identifying information:
733.28 - * "Portions Copyrighted [year] [name of copyright owner]"
733.29 - *
733.30 - * If you wish your version of this file to be governed by only the CDDL
733.31 - * or only the GPL Version 2, indicate your decision by adding
733.32 - * "[Contributor] elects to include this software in this distribution
733.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
733.34 - * single choice of license, a recipient has the option to distribute
733.35 - * your version of this file under either the CDDL, the GPL Version 2 or
733.36 - * to extend the choice of license to its licensees as provided above.
733.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
733.38 - * Version 2 license, then the option applies only if the new code is
733.39 - * made subject to such option by the copyright holder.
733.40 - *
733.41 - * Contributor(s):
733.42 - *
733.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
733.44 - */
733.45 -
733.46 -package org.netbeans.modules.python.testrunner;
733.47 -
733.48 -import org.netbeans.api.project.Project;
733.49 -import org.netbeans.spi.project.support.ant.PropertyEvaluator;
733.50 -
733.51 -/**
733.52 - * Utility methods for <code>TestRunner</code> implementations.
733.53 - *
733.54 - * @author Erno Mononen
733.55 - */
733.56 -final class TestRunnerUtilities {
733.57 -
733.58 - private TestRunnerUtilities() {
733.59 - }
733.60 -
733.61 - /**
733.62 - * Checks whether the given task should be run using the UI test runner.
733.63 - *
733.64 - * @param project
733.65 - * @param property
733.66 - * @param task
733.67 - * @param taskEvaluator
733.68 - * @return true if the given task should be run using the UI test runner;
733.69 - * false otherwise.
733.70 - */
733.71 - static boolean useTestRunner(Project project, String property, /*RakeTask task,*/ DefaultTaskEvaluator taskEvaluator) {
733.72 -throw new RuntimeException("useTestRunner -- not sure what to do here");
733.73 -// PropertyEvaluator evaluator = project.getLookup().lookup(PropertyEvaluator.class);
733.74 -// if (evaluator == null || evaluator.getProperty(property) == null) {
733.75 -// return taskEvaluator.isDefault(task);
733.76 -// }
733.77 -// String definedTasks = evaluator.getProperty(property);
733.78 -// if ("".equals(definedTasks.trim())) {
733.79 -// return false;
733.80 -// }
733.81 -// for (String each : definedTasks.split(",")) { //NOI18N
733.82 -// if (task.getTask().equals(each.trim())) {
733.83 -// return true;
733.84 -// }
733.85 -// }
733.86 -// return false;
733.87 -// return true;
733.88 - }
733.89 -
733.90 -
733.91 - interface DefaultTaskEvaluator {
733.92 -
733.93 - boolean isDefault(Object task/*RakeTask task*/);
733.94 - }
733.95 -
733.96 -}
734.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/BaseTestMethodNodeAction.java Sun Jan 04 13:11:53 2015 -0600
734.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
734.3 @@ -1,103 +0,0 @@
734.4 -/*
734.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
734.6 - *
734.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
734.8 - *
734.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
734.10 - * Other names may be trademarks of their respective owners.
734.11 - *
734.12 - * The contents of this file are subject to the terms of either the GNU
734.13 - * General Public License Version 2 only ("GPL") or the Common
734.14 - * Development and Distribution License("CDDL") (collectively, the
734.15 - * "License"). You may not use this file except in compliance with the
734.16 - * License. You can obtain a copy of the License at
734.17 - * http://www.netbeans.org/cddl-gplv2.html
734.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
734.19 - * specific language governing permissions and limitations under the
734.20 - * License. When distributing the software, include this License Header
734.21 - * Notice in each file and include the License file at
734.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
734.23 - * particular file as subject to the "Classpath" exception as provided
734.24 - * by Oracle in the GPL Version 2 section of the License file that
734.25 - * accompanied this code. If applicable, add the following below the
734.26 - * License Header, with the fields enclosed by brackets [] replaced by
734.27 - * your own identifying information:
734.28 - * "Portions Copyrighted [year] [name of copyright owner]"
734.29 - *
734.30 - * If you wish your version of this file to be governed by only the CDDL
734.31 - * or only the GPL Version 2, indicate your decision by adding
734.32 - * "[Contributor] elects to include this software in this distribution
734.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
734.34 - * single choice of license, a recipient has the option to distribute
734.35 - * your version of this file under either the CDDL, the GPL Version 2 or
734.36 - * to extend the choice of license to its licensees as provided above.
734.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
734.38 - * Version 2 license, then the option applies only if the new code is
734.39 - * made subject to such option by the copyright holder.
734.40 - *
734.41 - * Contributor(s):
734.42 - *
734.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
734.44 - */
734.45 -
734.46 -package org.netbeans.modules.python.testrunner.ui;
734.47 -
734.48 -import java.util.Collection;
734.49 -import java.util.logging.Logger;
734.50 -import org.netbeans.api.project.Project;
734.51 -import org.netbeans.modules.gsf.testrunner.ui.api.TestNodeAction;
734.52 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
734.53 -import org.netbeans.modules.python.project.PythonProject;
734.54 -import org.netbeans.modules.python.project.spi.TestRunner;
734.55 -import org.openide.filesystems.FileObject;
734.56 -import org.openide.util.Lookup;
734.57 -
734.58 -/**
734.59 - * Base class for actions associated with a test method node.
734.60 - *
734.61 - * @author Erno Mononen
734.62 - */
734.63 -abstract class BaseTestMethodNodeAction extends TestNodeAction {
734.64 -
734.65 - private static final Logger LOGGER = Logger.getLogger(BaseTestMethodNodeAction.class.getName());
734.66 -
734.67 - protected final Testcase testcase;
734.68 - protected final Project project;
734.69 - protected final String name;
734.70 -
734.71 - public BaseTestMethodNodeAction(Testcase testcase, Project project, String name) {
734.72 - this.testcase = testcase;
734.73 - this.project = project;
734.74 - this.name = name;
734.75 - }
734.76 -
734.77 - @Override
734.78 - public Object getValue(String key) {
734.79 - if (NAME.equals(key)) {
734.80 - return name;
734.81 - }
734.82 - return super.getValue(key);
734.83 - }
734.84 -
734.85 - protected String getTestMethod() {
734.86 - return testcase.getClassName() + "/" + testcase.getName(); //NOI18N
734.87 - }
734.88 -
734.89 - protected FileObject getTestSourceRoot() {
734.90 - PythonProject baseProject = project.getLookup().lookup(PythonProject.class);
734.91 - // need to use test source roots, not source roots -- see the comments in #135680
734.92 - FileObject[] testRoots = baseProject.getTestSourceRootFiles();
734.93 - // if there are not test roots, return the project root -- works in rails projects
734.94 - return 0 == testRoots.length ? project.getProjectDirectory() : testRoots[0];
734.95 - }
734.96 -
734.97 - protected TestRunner getTestRunner(TestRunner.TestType testType) {
734.98 - Collection<? extends TestRunner> testRunners = Lookup.getDefault().lookupAll(TestRunner.class);
734.99 - for (TestRunner each : testRunners) {
734.100 - if (each.supports(testType)) {
734.101 - return each;
734.102 - }
734.103 - }
734.104 - return null;
734.105 - }
734.106 -}
735.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
735.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
735.3 @@ -1,141 +0,0 @@
735.4 -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
735.5 -#
735.6 -# Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
735.7 -#
735.8 -# Oracle and Java are registered trademarks of Oracle and/or its affiliates.
735.9 -# Other names may be trademarks of their respective owners.
735.10 -#
735.11 -# The contents of this file are subject to the terms of either the GNU
735.12 -# General Public License Version 2 only ("GPL") or the Common
735.13 -# Development and Distribution License("CDDL") (collectively, the
735.14 -# "License"). You may not use this file except in compliance with the
735.15 -# License. You can obtain a copy of the License at
735.16 -# http://www.netbeans.org/cddl-gplv2.html
735.17 -# or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
735.18 -# specific language governing permissions and limitations under the
735.19 -# License. When distributing the software, include this License Header
735.20 -# Notice in each file and include the License file at
735.21 -# nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
735.22 -# particular file as subject to the "Classpath" exception as provided
735.23 -# by Oracle in the GPL Version 2 section of the License file that
735.24 -# accompanied this code. If applicable, add the following below the
735.25 -# License Header, with the fields enclosed by brackets [] replaced by
735.26 -# your own identifying information:
735.27 -# "Portions Copyrighted [year] [name of copyright owner]"
735.28 -#
735.29 -# Contributor(s):
735.30 -#
735.31 -# The Original Software is NetBeans. The Initial Developer of the Original
735.32 -# Software is Sun Microsystems, Inc. Portions Copyright 2006-2008 Sun
735.33 -# Microsystems, Inc. All Rights Reserved.
735.34 -#
735.35 -# If you wish your version of this file to be governed by only the CDDL
735.36 -# or only the GPL Version 2, indicate your decision by adding
735.37 -# "[Contributor] elects to include this software in this distribution
735.38 -# under the [CDDL or GPL Version 2] license." If you do not indicate a
735.39 -# single choice of license, a recipient has the option to distribute
735.40 -# your version of this file under either the CDDL, the GPL Version 2 or
735.41 -# to extend the choice of license to its licensees as provided above.
735.42 -# However, if you add GPL Version 2 code and therefore, elected the GPL
735.43 -# Version 2 license, then the option applies only if the new code is
735.44 -# made subject to such option by the copyright holder.
735.45 -
735.46 -TITLE_TEST_RESULTS=Python Test Results
735.47 -ResultWindowOpenAction.MenuName=Python &Test Results
735.48 -ACSN_TestResults=Python Test Results
735.49 -ACSD_TestResults=Displays information about passed and failed tests and output generated by them
735.50 -ACSN_FilterButton=Filter On/Off
735.51 -ACSN_RerunButton = Rerun
735.52 -ACSN_ResultPanelTree=Information about passed and failed tests
735.53 -ACSD_ResultPanelTree=Displays in a tree structure information about passed, failed and erroneous tests
735.54 -ACSN_HorizontalScrollbar=Horizontal scrollbar of the results panel
735.55 -ACSN_OutputTextPane=Test Output
735.56 -ACSD_OutputTextPane=Displays output and error output generated by executed test methods
735.57 -
735.58 -MSG_PassedTestsInfo={0,choice,0#No test|1#1 test|1<{0,number,integer} tests} passed
735.59 -MSG_FailedTestsInfo={0,choice,1#1 test|1<{0,number,integer} tests} failed
735.60 -MSG_PendingTestsInfo={0,choice,1#1 test|1<{0,number,integer} tests} pending
735.61 -MSG_ErrorTestsInfo={0,choice,1#1 test|1<{0,number,integer} tests} caused an error
735.62 -
735.63 -MSG_TestsInfoNoTests=No tests executed.
735.64 -
735.65 -# "All 58 tests passed."
735.66 -MSG_TestsInfoAllOK={0,choice,1#The test|2#Both tests|2<All {0,number,integer} tests} passed.
735.67 -
735.68 -# The result summary can be a combination of passed, pending, failed and error
735.69 -# causing tests. The keys below are for all combinations of these, the preferred
735.70 -# order is passed, pending, failed, error.
735.71 -MSG_TestResultSummary1 = {0}, {1}.
735.72 -MSG_TestResultSummary2 = {0}, {1}, {2}.
735.73 -MSG_TestResultSummary3 = {0}, {1}, {2}, {3}.
735.74 -
735.75 -# {0} .. name of the test class
735.76 -MSG_TestsuiteNoname=Test suite
735.77 -MSG_TestsuiteRunning={0} - running...
735.78 -MSG_TestsuiteRunningNoname=Test suite running...
735.79 -MSG_TestsuiteFailed={0} - FAILED
735.80 -MSG_TestsuitePending={0} - PENDING
735.81 -MSG_TestsuiteRunning_HTML=running...
735.82 -MSG_TestsuitePassed_HTML=passed
735.83 -MSG_TestsuiteFailed_HTML=FAILED
735.84 -MSG_TestsuitePending_HTML=PENDING
735.85 -
735.86 -# {0} .. name of the test method
735.87 -MSG_TestMethodFailed={0} - FAILED
735.88 -MSG_TestMethodPending={0} - PENDING
735.89 -MSG_TestMethodError={0} - caused an ERROR
735.90 -MSG_TestMethodPassed_HTML=passed
735.91 -MSG_TestMethodFailed_HTML=FAILED
735.92 -MSG_TestMethodPending_HTML=PENDING
735.93 -MSG_TestMethodError_HTML=caused an ERROR
735.94 -
735.95 -# {0} .. name of the test method, {1} .. elapsed time in seconds
735.96 -MSG_TestMethodPassed_time={0} ({1,number,0.0##} s)
735.97 -MSG_TestMethodFailed_time={0} - FAILED ({1,number,0.0##} s)
735.98 -MSG_TestMethodPending_time={0} - PENDING ({1,number,0.0##} s)
735.99 -MSG_TestMethodError_time={0} - caused an ERROR ({1,number,0.0##} s)
735.100 -MSG_TestMethodPassed_HTML_time=passed ({0,number,0.0##} s)
735.101 -MSG_TestMethodFailed_HTML_time=FAILED ({0,number,0.0##} s)
735.102 -MSG_TestMethodPending_HTML_time=PENDING ({0,number,0.0##} s)
735.103 -MSG_TestMethodError_HTML_time=caused an ERROR ({0,number,0.0##} s)
735.104 -
735.105 -MSG_TestMethodPassed_HTML_cause=passed
735.106 -MSG_TestMethodFailed_HTML_cause=FAILED ({0})
735.107 -MSG_TestMethodPending_HTML_cause=PENDING ({0})
735.108 -MSG_TestMethodError_HTML_cause=caused an ERROR ({0})
735.109 -
735.110 -# Elapsed time for a test suite
735.111 -MSG_TestSuiteElapsedTime= ({0,number,0.0##} s)
735.112 -
735.113 -#
735.114 -MSG_PassedNotDisplayed=Information about passed tests is not displayed.
735.115 -MSG_SomePassedNotDisplayed=Information about some passed tests is not displayed.
735.116 -
735.117 -MSG_StdOutput=Standard Output:
735.118 -MSG_ErrOutput=Error Output:
735.119 -
735.120 -#
735.121 -MultiviewPanel.btnFilter.showAll.tooltip=Show All Results
735.122 -MultiviewPanel.btnFilter.showFailures.tooltip=Show Failures Only
735.123 -
735.124 -MultiviewPanel.rerunButton.tooltip=Rerun
735.125 -
735.126 -LBL_RunningTests=Running...
735.127 -
735.128 -MSG_Error = {0}) Error:
735.129 -MSG_Failure = {0}) Failure:
735.130 -
735.131 -MSG_NextFailure = Next Failure - Ctrl+Period
735.132 -MSG_PreviousFailure = Previous Failure - Ctrl+Comma
735.133 -# test results summary
735.134 -MSG_TestSessionStarting = Running {0}...
735.135 -MSG_TestSessionFinished = Finished in {0,number,0.0##} seconds.
735.136 -MSG_TestSessionFinishedSummary = {0} tests, {1} failures, {2} errors
735.137 -
735.138 -# actions for a test method node
735.139 -LBL_RerunTest= &Run Again
735.140 -LBL_DebugTest= &Debug
735.141 -LBL_GoToSource = &Go to Source
735.142 -
735.143 -# displayed in tooltip of a test case / suite when there is no output for it
735.144 -MSG_NoOutput = No output.
736.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/DisplayOutputForNodeAction.java Sun Jan 04 13:11:53 2015 -0600
736.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
736.3 @@ -1,79 +0,0 @@
736.4 -/*
736.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
736.6 - *
736.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
736.8 - *
736.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
736.10 - * Other names may be trademarks of their respective owners.
736.11 - *
736.12 - * The contents of this file are subject to the terms of either the GNU
736.13 - * General Public License Version 2 only ("GPL") or the Common
736.14 - * Development and Distribution License("CDDL") (collectively, the
736.15 - * "License"). You may not use this file except in compliance with the
736.16 - * License. You can obtain a copy of the License at
736.17 - * http://www.netbeans.org/cddl-gplv2.html
736.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
736.19 - * specific language governing permissions and limitations under the
736.20 - * License. When distributing the software, include this License Header
736.21 - * Notice in each file and include the License file at
736.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
736.23 - * particular file as subject to the "Classpath" exception as provided
736.24 - * by Oracle in the GPL Version 2 section of the License file that
736.25 - * accompanied this code. If applicable, add the following below the
736.26 - * License Header, with the fields enclosed by brackets [] replaced by
736.27 - * your own identifying information:
736.28 - * "Portions Copyrighted [year] [name of copyright owner]"
736.29 - *
736.30 - * If you wish your version of this file to be governed by only the CDDL
736.31 - * or only the GPL Version 2, indicate your decision by adding
736.32 - * "[Contributor] elects to include this software in this distribution
736.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
736.34 - * single choice of license, a recipient has the option to distribute
736.35 - * your version of this file under either the CDDL, the GPL Version 2 or
736.36 - * to extend the choice of license to its licensees as provided above.
736.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
736.38 - * Version 2 license, then the option applies only if the new code is
736.39 - * made subject to such option by the copyright holder.
736.40 - *
736.41 - * Contributor(s):
736.42 - *
736.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
736.44 - */
736.45 -package org.netbeans.modules.python.testrunner.ui;
736.46 -
736.47 -//import java.awt.event.ActionEvent;
736.48 -//import java.util.List;
736.49 -//import javax.swing.AbstractAction;
736.50 -//import org.netbeans.modules.gsf.testrunner.Manager;
736.51 -//import org.netbeans.modules.gsf.testrunner.TestSession;
736.52 -////import org.netbeans.modules.gsf.testrunner.output.OutputLine;
736.53 -//
736.54 -///**
736.55 -// *
736.56 -// * @author Erno Mononen
736.57 -// */
736.58 -//final class DisplayOutputForNodeAction extends AbstractAction {
736.59 -//
736.60 -// private final List<OutputLine> output;
736.61 -// private final TestSession session;
736.62 -//
736.63 -// public DisplayOutputForNodeAction(List<OutputLine> output, TestSession session) {
736.64 -// this.output = output;
736.65 -// this.session = session;
736.66 -// }
736.67 -//
736.68 -//
736.69 -// public Object getValue(String key) {
736.70 -// if (NAME.equals(key)) {
736.71 -// return "display";
736.72 -// }
736.73 -// return super.getValue(key);
736.74 -// }
736.75 -//
736.76 -// public void actionPerformed(ActionEvent e) {
736.77 -// Manager manager = Manager.getInstance();
736.78 -// for (OutputLine ol : output) {
736.79 -// manager.displayOutput(session, ol.getLine(), ol.isError());
736.80 -// }
736.81 -// }
736.82 -//}
737.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/JumpToCallStackAction.java Sun Jan 04 13:11:53 2015 -0600
737.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
737.3 @@ -1,105 +0,0 @@
737.4 -/*
737.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
737.6 - *
737.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
737.8 - *
737.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
737.10 - * Other names may be trademarks of their respective owners.
737.11 - *
737.12 - * The contents of this file are subject to the terms of either the GNU
737.13 - * General Public License Version 2 only ("GPL") or the Common
737.14 - * Development and Distribution License("CDDL") (collectively, the
737.15 - * "License"). You may not use this file except in compliance with the
737.16 - * License. You can obtain a copy of the License at
737.17 - * http://www.netbeans.org/cddl-gplv2.html
737.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
737.19 - * specific language governing permissions and limitations under the
737.20 - * License. When distributing the software, include this License Header
737.21 - * Notice in each file and include the License file at
737.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
737.23 - * particular file as subject to the "Classpath" exception as provided
737.24 - * by Oracle in the GPL Version 2 section of the License file that
737.25 - * accompanied this code. If applicable, add the following below the
737.26 - * License Header, with the fields enclosed by brackets [] replaced by
737.27 - * your own identifying information:
737.28 - * "Portions Copyrighted [year] [name of copyright owner]"
737.29 - *
737.30 - * Contributor(s):
737.31 - *
737.32 - * The Original Software is NetBeans. The Initial Developer of the Original
737.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
737.34 - * Microsystems, Inc. All Rights Reserved.
737.35 - *
737.36 - * If you wish your version of this file to be governed by only the CDDL
737.37 - * or only the GPL Version 2, indicate your decision by adding
737.38 - * "[Contributor] elects to include this software in this distribution
737.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
737.40 - * single choice of license, a recipient has the option to distribute
737.41 - * your version of this file under either the CDDL, the GPL Version 2 or
737.42 - * to extend the choice of license to its licensees as provided above.
737.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
737.44 - * Version 2 license, then the option applies only if the new code is
737.45 - * made subject to such option by the copyright holder.
737.46 - */
737.47 -
737.48 -package org.netbeans.modules.python.testrunner.ui;
737.49 -
737.50 -import java.awt.event.ActionEvent;
737.51 -import javax.swing.AbstractAction;
737.52 -import org.openide.nodes.Node;
737.53 -import org.openide.util.NbBundle;
737.54 -
737.55 -/**
737.56 - * Jump to action for call stack lines.
737.57 - *
737.58 - * @author Marian Petras, Erno Mononen
737.59 - */
737.60 -final class JumpToCallStackAction extends AbstractAction {
737.61 -
737.62 - /** */
737.63 - private final Node node;
737.64 - /** */
737.65 - private final String callstackFrameInfo;
737.66 -
737.67 - private int line;
737.68 -
737.69 - /** Creates a new instance of JumpAction */
737.70 - JumpToCallStackAction(Node node, String callstackFrameInfo) {
737.71 - this(node, callstackFrameInfo, -1);
737.72 - }
737.73 -
737.74 - /**
737.75 - * @param node
737.76 - * @param callstackFrameInfo a line in call stack representing the location
737.77 - * to jump
737.78 - * @param line the line where to jump, if <code>line == -1</code>, then
737.79 - * the line will be computed from the given <code>callstackFrameInfo</code>.
737.80 - */
737.81 - JumpToCallStackAction(Node node, String callstackFrameInfo, int line) {
737.82 - this.node = node;
737.83 - this.callstackFrameInfo = callstackFrameInfo;
737.84 - this.line = line;
737.85 - }
737.86 -
737.87 -
737.88 - @Override
737.89 - public Object getValue(String key) {
737.90 - if (NAME.equals(key)) {
737.91 - return NbBundle.getMessage(JumpToCallStackAction.class, "LBL_GoToSource");
737.92 - }
737.93 - return super.getValue(key);
737.94 - }
737.95 -
737.96 - /**
737.97 - * If the <code>callstackFrameInfo</code> is not <code>null</code>,
737.98 - * tries to jump to the callstack frame source code. Otherwise does nothing.
737.99 - */
737.100 - public void actionPerformed(ActionEvent e) {
737.101 - if (callstackFrameInfo == null) {
737.102 - return;
737.103 - }
737.104 -
737.105 - OutputUtils.openCallstackFrame(node, callstackFrameInfo, line);
737.106 - }
737.107 -
737.108 -}
738.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/JumpToTestAction.java Sun Jan 04 13:11:53 2015 -0600
738.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
738.3 @@ -1,73 +0,0 @@
738.4 -/*
738.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
738.6 - *
738.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
738.8 - *
738.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
738.10 - * Other names may be trademarks of their respective owners.
738.11 - *
738.12 - * The contents of this file are subject to the terms of either the GNU
738.13 - * General Public License Version 2 only ("GPL") or the Common
738.14 - * Development and Distribution License("CDDL") (collectively, the
738.15 - * "License"). You may not use this file except in compliance with the
738.16 - * License. You can obtain a copy of the License at
738.17 - * http://www.netbeans.org/cddl-gplv2.html
738.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
738.19 - * specific language governing permissions and limitations under the
738.20 - * License. When distributing the software, include this License Header
738.21 - * Notice in each file and include the License file at
738.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
738.23 - * particular file as subject to the "Classpath" exception as provided
738.24 - * by Oracle in the GPL Version 2 section of the License file that
738.25 - * accompanied this code. If applicable, add the following below the
738.26 - * License Header, with the fields enclosed by brackets [] replaced by
738.27 - * your own identifying information:
738.28 - * "Portions Copyrighted [year] [name of copyright owner]"
738.29 - *
738.30 - * If you wish your version of this file to be governed by only the CDDL
738.31 - * or only the GPL Version 2, indicate your decision by adding
738.32 - * "[Contributor] elects to include this software in this distribution
738.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
738.34 - * single choice of license, a recipient has the option to distribute
738.35 - * your version of this file under either the CDDL, the GPL Version 2 or
738.36 - * to extend the choice of license to its licensees as provided above.
738.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
738.38 - * Version 2 license, then the option applies only if the new code is
738.39 - * made subject to such option by the copyright holder.
738.40 - *
738.41 - * Contributor(s):
738.42 - *
738.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
738.44 - */
738.45 -
738.46 -package org.netbeans.modules.python.testrunner.ui;
738.47 -
738.48 -import java.awt.event.ActionEvent;
738.49 -import org.netbeans.api.project.Project;
738.50 -import org.netbeans.modules.gsf.api.DeclarationFinder.DeclarationLocation;
738.51 -import org.netbeans.modules.gsf.spi.GsfUtilities;
738.52 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
738.53 -import org.netbeans.modules.python.editor.PythonDeclarationFinder;
738.54 -
738.55 -/**
738.56 - * Jump to action for test methods.
738.57 - *
738.58 - * @author Erno Mononen
738.59 - */
738.60 -final class JumpToTestAction extends BaseTestMethodNodeAction {
738.61 -
738.62 - private final boolean jumpToClass;
738.63 -
738.64 - JumpToTestAction(Testcase testcase, Project project, String name, boolean clazz) {
738.65 - super(testcase, project, name);
738.66 - this.jumpToClass = clazz;
738.67 - }
738.68 -
738.69 - protected void doActionPerformed(ActionEvent e) {
738.70 - DeclarationLocation location = PythonDeclarationFinder.getTestDeclaration(getTestSourceRoot(), getTestMethod(), jumpToClass);
738.71 - if (!(DeclarationLocation.NONE == location)) {
738.72 - GsfUtilities.open(location.getFileObject(), location.getOffset(), null);
738.73 - }
738.74 - }
738.75 -
738.76 -}
739.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/OutputUtils.java Sun Jan 04 13:11:53 2015 -0600
739.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
739.3 @@ -1,145 +0,0 @@
739.4 -/*
739.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
739.6 - *
739.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
739.8 - *
739.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
739.10 - * Other names may be trademarks of their respective owners.
739.11 - *
739.12 - * The contents of this file are subject to the terms of either the GNU
739.13 - * General Public License Version 2 only ("GPL") or the Common
739.14 - * Development and Distribution License("CDDL") (collectively, the
739.15 - * "License"). You may not use this file except in compliance with the
739.16 - * License. You can obtain a copy of the License at
739.17 - * http://www.netbeans.org/cddl-gplv2.html
739.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
739.19 - * specific language governing permissions and limitations under the
739.20 - * License. When distributing the software, include this License Header
739.21 - * Notice in each file and include the License file at
739.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
739.23 - * particular file as subject to the "Classpath" exception as provided
739.24 - * by Oracle in the GPL Version 2 section of the License file that
739.25 - * accompanied this code. If applicable, add the following below the
739.26 - * License Header, with the fields enclosed by brackets [] replaced by
739.27 - * your own identifying information:
739.28 - * "Portions Copyrighted [year] [name of copyright owner]"
739.29 - *
739.30 - * Contributor(s):
739.31 - *
739.32 - * The Original Software is NetBeans. The Initial Developer of the Original
739.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
739.34 - * Microsystems, Inc. All Rights Reserved.
739.35 - *
739.36 - * If you wish your version of this file to be governed by only the CDDL
739.37 - * or only the GPL Version 2, indicate your decision by adding
739.38 - * "[Contributor] elects to include this software in this distribution
739.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
739.40 - * single choice of license, a recipient has the option to distribute
739.41 - * your version of this file under either the CDDL, the GPL Version 2 or
739.42 - * to extend the choice of license to its licensees as provided above.
739.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
739.44 - * Version 2 license, then the option applies only if the new code is
739.45 - * made subject to such option by the copyright holder.
739.46 - */
739.47 -package org.netbeans.modules.python.testrunner.ui;
739.48 -
739.49 -import java.io.File;
739.50 -import java.util.logging.Logger;
739.51 -import java.util.regex.Matcher;
739.52 -import java.util.regex.Pattern;
739.53 -import javax.swing.text.BadLocationException;
739.54 -import org.netbeans.api.extexecution.print.LineConvertors.FileLocator;
739.55 -import org.netbeans.editor.BaseDocument;
739.56 -import org.netbeans.modules.gsf.spi.GsfUtilities;
739.57 -import org.netbeans.modules.gsf.testrunner.api.Report;
739.58 -import org.netbeans.modules.gsf.testrunner.ui.api.TestsuiteNode;
739.59 -import org.netbeans.modules.python.api.FileLocation;
739.60 -import org.openide.filesystems.FileObject;
739.61 -import org.openide.filesystems.FileUtil;
739.62 -import org.openide.nodes.Node;
739.63 -import org.openide.util.Exceptions;
739.64 -
739.65 -/**
739.66 - *
739.67 - * @author Marian Petras, Erno Mononen
739.68 - */
739.69 -final class OutputUtils {
739.70 -
739.71 - private static final Logger LOGGER = Logger.getLogger(OutputUtils.class.getName());
739.72 -
739.73 - private OutputUtils() {
739.74 - }
739.75 -
739.76 - /**
739.77 - */
739.78 - static void openCallstackFrame(Node node, String frameInfo, int line) {
739.79 - Report report = getTestsuiteNode(node).getReport();
739.80 -
739.81 - FileLocation location = null;
739.82 - // The stacktrace format is defined in nb_test_runner.py
739.83 - Pattern STACK_FRAME = Pattern.compile("\\S+ in (\\S+):(\\d+)"); // NOI18N
739.84 - Matcher matcher = STACK_FRAME.matcher(frameInfo);
739.85 - if (matcher.matches()) {
739.86 - String file = matcher.group(1);
739.87 - String lineStr = matcher.group(2);
739.88 - int lineNo = Integer.parseInt(lineStr);
739.89 - location = new FileLocation(file, lineNo);
739.90 - }
739.91 -
739.92 - if (location == null) {
739.93 - location = FileLocation.getLocation(frameInfo);
739.94 - }
739.95 -
739.96 - if (location != null) {
739.97 - FileObject fo = findFile(location.file, report.getFileLocator());
739.98 - if (fo != null) {
739.99 - if (line == -1) {
739.100 - line = location.line;
739.101 - }
739.102 -
739.103 - BaseDocument doc = GsfUtilities.getDocument(fo, true);
739.104 - if (doc != null) {
739.105 - int offset = org.netbeans.editor.Utilities.getRowStartFromLineOffset(doc, line-1);
739.106 - if (offset == -1) {
739.107 - // Invalid line number - just go to the end of the file
739.108 - offset = doc.getLength();
739.109 - }
739.110 - GsfUtilities.open(fo, offset, null);
739.111 - }
739.112 -
739.113 - return;
739.114 - }
739.115 - }
739.116 -
739.117 - LOGGER.info("Could not open a file for " + frameInfo) ;
739.118 - }
739.119 -
739.120 - static TestsuiteNode getTestsuiteNode(Node node) {
739.121 - while (!(node instanceof TestsuiteNode)) {
739.122 - node = node.getParentNode();
739.123 - }
739.124 - return (TestsuiteNode) node;
739.125 - }
739.126 -
739.127 - // TODO: copied from OutputUtils, should introduce this as a utility method
739.128 - // in python.platform
739.129 - static FileObject findFile(final String path, FileLocator fileLocator) {
739.130 - if (fileLocator != null) {
739.131 - FileObject fo = fileLocator.find(path);
739.132 - if (fo != null) {
739.133 - return fo;
739.134 - }
739.135 - }
739.136 -
739.137 - // Perhaps it's an absolute path of some sort... try to resolve those
739.138 - // Absolute path? Happens for stack traces in Jython libraries and such
739.139 - File file = new File(path);
739.140 - if (file.isFile()) {
739.141 - return FileUtil.toFileObject(FileUtil.normalizeFile(file));
739.142 - } else {
739.143 - LOGGER.warning("Cannot resolve file for \"" + path + "\" path.");
739.144 - return null;
739.145 - }
739.146 - }
739.147 -
739.148 -}
740.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/PyUnitHandlerFactory.java Sun Jan 04 13:11:53 2015 -0600
740.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
740.3 @@ -1,380 +0,0 @@
740.4 -/*
740.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
740.6 - *
740.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
740.8 - *
740.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
740.10 - * Other names may be trademarks of their respective owners.
740.11 - *
740.12 - * The contents of this file are subject to the terms of either the GNU
740.13 - * General Public License Version 2 only ("GPL") or the Common
740.14 - * Development and Distribution License("CDDL") (collectively, the
740.15 - * "License"). You may not use this file except in compliance with the
740.16 - * License. You can obtain a copy of the License at
740.17 - * http://www.netbeans.org/cddl-gplv2.html
740.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
740.19 - * specific language governing permissions and limitations under the
740.20 - * License. When distributing the software, include this License Header
740.21 - * Notice in each file and include the License file at
740.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
740.23 - * particular file as subject to the "Classpath" exception as provided
740.24 - * by Oracle in the GPL Version 2 section of the License file that
740.25 - * accompanied this code. If applicable, add the following below the
740.26 - * License Header, with the fields enclosed by brackets [] replaced by
740.27 - * your own identifying information:
740.28 - * "Portions Copyrighted [year] [name of copyright owner]"
740.29 - *
740.30 - * If you wish your version of this file to be governed by only the CDDL
740.31 - * or only the GPL Version 2, indicate your decision by adding
740.32 - * "[Contributor] elects to include this software in this distribution
740.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
740.34 - * single choice of license, a recipient has the option to distribute
740.35 - * your version of this file under either the CDDL, the GPL Version 2 or
740.36 - * to extend the choice of license to its licensees as provided above.
740.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
740.38 - * Version 2 license, then the option applies only if the new code is
740.39 - * made subject to such option by the copyright holder.
740.40 - *
740.41 - * Contributor(s):
740.42 - *
740.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
740.44 - */
740.45 -package org.netbeans.modules.python.testrunner.ui;
740.46 -
740.47 -import java.util.ArrayList;
740.48 -import java.util.Arrays;
740.49 -import java.util.Collections;
740.50 -import java.util.List;
740.51 -import java.util.logging.Level;
740.52 -import java.util.logging.Logger;
740.53 -import java.util.regex.Matcher;
740.54 -import java.util.regex.Pattern;
740.55 -import org.netbeans.modules.gsf.testrunner.ui.api.Manager;
740.56 -import org.netbeans.modules.gsf.testrunner.api.TestSession;
740.57 -import org.netbeans.modules.gsf.testrunner.api.TestSuite;
740.58 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
740.59 -import org.netbeans.modules.gsf.testrunner.api.Trouble;
740.60 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
740.61 -import org.netbeans.modules.python.project.spi.TestRunner.TestType;
740.62 -import org.netbeans.modules.python.testrunner.PyUnitRunner;
740.63 -import org.openide.util.NbBundle;
740.64 -
740.65 -/**
740.66 - * An output recognizer for parsing output of the PyUnit test runner
740.67 - * script, <code>nb_test_runner.py</code>. Updates the test result UI.
740.68 - *
740.69 - * Closely based on the TestUnitHandlerFactory for Ruby by Erno.
740.70 - *
740.71 - * @author Erno Mononen
740.72 - * @author Tor Norbye
740.73 - */
740.74 -public class PyUnitHandlerFactory implements TestHandlerFactory {
740.75 -
740.76 - private static final Logger LOGGER = Logger.getLogger(PyUnitHandlerFactory.class.getName());
740.77 -
740.78 - public boolean printSummary() {
740.79 - return true;
740.80 - }
740.81 -
740.82 - public List<TestRecognizerHandler> createHandlers() {
740.83 - List<TestRecognizerHandler> result = new ArrayList<TestRecognizerHandler>();
740.84 - result.add(new SuiteStartingHandler());
740.85 - result.add(new SuiteStartedHandler());
740.86 - result.add(new SuiteFinishedHandler());
740.87 - result.add(new SuiteErrorOutputHandler());
740.88 - result.add(new TestStartedHandler());
740.89 - result.add(new TestFailedHandler());
740.90 - result.add(new TestErrorHandler());
740.91 - result.add(new TestFinishedHandler());
740.92 - result.add(new TestLoggerHandler());
740.93 - result.add(new TestMiscHandler());
740.94 - result.add(new SuiteMiscHandler());
740.95 - return result;
740.96 - }
740.97 -
740.98 - private static String errorMsg(long failureCount) {
740.99 - return NbBundle.getMessage(PyUnitHandlerFactory.class, "MSG_Error", failureCount);
740.100 - }
740.101 -
740.102 - private static String failureMsg(long failureCount) {
740.103 - return NbBundle.getMessage(PyUnitHandlerFactory.class, "MSG_Failure", failureCount);
740.104 - }
740.105 -
740.106 - static String[] getStackTrace(String message, String stackTrace) {
740.107 - List<String> stackTraceList = new ArrayList<String>();
740.108 - stackTraceList.add(message);
740.109 - for (String location : stackTrace.split("%BR%")) { //NOI18N
740.110 - if (/*!location.contains(PyUnitRunner.MEDIATOR_SCRIPT_NAME) &&*/ !location.contains(PyUnitRunner.RUNNER_SCRIPT_NAME)) { //NOI18N
740.111 - stackTraceList.add(location);
740.112 - }
740.113 - }
740.114 - return stackTraceList.toArray(new String[stackTraceList.size()]);
740.115 - }
740.116 -
740.117 - // Doctest message defined in nb_test_runner.py, the other one is from unittest
740.118 - private static final Pattern STRING_COMPARISON = Pattern.compile("(Expected (.+) but got (.+))|((.+) != (.+))", Pattern.DOTALL); // NOI18N
740.119 -
740.120 - // Package private for tests
740.121 - static Trouble.ComparisonFailure getComparisonFailure(String msg) {
740.122 - Matcher comparisonMatcher = STRING_COMPARISON.matcher(msg);
740.123 - if (!comparisonMatcher.matches()) {
740.124 - return null;
740.125 - }
740.126 - String expected;
740.127 - String actual;
740.128 -
740.129 - boolean isDocTest = false;
740.130 - expected = comparisonMatcher.group(2);
740.131 - if (expected == null) {
740.132 - expected = comparisonMatcher.group(5);
740.133 - actual = comparisonMatcher.group(6);
740.134 - } else {
740.135 - isDocTest = true;
740.136 - actual = comparisonMatcher.group(3);
740.137 - }
740.138 -
740.139 - // Convert back to multiline strings, if applicable
740.140 - expected = expected.replace("\\n", "\n"); // NOI18N
740.141 - actual = actual.replace("\\n", "\n"); // NOI18N
740.142 -
740.143 - if (isDocTest) {
740.144 - // We know the doc test output is in python console format which generally
740.145 - // can be highlighted by the python lexer (for string literals, etc.)
740.146 - return new Trouble.ComparisonFailure(expected, actual, PythonTokenId.PYTHON_MIME_TYPE);
740.147 - } else {
740.148 - return new Trouble.ComparisonFailure(expected, actual);
740.149 - }
740.150 - }
740.151 -
740.152 -
740.153 - static class TestFailedHandler extends TestRecognizerHandler {
740.154 - private List<String> output;
740.155 -
740.156 - public TestFailedHandler(String regex) {
740.157 - super(regex);
740.158 - }
740.159 -
740.160 - public TestFailedHandler() {
740.161 - super("%TEST_FAILED%\\stime=(.+)\\stestname=(.+) \\((.+)\\)\\smessage=(.*)\\slocation=(.*)"); //NOI18N
740.162 - }
740.163 -
740.164 - @Override
740.165 - void updateUI( Manager manager, TestSession session) {
740.166 - Testcase testcase = new Testcase(matcher.group(2), TestType.PY_UNIT.name(), session);
740.167 - testcase.setTimeMillis(toMillis(matcher.group(1)));
740.168 - testcase.setClassName(matcher.group(3));
740.169 - testcase.setTrouble(new Trouble(false));
740.170 - String message = matcher.group(4).replace("%BR%", "\n");
740.171 - String location = matcher.group(5);
740.172 - testcase.getTrouble().setStackTrace(getStackTrace(message, location));
740.173 - testcase.getTrouble().setComparisonFailure(getComparisonFailure(message));
740.174 -
740.175 - session.addTestCase(testcase);
740.176 -
740.177 - String failureMsg = failureMsg(session.incrementFailuresCount());
740.178 - String testCase = testcase.getName() + "(" + testcase.getClassName() + "):";
740.179 - output = new ArrayList<String>();
740.180 - output.add("");
740.181 - output.add(failureMsg);
740.182 - output.add(testCase);
740.183 - output.addAll(Arrays.asList(testcase.getTrouble().getStackTrace()));
740.184 - output.add("");
740.185 -
740.186 - manager.displayOutput(session, "", false);
740.187 - manager.displayOutput(session, failureMsg, false);
740.188 - manager.displayOutput(session, testCase, false); //NOI18N
740.189 - for (String line : testcase.getTrouble().getStackTrace()) {
740.190 - manager.displayOutput(session, line, false);
740.191 - }
740.192 - manager.displayOutput(session, "", false);
740.193 - testcase.addOutputLines(output);
740.194 - }
740.195 -
740.196 - @Override
740.197 - List<String> getRecognizedOutput() {
740.198 - return new ArrayList<String>(output);
740.199 - }
740.200 - }
740.201 -
740.202 - static class TestErrorHandler extends TestRecognizerHandler {
740.203 -
740.204 - private List<String> output;
740.205 -
740.206 - public TestErrorHandler() {
740.207 - super("%TEST_ERROR%\\stime=(.+)\\stestname=(.+) \\((.+)\\)\\smessage=(.*)\\slocation=(.*)"); //NOI18N
740.208 - }
740.209 -
740.210 - @Override
740.211 - void updateUI( Manager manager, TestSession session) {
740.212 - Testcase testcase = new Testcase(matcher.group(2), TestType.PY_UNIT.name(), session);
740.213 - testcase.setTimeMillis(toMillis(matcher.group(1)));
740.214 - testcase.setClassName(matcher.group(3));
740.215 - testcase.setTrouble(new Trouble(true));
740.216 - testcase.getTrouble().setStackTrace(getStackTrace(matcher.group(4).replace("%BR%", "\n"), matcher.group(5)));
740.217 - session.addTestCase(testcase);
740.218 -
740.219 - String errorMsg = errorMsg(session.incrementFailuresCount());
740.220 - String testCase = testcase.getName() + "(" + testcase.getClassName() + "):";
740.221 - output = new ArrayList<String>();
740.222 - output.add("");
740.223 - output.add(errorMsg);
740.224 - output.add(testCase);
740.225 - output.addAll(Arrays.asList(testcase.getTrouble().getStackTrace()));
740.226 - output.add("");
740.227 -
740.228 - manager.displayOutput(session, "", false);
740.229 - manager.displayOutput(session, errorMsg, false);
740.230 - manager.displayOutput(session, testCase, false); //NOI18N
740.231 - for (String line : testcase.getTrouble().getStackTrace()) {
740.232 - manager.displayOutput(session, line, true);
740.233 - }
740.234 - manager.displayOutput(session, "", false);
740.235 - testcase.addOutputLines(output);
740.236 - }
740.237 -
740.238 - @Override
740.239 - List<String> getRecognizedOutput() {
740.240 - return new ArrayList<String>(output);
740.241 - }
740.242 - }
740.243 -
740.244 - static class TestStartedHandler extends TestRecognizerHandler {
740.245 -
740.246 - public TestStartedHandler() {
740.247 - super("%TEST_STARTED%\\s*(.+) \\((.+)\\)"); //NOI18N
740.248 - }
740.249 -
740.250 - @Override
740.251 - void updateUI( Manager manager, TestSession session) {
740.252 - }
740.253 - }
740.254 -
740.255 - static class TestFinishedHandler extends TestRecognizerHandler {
740.256 -
740.257 - public TestFinishedHandler(String regex) {
740.258 - super(regex);
740.259 - }
740.260 -
740.261 - public TestFinishedHandler() {
740.262 - super("%TEST_FINISHED%\\stime=(.+)\\s+(.+) \\((.+)\\)"); //NOI18N
740.263 - }
740.264 -
740.265 - @Override
740.266 - void updateUI( Manager manager, TestSession session) {
740.267 - Testcase testcase = new Testcase(matcher.group(2), TestType.PY_UNIT.name(), session);
740.268 - testcase.setTimeMillis(toMillis(matcher.group(1)));
740.269 - testcase.setClassName(matcher.group(3));
740.270 - session.addTestCase(testcase);
740.271 - }
740.272 - }
740.273 -
740.274 - /**
740.275 - * Captures the rest of %TEST_* patterns that are not handled
740.276 - * otherwise (yet).
740.277 - */
740.278 - static class TestMiscHandler extends TestRecognizerHandler {
740.279 -
740.280 - public TestMiscHandler() {
740.281 - super("%TEST_.*"); //NOI18N
740.282 - }
740.283 -
740.284 - @Override
740.285 - void updateUI( Manager manager, TestSession session) {
740.286 - }
740.287 - }
740.288 -
740.289 - static class SuiteFinishedHandler extends TestRecognizerHandler {
740.290 -
740.291 - public SuiteFinishedHandler() {
740.292 - super("%SUITE_FINISHED%\\s+time=(.+)"); //NOI18N
740.293 - }
740.294 -
740.295 - @Override
740.296 - void updateUI( Manager manager, TestSession session) {
740.297 - manager.displayReport(session, session.getReport(toMillis(matcher.group(1))));
740.298 - }
740.299 - }
740.300 -
740.301 - static class SuiteStartedHandler extends TestRecognizerHandler {
740.302 -
740.303 - public SuiteStartedHandler() {
740.304 - super("%SUITE_STARTED%\\s.*"); //NOI18N
740.305 - }
740.306 -
740.307 - @Override
740.308 - void updateUI( Manager manager, TestSession session) {
740.309 - }
740.310 - }
740.311 -
740.312 - static class SuiteErrorOutputHandler extends TestRecognizerHandler {
740.313 -
740.314 - public SuiteErrorOutputHandler() {
740.315 - super("%SUITE_ERROR_OUTPUT%\\serror=(.*)"); //NOI18N
740.316 - }
740.317 -
740.318 - @Override
740.319 - void updateUI( Manager manager, TestSession session) {
740.320 - manager.displayOutput(session, matcher.group(1), true);
740.321 - manager.displayOutput(session, "", false);
740.322 - }
740.323 -
740.324 - @Override
740.325 - List<String> getRecognizedOutput() {
740.326 - return Collections.<String>singletonList(matcher.group(1));
740.327 - }
740.328 -
740.329 - }
740.330 -
740.331 - static class SuiteStartingHandler extends TestRecognizerHandler {
740.332 -
740.333 - private boolean firstSuite = true;
740.334 -
740.335 - public SuiteStartingHandler() {
740.336 - super("%SUITE_STARTING%\\s+(.+)"); //NOI18N
740.337 - }
740.338 -
740.339 - @Override
740.340 - void updateUI( Manager manager, TestSession session) {
740.341 - if (firstSuite) {
740.342 - firstSuite = false;
740.343 - manager.testStarted(session);
740.344 - }
740.345 - String suiteName = matcher.group(1);
740.346 - session.addSuite(new TestSuite(suiteName));
740.347 - manager.displaySuiteRunning(session, suiteName);
740.348 - }
740.349 - }
740.350 -
740.351 - /**
740.352 - * Captures the rest of %SUITE_* patterns that are not handled
740.353 - * otherwise (yet).
740.354 - */
740.355 - static class SuiteMiscHandler extends TestRecognizerHandler {
740.356 -
740.357 - public SuiteMiscHandler() {
740.358 - super("%SUITE_.*"); //NOI18N
740.359 - }
740.360 -
740.361 - @Override
740.362 - void updateUI( Manager manager, TestSession session) {
740.363 - }
740.364 - }
740.365 -
740.366 - /**
740.367 - * Captures output meant for logging.
740.368 - */
740.369 - static class TestLoggerHandler extends TestRecognizerHandler {
740.370 -
740.371 - public TestLoggerHandler() {
740.372 - super("%TEST_LOGGER%\\slevel=(.+)\\smsg=(.*)"); //NOI18N
740.373 - }
740.374 -
740.375 - @Override
740.376 - void updateUI( Manager manager, TestSession session) {
740.377 - Level level = Level.parse(matcher.group(1));
740.378 - if (LOGGER.isLoggable(level))
740.379 - LOGGER.log(level, matcher.group(2));
740.380 - }
740.381 - }
740.382 -}
740.383 -
741.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/PythonCallstackFrameNode.java Sun Jan 04 13:11:53 2015 -0600
741.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
741.3 @@ -1,84 +0,0 @@
741.4 -/*
741.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
741.6 - *
741.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
741.8 - *
741.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
741.10 - * Other names may be trademarks of their respective owners.
741.11 - *
741.12 - * The contents of this file are subject to the terms of either the GNU
741.13 - * General Public License Version 2 only ("GPL") or the Common
741.14 - * Development and Distribution License("CDDL") (collectively, the
741.15 - * "License"). You may not use this file except in compliance with the
741.16 - * License. You can obtain a copy of the License at
741.17 - * http://www.netbeans.org/cddl-gplv2.html
741.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
741.19 - * specific language governing permissions and limitations under the
741.20 - * License. When distributing the software, include this License Header
741.21 - * Notice in each file and include the License file at
741.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
741.23 - * particular file as subject to the "Classpath" exception as provided
741.24 - * by Oracle in the GPL Version 2 section of the License file that
741.25 - * accompanied this code. If applicable, add the following below the
741.26 - * License Header, with the fields enclosed by brackets [] replaced by
741.27 - * your own identifying information:
741.28 - * "Portions Copyrighted [year] [name of copyright owner]"
741.29 - *
741.30 - * Contributor(s):
741.31 - *
741.32 - * The Original Software is NetBeans. The Initial Developer of the Original
741.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
741.34 - * Microsystems, Inc. All Rights Reserved.
741.35 - *
741.36 - * If you wish your version of this file to be governed by only the CDDL
741.37 - * or only the GPL Version 2, indicate your decision by adding
741.38 - * "[Contributor] elects to include this software in this distribution
741.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
741.40 - * single choice of license, a recipient has the option to distribute
741.41 - * your version of this file under either the CDDL, the GPL Version 2 or
741.42 - * to extend the choice of license to its licensees as provided above.
741.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
741.44 - * Version 2 license, then the option applies only if the new code is
741.45 - * made subject to such option by the copyright holder.
741.46 - */
741.47 -
741.48 -package org.netbeans.modules.python.testrunner.ui;
741.49 -import javax.swing.Action;
741.50 -import org.netbeans.modules.gsf.testrunner.ui.api.CallstackFrameNode;
741.51 -import org.netbeans.modules.gsf.testrunner.ui.api.DiffViewAction;
741.52 -import org.netbeans.modules.gsf.testrunner.api.Trouble.ComparisonFailure;
741.53 -import org.openide.util.actions.SystemAction;
741.54 -
741.55 -/**
741.56 - *
741.57 - * @author Marian Petras
741.58 - */
741.59 -public final class PythonCallstackFrameNode extends CallstackFrameNode {
741.60 - private final String displayName;
741.61 -
741.62 - public PythonCallstackFrameNode(String frameInfo, String displayName) {
741.63 - super(frameInfo, displayName);
741.64 - // Keep our own copy since the parent will assign frameInfo to displayName
741.65 - // if none is provided
741.66 - this.displayName = displayName;
741.67 - }
741.68 -
741.69 - /**
741.70 - */
741.71 - @Override
741.72 - public Action getPreferredAction() {
741.73 - // If it's a diff failure line, the default action is to diff it!
741.74 - if (displayName != null) {
741.75 - ComparisonFailure failure = PyUnitHandlerFactory.getComparisonFailure(displayName);
741.76 - if (failure != null) {
741.77 - return new DiffViewAction(failure);
741.78 - }
741.79 - }
741.80 -
741.81 - return new JumpToCallStackAction(this, frameInfo);
741.82 - }
741.83 -
741.84 - public SystemAction[] getActions(boolean context) {
741.85 - return new SystemAction[0];
741.86 - }
741.87 -}
742.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/PythonTestMethodNode.java Sun Jan 04 13:11:53 2015 -0600
742.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
742.3 @@ -1,160 +0,0 @@
742.4 -/*
742.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
742.6 - *
742.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
742.8 - *
742.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
742.10 - * Other names may be trademarks of their respective owners.
742.11 - *
742.12 - * The contents of this file are subject to the terms of either the GNU
742.13 - * General Public License Version 2 only ("GPL") or the Common
742.14 - * Development and Distribution License("CDDL") (collectively, the
742.15 - * "License"). You may not use this file except in compliance with the
742.16 - * License. You can obtain a copy of the License at
742.17 - * http://www.netbeans.org/cddl-gplv2.html
742.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
742.19 - * specific language governing permissions and limitations under the
742.20 - * License. When distributing the software, include this License Header
742.21 - * Notice in each file and include the License file at
742.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
742.23 - * particular file as subject to the "Classpath" exception as provided
742.24 - * by Oracle in the GPL Version 2 section of the License file that
742.25 - * accompanied this code. If applicable, add the following below the
742.26 - * License Header, with the fields enclosed by brackets [] replaced by
742.27 - * your own identifying information:
742.28 - * "Portions Copyrighted [year] [name of copyright owner]"
742.29 - *
742.30 - * Contributor(s):
742.31 - *
742.32 - * The Original Software is NetBeans. The Initial Developer of the Original
742.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
742.34 - * Microsystems, Inc. All Rights Reserved.
742.35 - *
742.36 - * If you wish your version of this file to be governed by only the CDDL
742.37 - * or only the GPL Version 2, indicate your decision by adding
742.38 - * "[Contributor] elects to include this software in this distribution
742.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
742.40 - * single choice of license, a recipient has the option to distribute
742.41 - * your version of this file under either the CDDL, the GPL Version 2 or
742.42 - * to extend the choice of license to its licensees as provided above.
742.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
742.44 - * Version 2 license, then the option applies only if the new code is
742.45 - * made subject to such option by the copyright holder.
742.46 - */
742.47 -
742.48 -package org.netbeans.modules.python.testrunner.ui;
742.49 -
742.50 -import java.util.ArrayList;
742.51 -import java.util.List;
742.52 -import javax.swing.Action;
742.53 -import org.netbeans.api.project.Project;
742.54 -import org.netbeans.modules.gsf.testrunner.ui.api.DiffViewAction;
742.55 -import org.netbeans.modules.gsf.testrunner.ui.api.Locator;
742.56 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
742.57 -import org.netbeans.modules.gsf.testrunner.ui.api.TestMethodNode;
742.58 -import org.openide.nodes.Node;
742.59 -import org.openide.util.NbBundle;
742.60 -import org.openide.util.lookup.Lookups;
742.61 -
742.62 -/**
742.63 - *
742.64 - * @author Marian Petras, Erno Mononen
742.65 - */
742.66 -public final class PythonTestMethodNode extends TestMethodNode {
742.67 -
742.68 - public PythonTestMethodNode(Testcase testcase, Project project) {
742.69 - super(testcase, project, Lookups.singleton(new Locator() {
742.70 -
742.71 - public void jumpToSource(Node node) {
742.72 - node.getPreferredAction().actionPerformed(null);
742.73 - }
742.74 - }));
742.75 - }
742.76 -
742.77 - /**
742.78 - */
742.79 - @Override
742.80 - public Action getPreferredAction() {
742.81 - // the location to jump from the node
742.82 - String testLocation = getTestLocation(testcase, getProject());
742.83 - String stackTrace = getTestCaseLineFromStackTrace(testcase);
742.84 - String jumpToLocation = stackTrace != null
742.85 - ? stackTrace
742.86 - : testLocation;
742.87 -
742.88 - return jumpToLocation == null
742.89 - ? new JumpToTestAction(testcase, getProject(), NbBundle.getMessage(PythonTestMethodNode.class, "LBL_GoToSource"), false)
742.90 - : new JumpToCallStackAction(this, jumpToLocation);
742.91 - }
742.92 -
742.93 - static String getTestLocation(Testcase testcase, Project project) {
742.94 - if (testcase.getLocation() == null) {
742.95 - return null;
742.96 - }
742.97 -// PythonPlatform platform = PythonPlatform.platformFor(project);
742.98 -// if (platform != null && platform.isJython()) {
742.99 -// // XXX: return no location for Jython -- ExampleMethods#implementation_backtrace
742.100 -// // behaves differently for MRI and Jython, on Jython the test file itself is not present
742.101 -// return null;
742.102 -// }
742.103 - return testcase.getLocation();
742.104 - }
742.105 -
742.106 - /**
742.107 - * Gets the line from the stack trace representing the last line in the test class.
742.108 - * If that can't be resolved
742.109 - * then returns the second line of the stack trace (the
742.110 - * first line represents the error message) or <code>null</code> if there
742.111 - * was no (usable) stack trace attached.
742.112 - *
742.113 - * @return
742.114 - */
742.115 - private static String getTestCaseLineFromStackTrace(Testcase testcase) {
742.116 - if (testcase.getTrouble() == null) {
742.117 - return null;
742.118 - }
742.119 - String[] stacktrace = testcase.getTrouble().getStackTrace();
742.120 - if (stacktrace == null || stacktrace.length <= 1) {
742.121 - return null;
742.122 - }
742.123 -
742.124 - // Skip unittest.py stuff
742.125 - int j = 1;
742.126 - for (; j < stacktrace.length; j++) {
742.127 - if (!stacktrace[j].contains("unittest.py")) {
742.128 - break;
742.129 - }
742.130 - }
742.131 -
742.132 - // Rails specific - maybe this doesn't apply to Python/Django?
742.133 -// if (stacktrace.length > 2) {
742.134 -// String underscoreName = PythonUtils.camelToUnderlinedName(testcase.getClassName());
742.135 -// for (int i = 0; i < stacktrace.length; i++) {
742.136 -// if (stacktrace[i].contains(underscoreName) && stacktrace[i].contains(testcase.getName())) {
742.137 -// return stacktrace[i];
742.138 -// }
742.139 -// }
742.140 -// }
742.141 -
742.142 - if (j == stacktrace.length) {
742.143 - j = stacktrace.length-1;
742.144 - }
742.145 -
742.146 - return stacktrace[j];
742.147 - }
742.148 -
742.149 -
742.150 - @Override
742.151 - public Action[] getActions(boolean context) {
742.152 - if (context) {
742.153 - return new Action[0];
742.154 - }
742.155 - List<Action> actions = new ArrayList<Action>();
742.156 - actions.add(getPreferredAction());
742.157 - actions.add(new DiffViewAction(testcase));
742.158 - actions.add(new RunTestMethodAction(testcase, getProject(), NbBundle.getMessage(PythonTestMethodNode.class, "LBL_RerunTest"), false));
742.159 - actions.add(new RunTestMethodAction(testcase, getProject(), NbBundle.getMessage(PythonTestMethodNode.class, "LBL_DebugTest"), true));
742.160 -// actions.add(new DisplayOutputForNodeAction(testcase.getOutput(), testcase.getSession()));
742.161 - return actions.toArray(new Action[actions.size()]);
742.162 - }
742.163 -}
743.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/PythonTestsuiteNode.java Sun Jan 04 13:11:53 2015 -0600
743.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
743.3 @@ -1,116 +0,0 @@
743.4 -/*
743.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
743.6 - *
743.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
743.8 - *
743.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
743.10 - * Other names may be trademarks of their respective owners.
743.11 - *
743.12 - * The contents of this file are subject to the terms of either the GNU
743.13 - * General Public License Version 2 only ("GPL") or the Common
743.14 - * Development and Distribution License("CDDL") (collectively, the
743.15 - * "License"). You may not use this file except in compliance with the
743.16 - * License. You can obtain a copy of the License at
743.17 - * http://www.netbeans.org/cddl-gplv2.html
743.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
743.19 - * specific language governing permissions and limitations under the
743.20 - * License. When distributing the software, include this License Header
743.21 - * Notice in each file and include the License file at
743.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
743.23 - * particular file as subject to the "Classpath" exception as provided
743.24 - * by Oracle in the GPL Version 2 section of the License file that
743.25 - * accompanied this code. If applicable, add the following below the
743.26 - * License Header, with the fields enclosed by brackets [] replaced by
743.27 - * your own identifying information:
743.28 - * "Portions Copyrighted [year] [name of copyright owner]"
743.29 - *
743.30 - * Contributor(s):
743.31 - *
743.32 - * The Original Software is NetBeans. The Initial Developer of the Original
743.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
743.34 - * Microsystems, Inc. All Rights Reserved.
743.35 - *
743.36 - * If you wish your version of this file to be governed by only the CDDL
743.37 - * or only the GPL Version 2, indicate your decision by adding
743.38 - * "[Contributor] elects to include this software in this distribution
743.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
743.40 - * single choice of license, a recipient has the option to distribute
743.41 - * your version of this file under either the CDDL, the GPL Version 2 or
743.42 - * to extend the choice of license to its licensees as provided above.
743.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
743.44 - * Version 2 license, then the option applies only if the new code is
743.45 - * made subject to such option by the copyright holder.
743.46 - */
743.47 -
743.48 -package org.netbeans.modules.python.testrunner.ui;
743.49 -
743.50 -import java.util.ArrayList;
743.51 -import java.util.List;
743.52 -import javax.swing.Action;
743.53 -import org.netbeans.modules.gsf.testrunner.ui.api.Locator;
743.54 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
743.55 -import org.netbeans.modules.gsf.testrunner.ui.api.TestsuiteNode;
743.56 -import org.netbeans.modules.python.project.spi.TestRunner.TestType;
743.57 -import org.openide.nodes.Node;
743.58 -import org.openide.util.NbBundle;
743.59 -import org.openide.util.lookup.Lookups;
743.60 -
743.61 -/**
743.62 - *
743.63 - * @author Marian Petras, Erno Mononen
743.64 - */
743.65 -public final class PythonTestsuiteNode extends TestsuiteNode {
743.66 -
743.67 - public PythonTestsuiteNode(String suiteName, boolean filtered) {
743.68 - super(null, suiteName, filtered, Lookups.singleton(new Locator() {
743.69 -
743.70 - public void jumpToSource(Node node) {
743.71 - Action jumpTo = node.getPreferredAction();
743.72 - if (jumpTo != null) {
743.73 - jumpTo.actionPerformed(null);
743.74 - }
743.75 - }
743.76 - }));
743.77 - }
743.78 -
743.79 - private Testcase getFirstTestCase() {
743.80 - return report.getTests().isEmpty() ? null : report.getTests().iterator().next();
743.81 - }
743.82 -
743.83 - @Override
743.84 - public Action getPreferredAction() {
743.85 - Testcase testcase = getFirstTestCase();
743.86 - if (testcase == null) {
743.87 - // need to have at least one test case to locate the test file
743.88 - return null;
743.89 - }
743.90 - TestType type = TestType.valueOf(testcase.getType());
743.91 - //if (TestType.RSPEC == type) {
743.92 - // //XXX: not the exact location of the class
743.93 - // return new JumpToCallStackAction(this, PythonTestMethodNode.getTestLocation(testcase, report.getProject()), 1);
743.94 - //}
743.95 - return new JumpToTestAction(getFirstTestCase(), report.getProject(), NbBundle.getMessage(PythonTestsuiteNode.class, "LBL_GoToSource"), true);
743.96 - }
743.97 -
743.98 - @Override
743.99 - public Action[] getActions(boolean context) {
743.100 - if (context) {
743.101 - return new Action[0];
743.102 - }
743.103 - List<Action> actions = new ArrayList<Action>(3);
743.104 - Action preferred = getPreferredAction();
743.105 - if (preferred != null) {
743.106 - actions.add(preferred);
743.107 - }
743.108 - Testcase testcase = getFirstTestCase();
743.109 - // these actions are enable only if the suite had at least one test (otherwise
743.110 - // we can't reliably locate the test file)
743.111 - if (testcase != null) {
743.112 - actions.add(new RunTestSuiteAction(testcase, report.getProject(), NbBundle.getMessage(PythonTestMethodNode.class, "LBL_RerunTest"), false));
743.113 - actions.add(new RunTestSuiteAction(testcase, report.getProject(), NbBundle.getMessage(PythonTestMethodNode.class, "LBL_DebugTest"), true));
743.114 -// actions.add(new DisplayOutputForNodeAction(getOutput(), testcase.getSession()));
743.115 - }
743.116 - return actions.toArray(new Action[actions.size()]);
743.117 - }
743.118 -
743.119 -}
744.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/RunTestMethodAction.java Sun Jan 04 13:11:53 2015 -0600
744.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
744.3 @@ -1,78 +0,0 @@
744.4 -/*
744.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
744.6 - *
744.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
744.8 - *
744.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
744.10 - * Other names may be trademarks of their respective owners.
744.11 - *
744.12 - * The contents of this file are subject to the terms of either the GNU
744.13 - * General Public License Version 2 only ("GPL") or the Common
744.14 - * Development and Distribution License("CDDL") (collectively, the
744.15 - * "License"). You may not use this file except in compliance with the
744.16 - * License. You can obtain a copy of the License at
744.17 - * http://www.netbeans.org/cddl-gplv2.html
744.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
744.19 - * specific language governing permissions and limitations under the
744.20 - * License. When distributing the software, include this License Header
744.21 - * Notice in each file and include the License file at
744.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
744.23 - * particular file as subject to the "Classpath" exception as provided
744.24 - * by Oracle in the GPL Version 2 section of the License file that
744.25 - * accompanied this code. If applicable, add the following below the
744.26 - * License Header, with the fields enclosed by brackets [] replaced by
744.27 - * your own identifying information:
744.28 - * "Portions Copyrighted [year] [name of copyright owner]"
744.29 - *
744.30 - * If you wish your version of this file to be governed by only the CDDL
744.31 - * or only the GPL Version 2, indicate your decision by adding
744.32 - * "[Contributor] elects to include this software in this distribution
744.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
744.34 - * single choice of license, a recipient has the option to distribute
744.35 - * your version of this file under either the CDDL, the GPL Version 2 or
744.36 - * to extend the choice of license to its licensees as provided above.
744.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
744.38 - * Version 2 license, then the option applies only if the new code is
744.39 - * made subject to such option by the copyright holder.
744.40 - *
744.41 - * Contributor(s):
744.42 - *
744.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
744.44 - */
744.45 -package org.netbeans.modules.python.testrunner.ui;
744.46 -
744.47 -import java.awt.event.ActionEvent;
744.48 -import java.util.logging.Logger;
744.49 -import org.netbeans.api.project.Project;
744.50 -import org.netbeans.modules.gsf.api.DeclarationFinder.DeclarationLocation;
744.51 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
744.52 -import org.netbeans.modules.python.editor.PythonDeclarationFinder;
744.53 -import org.netbeans.modules.python.project.spi.TestRunner;
744.54 -
744.55 -/**
744.56 - * An action for running/debugging a singe test method.
744.57 - *
744.58 - * @author Erno Mononen
744.59 - */
744.60 -class RunTestMethodAction extends BaseTestMethodNodeAction {
744.61 -
744.62 - private static final Logger LOGGER = Logger.getLogger(RunTestMethodAction.class.getName());
744.63 - private final boolean debug;
744.64 -
744.65 - public RunTestMethodAction(Testcase testcase, Project project, String name, boolean debug) {
744.66 - super(testcase, project, name);
744.67 - this.debug = debug;
744.68 - }
744.69 -
744.70 - protected void doActionPerformed(ActionEvent e) {
744.71 - TestRunner.TestType type = TestRunner.TestType.valueOf(testcase.getType());
744.72 - //if (TestRunner.TestType.RSPEC == type) {
744.73 - // runRspec();
744.74 - // return;
744.75 - //}
744.76 - DeclarationLocation location = PythonDeclarationFinder.getTestDeclaration(getTestSourceRoot(), getTestMethod(), false);
744.77 - if (!(DeclarationLocation.NONE == location)) {
744.78 - getTestRunner(type).runSingleTest(location.getFileObject(),testcase.getClassName(), testcase.getName(), debug);
744.79 - }
744.80 - }
744.81 -}
745.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/RunTestSuiteAction.java Sun Jan 04 13:11:53 2015 -0600
745.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
745.3 @@ -1,77 +0,0 @@
745.4 -/*
745.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
745.6 - *
745.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
745.8 - *
745.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
745.10 - * Other names may be trademarks of their respective owners.
745.11 - *
745.12 - * The contents of this file are subject to the terms of either the GNU
745.13 - * General Public License Version 2 only ("GPL") or the Common
745.14 - * Development and Distribution License("CDDL") (collectively, the
745.15 - * "License"). You may not use this file except in compliance with the
745.16 - * License. You can obtain a copy of the License at
745.17 - * http://www.netbeans.org/cddl-gplv2.html
745.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
745.19 - * specific language governing permissions and limitations under the
745.20 - * License. When distributing the software, include this License Header
745.21 - * Notice in each file and include the License file at
745.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
745.23 - * particular file as subject to the "Classpath" exception as provided
745.24 - * by Oracle in the GPL Version 2 section of the License file that
745.25 - * accompanied this code. If applicable, add the following below the
745.26 - * License Header, with the fields enclosed by brackets [] replaced by
745.27 - * your own identifying information:
745.28 - * "Portions Copyrighted [year] [name of copyright owner]"
745.29 - *
745.30 - * If you wish your version of this file to be governed by only the CDDL
745.31 - * or only the GPL Version 2, indicate your decision by adding
745.32 - * "[Contributor] elects to include this software in this distribution
745.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
745.34 - * single choice of license, a recipient has the option to distribute
745.35 - * your version of this file under either the CDDL, the GPL Version 2 or
745.36 - * to extend the choice of license to its licensees as provided above.
745.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
745.38 - * Version 2 license, then the option applies only if the new code is
745.39 - * made subject to such option by the copyright holder.
745.40 - *
745.41 - * Contributor(s):
745.42 - *
745.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
745.44 - */
745.45 -package org.netbeans.modules.python.testrunner.ui;
745.46 -
745.47 -import java.awt.event.ActionEvent;
745.48 -import org.netbeans.api.project.Project;
745.49 -import org.netbeans.modules.gsf.api.DeclarationFinder.DeclarationLocation;
745.50 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
745.51 -import org.netbeans.modules.python.editor.PythonDeclarationFinder;
745.52 -import org.netbeans.modules.python.project.spi.TestRunner;
745.53 -
745.54 -/**
745.55 - * Action for running all tests in a file.
745.56 - *
745.57 - * @author Erno Mononen
745.58 - */
745.59 -final class RunTestSuiteAction extends BaseTestMethodNodeAction {
745.60 -
745.61 - private final boolean debug;
745.62 -
745.63 - public RunTestSuiteAction(Testcase testcase, Project project, String name, boolean debug) {
745.64 - super(testcase, project, name);
745.65 - this.debug = debug;
745.66 - }
745.67 -
745.68 - protected void doActionPerformed(ActionEvent e) {
745.69 - TestRunner.TestType type = TestRunner.TestType.valueOf(testcase.getType());
745.70 - //if (TestRunner.TestType.RSPEC == type) {
745.71 - // runRspec();
745.72 - // return;
745.73 - //}
745.74 - DeclarationLocation location = PythonDeclarationFinder.getTestDeclaration(getTestSourceRoot(), getTestMethod(), true);
745.75 - if (!(DeclarationLocation.NONE == location)) {
745.76 - getTestRunner(type).runTest(location.getFileObject(), debug);
745.77 - }
745.78 -
745.79 - }
745.80 -}
746.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/TestHandlerFactory.java Sun Jan 04 13:11:53 2015 -0600
746.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
746.3 @@ -1,57 +0,0 @@
746.4 -/*
746.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
746.6 - *
746.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
746.8 - *
746.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
746.10 - * Other names may be trademarks of their respective owners.
746.11 - *
746.12 - * The contents of this file are subject to the terms of either the GNU
746.13 - * General Public License Version 2 only ("GPL") or the Common
746.14 - * Development and Distribution License("CDDL") (collectively, the
746.15 - * "License"). You may not use this file except in compliance with the
746.16 - * License. You can obtain a copy of the License at
746.17 - * http://www.netbeans.org/cddl-gplv2.html
746.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
746.19 - * specific language governing permissions and limitations under the
746.20 - * License. When distributing the software, include this License Header
746.21 - * Notice in each file and include the License file at
746.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
746.23 - * particular file as subject to the "Classpath" exception as provided
746.24 - * by Oracle in the GPL Version 2 section of the License file that
746.25 - * accompanied this code. If applicable, add the following below the
746.26 - * License Header, with the fields enclosed by brackets [] replaced by
746.27 - * your own identifying information:
746.28 - * "Portions Copyrighted [year] [name of copyright owner]"
746.29 - *
746.30 - * If you wish your version of this file to be governed by only the CDDL
746.31 - * or only the GPL Version 2, indicate your decision by adding
746.32 - * "[Contributor] elects to include this software in this distribution
746.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
746.34 - * single choice of license, a recipient has the option to distribute
746.35 - * your version of this file under either the CDDL, the GPL Version 2 or
746.36 - * to extend the choice of license to its licensees as provided above.
746.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
746.38 - * Version 2 license, then the option applies only if the new code is
746.39 - * made subject to such option by the copyright holder.
746.40 - *
746.41 - * Contributor(s):
746.42 - *
746.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
746.44 - */
746.45 -
746.46 -package org.netbeans.modules.python.testrunner.ui;
746.47 -
746.48 -import java.util.List;
746.49 -
746.50 -/**
746.51 - *
746.52 - * @author Erno Mononen
746.53 - */
746.54 -public interface TestHandlerFactory {
746.55 -
746.56 - List<TestRecognizerHandler> createHandlers();
746.57 -
746.58 - boolean printSummary();
746.59 -
746.60 -}
747.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/TestRecognizerHandler.java Sun Jan 04 13:11:53 2015 -0600
747.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
747.3 @@ -1,113 +0,0 @@
747.4 -/*
747.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
747.6 - *
747.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
747.8 - *
747.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
747.10 - * Other names may be trademarks of their respective owners.
747.11 - *
747.12 - * The contents of this file are subject to the terms of either the GNU
747.13 - * General Public License Version 2 only ("GPL") or the Common
747.14 - * Development and Distribution License("CDDL") (collectively, the
747.15 - * "License"). You may not use this file except in compliance with the
747.16 - * License. You can obtain a copy of the License at
747.17 - * http://www.netbeans.org/cddl-gplv2.html
747.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
747.19 - * specific language governing permissions and limitations under the
747.20 - * License. When distributing the software, include this License Header
747.21 - * Notice in each file and include the License file at
747.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
747.23 - * particular file as subject to the "Classpath" exception as provided
747.24 - * by Oracle in the GPL Version 2 section of the License file that
747.25 - * accompanied this code. If applicable, add the following below the
747.26 - * License Header, with the fields enclosed by brackets [] replaced by
747.27 - * your own identifying information:
747.28 - * "Portions Copyrighted [year] [name of copyright owner]"
747.29 - *
747.30 - * If you wish your version of this file to be governed by only the CDDL
747.31 - * or only the GPL Version 2, indicate your decision by adding
747.32 - * "[Contributor] elects to include this software in this distribution
747.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
747.34 - * single choice of license, a recipient has the option to distribute
747.35 - * your version of this file under either the CDDL, the GPL Version 2 or
747.36 - * to extend the choice of license to its licensees as provided above.
747.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
747.38 - * Version 2 license, then the option applies only if the new code is
747.39 - * made subject to such option by the copyright holder.
747.40 - *
747.41 - * Contributor(s):
747.42 - *
747.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
747.44 - */
747.45 -package org.netbeans.modules.python.testrunner.ui;
747.46 -
747.47 -import java.util.Collections;
747.48 -import java.util.List;
747.49 -import java.util.logging.Level;
747.50 -import java.util.logging.Logger;
747.51 -import java.util.regex.Matcher;
747.52 -import java.util.regex.Pattern;
747.53 -import org.netbeans.modules.gsf.testrunner.ui.api.Manager;
747.54 -import org.netbeans.modules.gsf.testrunner.api.TestSession;
747.55 -
747.56 -/**
747.57 - * Base class for test recognizer handlers.
747.58 - *
747.59 - * @author Erno Mononen
747.60 - */
747.61 -abstract class TestRecognizerHandler {
747.62 -
747.63 - private static final Logger LOGGER = Logger.getLogger(TestRecognizerHandler.class.getName());
747.64 -
747.65 - protected final Pattern pattern;
747.66 - protected Matcher matcher;
747.67 -
747.68 - TestRecognizerHandler(String regex) {
747.69 - // handle newline chars at the end -- see #143508
747.70 - if (!regex.endsWith(".*")) { //NOI18N
747.71 - regex += ".*"; //NOI18N
747.72 - }
747.73 - // see #151725
747.74 - if (!regex.startsWith(".*")) { //NOI18N
747.75 - regex = ".*" + regex; //NOI18N
747.76 - }
747.77 - this.pattern = Pattern.compile(regex, Pattern.DOTALL);
747.78 - }
747.79 -
747.80 - final boolean matches(String line) {
747.81 - return match(line).matches();
747.82 - }
747.83 -
747.84 - /**
747.85 - * <i>Package private for unit tests, otherwise don't use directly</i>.
747.86 - */
747.87 - final Matcher match(String line) {
747.88 - this.matcher = pattern.matcher(line);
747.89 - return matcher;
747.90 - }
747.91 -
747.92 - abstract void updateUI(Manager manager, TestSession session);
747.93 -
747.94 - /**
747.95 - * Gets the RecognizedOutput for output that should be passed on
747.96 - * for printing to Output. Override in subclasses as needed, the default
747.97 - * implementation supresses all output (i.e. nothing is passed on
747.98 - * for printing).
747.99 - *
747.100 - * @return the RecognizedOutput for output that should be passed on
747.101 - * for printing to Output.
747.102 - */
747.103 - List<String> getRecognizedOutput() {
747.104 - return Collections.<String>emptyList();
747.105 - }
747.106 -
747.107 - protected static int toMillis(String timeInSeconds) {
747.108 - try {
747.109 - Double elapsedTimeMillis = Double.parseDouble(timeInSeconds) * 1000;
747.110 - return elapsedTimeMillis.intValue();
747.111 - } catch (NumberFormatException nfe) {
747.112 - LOGGER.log(Level.WARNING, "Could not parse time, returning 0", nfe);
747.113 - }
747.114 - return 0;
747.115 - }
747.116 -}
748.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/TestRunnerInputProcessorFactory.java Sun Jan 04 13:11:53 2015 -0600
748.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
748.3 @@ -1,143 +0,0 @@
748.4 -/*
748.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
748.6 - *
748.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
748.8 - *
748.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
748.10 - * Other names may be trademarks of their respective owners.
748.11 - *
748.12 - * The contents of this file are subject to the terms of either the GNU
748.13 - * General Public License Version 2 only ("GPL") or the Common
748.14 - * Development and Distribution License("CDDL") (collectively, the
748.15 - * "License"). You may not use this file except in compliance with the
748.16 - * License. You can obtain a copy of the License at
748.17 - * http://www.netbeans.org/cddl-gplv2.html
748.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
748.19 - * specific language governing permissions and limitations under the
748.20 - * License. When distributing the software, include this License Header
748.21 - * Notice in each file and include the License file at
748.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
748.23 - * particular file as subject to the "Classpath" exception as provided
748.24 - * by Oracle in the GPL Version 2 section of the License file that
748.25 - * accompanied this code. If applicable, add the following below the
748.26 - * License Header, with the fields enclosed by brackets [] replaced by
748.27 - * your own identifying information:
748.28 - * "Portions Copyrighted [year] [name of copyright owner]"
748.29 - *
748.30 - * If you wish your version of this file to be governed by only the CDDL
748.31 - * or only the GPL Version 2, indicate your decision by adding
748.32 - * "[Contributor] elects to include this software in this distribution
748.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
748.34 - * single choice of license, a recipient has the option to distribute
748.35 - * your version of this file under either the CDDL, the GPL Version 2 or
748.36 - * to extend the choice of license to its licensees as provided above.
748.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
748.38 - * Version 2 license, then the option applies only if the new code is
748.39 - * made subject to such option by the copyright holder.
748.40 - *
748.41 - * Contributor(s):
748.42 - *
748.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
748.44 - */
748.45 -package org.netbeans.modules.python.testrunner.ui;
748.46 -
748.47 -import java.io.IOException;
748.48 -import java.util.ArrayList;
748.49 -import java.util.List;
748.50 -import java.util.logging.Level;
748.51 -import java.util.logging.Logger;
748.52 -import org.netbeans.api.extexecution.ExecutionDescriptor;
748.53 -import org.netbeans.api.extexecution.input.InputProcessor;
748.54 -import org.netbeans.modules.gsf.testrunner.ui.api.Manager;
748.55 -import org.netbeans.modules.gsf.testrunner.api.TestSession;
748.56 -import org.openide.util.Exceptions;
748.57 -import org.openide.util.NbBundle;
748.58 -
748.59 -/**
748.60 - *
748.61 - * @author Erno Mononen
748.62 - */
748.63 -public final class TestRunnerInputProcessorFactory implements ExecutionDescriptor.InputProcessorFactory {
748.64 -
748.65 - private static final Logger LOGGER = Logger.getLogger(TestRunnerInputProcessorFactory.class.getName());
748.66 -
748.67 - private final Data data;
748.68 -
748.69 - public TestRunnerInputProcessorFactory(Manager manager, TestSession session, boolean printSummary) {
748.70 - this.data = new Data(manager, session, printSummary);
748.71 - }
748.72 -
748.73 - public InputProcessor newInputProcessor(InputProcessor defaultProcessor) {
748.74 - return new TestRunnerInputProcessor(defaultProcessor, data);
748.75 - }
748.76 -
748.77 - // just a helper for holding conf data
748.78 - private static class Data {
748.79 - private final Manager manager;
748.80 - private final TestSession session;
748.81 - private final boolean printSummary;
748.82 -
748.83 - public Data(Manager manager, TestSession session, boolean printSummary) {
748.84 - this.manager = manager;
748.85 - this.session = session;
748.86 - this.printSummary = printSummary;
748.87 - }
748.88 - }
748.89 -
748.90 - private static class TestRunnerInputProcessor implements InputProcessor {
748.91 -
748.92 - private final InputProcessor delegate;
748.93 - private final Data data;
748.94 -
748.95 - public TestRunnerInputProcessor(InputProcessor delegate, Data data) {
748.96 - this.delegate = delegate;
748.97 - this.data = data;
748.98 - }
748.99 -
748.100 - public void processInput(char[] chars) throws IOException {
748.101 - delegate.processInput(chars);
748.102 - }
748.103 -
748.104 - public void reset() throws IOException {
748.105 - delegate.reset();
748.106 - }
748.107 -
748.108 - public void close() throws IOException {
748.109 - finish();
748.110 - delegate.close();
748.111 - }
748.112 -
748.113 - private synchronized void finish() {
748.114 -
748.115 - printSummary();
748.116 -
748.117 - if (LOGGER.isLoggable(Level.FINE)) {
748.118 - LOGGER.log(Level.FINE, "Session finished: " + data.session);
748.119 - }
748.120 - data.manager.sessionFinished(data.session);
748.121 - }
748.122 -
748.123 - private void printSummary() {
748.124 - if (!data.printSummary) {
748.125 - return;
748.126 - }
748.127 - List<String> output = new ArrayList<String>(2);
748.128 - output.add(""); //NOI18N
748.129 - output.add(NbBundle.getMessage(TestRunnerInputProcessorFactory.class,
748.130 - "MSG_TestSessionFinished", new Double(data.session.getSessionResult().getElapsedTime() / 1000d)));
748.131 - output.add(NbBundle.getMessage(TestRunnerInputProcessorFactory.class,
748.132 - "MSG_TestSessionFinishedSummary",
748.133 - data.session.getSessionResult().getTotal(),
748.134 - data.session.getSessionResult().getFailed(),
748.135 - data.session.getSessionResult().getErrors()));
748.136 -
748.137 - try {
748.138 - for (String line : output) {
748.139 - delegate.processInput((line + "\n").toCharArray()); //NOI18N
748.140 - }
748.141 - } catch (IOException ex) {
748.142 - Exceptions.printStackTrace(ex);
748.143 - }
748.144 - }
748.145 - }
748.146 -}
749.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/TestRunnerLineConvertor.java Sun Jan 04 13:11:53 2015 -0600
749.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
749.3 @@ -1,127 +0,0 @@
749.4 -/*
749.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
749.6 - *
749.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
749.8 - *
749.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
749.10 - * Other names may be trademarks of their respective owners.
749.11 - *
749.12 - * The contents of this file are subject to the terms of either the GNU
749.13 - * General Public License Version 2 only ("GPL") or the Common
749.14 - * Development and Distribution License("CDDL") (collectively, the
749.15 - * "License"). You may not use this file except in compliance with the
749.16 - * License. You can obtain a copy of the License at
749.17 - * http://www.netbeans.org/cddl-gplv2.html
749.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
749.19 - * specific language governing permissions and limitations under the
749.20 - * License. When distributing the software, include this License Header
749.21 - * Notice in each file and include the License file at
749.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
749.23 - * particular file as subject to the "Classpath" exception as provided
749.24 - * by Oracle in the GPL Version 2 section of the License file that
749.25 - * accompanied this code. If applicable, add the following below the
749.26 - * License Header, with the fields enclosed by brackets [] replaced by
749.27 - * your own identifying information:
749.28 - * "Portions Copyrighted [year] [name of copyright owner]"
749.29 - *
749.30 - * If you wish your version of this file to be governed by only the CDDL
749.31 - * or only the GPL Version 2, indicate your decision by adding
749.32 - * "[Contributor] elects to include this software in this distribution
749.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
749.34 - * single choice of license, a recipient has the option to distribute
749.35 - * your version of this file under either the CDDL, the GPL Version 2 or
749.36 - * to extend the choice of license to its licensees as provided above.
749.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
749.38 - * Version 2 license, then the option applies only if the new code is
749.39 - * made subject to such option by the copyright holder.
749.40 - *
749.41 - * Contributor(s):
749.42 - *
749.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
749.44 - */
749.45 -package org.netbeans.modules.python.testrunner.ui;
749.46 -
749.47 -import java.util.ArrayList;
749.48 -import java.util.List;
749.49 -import java.util.logging.Level;
749.50 -import java.util.logging.Logger;
749.51 -import org.netbeans.api.extexecution.print.ConvertedLine;
749.52 -import org.netbeans.api.extexecution.print.LineConvertor;
749.53 -import org.netbeans.modules.gsf.testrunner.ui.api.Manager;
749.54 -import org.netbeans.modules.gsf.testrunner.api.RerunHandler;
749.55 -import org.netbeans.modules.gsf.testrunner.api.TestSession;
749.56 -import org.netbeans.modules.python.api.PythonLineConvertorFactory;
749.57 -import org.netbeans.modules.python.testrunner.PythonTestRunnerNodeFactory;
749.58 -
749.59 -/**
749.60 - *
749.61 - * @author Erno Mononen
749.62 - */
749.63 -public final class TestRunnerLineConvertor implements LineConvertor {
749.64 -
749.65 - private static final Logger LOGGER = Logger.getLogger(TestRunnerLineConvertor.class.getName());
749.66 - private final Manager manager;
749.67 - private TestSession session;
749.68 - private final List<TestRecognizerHandler> handlers;
749.69 -
749.70 - public TestRunnerLineConvertor(Manager manager, TestSession session, TestHandlerFactory handlerFactory) {
749.71 - this.manager = manager;
749.72 - this.session = session;
749.73 - this.handlers = handlerFactory.createHandlers();
749.74 - }
749.75 -
749.76 - public synchronized void refreshSession() {
749.77 - RerunHandler handler = this.session.getRerunHandler();
749.78 - Manager.getInstance().setNodeFactory(new PythonTestRunnerNodeFactory());
749.79 - this.session = new TestSession(session.getName(), session.getProject(), session.getSessionType());
749.80 - session.setRerunHandler(handler);
749.81 - }
749.82 -
749.83 - public synchronized List<ConvertedLine> convert(String line) {
749.84 -
749.85 - for (TestRecognizerHandler handler : handlers) {
749.86 - if (handler.matches(line)) {
749.87 - if (LOGGER.isLoggable(Level.FINE)) {
749.88 - LOGGER.log(Level.FINE, "Handler [" + handler + "] matched line: " + line);
749.89 - }
749.90 - try {
749.91 - handler.updateUI(manager, session);
749.92 - return asConvertedLines(handler.getRecognizedOutput());
749.93 - } catch (IllegalStateException ise) {
749.94 - // ISE is thrown when mathing a group fails, should be enough to log a warning
749.95 - LOGGER.log(Level.WARNING, "Failed to process line: " + line + " with handler: " + handler, ise);
749.96 - } catch (IndexOutOfBoundsException ioobe) {
749.97 - // IOOBE is thrown when there is no group with the expected index.
749.98 - LOGGER.log(Level.WARNING, "Failed to process line: " + line + " with handler: " + handler, ioobe);
749.99 - }
749.100 - }
749.101 - }
749.102 -
749.103 - if (LOGGER.isLoggable(Level.FINE)) {
749.104 - LOGGER.log(Level.FINE, "No handler for line: " + line);
749.105 - }
749.106 - session.addOutput(line);
749.107 - manager.displayOutput(session, line, false);
749.108 - return null;
749.109 - }
749.110 -
749.111 - private List<ConvertedLine> asConvertedLines(List<String> lines) {
749.112 - List<ConvertedLine> result = new ArrayList<ConvertedLine>(lines.size());
749.113 -
749.114 - boolean handled = false;
749.115 - for (String line : lines) {
749.116 - for (LineConvertor convertor : PythonLineConvertorFactory.getStandardConvertors(session.getFileLocator())) {
749.117 - List<ConvertedLine> converted = convertor.convert(line);
749.118 - if (converted != null) {
749.119 - result.addAll(converted);
749.120 - handled = true;
749.121 - break;
749.122 - }
749.123 - }
749.124 - if (!handled) {
749.125 - result.add(ConvertedLine.forText(line, null));
749.126 - }
749.127 - }
749.128 - return result;
749.129 - }
749.130 -}
750.1 --- a/python.testrunner/test/unit/src/org/netbeans/modules/python/testrunner/ui/PyUnitRecognizerTest.java Sun Jan 04 13:11:53 2015 -0600
750.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
750.3 @@ -1,268 +0,0 @@
750.4 -/*
750.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
750.6 - *
750.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
750.8 - *
750.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
750.10 - * Other names may be trademarks of their respective owners.
750.11 - *
750.12 - * The contents of this file are subject to the terms of either the GNU
750.13 - * General Public License Version 2 only ("GPL") or the Common
750.14 - * Development and Distribution License("CDDL") (collectively, the
750.15 - * "License"). You may not use this file except in compliance with the
750.16 - * License. You can obtain a copy of the License at
750.17 - * http://www.netbeans.org/cddl-gplv2.html
750.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
750.19 - * specific language governing permissions and limitations under the
750.20 - * License. When distributing the software, include this License Header
750.21 - * Notice in each file and include the License file at
750.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
750.23 - * particular file as subject to the "Classpath" exception as provided
750.24 - * by Oracle in the GPL Version 2 section of the License file that
750.25 - * accompanied this code. If applicable, add the following below the
750.26 - * License Header, with the fields enclosed by brackets [] replaced by
750.27 - * your own identifying information:
750.28 - * "Portions Copyrighted [year] [name of copyright owner]"
750.29 - *
750.30 - * If you wish your version of this file to be governed by only the CDDL
750.31 - * or only the GPL Version 2, indicate your decision by adding
750.32 - * "[Contributor] elects to include this software in this distribution
750.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
750.34 - * single choice of license, a recipient has the option to distribute
750.35 - * your version of this file under either the CDDL, the GPL Version 2 or
750.36 - * to extend the choice of license to its licensees as provided above.
750.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
750.38 - * Version 2 license, then the option applies only if the new code is
750.39 - * made subject to such option by the copyright holder.
750.40 - *
750.41 - * Contributor(s):
750.42 - *
750.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
750.44 - */
750.45 -package org.netbeans.modules.python.testrunner.ui;
750.46 -
750.47 -import java.util.regex.Matcher;
750.48 -import junit.framework.TestCase;
750.49 -import org.netbeans.modules.gsf.testrunner.api.Trouble.ComparisonFailure;
750.50 -
750.51 -/**
750.52 - * Unit test for the PyUnitHandler - adapted from the Test::Unit testcases by
750.53 - * Erno.
750.54 - *
750.55 - * @author Erno Mononen
750.56 - * @author Tor Norbye
750.57 - */
750.58 -public class PyUnitRecognizerTest extends TestCase {
750.59 - public void testTestStarted() {
750.60 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestStartedHandler();
750.61 - String output = "%TEST_STARTED% test_foo (TestFooBar)";
750.62 - Matcher matcher = handler.match(output);
750.63 - assertTrue(matcher.matches());
750.64 - assertEquals(2, matcher.groupCount());
750.65 - assertEquals("test_foo", matcher.group(1));
750.66 - assertEquals("TestFooBar", matcher.group(2));
750.67 -
750.68 - output = "%TEST_STARTED% test_foo (Foo::Bar::TestFooBar)";
750.69 - matcher = handler.match(output);
750.70 - assertTrue(matcher.matches());
750.71 - assertEquals(2, matcher.groupCount());
750.72 - assertEquals("test_foo", matcher.group(1));
750.73 - assertEquals("Foo::Bar::TestFooBar", matcher.group(2));
750.74 - }
750.75 -
750.76 - public void testTestFinished() {
750.77 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestFinishedHandler();
750.78 - String output = "%TEST_FINISHED% time=0.008765 test_foo (TestFooBar)";
750.79 - Matcher matcher = handler.match(output);
750.80 - assertTrue(matcher.matches());
750.81 - assertEquals(3, matcher.groupCount());
750.82 - assertEquals("0.008765", matcher.group(1));
750.83 - assertEquals("test_foo", matcher.group(2));
750.84 - assertEquals("TestFooBar", matcher.group(3));
750.85 -
750.86 - output = "%TEST_FINISHED% time=0.008765 test_foo (FooModule::TestFooBar)";
750.87 - matcher = handler.match(output);
750.88 - assertTrue(matcher.matches());
750.89 - assertEquals(3, matcher.groupCount());
750.90 - assertEquals("0.008765", matcher.group(1));
750.91 - assertEquals("test_foo", matcher.group(2));
750.92 - assertEquals("FooModule::TestFooBar", matcher.group(3));
750.93 - }
750.94 -
750.95 - public void testTestFinished2() {
750.96 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestFinishedHandler();
750.97 - String output = "%TEST_FINISHED% time=8.4e-05 test_foo (TestFooBar)";
750.98 - Matcher matcher = handler.match(output);
750.99 - assertTrue(matcher.matches());
750.100 - assertEquals(3, matcher.groupCount());
750.101 - assertEquals("8.4e-05", matcher.group(1));
750.102 - assertEquals("test_foo", matcher.group(2));
750.103 - assertEquals("TestFooBar", matcher.group(3));
750.104 - }
750.105 -
750.106 - public void testTestFailed() {
750.107 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestFailedHandler();
750.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'";
750.109 - Matcher matcher = handler.match(output);
750.110 - assertTrue(matcher.matches());
750.111 -
750.112 - assertEquals(5, matcher.groupCount());
750.113 - assertEquals("0.007233", matcher.group(1));
750.114 - assertEquals("test_positive_price", matcher.group(2));
750.115 - assertEquals("ProductTest", matcher.group(3));
750.116 - assertEquals("<false> is not true.", matcher.group(4));
750.117 - assertEquals("./test/unit/product_test.rb:69:in `test_positive_price'", matcher.group(5));
750.118 -
750.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'";
750.120 - matcher = handler.match(outputScientificNotation);
750.121 - assertTrue(matcher.matches());
750.122 - assertEquals("9.8e-07", matcher.group(1));
750.123 -
750.124 - // nested class name
750.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'";
750.126 - matcher = handler.match(outputNestedClass);
750.127 - assertTrue(matcher.matches());
750.128 -
750.129 - assertEquals(5, matcher.groupCount());
750.130 - assertEquals("0.0060", matcher.group(1));
750.131 - assertEquals("test_foo", matcher.group(2));
750.132 - assertEquals("TestSomething::TestNotExecuted", matcher.group(3));
750.133 - assertEquals("this test is not executed.", matcher.group(4));
750.134 - assertEquals("/a/path/to/somewhere/test/test_something.rb:21:in `test_foo'", matcher.group(5));
750.135 - }
750.136 -
750.137 -
750.138 - /*
750.139 - FAen ta meg!
750.140 - %SUITE_STARTING% Other_TestCase
750.141 - Joda!
750.142 - %TEST_STARTED% test_probably_errs (other_test.Other_TestCase)
750.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%
750.144 - %TEST_STARTED% test_probably_fails (other_test.Other_TestCase)
750.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%
750.146 - %TEST_STARTED% test_should_succeed (other_test.Other_TestCase)
750.147 - %TEST_FINISHED% time=0.000013 test_should_succeed (other_test.Other_TestCase)
750.148 - %SUITE_FAILURES% 1
750.149 - %SUITE_ERRORS% 1
750.150 - %SUITE_FINISHED% time=0.0005
750.151 -
750.152 -
750.153 - */
750.154 - public void testTestError() {
750.155 - PyUnitHandlerFactory.TestErrorHandler handler = new PyUnitHandlerFactory.TestErrorHandler();
750.156 -
750.157 -
750.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%";
750.159 -
750.160 - Matcher matcher = handler.match(output);
750.161 - assertTrue(matcher.matches());
750.162 -
750.163 - assertEquals(5, matcher.groupCount());
750.164 - assertEquals("0.000024", matcher.group(1));
750.165 - assertEquals("test_probably_errs", matcher.group(2));
750.166 - assertEquals("other_test.Other_TestCase", matcher.group(3));
750.167 - assertEquals("integer division or modulo by zero", matcher.group(4));
750.168 -
750.169 - String[] stackTrace = PyUnitHandlerFactory.getStackTrace(matcher.group(4), matcher.group(5));
750.170 - assertEquals(3, stackTrace.length);
750.171 - assertEquals("integer division or modulo by zero", stackTrace[0]);
750.172 - assertEquals("test_probably_errs() in /Users/tor/NetBeansProjects/NewPythonProject44/src/other_test.py:27", stackTrace[2]);
750.173 - assertEquals("run() in /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/unittest.py:267", stackTrace[1]);
750.174 - }
750.175 -
750.176 - public void testSuiteFinished() {
750.177 - TestRecognizerHandler handler = new PyUnitHandlerFactory.SuiteFinishedHandler();
750.178 - String output = "%SUITE_FINISHED% time=0.124";
750.179 - Matcher matcher = handler.match(output);
750.180 - assertTrue(matcher.matches());
750.181 -
750.182 - assertEquals(1, matcher.groupCount());
750.183 - assertEquals("0.124", matcher.group(1));
750.184 - }
750.185 -
750.186 - public void testSuiteFinished2() {
750.187 - TestRecognizerHandler handler = new PyUnitHandlerFactory.SuiteFinishedHandler();
750.188 - String output = "%SUITE_FINISHED% time=8.4e-05";
750.189 - Matcher matcher = handler.match(output);
750.190 - assertTrue(matcher.matches());
750.191 -
750.192 - assertEquals(1, matcher.groupCount());
750.193 - assertEquals("8.4e-05", matcher.group(1));
750.194 - }
750.195 -
750.196 - public void testSuiteStarted() {
750.197 - TestRecognizerHandler handler = new PyUnitHandlerFactory.SuiteStartedHandler();
750.198 - String output = "%SUITE_STARTED% 0 tests, 0 assertions, 0 failures, 0 errors";
750.199 - Matcher matcher = handler.match(output);
750.200 - assertTrue(matcher.matches());
750.201 - }
750.202 -
750.203 - public void testSuiteStarting() throws InterruptedException {
750.204 - TestRecognizerHandler handler = new PyUnitHandlerFactory.SuiteStartingHandler();
750.205 - String output = "%SUITE_STARTING% TestMe";
750.206 - Matcher matcher = handler.match(output);
750.207 - assertTrue(matcher.matches());
750.208 - assertEquals(1, matcher.groupCount());
750.209 - assertEquals("TestMe", matcher.group(1));
750.210 -
750.211 - output = "%SUITE_STARTING% MyModule::TestMe";
750.212 - matcher = handler.match(output);
750.213 - assertTrue(matcher.matches());
750.214 - assertEquals(1, matcher.groupCount());
750.215 - assertEquals("MyModule::TestMe", matcher.group(1));
750.216 - }
750.217 -
750.218 - public void testSuiteErrorOutput() throws InterruptedException {
750.219 - TestRecognizerHandler handler = new PyUnitHandlerFactory.SuiteErrorOutputHandler();
750.220 - String output = "%SUITE_ERROR_OUTPUT% error=undefined method `size' for UserHelperTest:Class";
750.221 - Matcher matcher = handler.match(output);
750.222 - assertTrue(matcher.matches());
750.223 - assertEquals(1, matcher.groupCount());
750.224 - assertEquals("undefined method `size' for UserHelperTest:Class", matcher.group(1));
750.225 - }
750.226 -
750.227 - public void testTestLogger() throws InterruptedException {
750.228 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestLoggerHandler();
750.229 - String output = "%TEST_LOGGER% level=FINE msg=Loading 3 files took 12.345";
750.230 - Matcher matcher = handler.match(output);
750.231 - assertTrue(matcher.matches());
750.232 - assertEquals(2, matcher.groupCount());
750.233 - assertEquals("FINE", matcher.group(1));
750.234 - assertEquals("Loading 3 files took 12.345", matcher.group(2));
750.235 - }
750.236 -
750.237 - public void testIssue143508TestStarted() {
750.238 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestStartedHandler();
750.239 - String output = "%TEST_STARTED% test_foo (FooTest)\\n";
750.240 - Matcher matcher = handler.match(output);
750.241 - assertTrue(matcher.matches());
750.242 - assertEquals(2, matcher.groupCount());
750.243 - assertEquals("test_foo", matcher.group(1));
750.244 - assertEquals("FooTest", matcher.group(2));
750.245 - }
750.246 -
750.247 - public void testIssue143508TestFinished() {
750.248 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestFinishedHandler();
750.249 - String output = "%TEST_FINISHED% time=0.203 test_foo (FooTest)\\n";
750.250 - Matcher matcher = handler.match(output);
750.251 - assertTrue(matcher.matches());
750.252 - assertEquals(3, matcher.groupCount());
750.253 - assertEquals("0.203", matcher.group(1));
750.254 - assertEquals("test_foo", matcher.group(2));
750.255 - assertEquals("FooTest", matcher.group(3));
750.256 - }
750.257 -
750.258 - public void testExtractDiff1() {
750.259 - ComparisonFailure failure = PyUnitHandlerFactory.getComparisonFailure("'foo\nbar\nbaz' != 'foo\nbr\nbazz'");
750.260 - assertNotNull(failure);
750.261 - assertEquals("'foo\nbar\nbaz'", failure.getExpected());
750.262 - assertEquals("'foo\nbr\nbazz'", failure.getActual());
750.263 - }
750.264 -
750.265 - public void testExtractDiff2() {
750.266 - ComparisonFailure failure = PyUnitHandlerFactory.getComparisonFailure("Expected 265252859812191058636308480000000L but got 132626429906095529318154240000000L");
750.267 - assertNotNull(failure);
750.268 - assertEquals("265252859812191058636308480000000L", failure.getExpected());
750.269 - assertEquals("132626429906095529318154240000000L", failure.getActual());
750.270 - }
750.271 -}