Skip to content

Commit

Permalink
Remove all lazy_imports
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielNoord committed Apr 23, 2023
1 parent 30df5a8 commit f4a1168
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 34 deletions.
9 changes: 2 additions & 7 deletions astroid/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,12 @@
from collections.abc import Iterator, Sequence
from io import TextIOWrapper
from tokenize import detect_encoding
from typing import TYPE_CHECKING

from astroid import bases, modutils, nodes, raw_building, rebuilder, util
from astroid._ast import ParserModule, get_parser_module
from astroid.exceptions import AstroidBuildingError, AstroidSyntaxError, InferenceError
from astroid.manager import AstroidManager

if TYPE_CHECKING:
from astroid import objects
else:
objects = util.lazy_import("objects")


# The name of the transient function that is used to
# wrap expressions to be extracted when calling
# extract_node.
Expand Down Expand Up @@ -235,6 +228,8 @@ def delayed_assattr(self, node: nodes.AssignAttr) -> None:
This adds name to locals and handle members definition.
"""
from astroid import objects # pylint: disable=import-outside-toplevel

try:
frame = node.frame(future=True)
for inferred in node.expr.infer():
Expand Down
13 changes: 10 additions & 3 deletions astroid/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,16 @@
from collections.abc import Callable, Generator, Iterable, Iterator
from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union

from astroid import bases, constraint, decorators, helpers, nodes, protocols, util
from astroid import (
bases,
constraint,
decorators,
helpers,
nodes,
objects,
protocols,
util,
)
from astroid.const import PY310_PLUS
from astroid.context import (
CallContext,
Expand Down Expand Up @@ -44,8 +53,6 @@
if TYPE_CHECKING:
from astroid.objects import Property

# Prevents circular imports
objects = util.lazy_import("objects")

_T = TypeVar("_T")
_BaseContainerT = TypeVar("_BaseContainerT", bound=nodes.BaseContainer)
Expand Down
30 changes: 20 additions & 10 deletions astroid/interpreter/objectmodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,12 @@
from astroid.manager import AstroidManager
from astroid.nodes import node_classes

objects = util.lazy_import("objects")
builder = util.lazy_import("builder")

if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal

if TYPE_CHECKING:
from astroid import builder
from astroid.objects import Property

IMPL_PREFIX = "attr_"
Expand Down Expand Up @@ -137,6 +133,8 @@ def lookup(self, name):
@property
def attr___new__(self) -> bases.BoundMethod:
"""Calling cls.__new__(type) on an object returns an instance of 'type'."""
from astroid import builder # pylint: disable=import-outside-toplevel

node: nodes.FunctionDef = builder.extract_node(
"""def __new__(self, cls): return cls()"""
)
Expand All @@ -149,6 +147,8 @@ def attr___new__(self) -> bases.BoundMethod:
@property
def attr___init__(self) -> bases.BoundMethod:
"""Calling cls.__init__() normally returns None."""
from astroid import builder # pylint: disable=import-outside-toplevel

# The *args and **kwargs are necessary not to trigger warnings about missing
# or extra parameters for '__init__' methods we don't infer correctly.
# This BoundMethod is the fallback value for those.
Expand Down Expand Up @@ -628,6 +628,8 @@ def attr___enter__(self) -> bases.BoundMethod:
will bind this method's return value to the target(s) specified in the
as clause of the statement, if any.
"""
from astroid import builder # pylint: disable=import-outside-toplevel

node: nodes.FunctionDef = builder.extract_node("""def __enter__(self): ...""")
# We set the parent as being the ClassDef of 'object' as that
# is where this method originally comes from
Expand All @@ -644,6 +646,8 @@ def attr___exit__(self) -> bases.BoundMethod:
exception that caused the context to be exited. If the context was exited
without an exception, all three arguments will be None.
"""
from astroid import builder # pylint: disable=import-outside-toplevel

node: nodes.FunctionDef = builder.extract_node(
"""def __exit__(self, exc_type, exc_value, traceback): ..."""
)
Expand Down Expand Up @@ -828,6 +832,8 @@ def infer_call_result(

@property
def attr_items(self):
from astroid import objects # pylint: disable=import-outside-toplevel

elems = []
obj = node_classes.List(parent=self._instance)
for key, value in self._instance.items:
Expand All @@ -836,26 +842,30 @@ def attr_items(self):
elems.append(elem)
obj.postinit(elts=elems)

obj = objects.DictItems(obj)
return self._generic_dict_attribute(obj, "items")
items_obj = objects.DictItems(obj)
return self._generic_dict_attribute(items_obj, "items")

@property
def attr_keys(self):
from astroid import objects # pylint: disable=import-outside-toplevel

keys = [key for (key, _) in self._instance.items]
obj = node_classes.List(parent=self._instance)
obj.postinit(elts=keys)

obj = objects.DictKeys(obj)
return self._generic_dict_attribute(obj, "keys")
keys_obj = objects.DictKeys(obj)
return self._generic_dict_attribute(keys_obj, "keys")

@property
def attr_values(self):
from astroid import objects # pylint: disable=import-outside-toplevel

values = [value for (_, value) in self._instance.items]
obj = node_classes.List(parent=self._instance)
obj.postinit(values)

obj = objects.DictValues(obj)
return self._generic_dict_attribute(obj, "values")
values_obj = objects.DictValues(obj)
return self._generic_dict_attribute(values_obj, "values")


class PropertyModel(ObjectModel):
Expand Down
7 changes: 6 additions & 1 deletion astroid/nodes/scoped_nodes/scoped_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@

ITER_METHODS = ("__iter__", "__getitem__")
EXCEPTION_BASE_CLASSES = frozenset({"Exception", "BaseException"})
objects = util.lazy_import("objects")
BUILTIN_DESCRIPTORS = frozenset(
{"classmethod", "staticmethod", "builtins.classmethod", "builtins.staticmethod"}
)
Expand Down Expand Up @@ -2365,6 +2364,8 @@ def instantiate_class(self) -> bases.Instance:
:returns: An :class:`Instance` of the :class:`ClassDef` node
"""
from astroid import objects # pylint: disable=import-outside-toplevel

try:
if any(cls.name in EXCEPTION_BASE_CLASSES for cls in self.mro()):
# Subclasses of exceptions can be exception instances
Expand Down Expand Up @@ -2446,6 +2447,8 @@ def _metaclass_lookup_attribute(self, name, context):
return attrs

def _get_attribute_from_metaclass(self, cls, name, context):
from astroid import objects # pylint: disable=import-outside-toplevel

try:
attrs = cls.getattr(name, context=context, class_context=True)
except AttributeInferenceError:
Expand Down Expand Up @@ -2484,6 +2487,8 @@ def igetattr(
:returns: The inferred possible values.
"""
from astroid import objects # pylint: disable=import-outside-toplevel

# set lookup name since this is necessary to infer on import nodes for
# instance
context = copy_context(context)
Expand Down
6 changes: 1 addition & 5 deletions astroid/protocols.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from collections.abc import Callable, Generator, Iterator, Sequence
from typing import Any, TypeVar

from astroid import arguments, bases, decorators, helpers, nodes, util
from astroid import arguments, bases, decorators, helpers, nodes, objects, util
from astroid.const import Context
from astroid.context import InferenceContext, copy_context
from astroid.exceptions import (
Expand All @@ -31,10 +31,6 @@
SuccessfulInferenceResult,
)

raw_building = util.lazy_import("raw_building")
objects = util.lazy_import("objects")


_TupleListNodeT = TypeVar("_TupleListNodeT", nodes.Tuple, nodes.List)


Expand Down
10 changes: 2 additions & 8 deletions astroid/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

from __future__ import annotations

import importlib
import sys
import warnings
from typing import Any
Expand All @@ -26,12 +25,6 @@ def __get__(self, instance, owner=None):
return DescriptorProxy(obj)


def lazy_import(module_name: str) -> lazy_object_proxy.Proxy:
return lazy_object_proxy.Proxy(
lambda: importlib.import_module("." + module_name, "astroid")
)


class UninferableBase:
"""Special inference object, which is returned when inference fails.
Expand Down Expand Up @@ -85,7 +78,8 @@ def __init__(self, operand, op, error):

@property
def _object_type_helper(self):
helpers = lazy_import("helpers")
from astroid import helpers # pylint: disable=import-outside-toplevel

return helpers.object_type

def _object_type(self, obj):
Expand Down

0 comments on commit f4a1168

Please sign in to comment.