Skip to content

trim six usage #1082

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions pyVim/sso.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@
#Standard library imports.
from six.moves.http_client import HTTPConnection, HTTPSConnection
import re
from six import PY3
if PY3:
from html import escape
else:
from cgi import escape
from html import escape
import datetime
import base64
import hashlib
Expand All @@ -25,7 +21,7 @@

from uuid import uuid4
from io import BytesIO
from six.moves.urllib.parse import urlparse
from urllib.parse import urlparse
#Third-party imports.
from lxml import etree
from OpenSSL import crypto
Expand Down
7 changes: 2 additions & 5 deletions pyVmomi/Differ.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@

import logging

import six
from six.moves import zip

from .VmomiSupport import F_LINK, F_OPTIONAL, GetWsdlName, Type, types

__Log__ = logging.getLogger('ObjDiffer')
Expand All @@ -23,9 +20,9 @@ def IsPrimitiveType(obj):
"""See if the passed in type is a Primitive Type"""
return (isinstance(obj, types.bool) or isinstance(obj, types.byte)
or isinstance(obj, types.short)
or isinstance(obj, six.integer_types)
or isinstance(obj, int)
or isinstance(obj, types.double) or isinstance(obj, types.float)
or isinstance(obj, six.string_types)
or isinstance(obj, str)
or isinstance(obj, types.PropertyPath)
or isinstance(obj, types.ManagedMethod)
or isinstance(obj, types.datetime) or isinstance(obj, types.URI)
Expand Down
4 changes: 1 addition & 3 deletions pyVmomi/Iso8601.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
import time
from datetime import datetime, timedelta, tzinfo

import six

# Regular expression to parse a subset of ISO 8601 format
_dtExpr = re.compile(
# XMLSchema datetime. Mandatory to have - and :
Expand Down Expand Up @@ -112,7 +110,7 @@ def ParseISO8601(datetimeStr):
if match:
try:
dt = {}
for key, defaultVal in six.iteritems(_dtExprKeyDefValMap):
for key, defaultVal in _dtExprKeyDefValMap.items():
val = match.group(key)
if val:
if key == 'microsecond':
Expand Down
25 changes: 11 additions & 14 deletions pyVmomi/SoapAdapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,12 @@
import threading
import time
from datetime import datetime
from io import StringIO
from xml.parsers.expat import ExpatError, ParserCreate
# For Visor, space is very limited. Import xml.sax pull in too much junk.
# Define our own xml escape instead
# from xml.sax.saxutils import escape

import six
from six import PY3
from six.moves import StringIO, zip
from six.moves.urllib.parse import urlparse
from six.moves.http_cookies import SimpleCookie
from six.moves.http_client import (HTTPConnection, HTTPSConnection,
Expand Down Expand Up @@ -74,7 +72,7 @@

NSMAP_DEF = ' '.join([
'xmlns:{}="{}"'.format(prefix, urn)
for urn, prefix in six.iteritems(SOAP_NSMAP)
for urn, prefix in SOAP_NSMAP.items()
])

SOAP_ENVELOPE_START = '<{} {}>\n'.format(SOAP_ENVELOPE_TAG, NSMAP_DEF)
Expand Down Expand Up @@ -286,7 +284,7 @@ def __init__(self, writer, version, nsMap, encoding=None):
self.writer = writer
self.version = version
self.nsMap = nsMap and nsMap or {}
for ns, prefix in six.iteritems(self.nsMap):
for ns, prefix in self.nsMap.items():
if prefix == '':
self.defaultNS = ns
break
Expand Down Expand Up @@ -485,7 +483,7 @@ def _Serialize(self, val, info, defNS):
attr += '{0} {1}type="{2}"'.format(
nsattr, self.xsiPrefix, qName)
result = base64.b64encode(val)
if PY3:
if True:
# In python3 the bytes result after the base64 encoding has a
# leading 'b' which causes error when we use it to construct
# the soap message. Workaround the issue by converting the
Expand All @@ -503,12 +501,12 @@ def _Serialize(self, val, info, defNS):
result = val and "true" or "false"
self.writer.write('<{0}{1}>{2}</{0}>'.format(
info.name, attr, result))
elif isinstance(val, six.integer_types) or isinstance(val, float):
elif isinstance(val, int) or isinstance(val, float):
if info.type is object:
nsattr, qName = self._QName(Type(val), currDefNS)
attr += '{0} {1}type="{2}"'.format(
nsattr, self.xsiPrefix, qName)
result = six.text_type(val)
result = str(val)
self.writer.write('<{0}{1}>{2}</{0}>'.format(
info.name, attr, result))
elif isinstance(val, Enum):
Expand All @@ -528,7 +526,7 @@ def _Serialize(self, val, info, defNS):
attr += '{0} {1}type="{2}"'.format(
nsattr, self.xsiPrefix, qName)

if isinstance(val, six.binary_type):
if isinstance(val, bytes):
# Use UTF-8 rather than self.encoding. self.encoding is for
# output of serializer, while 'val' is our input.
# And regardless of what our output is, our input should be
Expand Down Expand Up @@ -589,7 +587,7 @@ def Deserialize(data, resultType=object, stub=None):
# But in python3 the input become unicode and the handling will fall into
# ParseFile case.
# Adding unicode input support to make it more test friendly.
if isinstance(data, six.binary_type) or isinstance(data, six.text_type):
if isinstance(data, bytes) or isinstance(data, str):
parser.Parse(data)
else:
parser.ParseFile(data)
Expand Down Expand Up @@ -917,8 +915,7 @@ def Deserialize(self, response, resultType, nsMap=None):
# purpose. But in python3 the input become unicode and the handling
# will fall into ParseFile case.
# Adding unicode input support to make it more test friendly.
if isinstance(response, six.binary_type) or isinstance(
response, six.text_type):
if isinstance(response, (bytes, str)):
self.parser.Parse(response)
else:
self.parser.ParseFile(response)
Expand Down Expand Up @@ -1019,9 +1016,9 @@ def SerializeRequest(self, mo, info, args):

if reqContexts or samlToken:
result.append(SOAP_HEADER_START)
for key, val in six.iteritems(reqContexts):
for key, val in reqContexts.items():
# Note: Support req context of string type only
if not isinstance(val, six.string_types):
if not isinstance(val, str):
raise TypeError(
"Request context key ({0}) has non-string value"
" ({1}) of {2}".format(key, val, type(val)))
Expand Down
5 changes: 2 additions & 3 deletions pyVmomi/VmomiJSONEncoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import json

from datetime import datetime
from six import PY3

from . import Iso8601
from .VmomiSupport import ManagedObject, DataObject, ManagedMethod, \
Expand Down Expand Up @@ -91,8 +90,8 @@ def default(self, obj): # pylint: disable=method-hidden
return self._remove_empty_dynamic_if(result)
if isinstance(obj, binary):
result = base64.b64encode(obj)
if PY3: # see VmomiSupport.FormatObject
result = str(result, 'utf-8')
# see VmomiSupport.FormatObject
result = str(result, 'utf-8')
return result
if isinstance(obj, datetime):
return Iso8601.ISO8601Format(obj)
Expand Down
46 changes: 19 additions & 27 deletions pyVmomi/VmomiSupport.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,14 @@
from functools import partial
from sys import version_info

import six
from six import PY3, binary_type, string_types
from six.moves import map, range
from six import PY3, binary_type

from . import Iso8601
from . import _allowGetSet
from . import _allowCapitalizedNames
from . import _binaryIsBytearray

if version_info[0] >= 3:
from functools import cmp_to_key
from functools import cmp_to_key
NoneType = type(None)

try:
Expand Down Expand Up @@ -171,13 +168,13 @@ def __getattr__(self, attr):
raise AttributeError(attr)


class Link(six.text_type):
class Link(str):
def __new__(cls, obj):
if isinstance(obj, string_types):
return six.text_type.__new__(cls, obj)
if isinstance(obj, str):
return str.__new__(cls, obj)
elif isinstance(obj, DataObject):
if obj.key:
return six.text_type.__new__(cls, obj.key)
return str.__new__(cls, obj.key)
raise AttributeError("DataObject does not have a key to link")
else:
raise ValueError
Expand Down Expand Up @@ -1099,8 +1096,8 @@ def _areBasicTypes(info, valType):
or issubclass(info, long) and (issubclass(valType, int)
or issubclass(valType, long))
or issubclass(info, float) and issubclass(valType, float)
or issubclass(info, string_types) and issubclass(valType, string_types)
or issubclass(info, binary_type) and issubclass(valType, binary_type))
or issubclass(info, str) and issubclass(valType, str)
or issubclass(info, bytes) and issubclass(valType, bytes))


# Check that a value matches a given type, and annotate if neccesary
Expand Down Expand Up @@ -1142,7 +1139,7 @@ def CheckField(info, val):
if issubclass(valType, GetVmodlType(info.expectedType)):
return
elif issubclass(info.type.Item, Enum) and issubclass(
valType.Item, string_types):
valType.Item, str):
# Allow String array object to be assigned to enum array
return
elif val:
Expand Down Expand Up @@ -1286,7 +1283,7 @@ def GetWsdlTypes():
with _lazyLock:
for ns, name in _wsdlDefMap:
GetWsdlType(ns, name)
return six.itervalues(_wsdlTypeMap)
return _wsdlTypeMap.values()


# Get the qualified XML schema name (ns, name) of a type
Expand Down Expand Up @@ -1438,14 +1435,9 @@ def compare(a, b):
return 1
return (a > b) - (a < b)

if version_info[0] >= 3:
return sorted(
[v for (v, n) in six.iteritems(serviceNsMap) if n == namespace],
return sorted(
[v for (v, n) in serviceNsMap.items() if n == namespace],
key=cmp_to_key(compare))
else:
return sorted(
[v for (v, n) in six.iteritems(serviceNsMap) if n == namespace],
compare)


# Set a WSDL method with wsdl namespace and wsdl name
Expand Down Expand Up @@ -1549,7 +1541,7 @@ def GetCompatibleType(type, version):

# Invert an injective mapping
def InverseMap(map):
return dict([(v, k) for (k, v) in six.iteritems(map)])
return dict([(v, k) for (k, v) in map.items()])


def GetVmodlNs(version):
Expand Down Expand Up @@ -1702,7 +1694,7 @@ def EnumerateWireIds(self):
binary = type("binary", (bytearray,), {})
else:
binary = type("binary", (binary_type,), {})
PropertyPath = type("PropertyPath", (six.text_type, ), {})
PropertyPath = type("PropertyPath", (str, ), {})

# _wsdlTypeMapNSs store namespaces added to _wsdlTypeMap in _SetWsdlType
_wsdlTypeMapNSs = set()
Expand Down Expand Up @@ -1759,8 +1751,8 @@ def EnumerateWireIds(self):

# unicode is mapped to wsdl name 'string' (Cannot put in wsdlTypeMap or name
# collision with non-unicode string)
_wsdlNameMap[six.text_type] = (XMLNS_XSD, 'string')
_wsdlNameMap[CreateArrayType(six.text_type)] = (XMLNS_VMODL_BASE,
_wsdlNameMap[str] = (XMLNS_XSD, 'string')
_wsdlNameMap[CreateArrayType(str)] = (XMLNS_VMODL_BASE,
'ArrayOfString')

# _wsdlMethodNSs store namespaces added to _wsdlMethodMap in _SetWsdlMethod
Expand Down Expand Up @@ -1806,7 +1798,7 @@ def EnumerateWireIds(self):


# Add array type into special names
for name, typ in six.iteritems(vmodlTypes.copy()):
for name, typ in vmodlTypes.copy().items():
if typ is not NoneType:
try:
arrayType = typ.Array
Expand Down Expand Up @@ -1976,7 +1968,7 @@ def __init__(self, *args, **kwargs):

# Same as dict setdefault, except this will call through our __setitem__
def update(self, *args, **kwargs):
for k, v in six.iteritems(dict(*args, **kwargs)):
for k, v in dict(*args, **kwargs).items():
self[k] = v

# Same as dict setdefault, except this will call through our __setitem__
Expand All @@ -1989,7 +1981,7 @@ def setdefault(self, key, val=None):

def __setitem__(self, key, val):
"""x.__setitem__(i, y) <==> x[i]=y, where y must be a string"""
if not isinstance(val, string_types):
if not isinstance(val, str):
raise TypeError("key %s has non-string value %s of %s" %
(key, val, type(val)))
return dict.__setitem__(self, key, val)
Expand Down
6 changes: 1 addition & 5 deletions tests/test_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,11 @@
import tests
import unittest
import sys
from unittest.mock import patch, MagicMock

from pyVim import connect
from pyVmomi import vim

if sys.version_info >= (3, 3):
from unittest.mock import patch, MagicMock
else:
from mock import patch, MagicMock


class ConnectionTests(tests.VCRTestBase):

Expand Down