From: Gilles DAVID Date: Wed, 27 Aug 2014 13:33:14 +0000 (+0200) Subject: Remove use of mutable as default parameter value X-Git-Tag: V7_5_0a1~12 X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=3091a8beac430b5b36c7606fc672dcf869a8683d;p=modules%2Fkernel.git Remove use of mutable as default parameter value 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 --- diff --git a/bin/appliskel/tests/concurrentSession/TestConcurrentSession.py b/bin/appliskel/tests/concurrentSession/TestConcurrentSession.py index aab1777af..1bc310ccc 100644 --- a/bin/appliskel/tests/concurrentSession/TestConcurrentSession.py +++ b/bin/appliskel/tests/concurrentSession/TestConcurrentSession.py @@ -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: diff --git a/bin/appliskel/tests/launcher/TestLauncherSessionArgs.py b/bin/appliskel/tests/launcher/TestLauncherSessionArgs.py index 20445e9df..f3987f18b 100644 --- a/bin/appliskel/tests/launcher/TestLauncherSessionArgs.py +++ b/bin/appliskel/tests/launcher/TestLauncherSessionArgs.py @@ -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: diff --git a/bin/appliskel/tests/launcher/getLogger.py b/bin/appliskel/tests/launcher/getLogger.py index 8e952ebf5..4d45dc3f1 100644 --- a/bin/appliskel/tests/launcher/getLogger.py +++ b/bin/appliskel/tests/launcher/getLogger.py @@ -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 ] diff --git a/bin/launchConfigureParser.py b/bin/launchConfigureParser.py index cfb247f61..77df1a60d 100755 --- a/bin/launchConfigureParser.py +++ b/bin/launchConfigureParser.py @@ -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 "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 _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 diff --git a/bin/parseConfigFile.py b/bin/parseConfigFile.py index 3054ed1f3..2f2bbb2ea 100644 --- a/bin/parseConfigFile.py +++ b/bin/parseConfigFile.py @@ -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() diff --git a/bin/runConsole.py b/bin/runConsole.py index fdaba6ce5..57c54d0ed 100644 --- a/bin/runConsole.py +++ b/bin/runConsole.py @@ -21,10 +21,12 @@ # 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() # diff --git a/bin/runSession.py b/bin/runSession.py index 92c6b4705..f698e323d 100644 --- a/bin/runSession.py +++ b/bin/runSession.py @@ -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. diff --git a/bin/salomeContext.py b/bin/salomeContext.py index f4eb21508..00de96345 100644 --- a/bin/salomeContext.py +++ b/bin/salomeContext.py @@ -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]) diff --git a/bin/salomeContextUtils.py.in b/bin/salomeContextUtils.py.in index 3f517dcf7..6e6a8fe0a 100644 --- a/bin/salomeContextUtils.py.in +++ b/bin/salomeContextUtils.py.in @@ -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 diff --git a/bin/salome_session.py b/bin/salome_session.py index d7d79639c..e9f3b088b 100644 --- a/bin/salome_session.py +++ b/bin/salome_session.py @@ -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 diff --git a/doc/salome/salome_command.dox b/doc/salome/salome_command.dox index e4c924d54..dd52d38fd 100644 --- a/doc/salome/salome_command.dox +++ b/doc/salome/salome_command.dox @@ -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: diff --git a/src/Container/SALOME_ComponentPy.py b/src/Container/SALOME_ComponentPy.py index 3a801a753..e581178d2 100755 --- a/src/Container/SALOME_ComponentPy.py +++ b/src/Container/SALOME_ComponentPy.py @@ -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 diff --git a/src/KERNEL_PY/kernel/diclookup.py b/src/KERNEL_PY/kernel/diclookup.py index 140d13ad8..7c7095a04 100644 --- a/src/KERNEL_PY/kernel/diclookup.py +++ b/src/KERNEL_PY/kernel/diclookup.py @@ -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 diff --git a/src/KERNEL_PY/kernel/parametric/study_exchange_vars.py b/src/KERNEL_PY/kernel/parametric/study_exchange_vars.py index e30a33949..ccc1cb53b 100644 --- a/src/KERNEL_PY/kernel/parametric/study_exchange_vars.py +++ b/src/KERNEL_PY/kernel/parametric/study_exchange_vars.py @@ -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 diff --git a/src/KERNEL_PY/kernel/syshelper.py b/src/KERNEL_PY/kernel/syshelper.py index eb83e7966..e76502b64 100644 --- a/src/KERNEL_PY/kernel/syshelper.py +++ b/src/KERNEL_PY/kernel/syshelper.py @@ -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 diff --git a/src/LifeCycleCORBA_SWIG/LifeCycleCORBA.py b/src/LifeCycleCORBA_SWIG/LifeCycleCORBA.py index 9a4995c0d..fd1fa6508 100644 --- a/src/LifeCycleCORBA_SWIG/LifeCycleCORBA.py +++ b/src/LifeCycleCORBA_SWIG/LifeCycleCORBA.py @@ -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,