Skip to content

Commit

Permalink
add functools.file_import
Browse files Browse the repository at this point in the history
  • Loading branch information
lidong committed Jul 15, 2024
1 parent 795fb4a commit 8987ff6
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
### 1.0.7 (2024-07-15)
1. add `functools.file_import`

### 1.0.6 (2024-07-10)
1. fix `utils.Validator` typing-hint class

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ print(morebuiltins.__file__)

3.9 `func_cmd` - Handle function with argparse, typing-hint is nessessary.

3.10 `file_import` - Import function from file path.


## 4. morebuiltins.ipc

Expand Down
18 changes: 18 additions & 0 deletions doc.md
Original file line number Diff line number Diff line change
Expand Up @@ -1301,6 +1301,24 @@
---



3.10 `file_import` - Import function from file path.


```python

Demo::
>>> from pathlib import Path
>>> file_path = Path(__file__).parent / "utils.py"
>>> list(file_import(file_path, ["get_hash", "find_jsons"]).keys())
['get_hash', 'find_jsons']

```


---


## 4. morebuiltins.ipc


Expand Down
2 changes: 1 addition & 1 deletion morebuiltins/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__version__ = "1.0.6"
__version__ = "1.0.7"
__all__ = [
"morebuiltins.utils",
"morebuiltins.date",
Expand Down
19 changes: 19 additions & 0 deletions morebuiltins/functools.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import asyncio
import importlib.util
import inspect
import json
import os
import re
import time
from collections import deque
Expand All @@ -22,6 +24,7 @@
"SizedTimedRotatingFileHandler",
"get_type_default",
"func_cmd",
"file_import",
]


Expand Down Expand Up @@ -688,6 +691,22 @@ def test(str: str, /, int=1, *, list=["d"], float=0.1, set={"f"}, tuple=(1, 2),
return args, kwargs


def file_import(file_path, names):
"""Import function from file path.
Demo::
>>> from pathlib import Path
>>> file_path = Path(__file__).parent / "utils.py"
>>> list(file_import(file_path, ["get_hash", "find_jsons"]).keys())
['get_hash', 'find_jsons']
"""
module_name = os.path.splitext(os.path.basename(file_path))[0]
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return {name: getattr(module, name) for name in names}


def test_bg_task():
async def _test_bg_task():
async def coro():
Expand Down

0 comments on commit 8987ff6

Please sign in to comment.