Skip to content
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

Chore: Reduce 'six' usage #777

Merged
merged 8 commits into from
Jul 15, 2024
Merged
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
6 changes: 2 additions & 4 deletions client/ayon_core/addon/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@
import threading
import collections
from uuid import uuid4
from abc import ABCMeta, abstractmethod
from abc import ABC, abstractmethod

import six
import appdirs
import ayon_api
from semver import VersionInfo
Expand Down Expand Up @@ -499,8 +498,7 @@ def is_func_marked(func):
return getattr(func, _MARKING_ATTR, False)


@six.add_metaclass(ABCMeta)
class AYONAddon(object):
class AYONAddon(ABC):
"""Base class of AYON addon.

Attributes:
Expand Down
5 changes: 1 addition & 4 deletions client/ayon_core/addon/interfaces.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from abc import ABCMeta, abstractmethod

import six

from ayon_core import resources


Expand All @@ -15,8 +13,7 @@ def __repr__(self):
return str(self)


@six.add_metaclass(_AYONInterfaceMeta)
class AYONInterface:
class AYONInterface(metaclass=_AYONInterfaceMeta):
"""Base class of Interface that can be used as Mixin with abstract parts.

This is way how AYON addon can define that contains specific predefined
Expand Down
7 changes: 2 additions & 5 deletions client/ayon_core/host/dirmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,15 @@
"""

import os
from abc import ABCMeta, abstractmethod
from abc import ABC, abstractmethod
import platform

import six

from ayon_core.lib import Logger
from ayon_core.addon import AddonsManager
from ayon_core.settings import get_project_settings


@six.add_metaclass(ABCMeta)
class HostDirmap(object):
class HostDirmap(ABC):
"""Abstract class for running dirmap on a workfile in a host.

Dirmap is used to translate paths inside of host workfile from one
Expand Down
6 changes: 2 additions & 4 deletions client/ayon_core/host/host.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import os
import logging
import contextlib
from abc import ABCMeta, abstractproperty
import six
from abc import ABC, abstractproperty

# NOTE can't import 'typing' because of issues in Maya 2020
# - shiboken crashes on 'typing' module import


@six.add_metaclass(ABCMeta)
class HostBase(object):
class HostBase(ABC):
"""Base of host implementation class.

Host is pipeline implementation of DCC application. This class should help
Expand Down
6 changes: 2 additions & 4 deletions client/ayon_core/host/interfaces.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from abc import ABCMeta, abstractmethod
import six
from abc import ABC, abstractmethod


class MissingMethodsError(ValueError):
Expand Down Expand Up @@ -106,8 +105,7 @@ def ls(self):
return self.get_containers()


@six.add_metaclass(ABCMeta)
class IWorkfileHost:
class IWorkfileHost(ABC):
"""Implementation requirements to be able use workfile utils and tool."""

@staticmethod
Expand Down
24 changes: 11 additions & 13 deletions client/ayon_core/lib/attribute_definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import copy
from abc import ABCMeta, abstractmethod, abstractproperty

import six
import clique

# Global variable which store attribute definitions by type
Expand Down Expand Up @@ -91,8 +90,7 @@ def __call__(self, *args, **kwargs):
return obj


@six.add_metaclass(AbstractAttrDefMeta)
class AbstractAttrDef(object):
class AbstractAttrDef(metaclass=AbstractAttrDefMeta):
"""Abstraction of attribute definition.

Each attribute definition must have implemented validation and
Expand Down Expand Up @@ -349,7 +347,7 @@ def __eq__(self, other):
)

def convert_value(self, value):
if isinstance(value, six.string_types):
if isinstance(value, str):
try:
value = float(value)
except Exception:
Expand Down Expand Up @@ -396,12 +394,12 @@ def __init__(
if multiline is None:
multiline = False

elif not isinstance(default, six.string_types):
elif not isinstance(default, str):
raise TypeError((
"'default' argument must be a {}, not '{}'"
).format(six.string_types, type(default)))
f"'default' argument must be a str, not '{type(default)}'"
))

if isinstance(regex, six.string_types):
if isinstance(regex, str):
regex = re.compile(regex)

self.multiline = multiline
Expand All @@ -418,7 +416,7 @@ def __eq__(self, other):
)

def convert_value(self, value):
if isinstance(value, six.string_types):
if isinstance(value, str):
return value
return self.default

Expand Down Expand Up @@ -736,7 +734,7 @@ def from_value(cls, value, allow_sequences):
else:
output.append(item)

elif isinstance(item, six.string_types):
elif isinstance(item, str):
str_filepaths.append(item)
else:
raise TypeError(
Expand Down Expand Up @@ -844,7 +842,7 @@ def __init__(
if isinstance(default, dict):
FileDefItem.from_dict(default)

elif isinstance(default, six.string_types):
elif isinstance(default, str):
default = FileDefItem.from_paths([default.strip()])[0]

else:
Expand Down Expand Up @@ -883,14 +881,14 @@ def __eq__(self, other):
)

def convert_value(self, value):
if isinstance(value, six.string_types) or isinstance(value, dict):
if isinstance(value, (str, dict)):
value = [value]

if isinstance(value, (tuple, list, set)):
string_paths = []
dict_items = []
for item in value:
if isinstance(item, six.string_types):
if isinstance(item, str):
string_paths.append(item.strip())
elif isinstance(item, dict):
try:
Expand Down
16 changes: 8 additions & 8 deletions client/ayon_core/lib/file_transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import logging
import sys
import errno
import six

from ayon_core.lib import create_hard_link

Expand Down Expand Up @@ -158,11 +157,13 @@ def finalize(self):

def rollback(self):
errors = 0
last_exc = None
# Rollback any transferred files
for path in self._transferred:
try:
os.remove(path)
except OSError:
except OSError as exc:
last_exc = exc
errors += 1
self.log.error(
"Failed to rollback created file: {}".format(path),
Expand All @@ -172,7 +173,8 @@ def rollback(self):
for backup, original in self._backup_to_original.items():
try:
os.rename(backup, original)
except OSError:
except OSError as exc:
last_exc = exc
errors += 1
self.log.error(
"Failed to restore original file: {} -> {}".format(
Expand All @@ -183,7 +185,7 @@ def rollback(self):
self.log.error(
"{} errors occurred during rollback.".format(errors),
exc_info=True)
six.reraise(*sys.exc_info())
raise last_exc

@property
def transferred(self):
Expand All @@ -200,11 +202,9 @@ def _create_folder_for_file(self, path):
try:
os.makedirs(dirname)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
if e.errno != errno.EEXIST:
self.log.critical("An unexpected error occurred.")
six.reraise(*sys.exc_info())
raise e

def _same_paths(self, src, dst):
# handles same paths but with C:/project vs c:/project
Expand Down
6 changes: 2 additions & 4 deletions client/ayon_core/lib/local_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import json
import platform
from datetime import datetime
from abc import ABCMeta, abstractmethod
from abc import ABC, abstractmethod

# disable lru cache in Python 2
try:
Expand All @@ -24,7 +24,6 @@ def wrapper(*args, **kwargs):
except ImportError:
import ConfigParser as configparser

import six
import appdirs
import ayon_api

Expand Down Expand Up @@ -133,8 +132,7 @@ def delete_item(self, name):
keyring.delete_password(self._name, name)


@six.add_metaclass(ABCMeta)
class ASettingRegistry():
class ASettingRegistry(ABC):
"""Abstract class defining structure of **SettingRegistry** class.

It is implementing methods to store secure items into keyring, otherwise
Expand Down
21 changes: 10 additions & 11 deletions client/ayon_core/lib/path_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
import re
import numbers

import six

KEY_PATTERN = re.compile(r"(\{.*?[^{0]*\})")
KEY_PADDING_PATTERN = re.compile(r"([^:]+)\S+[><]\S+")
SUB_DICT_PATTERN = re.compile(r"([^\[\]]+)")
Expand All @@ -14,7 +12,7 @@ class TemplateUnsolved(Exception):
"""Exception for unsolved template when strict is set to True."""

msg = "Template \"{0}\" is unsolved.{1}{2}"
invalid_types_msg = " Keys with invalid DataType: `{0}`."
invalid_types_msg = " Keys with invalid data type: `{0}`."
missing_keys_msg = " Missing keys: \"{0}\"."

def __init__(self, template, missing_keys, invalid_types):
Expand Down Expand Up @@ -43,7 +41,7 @@ def __init__(self, template, missing_keys, invalid_types):
class StringTemplate(object):
"""String that can be formatted."""
def __init__(self, template):
if not isinstance(template, six.string_types):
if not isinstance(template, str):
raise TypeError("<{}> argument must be a string, not {}.".format(
self.__class__.__name__, str(type(template))
))
Expand All @@ -63,7 +61,7 @@ def __init__(self, template):

new_parts = []
for part in parts:
if not isinstance(part, six.string_types):
if not isinstance(part, str):
new_parts.append(part)
continue

Expand Down Expand Up @@ -113,7 +111,7 @@ def format(self, data):
"""
result = TemplatePartResult()
for part in self._parts:
if isinstance(part, six.string_types):
if isinstance(part, str):
result.add_output(part)
else:
part.format(data, result)
Expand Down Expand Up @@ -176,7 +174,7 @@ def find_optional_parts(parts):
value = "<>"
elif (
len(parts) == 1
and isinstance(parts[0], six.string_types)
and isinstance(parts[0], str)
):
value = "<{}>".format(parts[0])
else:
Expand All @@ -200,8 +198,9 @@ def find_optional_parts(parts):
new_parts.extend(tmp_parts[idx])
return new_parts


class TemplateResult(str):
"""Result of template format with most of information in.
"""Result of template format with most of the information in.

Args:
used_values (dict): Dictionary of template filling data with
Expand Down Expand Up @@ -299,7 +298,7 @@ def __init__(self, optional=False):
self._optional = True

def add_output(self, other):
if isinstance(other, six.string_types):
if isinstance(other, str):
self._output += other

elif isinstance(other, TemplatePartResult):
Expand Down Expand Up @@ -457,7 +456,7 @@ def validate_value_type(value):
return True

for inh_class in type(value).mro():
if inh_class in six.string_types:
if inh_class is str:
BigRoy marked this conversation as resolved.
Show resolved Hide resolved
return True
return False

Expand Down Expand Up @@ -568,7 +567,7 @@ def __repr__(self):
def format(self, data, result):
new_result = TemplatePartResult(True)
for part in self._parts:
if isinstance(part, six.string_types):
if isinstance(part, str):
new_result.add_output(part)
else:
part.format(data, new_result)
Expand Down
10 changes: 3 additions & 7 deletions client/ayon_core/pipeline/create/creator_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
import collections
from typing import TYPE_CHECKING, Optional

from abc import ABCMeta, abstractmethod

import six
from abc import ABC, abstractmethod

from ayon_core.settings import get_project_settings
from ayon_core.lib import Logger
Expand Down Expand Up @@ -38,8 +36,7 @@ def __init__(self, message):
super(CreatorError, self).__init__(message)


@six.add_metaclass(ABCMeta)
class ProductConvertorPlugin(object):
class ProductConvertorPlugin(ABC):
"""Helper for conversion of instances created using legacy creators.

Conversion from legacy creators would mean to lose legacy instances,
Expand Down Expand Up @@ -152,8 +149,7 @@ def remove_convertor_item(self):
self._create_context.remove_convertor_item(self.identifier)


@six.add_metaclass(ABCMeta)
class BaseCreator:
class BaseCreator(ABC):
"""Plugin that create and modify instance data before publishing process.

We should maybe find better name as creation is only one part of its logic
Expand Down
Loading