Removed uses of dict.has_key() from distutils, and uses of

callable() from copy_reg.py, so the interpreter now starts up
without warnings when '-3' is given.  More work like this needs to
be done in the rest of the stdlib.
This commit is contained in:
Guido van Rossum 2008-02-21 18:18:37 +00:00
parent b5e2684a1a
commit 8bc0965adf
17 changed files with 44 additions and 39 deletions

View File

@ -55,7 +55,7 @@ def update(self, dict=None, **kwargs):
if len(kwargs): if len(kwargs):
self.data.update(kwargs) self.data.update(kwargs)
def get(self, key, failobj=None): def get(self, key, failobj=None):
if not self.has_key(key): if key not in self:
return failobj return failobj
return self[key] return self[key]
def setdefault(self, key, failobj=None): def setdefault(self, key, failobj=None):

View File

@ -15,7 +15,7 @@ def pickle(ob_type, pickle_function, constructor_ob=None):
if type(ob_type) is _ClassType: if type(ob_type) is _ClassType:
raise TypeError("copy_reg is not intended for use with classes") raise TypeError("copy_reg is not intended for use with classes")
if not callable(pickle_function): if not hasattr(pickle_function, '__call__'):
raise TypeError("reduction functions must be callable") raise TypeError("reduction functions must be callable")
dispatch_table[ob_type] = pickle_function dispatch_table[ob_type] = pickle_function
@ -25,7 +25,7 @@ def pickle(ob_type, pickle_function, constructor_ob=None):
constructor(constructor_ob) constructor(constructor_ob)
def constructor(object): def constructor(object):
if not callable(object): if not hasattr(object, '__call__'):
raise TypeError("constructors must be callable") raise TypeError("constructors must be callable")
# Example: provide pickling support for complex numbers. # Example: provide pickling support for complex numbers.

View File

@ -124,7 +124,7 @@ def visit (z, dirname, names):
def check_archive_formats (formats): def check_archive_formats (formats):
for format in formats: for format in formats:
if not ARCHIVE_FORMATS.has_key(format): if format not in ARCHIVE_FORMATS:
return format return format
else: else:
return None return None

View File

@ -159,7 +159,7 @@ class (via the 'executables' class attribute), but most will have:
# basically the same things with Unix C compilers. # basically the same things with Unix C compilers.
for key in args.keys(): for key in args.keys():
if not self.executables.has_key(key): if key not in self.executables:
raise ValueError, \ raise ValueError, \
"unknown executable '%s' for class %s" % \ "unknown executable '%s' for class %s" % \
(key, self.__class__.__name__) (key, self.__class__.__name__)

View File

@ -362,7 +362,7 @@ def check_extensions_list (self, extensions):
# Medium-easy stuff: same syntax/semantics, different names. # Medium-easy stuff: same syntax/semantics, different names.
ext.runtime_library_dirs = build_info.get('rpath') ext.runtime_library_dirs = build_info.get('rpath')
if build_info.has_key('def_file'): if 'def_file' in build_info:
log.warn("'def_file' element of build info dict " log.warn("'def_file' element of build info dict "
"no longer supported") "no longer supported")

View File

@ -352,7 +352,7 @@ def dump_dirs (self, msg):
opt_name = opt[0] opt_name = opt[0]
if opt_name[-1] == "=": if opt_name[-1] == "=":
opt_name = opt_name[0:-1] opt_name = opt_name[0:-1]
if self.negative_opt.has_key(opt_name): if opt_name in self.negative_opt:
opt_name = string.translate(self.negative_opt[opt_name], opt_name = string.translate(self.negative_opt[opt_name],
longopt_xlate) longopt_xlate)
val = not getattr(self, opt_name) val = not getattr(self, opt_name)

View File

@ -120,7 +120,7 @@ def send_metadata(self):
# see if we can short-cut and get the username/password from the # see if we can short-cut and get the username/password from the
# config # config
config = None config = None
if os.environ.has_key('HOME'): if 'HOME' in os.environ:
rc = os.path.join(os.environ['HOME'], '.pypirc') rc = os.path.join(os.environ['HOME'], '.pypirc')
if os.path.exists(rc): if os.path.exists(rc):
print 'Using PyPI login from %s'%rc print 'Using PyPI login from %s'%rc
@ -163,7 +163,7 @@ def send_metadata(self):
print 'Server response (%s): %s'%(code, result) print 'Server response (%s): %s'%(code, result)
# possibly save the login # possibly save the login
if os.environ.has_key('HOME') and config is None and code == 200: if 'HOME' in os.environ and config is None and code == 200:
rc = os.path.join(os.environ['HOME'], '.pypirc') rc = os.path.join(os.environ['HOME'], '.pypirc')
print 'I can store your PyPI login so future submissions will be faster.' print 'I can store your PyPI login so future submissions will be faster.'
print '(the login will be stored in %s)'%rc print '(the login will be stored in %s)'%rc

View File

@ -46,7 +46,7 @@ def finalize_options(self):
raise DistutilsOptionError( raise DistutilsOptionError(
"Must use --sign for --identity to have meaning" "Must use --sign for --identity to have meaning"
) )
if os.environ.has_key('HOME'): if 'HOME' in os.environ:
rc = os.path.join(os.environ['HOME'], '.pypirc') rc = os.path.join(os.environ['HOME'], '.pypirc')
if os.path.exists(rc): if os.path.exists(rc):
self.announce('Using PyPI login from %s' % rc) self.announce('Using PyPI login from %s' % rc)

View File

@ -101,9 +101,9 @@ class found in 'cmdclass' is used in place of the default, which is
else: else:
klass = Distribution klass = Distribution
if not attrs.has_key('script_name'): if 'script_name' not in attrs:
attrs['script_name'] = os.path.basename(sys.argv[0]) attrs['script_name'] = os.path.basename(sys.argv[0])
if not attrs.has_key('script_args'): if 'script_args' not in attrs:
attrs['script_args'] = sys.argv[1:] attrs['script_args'] = sys.argv[1:]
# Create the Distribution instance, using the remaining arguments # Create the Distribution instance, using the remaining arguments
@ -111,7 +111,7 @@ class found in 'cmdclass' is used in place of the default, which is
try: try:
_setup_distribution = dist = klass(attrs) _setup_distribution = dist = klass(attrs)
except DistutilsSetupError, msg: except DistutilsSetupError, msg:
if attrs.has_key('name'): if 'name' in attrs:
raise SystemExit, "error in %s setup command: %s" % \ raise SystemExit, "error in %s setup command: %s" % \
(attrs['name'], msg) (attrs['name'], msg)
else: else:

View File

@ -207,7 +207,7 @@ def remove_tree (directory, verbose=0, dry_run=0):
apply(cmd[0], (cmd[1],)) apply(cmd[0], (cmd[1],))
# remove dir from cache if it's already there # remove dir from cache if it's already there
abspath = os.path.abspath(cmd[1]) abspath = os.path.abspath(cmd[1])
if _path_created.has_key(abspath): if abspath in _path_created:
del _path_created[abspath] del _path_created[abspath]
except (IOError, OSError), exc: except (IOError, OSError), exc:
log.warn(grok_environment_error( log.warn(grok_environment_error(

View File

@ -239,7 +239,7 @@ def __init__ (self, attrs=None):
for (opt, val) in cmd_options.items(): for (opt, val) in cmd_options.items():
opt_dict[opt] = ("setup script", val) opt_dict[opt] = ("setup script", val)
if attrs.has_key('licence'): if 'licence' in attrs:
attrs['license'] = attrs['licence'] attrs['license'] = attrs['licence']
del attrs['licence'] del attrs['licence']
msg = "'licence' distribution option is deprecated; use 'license'" msg = "'licence' distribution option is deprecated; use 'license'"
@ -343,7 +343,7 @@ def find_config_files (self):
user_filename = "pydistutils.cfg" user_filename = "pydistutils.cfg"
# And look for the user config file # And look for the user config file
if os.environ.has_key('HOME'): if 'HOME' in os.environ:
user_file = os.path.join(os.environ.get('HOME'), user_filename) user_file = os.path.join(os.environ.get('HOME'), user_filename)
if os.path.isfile(user_file): if os.path.isfile(user_file):
files.append(user_file) files.append(user_file)
@ -388,7 +388,7 @@ def parse_config_files (self, filenames=None):
# If there was a "global" section in the config file, use it # If there was a "global" section in the config file, use it
# to set Distribution options. # to set Distribution options.
if self.command_options.has_key('global'): if 'global' in self.command_options:
for (opt, (src, val)) in self.command_options['global'].items(): for (opt, (src, val)) in self.command_options['global'].items():
alias = self.negative_opt.get(opt) alias = self.negative_opt.get(opt)
try: try:
@ -907,7 +907,7 @@ def _set_command_options (self, command_obj, option_dict=None):
try: try:
is_string = type(value) is StringType is_string = type(value) is StringType
if neg_opt.has_key(option) and is_string: if option in neg_opt and is_string:
setattr(command_obj, neg_opt[option], not strtobool(value)) setattr(command_obj, neg_opt[option], not strtobool(value))
elif option in bool_opts and is_string: elif option in bool_opts and is_string:
setattr(command_obj, option, strtobool(value)) setattr(command_obj, option, strtobool(value))

View File

@ -97,7 +97,7 @@ def set_option_table (self, option_table):
self._build_index() self._build_index()
def add_option (self, long_option, short_option=None, help_string=None): def add_option (self, long_option, short_option=None, help_string=None):
if self.option_index.has_key(long_option): if long_option in self.option_index:
raise DistutilsGetoptError, \ raise DistutilsGetoptError, \
"option conflict: already an option '%s'" % long_option "option conflict: already an option '%s'" % long_option
else: else:
@ -109,7 +109,7 @@ def add_option (self, long_option, short_option=None, help_string=None):
def has_option (self, long_option): def has_option (self, long_option):
"""Return true if the option table for this parser has an """Return true if the option table for this parser has an
option with long name 'long_option'.""" option with long name 'long_option'."""
return self.option_index.has_key(long_option) return long_option in self.option_index
def get_attr_name (self, long_option): def get_attr_name (self, long_option):
"""Translate long option name 'long_option' to the form it """Translate long option name 'long_option' to the form it
@ -121,11 +121,11 @@ def get_attr_name (self, long_option):
def _check_alias_dict (self, aliases, what): def _check_alias_dict (self, aliases, what):
assert type(aliases) is DictionaryType assert type(aliases) is DictionaryType
for (alias, opt) in aliases.items(): for (alias, opt) in aliases.items():
if not self.option_index.has_key(alias): if alias not in self.option_index:
raise DistutilsGetoptError, \ raise DistutilsGetoptError, \
("invalid %s '%s': " ("invalid %s '%s': "
"option '%s' not defined") % (what, alias, alias) "option '%s' not defined") % (what, alias, alias)
if not self.option_index.has_key(opt): if opt not in self.option_index:
raise DistutilsGetoptError, \ raise DistutilsGetoptError, \
("invalid %s '%s': " ("invalid %s '%s': "
"aliased option '%s' not defined") % (what, alias, opt) "aliased option '%s' not defined") % (what, alias, opt)

View File

@ -252,7 +252,7 @@ def __init__ (self, verbose=0, dry_run=0, force=0):
def initialize(self): def initialize(self):
self.__paths = [] self.__paths = []
if os.environ.has_key("DISTUTILS_USE_SDK") and os.environ.has_key("MSSdk") and self.find_exe("cl.exe"): if "DISTUTILS_USE_SDK" in os.environ and "MSSdk" in os.environ and self.find_exe("cl.exe"):
# Assume that the SDK set up everything alright; don't try to be # Assume that the SDK set up everything alright; don't try to be
# smarter # smarter
self.cc = "cl.exe" self.cc = "cl.exe"

View File

@ -161,22 +161,22 @@ def customize_compiler(compiler):
get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
'CCSHARED', 'LDSHARED', 'SO') 'CCSHARED', 'LDSHARED', 'SO')
if os.environ.has_key('CC'): if 'CC' in os.environ:
cc = os.environ['CC'] cc = os.environ['CC']
if os.environ.has_key('CXX'): if 'CXX' in os.environ:
cxx = os.environ['CXX'] cxx = os.environ['CXX']
if os.environ.has_key('LDSHARED'): if 'LDSHARED' in os.environ:
ldshared = os.environ['LDSHARED'] ldshared = os.environ['LDSHARED']
if os.environ.has_key('CPP'): if 'CPP' in os.environ:
cpp = os.environ['CPP'] cpp = os.environ['CPP']
else: else:
cpp = cc + " -E" # not always cpp = cc + " -E" # not always
if os.environ.has_key('LDFLAGS'): if 'LDFLAGS' in os.environ:
ldshared = ldshared + ' ' + os.environ['LDFLAGS'] ldshared = ldshared + ' ' + os.environ['LDFLAGS']
if os.environ.has_key('CFLAGS'): if 'CFLAGS' in os.environ:
cflags = opt + ' ' + os.environ['CFLAGS'] cflags = opt + ' ' + os.environ['CFLAGS']
ldshared = ldshared + ' ' + os.environ['CFLAGS'] ldshared = ldshared + ' ' + os.environ['CFLAGS']
if os.environ.has_key('CPPFLAGS'): if 'CPPFLAGS' in os.environ:
cpp = cpp + ' ' + os.environ['CPPFLAGS'] cpp = cpp + ' ' + os.environ['CPPFLAGS']
cflags = cflags + ' ' + os.environ['CPPFLAGS'] cflags = cflags + ' ' + os.environ['CPPFLAGS']
ldshared = ldshared + ' ' + os.environ['CPPFLAGS'] ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
@ -291,12 +291,12 @@ def parse_makefile(fn, g=None):
if m: if m:
n = m.group(1) n = m.group(1)
found = True found = True
if done.has_key(n): if n in done:
item = str(done[n]) item = str(done[n])
elif notdone.has_key(n): elif n in notdone:
# get it on a subsequent round # get it on a subsequent round
found = False found = False
elif os.environ.has_key(n): elif n in os.environ:
# do it like make: fall back to environment # do it like make: fall back to environment
item = os.environ[n] item = os.environ[n]
else: else:
@ -380,7 +380,7 @@ def _init_posix():
# MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so # MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so
# it needs to be compatible. # it needs to be compatible.
# If it isn't set we set it to the configure-time value # If it isn't set we set it to the configure-time value
if sys.platform == 'darwin' and g.has_key('MACOSX_DEPLOYMENT_TARGET'): if sys.platform == 'darwin' and 'MACOSX_DEPLOYMENT_TARGET' in g:
cfg_target = g['MACOSX_DEPLOYMENT_TARGET'] cfg_target = g['MACOSX_DEPLOYMENT_TARGET']
cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '') cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '')
if cur_target == '': if cur_target == '':

View File

@ -89,7 +89,7 @@ def __init__ (self, filename=None, file=None, **options):
# set values for all options -- either from client option hash # set values for all options -- either from client option hash
# or fallback to default_options # or fallback to default_options
for opt in self.default_options.keys(): for opt in self.default_options.keys():
if options.has_key (opt): if opt in options:
setattr (self, opt, options[opt]) setattr (self, opt, options[opt])
else: else:
@ -97,7 +97,7 @@ def __init__ (self, filename=None, file=None, **options):
# sanity check client option hash # sanity check client option hash
for opt in options.keys(): for opt in options.keys():
if not self.default_options.has_key (opt): if opt not in self.default_options:
raise KeyError, "invalid TextFile option '%s'" % opt raise KeyError, "invalid TextFile option '%s'" % opt
if file is None: if file is None:

View File

@ -219,11 +219,11 @@ def check_environ ():
if _environ_checked: if _environ_checked:
return return
if os.name == 'posix' and not os.environ.has_key('HOME'): if os.name == 'posix' and 'HOME' not in os.environ:
import pwd import pwd
os.environ['HOME'] = pwd.getpwuid(os.getuid())[5] os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
if not os.environ.has_key('PLAT'): if 'PLAT' not in os.environ:
os.environ['PLAT'] = get_platform() os.environ['PLAT'] = get_platform()
_environ_checked = 1 _environ_checked = 1
@ -241,7 +241,7 @@ def subst_vars (s, local_vars):
check_environ() check_environ()
def _subst (match, local_vars=local_vars): def _subst (match, local_vars=local_vars):
var_name = match.group(1) var_name = match.group(1)
if local_vars.has_key(var_name): if var_name in local_vars:
return str(local_vars[var_name]) return str(local_vars[var_name])
else: else:
return os.environ[var_name] return os.environ[var_name]

View File

@ -423,6 +423,11 @@ Core and builtins
Library Library
------- -------
- Removed uses of dict.has_key() from distutils, and uses of
callable() from copy_reg.py, so the interpreter now starts up
without warnings when '-3' is given. More work like this needs to
be done in the rest of the stdlib.
- Issue #1916. Added isgenerator() and isgeneratorfunction() to inspect.py. - Issue #1916. Added isgenerator() and isgeneratorfunction() to inspect.py.
- #1224: Fixed bad url parsing when path begins with double slash. - #1224: Fixed bad url parsing when path begins with double slash.