Salome HOME
Remove use of mutable as default parameter value
authorGilles DAVID <gilles-g.david@edf.fr>
Wed, 27 Aug 2014 13:33:14 +0000 (15:33 +0200)
committerGilles DAVID <gilles-g.david@edf.fr>
Wed, 27 Aug 2014 13:33:14 +0000 (15:33 +0200)
Usually the use of a mutable as a default parameter value is not
advised.
This is well explained in http://effbot.org/zone/default-values.htm

16 files changed:
bin/appliskel/tests/concurrentSession/TestConcurrentSession.py
bin/appliskel/tests/launcher/TestLauncherSessionArgs.py
bin/appliskel/tests/launcher/getLogger.py
bin/launchConfigureParser.py
bin/parseConfigFile.py
bin/runConsole.py
bin/runSession.py
bin/salomeContext.py
bin/salomeContextUtils.py.in
bin/salome_session.py
doc/salome/salome_command.dox
src/Container/SALOME_ComponentPy.py
src/KERNEL_PY/kernel/diclookup.py
src/KERNEL_PY/kernel/parametric/study_exchange_vars.py
src/KERNEL_PY/kernel/syshelper.py
src/LifeCycleCORBA_SWIG/LifeCycleCORBA.py

index aab1777af46e7363f2ad8b167508f7f047904848..1bc310ccc3983411eff9dc9fc62eec89415a417b 100644 (file)
@@ -42,7 +42,9 @@ class TestConcurrentLaunch(unittest.TestCase):
   def tearDown(self):
     pass
   #
-  def appli(self, args=[]):
+  def appli(self, args=None):
+    if args is None:
+      args = []
     try:
       self.SALOME.main(self.SALOME_appli_args + args)
     except SystemExit, e:
@@ -50,7 +52,9 @@ class TestConcurrentLaunch(unittest.TestCase):
         logging.error(e)
       pass
   #
-  def session(self, args=[]):
+  def session(self, args=None):
+    if args is None:
+      args = []
     try:
       self.SALOME.main(self.SALOME_shell_args + args)
     except SystemExit, e:
index 20445e9df9a9e2b74cede9ed59863e6946e5485b..f3987f18b4ef8b28ef90c2658b6a9991e1801e4f 100644 (file)
@@ -67,7 +67,9 @@ class TestSessionArgs(unittest.TestCase):
   def tearDown(self):
     self.removeLogFile()
   #
-  def session(self, args=[]):
+  def session(self, args=None):
+    if args is None:
+      args = []
     try:
       self.SALOME.main(self.SALOME_args + args)
     except SystemExit, e:
index 8e952ebf52b42b1829ea24730fb9e6cff34467da..4d45dc3f13b01b97ca90b5a151a1759e81d6539b 100644 (file)
@@ -21,7 +21,9 @@ import os
 import sys
 import logging
 
-def getLogger(args=[]):
+def getLogger(args=None):
+  if args is None:
+    args = []
   outfileOptionPrefix = "outfile="
   outfileArgs = [ str(x) for x in args if str(x).startswith(outfileOptionPrefix) ]
   allFiles = [ x.replace(outfileOptionPrefix, '') for x in outfileArgs ]
index cfb247f619dcbfef936d53549b6061ca2a5d0519..77df1a60d64b7f23e1ca8b8c807676a90db49e6d 100755 (executable)
@@ -483,7 +483,9 @@ def store_boolean (option, opt, value, parser, *args):
         for attribute in args:
             setattr(parser.values, attribute, value)
 
-def CreateOptionParser (theAdditionalOptions=[]):
+def CreateOptionParser (theAdditionalOptions=None):
+    if theAdditionalOptions is None:
+        theAdditionalOptions = []
     # GUI/Terminal. Default: GUI
     help_str = "Launch without GUI (in the terminal mode)."
     o_t = optparse.Option("-t",
@@ -871,7 +873,7 @@ Python file arguments, if any, must be comma-separated (without blank characters
 args = {}
 #def get_env():
 #args = []
-def get_env(theAdditionalOptions=[], appname=salomeappname, cfgname=salomecfgname):
+def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgname):
     ###
     # Collect launch configuration files:
     # - The environment variable "<appname>Config" (SalomeAppConfig) which can
@@ -894,6 +896,9 @@ def get_env(theAdditionalOptions=[], appname=salomeappname, cfgname=salomecfgnam
     #   specified in configuration file(s)
     ###
 
+    if theAdditionalOptions is None:
+        theAdditionalOptions = []
+
     global args
     config_var = appname+'Config'
 
@@ -902,15 +907,13 @@ def get_env(theAdditionalOptions=[], appname=salomeappname, cfgname=salomecfgnam
         separator = ";"
 
     # check KERNEL_ROOT_DIR
-    try:
-        kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
-    except:
+    kernel_root_dir = os.environ.get("KERNEL_ROOT_DIR", None)
+    if kernel_root_dir is None:
         print """
         For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
         KERNEL_ROOT_DIR is mandatory.
         """
         sys.exit(1)
-        pass
 
     ############################
     # parse command line options
@@ -1000,15 +1003,15 @@ def get_env(theAdditionalOptions=[], appname=salomeappname, cfgname=salomecfgnam
     # set default values for options which are NOT set in config files
     for aKey in listKeys:
         if not args.has_key( aKey ):
-            args[aKey]=[]
+            args[aKey] = []
 
     for aKey in boolKeys:
         if not args.has_key( aKey ):
-            args[aKey]=0
+            args[aKey] = 0
 
     if args[file_nam]:
         afile=args[file_nam]
-        args[file_nam]=[afile]
+        args[file_nam] = [afile]
 
     args[appname_nam] = appname
 
index 3054ed1f341eeb2154d3280befda32627afe1970..2f2bbb2ead9cf4998129338d3600b2bcb9c2d6f1 100644 (file)
@@ -163,7 +163,9 @@ class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser):
 # Input: filename, and a list of reserved keywords (environment variables)
 # Output: a list of pairs (variable, value), and a dictionary associating a list of user-defined values to each reserved keywords
 # Note: Does not support duplicate keys in a same section
-def parseConfigFile(filename, reserved = []):
+def parseConfigFile(filename, reserved = None):
+  if reserved is None:
+    reserved = []
   config = MultiOptSafeConfigParser()
   config.optionxform = str # case sensitive
 
@@ -183,10 +185,12 @@ def parseConfigFile(filename, reserved = []):
     raise SalomeContextException(msg)
 #
 
-def __processConfigFile(config, reserved = [], filename="UNKNOWN FILENAME"):
+def __processConfigFile(config, reserved = None, filename="UNKNOWN FILENAME"):
   # :TODO: may detect duplicated variables in the same section (raise a warning)
   #        or even duplicate sections
 
+  if reserved is None:
+    reserved = []
   unsetVariables = []
   outputVariables = []
   # Get raw items for each section, and make some processing for environment variables management
@@ -245,12 +249,14 @@ def _trimColons(var):
 #    - virtually add a section to configuration file
 #    - process shell keywords (if, then...)
 class EnvFileConverter(object):
-  def __init__(self, fp, section_name, reserved = [], outputFile=None):
+  def __init__(self, fp, section_name, reserved = None, outputFile=None):
+    if reserved is None:
+      reserved = []
     self.fp = fp
     self.sechead = '[' + section_name + ']\n'
     self.reserved = reserved
     self.outputFile = outputFile
-    self.allParsedVariableNames=[]
+    self.allParsedVariableNames = []
     # exclude line that begin with:
     self.exclude = [ 'if', 'then', 'else', 'fi', '#', 'echo', 'exit' ]
     self.exclude.append('$gconfTool') # QUICK FIX :TODO: provide method to extend this variable
@@ -371,7 +377,9 @@ class EnvFileConverter(object):
   #
 
 # Convert .sh environment file to configuration file format
-def convertEnvFileToConfigFile(envFilename, configFilename, reserved=[]):
+def convertEnvFileToConfigFile(envFilename, configFilename, reserved=None):
+  if reserved is None:
+    reserved = []
   logConfigParser.debug('convert env file %s to %s'%(envFilename, configFilename))
   fileContents = open(envFilename, 'r').read()
 
index fdaba6ce5abbf6e4d96288d9f9d2471708004f11..57c54d0ed367c8a1c59b7c56ed04e793427fb613 100644 (file)
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-def __prompt(environment = None, commands=[], message = "Connecting to SALOME"):
+def __prompt(environment = None, commands=None, message = "Connecting to SALOME"):
   if environment is None:
     environment = globals().copy()
     environment.update(locals())
+  if commands is None:
+    commands = []
 
   import code
   import rlcompleter
@@ -38,7 +40,9 @@ def __prompt(environment = None, commands=[], message = "Connecting to SALOME"):
   return shell.interact
 #
 
-def connect(args=[]):
+def connect(args=None):
+  if args is None:
+    args = []
   p = __prompt(commands=["import salomeConsole"])
   p()
 #
index 92c6b4705936450753b0c0c2375419ef5687f477..f698e323d252914a436b0cbc298a2c3cbb9d49b8 100644 (file)
@@ -34,7 +34,9 @@ class MyParser(OptionParser):
         return self.epilog
 #
 
-def configureSession(args=[]):
+def configureSession(args=None):
+  if args is None:
+    args = []
   usage = "Usage: %prog [options] [command]"
   epilog  = """\n
 If the command is not given a shell is opened; else execute the given command.
index f4eb21508eb2fbfed0d8be11c1ff1644b98b796b..00de96345629011071517ea9ef43a30ef26091ad 100644 (file)
@@ -69,11 +69,11 @@ class SalomeContext:
   the SalomeContext class will try to automatically convert them
   to .cfg format before setting the environment.
   """
-  def __init__(self, configFileNames=[]):
+  def __init__(self, configFileNames=0):
     #it could be None explicitely (if user use multiples setVariable...for standalone)
-    if configFileNames==None:
+    if configFileNames is None:
        return
-
+    configFileNames = configFileNames or []
     if len(configFileNames) == 0:
       raise SalomeContextException("No configuration files given")
 
@@ -231,7 +231,9 @@ class SalomeContext:
       sys.exit(1)
   #
 
-  def __setEnvironmentFromConfigFile(self, filename, reserved=[]):
+  def __setEnvironmentFromConfigFile(self, filename, reserved=None):
+    if reserved is None:
+      reserved = []
     try:
       unsetVars, configVars, reservedDict = parseConfigFile(filename, reserved)
     except SalomeContextException, e:
@@ -277,7 +279,9 @@ class SalomeContext:
     sys.path[:0] = os.getenv('PYTHONPATH','').split(':')
   #
 
-  def _runAppli(self, args=[]):
+  def _runAppli(self, args=None):
+    if args is None:
+      args = []
     # Initialize SALOME environment
     sys.argv = ['runSalome'] + args
     import setenv
@@ -287,7 +291,9 @@ class SalomeContext:
     runSalome.runSalome()
   #
 
-  def _runSession(self, args=[]):
+  def _runSession(self, args=None):
+    if args is None:
+      args = []
     sys.argv = ['runSession'] + args
     import runSession
     runSession.configureSession(args)
@@ -300,7 +306,9 @@ class SalomeContext:
     return runSession.runSession(command)
   #
 
-  def _runConsole(self, args=[]):
+  def _runConsole(self, args=None):
+    if args is None:
+      args = []
     # Initialize SALOME environment
     sys.argv = ['runConsole'] + args
     import setenv
@@ -311,7 +319,9 @@ class SalomeContext:
     return proc.communicate()
   #
 
-  def _killAll(self, args=[]):
+  def _killAll(self, args=None):
+    if args is None:
+      args = []
     try:
       import PortManager # mandatory
       from multiprocessing import Process
@@ -332,16 +342,16 @@ class SalomeContext:
 
   #
 
-  def _showInfo(self, args=[]):
+  def _showInfo(self, args=None):
     print "Running with python", platform.python_version()
     self._runAppli(["--version"])
   #
 
-  def _usage(self, unused=[]):
+  def _usage(self, unused=None):
     usage()
   #
 
-  def _makeCoffee(self, args=[]):
+  def _makeCoffee(self, args=None):
     print "                        ("
     print "                          )     ("
     print "                   ___...(-------)-....___"
@@ -388,7 +398,6 @@ class SalomeContext:
     return self._logger
   #
 
-import pickle
 if __name__ == "__main__":
   if len(sys.argv) == 3:
     context = pickle.loads(sys.argv[1])
index 3f517dcf73b3c154d03c8d0dc99170cce3e16ac0..6e6a8fe0ae3af54fbab910b535a156c137ce4933 100644 (file)
@@ -102,7 +102,9 @@ def __getScriptPath(scriptName, searchPathList):
 #
 
 # Return an array of dictionaries {script_name: [list_of_its_args]}
-def getScriptsAndArgs(args=[], searchPathList=None):
+def getScriptsAndArgs(args=None, searchPathList=None):
+  if args is None:
+    args = []
   if searchPathList is None:
     searchPathList = sys.path
 
@@ -175,7 +177,9 @@ def getScriptsAndArgs(args=[], searchPathList=None):
 
 # Formatting scripts and args as a Bash-like command-line:
 # script1.py [args] ; script2.py [args] ; ...
-def formatScriptsAndArgs(scriptArgs=[]):
+def formatScriptsAndArgs(scriptArgs=None):
+    if scriptArgs is None:
+      scriptArgs = []
     commands = []
     for sc_dict in scriptArgs:
       for script, sc_args in sc_dict.items(): # single entry
index d7d79639c2aa57d924113cff0a12812a9e24c4c1..e9f3b088b26bc37a57d05e5a215949a54ce9557f 100644 (file)
@@ -33,7 +33,9 @@ import socket
 
 _session = None
 
-def startSession(modules=[]):
+def startSession(modules=None):
+    if modules is None:
+        modules = []
     global _session
     if _session: return
     from searchFreePort import searchFreePort
index e4c924d540b6eec0e527cbca33f4171a784833ec..dd52d38fd2b5a015985d03e0bfcdd8c66d850a2a 100644 (file)
@@ -118,7 +118,7 @@ except SystemExit, e:
 \section salome_api The API
 An API named \c SalomeContext, written in Python, allows for the construction of SALOME execution context and for application start. Each launcher creates a \c SalomeContext object, and optionally gives it a list of configuration files to describe the context:
 \code
-SalomeContext.__init__(configFileNames=[])
+SalomeContext.__init__(configFileNames=None)
 \endcode
 
 A launcher can also directly call the API functions to define, suppress or extend (add information) an environment variable:
index 3a801a75329ab19136b48e242c3cc1c3e8d19d11..e581178d2b15e846c68960a78b2d1690e7461db3 100755 (executable)
@@ -322,11 +322,11 @@ class SALOME_ComponentPy_i (Engines__POA.EngineComponent):
     #-------------------------------------------------------------------------    
 
     def importData(self, studyId, dataContainer, options):
-       return [] # no implmenetation by default
+       return [] # no implementation by default
 
     #-------------------------------------------------------------------------    
 
     def getModifiedData(self, studyId):
-       return [] # no implmenetation by default
+       return [] # no implementation by default
 
     pass # end of SALOME_ComponentPy_i
index 140d13ad86e10b63d7148a6cb759ce63748b992f..7c7095a04dfe511124a1273522506e79bf69145e 100644 (file)
@@ -53,8 +53,10 @@ class Lookup(dict):
     a dictionary which can lookup value by key, or keys by value
     """
     ## items can be a list of pair_lists or a dictionary
-    def __init__(self, items=[]):
+    def __init__(self, items=None):
         """items can be a list of pair_lists or a dictionary"""
+       if items is None:
+           items = []
         dict.__init__(self, items)
 
     ## find the key(s) as a list given a value
index e30a33949d811b35fd308a1018fb2be7d30f060d..ccc1cb53be228f0f075e5341d8cca957f49d8fe6 100644 (file)
@@ -50,8 +50,10 @@ class Variable:
     its name. Other attributes are reserved for future use.
     """
     
-    def __init__(self, name, dimension = [], minValue = None, maxValue = None,
+    def __init__(self, name, dimension = None, minValue = None, maxValue = None,
                  initialValue = None):
+        if dimension is None:
+         dimension = []
         self.name = name
         
         # Reserved for future use
@@ -100,8 +102,12 @@ class ExchangeVariables:
 
     """
     
-    def __init__(self, inputVarList = [], outputVarList = [],
+    def __init__(self, inputVarList = None, outputVarList = None,
                  refEntry = None):
+        if inputVarList is None:
+         inputVarList = []
+       if outputVarList is None:
+         outputVarList = []
         self.inputVarList = inputVarList
         self.outputVarList = outputVarList
         self.refEntry = refEntry
index eb83e7966b546e81f7f8951fdb41422c2e07abde..e76502b646711fa80679ef09115ca1e54881404f 100644 (file)
@@ -25,7 +25,7 @@ __author__="gboulant"
 __date__ ="$21 mai 2010 18:00:23$"
 
 
-def findFiles(rootpath, excludes=[]):
+def findFiles(rootpath, excludes=None):
     """
     This looks after files recursively from the specified rootpath,
     but without visiting directories whose basename is in the list
@@ -34,6 +34,8 @@ def findFiles(rootpath, excludes=[]):
     if not os.path.exists(rootpath):
         raise RuntimeError("the path %s does not exists"%rootpath)
 
+    if excludes is None:
+        excludes = []
     exclude_options=""
     for excludepath in excludes:
         exclude_options+="-e %s "%excludepath
index 9a4995c0dd16a0ac64a2f9125a7c08a9f09b5916..fd1fa6508ab5b4efee4a85222a322e4d3565ac1e 100644 (file)
@@ -46,28 +46,40 @@ class ContainerParameters (Engines.ContainerParameters):
     Engines.ContainerParameters.__init__(self,container_name, mode, workingdir, nb_proc, isMPI, parallelLib,resource_params)
 
 class ResourceParameters (Engines.ResourceParameters):
-  def __init__(self, name="", hostname="", OS="", componentList=[],
+  def __init__(self, name="", hostname="", OS="", componentList=None,
                      nb_proc=0, mem_mb=0, cpu_clock=0, nb_node=0, nb_proc_per_node=0,
-                     policy="", resList=[], can_launch_batch_jobs = False, can_run_containers = False):
+                     policy="", resList=None, can_launch_batch_jobs = False, can_run_containers = False):
+    if componentList is None:
+      componentList = []
+    if resList is None:
+      resList = []
     Engines.ResourceParameters.__init__(self, name, hostname, can_launch_batch_jobs, can_run_containers,
                                         OS, componentList, nb_proc, mem_mb, cpu_clock, nb_node,
                                         nb_proc_per_node, policy, resList)
 
 class JobParameters (Engines.JobParameters):
-  def __init__(self, job_name="", job_type="", job_file="", env_file="", in_files=[], out_files=[],
+  def __init__(self, job_name="", job_type="", job_file="", env_file="", in_files=None, out_files=None,
                      work_directory="", local_directory="", result_directory="", maximum_duration="",
                      resource_required=None, queue="", exclusive = False, mem_per_cpu = 0,
-                     specific_parameters=[], launcher_file = "", launcher_args = ""):
+                     specific_parameters=None, launcher_file = "", launcher_args = ""):
+    if in_files is None:
+      in_files = []
+    if out_files is None:
+      out_files = []
+    if specific_parameters is None:
+      specific_parameters = []
     Engines.JobParameters.__init__(self, job_name, job_type, job_file, env_file, in_files, out_files,
                                          work_directory, local_directory, result_directory, maximum_duration,
                                          resource_required, queue, exclusive, mem_per_cpu,
                                          specific_parameters, launcher_file, launcher_args)
 
 class ResourceDefinition(Engines.ResourceDefinition):
-  def __init__(self, name="", hostname="", protocol="rsh", username="", applipath="", componentList=[],
+  def __init__(self, name="", hostname="", protocol="rsh", username="", applipath="", componentList=None,
                mode="interactive", OS="", mem_mb=1, cpu_clock=1, nb_node=1, nb_proc_per_node=1,
                batch="", mpiImpl="", iprotocol="rsh", type = "single_machine",
                can_launch_batch_jobs = False, can_run_containers = False, working_directory = ""):
+    if componentList is None:
+      componentList = []
     Engines.ResourceDefinition.__init__(self, name, hostname, type, protocol, username, applipath,
                                         componentList, OS, mem_mb, cpu_clock, nb_node, nb_proc_per_node,
                                         batch, mpiImpl, iprotocol, can_launch_batch_jobs,