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

Remove some legacy Python compatible codes #244

Merged
merged 3 commits into from
Mar 14, 2024

Conversation

aisk
Copy link
Member

@aisk aisk commented Feb 29, 2024

Summary by CodeRabbit

  • Refactor
    • Improved Python version compatibility in core classes and simplified test setup across various modules.
  • Tests
    • Streamlined test code by removing unnecessary imports and decorators.
  • Chores
    • Enhanced module loading with updated import statements in key components.

Copy link

coderabbitai bot commented Feb 29, 2024

Walkthrough

The recent updates focus on simplifying the test suite and enhancing Python version compatibility within the library. By removing unnecessary imports and version-specific conditions, the changes streamline the testing process. Additionally, the modifications to ThriftImporter and ThriftLoader classes, along with the removal of conditional checks for Windows and Python version in the parser, aim to improve the library's adaptability across different Python environments.

Changes

Files Change Summary
tests/conftest.py Removed sys import and conditional test exclusion.
tests/test_framed_transport.py
tests/test_tornado.py
Removed sys and pytest imports, eliminated pytest.mark.skipif decorators.
thriftpy2/hook.py Updated ThriftImporter and ThriftLoader for better Python version compatibility, included importlib modules for module loading.
thriftpy2/parser/parser.py Removed conditional check for Windows and Python version.

🐇✨
Changes abound, the code does leap,
Across the Python versions, so deep.
No more skips, nor imports in vain,
Our library grows, without the chain.
Together we hop, to the future we peer,
With code more clean, the path is clear.
🌟🐾

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 6

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between d81f47c and 79a5117.
Files selected for processing (5)
  • tests/conftest.py (1 hunks)
  • tests/test_framed_transport.py (3 hunks)
  • tests/test_tornado.py (7 hunks)
  • thriftpy2/hook.py (2 hunks)
  • thriftpy2/parser/parser.py (1 hunks)
Files skipped from review due to trivial changes (1)
  • tests/conftest.py
Additional comments: 3
thriftpy2/hook.py (1)
  • 5-6: The addition of importlib.abc and importlib.util is a positive change, aligning with the PR's objective to modernize the codebase by utilizing more current Python module loading techniques.
tests/test_framed_transport.py (1)
  • 2-7: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-100]

The removal of sys and pytest imports, as well as pytest.mark.skipif decorators, from tests/test_framed_transport.py simplifies the test setup by eliminating version-specific conditions. This change is consistent with the PR's objective to modernize the codebase. Ensure that the test suite still covers all necessary scenarios without relying on version-specific checks.

tests/test_tornado.py (1)
  • 10-15: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-100]

Removing pytest imports and @pytest.mark.skipif decorators from tests/test_tornado.py simplifies the test setup by eliminating version-specific skips. This is a positive change towards modernizing the test suite. However, it's important to verify that the removal of these conditions does not inadvertently exclude important test scenarios that are still relevant. Ensure comprehensive test coverage is maintained.

Comment on lines 540 to 545
cached, this is enabled by default. If `module_name`
is provided, use it as cache key, else use the `path`.
"""
if os.name == 'nt' and sys.version_info[0] < 3:
os.path.samefile = lambda f1, f2: os.stat(f1) == os.stat(f2)

# dead include checking on current stack
for thrift in thrift_stack:
if thrift.__thrift_file__ is not None and \
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [22-22]

The import of PY3 from thriftpy2._compat is no longer necessary if the goal is to remove legacy Python compatibility code. Since Python 2 support is being dropped, all code that is conditional on PY3 or Python 2 should be removed or simplified.

- from thriftpy2._compat import urlopen, urlparse, PY3
+ from thriftpy2._compat import urlopen, urlparse

And remove any usage of PY3 throughout the file.


📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [1013-1015]

Given the removal of Python 2 support, the conditional check for PY3 to decode bytes to a string is no longer necessary. All code can now assume Python 3 behavior, simplifying the handling of data read from files or URLs.

-    if PY3:
-        if isinstance(data, bytes):
-            data = data.decode(encoding)

This block can be removed, assuming all environments will be running Python 3 or later.


📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [27-29]

The conditional import of open from io for Python versions not equal to PY3 is unnecessary with the removal of Python 2 support. This can be removed to simplify the codebase.

- if not PY3:
-     from io import open

Removing this will also eliminate the need for the PY3 variable, further simplifying the code.

Comment on lines +15 to +23
class ThriftImporter(importlib.abc.MetaPathFinder):
def __init__(self, extension="_thrift"):
self.extension = extension

class ThriftImporter(importlib.abc.MetaPathFinder):
def __init__(self, extension="_thrift"):
self.extension = extension
def find_spec(self, fullname, path, target=None):
if not fullname.endswith(self.extension):
return None
return importlib.util.spec_from_loader(fullname,
ThriftLoader(fullname))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ThriftImporter class has been updated to implement the importlib.abc.MetaPathFinder interface. This is a good practice for custom module importers, ensuring compatibility with Python's import system. However, the find_spec method lacks documentation. Adding a docstring explaining its purpose, parameters, and return value would enhance maintainability.

+    def find_spec(self, fullname, path, target=None):
+        """
+        Find a module's spec based on its fullname, path, and target.
+
+        :param fullname: Full name of the module.
+        :param path: Path to the module, if available.
+        :param target: Target module, if available.
+        :return: Module spec if found, None otherwise.
+        """

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
class ThriftImporter(importlib.abc.MetaPathFinder):
def __init__(self, extension="_thrift"):
self.extension = extension
class ThriftImporter(importlib.abc.MetaPathFinder):
def __init__(self, extension="_thrift"):
self.extension = extension
def find_spec(self, fullname, path, target=None):
if not fullname.endswith(self.extension):
return None
return importlib.util.spec_from_loader(fullname,
ThriftLoader(fullname))
class ThriftImporter(importlib.abc.MetaPathFinder):
def __init__(self, extension="_thrift"):
self.extension = extension
def find_spec(self, fullname, path, target=None):
"""
Find a module's spec based on its fullname, path, and target.
:param fullname: Full name of the module.
:param path: Path to the module, if available.
:param target: Target module, if available.
:return: Module spec if found, None otherwise.
"""
if not fullname.endswith(self.extension):
return None
return importlib.util.spec_from_loader(fullname,
ThriftLoader(fullname))

Comment on lines +26 to +34
class ThriftLoader(importlib.abc.Loader):
def __init__(self, fullname):
self.fullname = fullname

class ThriftLoader(importlib.abc.Loader):
def __init__(self, fullname):
self.fullname = fullname
def create_module(self, spec):
return load_module(self.fullname)

def create_module(self, spec):
return load_module(self.fullname)

def exec_module(self, module):
pass
else:
class ThriftImporter(object):
def __init__(self, extension="_thrift"):
self.extension = extension

def find_module(self, fullname, path=None):
if fullname.endswith(self.extension):
return self

def load_module(self, fullname):
return load_module(fullname)
def exec_module(self, module):
pass
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ThriftLoader class correctly implements the importlib.abc.Loader interface. The create_module method is well-defined, but like ThriftImporter, it could benefit from additional documentation for clarity and maintainability.

+    def create_module(self, spec):
+        """
+        Create a module based on the provided spec.
+
+        :param spec: Specification of the module to be created.
+        :return: The loaded module.
+        """

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
class ThriftLoader(importlib.abc.Loader):
def __init__(self, fullname):
self.fullname = fullname
class ThriftLoader(importlib.abc.Loader):
def __init__(self, fullname):
self.fullname = fullname
def create_module(self, spec):
return load_module(self.fullname)
def create_module(self, spec):
return load_module(self.fullname)
def exec_module(self, module):
pass
else:
class ThriftImporter(object):
def __init__(self, extension="_thrift"):
self.extension = extension
def find_module(self, fullname, path=None):
if fullname.endswith(self.extension):
return self
def load_module(self, fullname):
return load_module(fullname)
def exec_module(self, module):
pass
class ThriftLoader(importlib.abc.Loader):
def __init__(self, fullname):
self.fullname = fullname
def create_module(self, spec):
"""
Create a module based on the provided spec.
:param spec: Specification of the module to be created.
:return: The loaded module.
"""
return load_module(self.fullname)
def exec_module(self, module):
pass

Comment on lines 12 to 37
# TODO: The load process does not compatible with Python standard, e.g., if the
# specified thrift file does not exists, it raises FileNotFoundError, and skiped
# the other meta finders in the sys.meta_path.
if sys.version_info >= (3, 4):
import importlib.abc
import importlib.util
class ThriftImporter(importlib.abc.MetaPathFinder):
def __init__(self, extension="_thrift"):
self.extension = extension

class ThriftImporter(importlib.abc.MetaPathFinder):
def __init__(self, extension="_thrift"):
self.extension = extension
def find_spec(self, fullname, path, target=None):
if not fullname.endswith(self.extension):
return None
return importlib.util.spec_from_loader(fullname,
ThriftLoader(fullname))

def find_spec(self, fullname, path, target=None):
if not fullname.endswith(self.extension):
return None
return importlib.util.spec_from_loader(fullname,
ThriftLoader(fullname))

class ThriftLoader(importlib.abc.Loader):
def __init__(self, fullname):
self.fullname = fullname

class ThriftLoader(importlib.abc.Loader):
def __init__(self, fullname):
self.fullname = fullname
def create_module(self, spec):
return load_module(self.fullname)

def create_module(self, spec):
return load_module(self.fullname)

def exec_module(self, module):
pass
else:
class ThriftImporter(object):
def __init__(self, extension="_thrift"):
self.extension = extension

def find_module(self, fullname, path=None):
if fullname.endswith(self.extension):
return self

def load_module(self, fullname):
return load_module(fullname)
def exec_module(self, module):
pass


_imp = ThriftImporter()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [5-34]

The TODO comment at the beginning of the file raises a concern about the load process not being compatible with the Python standard, specifically mentioning that a FileNotFoundError is raised, skipping other meta finders in sys.meta_path. This is a significant issue that could affect the robustness and predictability of the custom module loading mechanism. It's recommended to address this issue or at least document the current behavior and its implications clearly in the code.

Consider revising the loading process to adhere more closely to Python's standard behavior, or document the current behavior and its implications to ensure users are aware of this deviation.

@aisk aisk marked this pull request as draft February 29, 2024 11:49
@aisk aisk marked this pull request as ready for review March 5, 2024 12:28
@aisk
Copy link
Member Author

aisk commented Mar 5, 2024

I think we should keep this PR small to make it easy to review. So the removal of _compat.py will be in separate PRs.

@aisk aisk merged commit 5b62d0c into Thriftpy:master Mar 14, 2024
8 checks passed
@aisk aisk deleted the remove-python2-support branch March 14, 2024 14:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant