Skip to content

Commit

Permalink
fix to_type (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
goodwanghan committed Jan 11, 2021
1 parent 8bc9532 commit 42b9273
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 10 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ pip install triad

## Release History

### 0.5.0

* Fix to_type on full type path

### 0.4.9

* Fix numpy warning
Expand Down
20 changes: 20 additions & 0 deletions tests/utils/test_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
to_timedelta,
to_type,
)
import urllib # must keep for testing purpose
import urllib.request # must keep for testing purpose


def test_to_size():
Expand Down Expand Up @@ -94,6 +96,24 @@ def test_str_to_type():
assert RuntimeError == str_to_type("RuntimeError", Exception)
raises(TypeError, lambda: str_to_type("RuntimeError", int))

# test a full type path that only root was imported
str_to_type("urllib.request.OpenerDirector")

# test a full type path that was never imported
str_to_type("shutil.Error")
str_to_type("http.HTTPStatus")

# class and subclass
class T(object):
def __init__(self):
self.x = 10

class _TS(object):
pass

assert T == str_to_type("T")
assert T._TS == str_to_type("T._TS")


def test_str_to_instance():
i = str_to_instance("tests.utils.Class2")
Expand Down
17 changes: 8 additions & 9 deletions triad/utils/convert.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import datetime
import importlib
import inspect
from importlib import util as importlib_util
from types import ModuleType
from typing import Any, Dict, List, Optional, Tuple

import numpy as np
Expand Down Expand Up @@ -96,15 +96,14 @@ def __init__(self, x=1):
_globals, _locals = get_caller_global_local_vars(global_vars, local_vars)
if "." not in expr:
return eval(expr, _globals, _locals)
root = expr.split(".")[0]
if root not in _globals and root not in _locals:
spec = importlib_util.find_spec(root)
assert_or_throw(spec is not None, ValueError(expr))
_locals = dict(_locals)
_locals[root] = importlib.import_module(root)
return eval(expr, _globals, _locals)
parts = expr.split(".")
v = _locals.get(parts[0], _globals.get(parts[0], None))
if v is not None and not isinstance(v, ModuleType):
return eval(expr, _globals, _locals)
root = ".".join(parts[:-1])
return getattr(importlib.import_module(root), parts[-1])
except ValueError:
raise
raise # pragma: no cover
except Exception:
raise ValueError(expr)

Expand Down
2 changes: 1 addition & 1 deletion triad_version/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.4.9"
__version__ = "0.5.0"

0 comments on commit 42b9273

Please sign in to comment.