Remove most map() and filter() usage

They aren't available on python3 so pylint complains, and list
comprehensions are usually better.
This commit is contained in:
Cole Robinson 2013-04-11 16:32:00 -04:00
parent c5e45ae448
commit a386186c74
29 changed files with 91 additions and 88 deletions

View File

@ -20,6 +20,8 @@ import os
import virtinst
from tests import utils
# pylint: disable=W0212
# Access to protected member, needed to unittest stuff
# Force certain helpers to return consistent values
virtinst.util.is_blktap_capable = lambda: False

View File

@ -58,7 +58,8 @@ class TestCapabilities(unittest.TestCase):
self.assertEqual(secmodel[0], caps.host.secmodel.model)
self.assertEqual(secmodel[1], caps.host.secmodel.doi)
map(self._compareGuest, guests, caps.guests)
for idx in range(len(guests)):
self._compareGuest(guests[idx], caps.guests[idx])
def testCapabilities1(self):
host = ( 'x86_64', {'vmx': capabilities.FEATURE_ON})
@ -216,7 +217,7 @@ class TestCapabilities(unittest.TestCase):
cpu_random = caps.get_cpu_values("mips")
def test_cpu_map(cpumap, vendors, features, cpus):
cpunames = sorted(map(lambda c: c.model, cpumap.cpus),
cpunames = sorted([c.model for c in cpumap.cpus],
key=str.lower)
for v in vendors:

View File

@ -25,6 +25,10 @@ from tests import utils
qemuuri = "__virtinst_test__test:///default,caps=%s/tests/capabilities-xml/capabilities-kvm.xml,qemu,predictable" % os.getcwd()
# pylint: disable=W0212
# Access to protected member, needed to unittest stuff
class TestImageParser(unittest.TestCase):
basedir = "tests/image-xml/"

View File

@ -23,6 +23,9 @@ from tests import utils
import libvirt
# pylint: disable=W0212
# Access to protected member, needed to unittest stuff
basepath = os.path.join(os.getcwd(), "tests", "storage-xml")
def generate_uuid_from_string(msg):

View File

@ -29,8 +29,7 @@ class TestSupport(unittest.TestCase):
Verify no support.SUPPORT* have the same value
"""
valdict = {}
supportnames = filter(lambda x: x.startswith("SUPPORT"),
dir(support))
supportnames = [x for x in dir(support) if x.startswith("SUPPORT")]
for supportname in supportnames:
checkval = int(getattr(support, supportname))

View File

@ -35,6 +35,9 @@ from virtinst.OSDistro import MandrivaDistro
import libvirt
import urlgrabber.progress
# pylint: disable=W0212
# Access to protected member, needed to unittest stuff
# Filters for including/excluding certain distros.
MATCH_FILTER = ".*"

View File

@ -26,6 +26,9 @@ from virtinst import VirtualAudio
from virtinst import VirtualDisk
from virtinst import VirtualVideoDevice
# pylint: disable=W0212
# Access to protected member, needed to unittest stuff
# Used to ensure consistent SDL xml output
os.environ["HOME"] = "/tmp"
os.environ["DISPLAY"] = ":3.4"

View File

@ -32,8 +32,12 @@ from virtinst import VirtualController
from virtinst import VirtualWatchdog
from virtinst import VirtualInputDevice
from virtinst import VirtualMemballoon
from tests import utils
# pylint: disable=W0212
# Access to protected member, needed to unittest stuff
_testconn = utils.open_testdriver()
_kvmconn = utils.open_testkvmdriver()
_plainkvm = utils.open_plainkvm()

View File

@ -50,7 +50,7 @@ class XMLParseTest(unittest.TestCase):
failed = False
error = ""
for f in glob.glob("tests/xmlconfig-xml/*.xml"):
if filter(f.endswith, exclude):
if [e for e in exclude if f.endswith(e)]:
continue
try:

View File

@ -239,9 +239,9 @@ def prompt_virt(caps, arch, req_virt_type, req_accel):
def get_virt_type(conn, options):
# Set up all virt/hypervisor parameters
if sum(map(bool, [options.fullvirt,
options.paravirt,
options.container])) > 1:
if sum([bool(f) for f in [options.fullvirt,
options.paravirt,
options.container]]) > 1:
fail(_("Can't do more than one of --hvm, --paravirt, or --container"))
capabilities = virtinst.CapabilitiesParser.parse(conn.getCapabilities())
@ -410,8 +410,8 @@ def check_option_collisions(options, guest):
return
# Install collisions
if sum(map(bool, [options.pxe, options.location,
options.cdrom, options.import_install])) > 1:
if sum([bool(l) for l in [options.pxe, options.location,
options.cdrom, options.import_install]]) > 1:
fail(_("Only one install method can be used (%(methods)s)") %
{"methods" : install_methods})

View File

@ -601,7 +601,7 @@ class vmmAddHardware(vmmGObjectUI):
sparse = not self.widget("config-storage-nosparse").get_active()
if self.is_default_storage():
pathlist = map(lambda d: d.path, self.vm.get_disk_devices())
pathlist = [d.path for d in self.vm.get_disk_devices()]
path = util.get_default_path(self.conn,
self.vm.get_name(),
collidelist=pathlist)

View File

@ -343,7 +343,7 @@ class vmmCloneVM(vmmGObjectUI):
storage_list = {}
# We need to determine which disks fail (and why).
all_targets = map(lambda d: d.target, diskinfos)
all_targets = [d.target for d in diskinfos]
for disk in diskinfos:
force_target = disk.target

View File

@ -297,8 +297,7 @@ class vmmConfig(object):
uri = GConf.escape_key(uri, len(uri))
key = self.conf_dir + "/connection_prefs/%s/vms" % uri
kill_vms = []
gconf_vms = map(lambda inp: inp.split("/")[-1],
self.conf.all_dirs(key))
gconf_vms = [inp.split("/")[-1] for inp in self.conf.all_dirs(key)]
for uuid in gconf_vms:
if len(uuid) == 36 and not uuid in current_vms:
@ -360,7 +359,7 @@ class vmmConfig(object):
return ret
def set_keys_combination(self, val):
# Val have to be a list of integers
val = ','.join(map(str, val))
val = ','.join([str(v) for v in val])
self.conf.set_string(self.conf_dir + "/keys/grab-keys", val)
def on_keys_combination_changed(self, cb, userdata=None):
return self.conf.notify_add(self.conf_dir + "/keys/grab-keys", cb, userdata)

View File

@ -325,7 +325,7 @@ class VNCViewer(Viewer):
return
try:
keys = map(int, keys.split(','))
keys = [int(k) for k in keys.split(',')]
except:
logging.debug("Error in grab_keys configuration in GConf",
exc_info=True)
@ -472,7 +472,7 @@ class SpiceViewer(Viewer):
return
try:
keys = map(int, keys.split(','))
keys = [int(k) for k in keys.split(',')]
except:
logging.debug("Error in grab_keys configuration in GConf",
exc_info=True)

View File

@ -504,7 +504,7 @@ class vmmCreate(vmmGObjectUI):
break
if not (is_container or
filter(lambda w: w.get_sensitive(), virt_methods)):
[w for w in virt_methods if w.get_sensitive()]):
return self.startup_error(
_("No install methods available for this connection."),
hideinstall=False)

View File

@ -627,7 +627,7 @@ class vmmCreateInterface(vmmGObjectUI):
def get_config_ipv6_addresses(self):
src = self.widget("ipv6-address-list")
model = src.get_model()
return map(lambda x: x[0], model)
return [x[0] for x in model]
################
# UI Listeners #
@ -818,7 +818,7 @@ class vmmCreateInterface(vmmGObjectUI):
if v6_gate:
ipv6.gateway = v6_gate
if v6_addrlist:
ipv6.ips = map(build_ip, v6_addrlist)
ipv6.ips = [build_ip(i) for i in v6_addrlist]
return [is_manual, copy_name, ipv4, ipv6, proto_xml]
@ -924,7 +924,7 @@ class vmmCreateInterface(vmmGObjectUI):
# Pull info from selected interfaces
if hasattr(iobj, "interfaces"):
iobj.interfaces = map(lambda x: x[INTERFACE_ROW_KEY], ifaces)
iobj.interfaces = [x[INTERFACE_ROW_KEY] for x in ifaces]
check_conflict = True
elif hasattr(iobj, "parent_interface"):

View File

@ -206,8 +206,8 @@ class vmmCreatePool(vmmGObjectUI):
elif self._pool.type == Storage.StoragePool.TYPE_LOGICAL:
pool_list = self.list_pool_sources()
entry_list = map(lambda p: [p.target_path, p.target_path, p],
pool_list)
entry_list = [[p.target_path, p.target_path, p]
for p in pool_list]
use_list = target_list
use_model = target_model
@ -220,8 +220,8 @@ class vmmCreatePool(vmmGObjectUI):
host = self.get_config_host()
if host:
pool_list = self.list_pool_sources(host=host)
entry_list = map(lambda p: [p.source_path, p.source_path, p],
pool_list)
entry_list = [[p.source_path, p.source_path, p]
for p in pool_list]
use_list = source_list
use_model = source_model
@ -233,7 +233,7 @@ class vmmCreatePool(vmmGObjectUI):
def list_scsi_adapters(self):
scsi_hosts = self.conn.get_nodedevs("scsi_host")
host_list = map(lambda dev: dev.host, scsi_hosts)
host_list = [dev.host for dev in scsi_hosts]
clean_list = []
for h in host_list:
@ -243,7 +243,7 @@ class vmmCreatePool(vmmGObjectUI):
tmppool.source_path = name
entry = [name, name, tmppool]
if name not in map(lambda l: l[0], clean_list):
if name not in [l[0] for l in clean_list]:
clean_list.append(entry)
return clean_list
@ -263,7 +263,7 @@ class vmmCreatePool(vmmGObjectUI):
tmppool.source_path = dev
entry = [dev, dev, tmppool]
if dev not in map(lambda l: l[0], clean_list):
if dev not in [l[0] for l in clean_list]:
clean_list.append(entry)
return clean_list

View File

@ -677,18 +677,17 @@ class vmmDetails(vmmGObjectUI):
self.disk_io_graph.set_property("reversed", True)
self.disk_io_graph.set_property("filled", False)
self.disk_io_graph.set_property("num_sets", 2)
self.disk_io_graph.set_property("rgb", map(lambda x: x / 255.0,
[0x82, 0x00, 0x3B, 0x29, 0x5C, 0x45]))
self.disk_io_graph.set_property("rgb", [x / 255.0 for x in
[0x82, 0x00, 0x3B, 0x29, 0x5C, 0x45]])
graph_table.attach(self.disk_io_graph, 1, 2, 2, 3)
self.network_traffic_graph = Sparkline()
self.network_traffic_graph.set_property("reversed", True)
self.network_traffic_graph.set_property("filled", False)
self.network_traffic_graph.set_property("num_sets", 2)
self.network_traffic_graph.set_property("rgb",
map(lambda x: x / 255.0,
self.network_traffic_graph.set_property("rgb", [x / 255.0 for x in
[0x82, 0x00, 0x3B,
0x29, 0x5C, 0x45]))
0x29, 0x5C, 0x45]])
graph_table.attach(self.network_traffic_graph, 1, 2, 3, 4)
graph_table.show_all()
@ -862,7 +861,7 @@ class vmmDetails(vmmGObjectUI):
try:
cpu_values = caps.get_cpu_values(self.vm.get_arch())
cpu_names = sorted(map(lambda c: c.model, cpu_values.cpus),
cpu_names = sorted([c.model for c in cpu_values.cpus],
key=str.lower)
all_features = cpu_values.features
except:
@ -1020,7 +1019,7 @@ class vmmDetails(vmmGObjectUI):
if comparefunc:
model_in_list, idx = comparefunc(model_combo.get_model(), value)
else:
model_list = map(lambda x: x[model_idx], model_combo.get_model())
model_list = [x[model_idx] for x in model_combo.get_model()]
model_in_list = (value in model_list)
if model_in_list:
idx = model_list.index(value)
@ -2355,14 +2354,11 @@ class vmmDetails(vmmGObjectUI):
# Graphics options
def _do_change_spicevmc(self, gdev, newgtype):
has_multi_spice = (len(filter(
lambda dev: dev.type == dev.TYPE_SPICE,
self.vm.get_graphics_devices())) > 1)
has_spicevmc = bool(filter(
(lambda dev:
(dev.dev_type == dev.DEV_CHANNEL and
dev.char_type == dev.CHAR_SPICEVMC)),
self.vm.get_char_devices()))
has_multi_spice = (len([d for d in self.vm.get_graphics_devices() if
d.type == d.TYPE_SPICE]) > 1)
has_spicevmc = bool([d for d in self.vm.get_char_devices() if
(d.dev_type == d.DEV_CHANNEL and
d.char_type == d.CHAR_SPICEVMC)])
fromspice = (gdev.type == "spice")
tospice = (newgtype == "spice")
@ -3605,7 +3601,7 @@ class vmmDetails(vmmGObjectUI):
def repopulate_boot_list(self, bootdevs=None, dev_select=None):
boot_list = self.widget("config-boot-list")
boot_model = boot_list.get_model()
old_order = map(lambda x: x[BOOT_DEV_TYPE], boot_model)
old_order = [x[BOOT_DEV_TYPE] for x in boot_model]
boot_model.clear()
if bootdevs is None:

View File

@ -711,10 +711,9 @@ class vmmDomain(vmmLibvirtObject):
guest.add_device(VirtualCharSpicevmcDevice(guest.conn))
else:
channels = guest.get_devices("channel")
channels = filter(lambda x:
channels = [x for x in channels if
(x.char_type ==
virtinst.VirtualCharDevice.CHAR_SPICEVMC),
channels)
virtinst.VirtualCharDevice.CHAR_SPICEVMC)]
for dev in channels:
guest.remove_device(dev)
@ -779,9 +778,8 @@ class vmmDomain(vmmLibvirtObject):
guest = self._get_guest_to_define()
ctrls = guest.get_devices("controller")
ctrls = filter(lambda x: (x.type ==
virtinst.VirtualController.CONTROLLER_TYPE_USB),
ctrls)
ctrls = [x for x in ctrls if (x.type ==
virtinst.VirtualController.CONTROLLER_TYPE_USB)]
for dev in ctrls:
guest.remove_device(dev)
@ -1006,8 +1004,8 @@ class vmmDomain(vmmLibvirtObject):
devs = self.get_char_devices()
devlist = []
devlist += filter(lambda x: x.virtual_device_type == "serial", devs)
devlist += filter(lambda x: x.virtual_device_type == "console", devs)
devlist += [x for x in devs if x.virtual_device_type == "serial"]
devlist += [x for x in devs if x.virtual_device_type == "console"]
return devlist
def _build_device_list(self, device_type,
@ -1342,7 +1340,7 @@ class vmmDomain(vmmLibvirtObject):
if l > limit:
data = data[0:end] + data[l:l + end]
return map(lambda x, y: (x + y) / 2, data[0:end], data[end:end * 2])
return [(x + y) / 2 for x, y in zip(data[0:end], data[end:end * 2])]
def toggle_sample_network_traffic(self, ignore1=None, ignore2=None,
ignore3=None, ignore4=None):

View File

@ -124,7 +124,7 @@ class vmmInterface(vmmLibvirtObject):
def node_func(ctx):
nodes = ctx.xpathEval(xpath)
names = map(lambda x: x.content, nodes)
names = [x.content for x in nodes]
ret = []
for name in names:
@ -144,8 +144,7 @@ class vmmInterface(vmmLibvirtObject):
def get_slave_names(self):
# Returns a list of names of all enslaved interfaces
slaves = self.get_slaves()
return map(lambda x: x[0], slaves)
return [x[0] for x in self.get_slaves()]
def get_ipv4(self):
base_xpath = "/interface/protocol[@family='ipv4']"

View File

@ -68,7 +68,7 @@ def check_packagekit(errbox, packages, ishv):
found = progWin.get_data()
not_found = filter(lambda x: x not in found, packages)
not_found = [x for x in packages if x not in found]
logging.debug("Missing packages: %s", not_found)
do_install = not_found

View File

@ -247,13 +247,13 @@ class vmmPreferences(vmmGObjectUI):
return keystr
def grabkeys_dlg_press(self, src_ignore, event, label, events):
if not filter(lambda e: e[0] == event.hardware_keycode, events):
if not [e for e in events if e[0] == event.hardware_keycode]:
events.append((event.hardware_keycode, event.keyval))
label.set_text(self.grabkeys_get_string(events))
def grabkeys_dlg_release(self, src_ignore, event, label, events):
for e in filter(lambda e: e[0] == event.hardware_keycode, events):
for e in [e for e in events if e[0] == event.hardware_keycode]:
events.remove(e)
label.set_text(self.grabkeys_get_string(events))
@ -288,7 +288,7 @@ class vmmPreferences(vmmGObjectUI):
result = dialog.run()
if result == Gtk.ResponseType.ACCEPT:
self.config.set_keys_combination(map(lambda e: e[1], events))
self.config.set_keys_combination([e[1] for e in events])
self.refresh_grabkeys_combination()
dialog.destroy()

View File

@ -146,10 +146,10 @@ def build_video_combo(vm, video_dev, no_default=None):
def populate_video_combo(vm, video_dev, no_default=None):
video_dev_model = video_dev.get_model()
has_spice = any(map(lambda g: g.type == g.TYPE_SPICE,
vm.get_graphics_devices()))
has_qxl = any(map(lambda v: v.model_type == "qxl",
vm.get_video_devices()))
has_spice = bool([g for g in vm.get_graphics_devices()
if g.type == g.TYPE_SPICE])
has_qxl = bool([v for v in vm.get_video_devices()
if v.model_type == "qxl"])
video_dev_model.clear()
tmpdev = virtinst.VirtualVideoDevice(vm.conn.vmm)
@ -508,7 +508,7 @@ def populate_network_list(net_list, conn, show_direct_interfaces=True):
def add_dict(indict, model):
keylist = indict.keys()
keylist.sort()
rowlist = map(lambda key: indict[key], keylist)
rowlist = [indict[k] for k in keylist]
for row in rowlist:
model.append(row)

View File

@ -169,7 +169,7 @@ def parse_vmdk(disk, filename):
filename)
return
disklines = filter(lambda l: l.is_disk, vmdkfile.lines)
disklines = [l for l in vmdkfile.lines if l.is_disk]
if len(disklines) == 0:
raise RuntimeError(_("Didn't detect a storage line in the VMDK "
"descriptor file"))

View File

@ -30,12 +30,10 @@ import libxml2
from virtinst import util
from virtinst import CapabilitiesParser
from virtinst import VirtualGraphics
from virtinst import support
from virtinst import XMLBuilderDomain
import virtinst
from virtinst.XMLBuilderDomain import _xml_property
from virtinst import DistroInstaller
from virtinst.VirtualDevice import VirtualDevice
from virtinst.VirtualDisk import VirtualDisk
from virtinst.VirtualInputDevice import VirtualInputDevice
@ -234,10 +232,10 @@ class Guest(XMLBuilderDomain.XMLBuilderDomain):
return
if not self.installer:
i = DistroInstaller.DistroInstaller(type=type,
conn=conn,
os_type=self._default_os_type,
caps=self._get_caps())
i = virtinst.DistroInstaller(type=type,
conn=conn,
os_type=self._default_os_type,
caps=self._get_caps())
self.installer = i
# Add default devices (if applicable)
@ -580,7 +578,7 @@ class Guest(XMLBuilderDomain.XMLBuilderDomain):
raise ValueError(_("Graphics enabled must be True or False"))
if enabled:
gdev = VirtualGraphics.VirtualGraphics(type=gtype)
gdev = virtinst.VirtualGraphics(type=gtype)
if port:
gdev.port = port
if keymap:
@ -791,9 +789,9 @@ class Guest(XMLBuilderDomain.XMLBuilderDomain):
if node.name != "devices":
continue
children = filter(lambda x: (x.name in device_mappings and
x.parent == node),
node.children)
children = [x for x in node.children if
(x.name in device_mappings and
x.parent == node)]
for devnode in children:
objclass = device_mappings.get(devnode.name)

View File

@ -39,14 +39,8 @@ LIBVIRT_SCRATCH = "/var/lib/libvirt/boot"
def _pygrub_path(conn=None):
"""
Return the pygrub path for the current host, or connection if
available.
"""
# FIXME: This should be removed/deprecated when capabilities are
# fixed to provide bootloader info
from virtinst import CapabilitiesParser
if conn:
cap = CapabilitiesParser.parse(conn.getCapabilities())
if (cap.host.arch == "i86pc"):

View File

@ -30,7 +30,7 @@ class PXEInstaller(Installer.Installer):
bootdev = self.bootconfig.BOOT_DEVICE_NETWORK
if (not isinstall and
filter(lambda d: d.device == d.DEVICE_DISK, guest.disks)):
[d for d in guest.disks if d.device == d.DEVICE_DISK]):
# If doing post-install boot and guest has an HD attached
bootdev = self.bootconfig.BOOT_DEVICE_HARDDISK

View File

@ -857,7 +857,7 @@ def digest_networks(guest, options, numnics=1):
if bridges:
# Convert old --bridges to --networks
networks = map(lambda b: "bridge:" + b, bridges)
networks = ["bridge:" + b for b in bridges]
def padlist(l, padsize):
l = listify(l)
@ -909,7 +909,7 @@ def digest_graphics(guest, options, default_override=None):
if graphics and (vnc or sdl or keymap or vncport or vnclisten):
fail(_("Cannot mix --graphics and old style graphical options"))
optnum = sum(map(bool, [vnc, nographics, sdl, graphics]))
optnum = sum([bool(g) for g in [vnc, nographics, sdl, graphics]])
if optnum > 1:
raise ValueError(_("Can't specify more than one of VNC, SDL, "
"--graphics or --nographics"))
@ -1359,7 +1359,7 @@ def parse_boot(guest, optstring):
Helper to parse --boot string
"""
opts = parse_optstr(optstring)
optlist = map(lambda x: x[0], parse_optstr_tuples(optstring))
optlist = [x[0] for x in parse_optstr_tuples(optstring)]
menu = None
def set_param(paramname, dictname, val=None):
@ -1482,7 +1482,7 @@ def _parse_disk_source(guest, path, pool, vol, size, fmt, sparse):
volobj = None
# Strip media type
if sum(map(int, map(bool, [path, pool, vol]))) > 1:
if sum([bool(p) for p in [path, pool, vol]]) > 1:
fail(_("Cannot specify more than 1 storage path"))
if path:

View File

@ -542,7 +542,7 @@ def randomMAC(type="xen", conn=None):
random.randint(0x00, 0xff),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff)]
return ':'.join(map(lambda x: "%02x" % x, mac))
return ':'.join(["%02x" % x for x in mac])
# the following three functions are from xend/uuid.py and are thus