mo-imports


Namemo-imports JSON
Version 3.149.20327 PyPI version JSON
download
home_pagehttps://github.com/klahnakoski/mo-imports
SummaryMore Imports! - Delayed importing
upload_time2020-11-22 04:16:26
maintainer
docs_urlNone
authorKyle Lahnakoski
requires_python
licenseMPL 2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # More Imports! - Delayed importing 

A couple of methods to make late importing cleaner

## Problem

Splitting code into modules is nice, but it can result in cyclic dependencies.  


**foos.py**

```python
from bars import bar

def foo():
    bar()
```

**bars.py**

```python
from foos import foo

def bar():
    foo()
```

> We are not concerned with the infinite recursion; this is only for demonstrating cyclic dependencies. 


## More Imports!

### Solution: Use `expect`/`export` pattern

All your cyclic dependencies are covered with this one pattern: Break cycles by `expect`ing a name in the first module, and let the second module `export` to the first when the value is available

**foos.py**

```python
from mo_imports import expect

bar = expect("bar")

def foo():
    bar()
```

**bars.py**

```python
from mo_imports import export
from foos import foo

def bar():
    foo()

export("bars", bar)
```

**Benefits**
  
 
* every `expect` is verified to match with an `export` (and visa-versa)
* using an expected variable before `export` raises an error     
* code is run only once, at module load time, not later
* methods do not run import code
* all "imports" are at the top of the file


### Solution: Use `delay_import`

Provide a proxy which is responsible for import upon first use of the module variable.

**foos.py**

```python
from mo_imports import delay_import
from bars import bar

bar = delay_import("bars.bar")

def foo():
    bar()

```

**bars.py**

```python
from foos import foo

def bar():
    foo()
```

This is the cleanest, but it requires any of `__call__`, `__getitem__`, `__getattr__` to be called. Sentinals, placeholders, and default values can not be imported this way


  
## Other solutions

If you do not use `mo-imports` your import cycles can be broken using one of the following common patterns:


### Bad Solution: Keep in single file

You can declare yet-another-module that holds the cycles

**foosbars.py**

```python
    def foo():
        bar()

    def bar():
        foo()
```

but this breaks the code modularity



### Bad Solution: Use end-of-file imports

During import, setup of the first module is paused while it imports a second. A bottom-of-file import will ensure the first module is mostly setup to be used by the second. 

**foos.py**

```python
def foo():
    bar()

from bars import bar
```

**bars.py**

```python
def bar():
    foo()

from foos import foo
```

Linters do not like this pattern: You may miss imports, since these are hiding at the bottom.
    


### Bad Solution: Inline import

Import the name only when it is needed

**foos.py**

```python
def foo():
    from bars import bar
    bar()
```
    
**bars.py**


```python
def bar():
    from foos import foo
    foo()
```

This is fine for rarely run code, but there is an undesirable overhead because import is checked everytime the method is run. You may miss imports because they are hiding inline rather than at the top of the file.
  


### Bad Solution: Use the `_late_import()` pattern

When other bad solutions do not work work, then importing late is the remaining option

**foos.py**

```python
from bars import bar

def foo():
    bar()
```

**bars.py**

```python
foo = None

def _late_import():
    global foo
    from foos import foo
    _ = foo

def bar():
    if not foo:
        _late_import()
    foo()
```

Placeholders variables are added, which linters complain about type. There is the added `_late_import()` method. You risk it is not run everywhere as needed. This has less overhead than an inline import, but there is still a check.
            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/klahnakoski/mo-imports",
    "name": "mo-imports",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Kyle Lahnakoski",
    "author_email": "kyle@lahnakoski.com",
    "download_url": "https://files.pythonhosted.org/packages/e2/8a/52ec0e84bc8837d19da57ea9c1644c75b513d4f7aab7b3e24a437a4a047b/mo-imports-3.149.20327.tar.gz",
    "platform": "",
    "description": "# More Imports! - Delayed importing \n\nA couple of methods to make late importing cleaner\n\n## Problem\n\nSplitting code into modules is nice, but it can result in cyclic dependencies.  \n\n\n**foos.py**\n\n```python\nfrom bars import bar\n\ndef foo():\n    bar()\n```\n\n**bars.py**\n\n```python\nfrom foos import foo\n\ndef bar():\n    foo()\n```\n\n> We are not concerned with the infinite recursion; this is only for demonstrating cyclic dependencies. \n\n\n## More Imports!\n\n### Solution: Use `expect`/`export` pattern\n\nAll your cyclic dependencies are covered with this one pattern: Break cycles by `expect`ing a name in the first module, and let the second module `export` to the first when the value is available\n\n**foos.py**\n\n```python\nfrom mo_imports import expect\n\nbar = expect(\"bar\")\n\ndef foo():\n    bar()\n```\n\n**bars.py**\n\n```python\nfrom mo_imports import export\nfrom foos import foo\n\ndef bar():\n    foo()\n\nexport(\"bars\", bar)\n```\n\n**Benefits**\n  \n \n* every `expect` is verified to match with an `export` (and visa-versa)\n* using an expected variable before `export` raises an error     \n* code is run only once, at module load time, not later\n* methods do not run import code\n* all \"imports\" are at the top of the file\n\n\n### Solution: Use `delay_import`\n\nProvide a proxy which is responsible for import upon first use of the module variable.\n\n**foos.py**\n\n```python\nfrom mo_imports import delay_import\nfrom bars import bar\n\nbar = delay_import(\"bars.bar\")\n\ndef foo():\n    bar()\n\n```\n\n**bars.py**\n\n```python\nfrom foos import foo\n\ndef bar():\n    foo()\n```\n\nThis is the cleanest, but it requires any of `__call__`, `__getitem__`, `__getattr__` to be called. Sentinals, placeholders, and default values can not be imported this way\n\n\n  \n## Other solutions\n\nIf you do not use `mo-imports` your import cycles can be broken using one of the following common patterns:\n\n\n### Bad Solution: Keep in single file\n\nYou can declare yet-another-module that holds the cycles\n\n**foosbars.py**\n\n```python\n    def foo():\n        bar()\n\n    def bar():\n        foo()\n```\n\nbut this breaks the code modularity\n\n\n\n### Bad Solution: Use end-of-file imports\n\nDuring import, setup of the first module is paused while it imports a second. A bottom-of-file import will ensure the first module is mostly setup to be used by the second. \n\n**foos.py**\n\n```python\ndef foo():\n    bar()\n\nfrom bars import bar\n```\n\n**bars.py**\n\n```python\ndef bar():\n    foo()\n\nfrom foos import foo\n```\n\nLinters do not like this pattern: You may miss imports, since these are hiding at the bottom.\n    \n\n\n### Bad Solution: Inline import\n\nImport the name only when it is needed\n\n**foos.py**\n\n```python\ndef foo():\n    from bars import bar\n    bar()\n```\n    \n**bars.py**\n\n\n```python\ndef bar():\n    from foos import foo\n    foo()\n```\n\nThis is fine for rarely run code, but there is an undesirable overhead because import is checked everytime the method is run. You may miss imports because they are hiding inline rather than at the top of the file.\n  \n\n\n### Bad Solution: Use the `_late_import()` pattern\n\nWhen other bad solutions do not work work, then importing late is the remaining option\n\n**foos.py**\n\n```python\nfrom bars import bar\n\ndef foo():\n    bar()\n```\n\n**bars.py**\n\n```python\nfoo = None\n\ndef _late_import():\n    global foo\n    from foos import foo\n    _ = foo\n\ndef bar():\n    if not foo:\n        _late_import()\n    foo()\n```\n\nPlaceholders variables are added, which linters complain about type. There is the added `_late_import()` method. You risk it is not run everywhere as needed. This has less overhead than an inline import, but there is still a check.",
    "bugtrack_url": null,
    "license": "MPL 2.0",
    "summary": "More Imports! - Delayed importing",
    "version": "3.149.20327",
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "145b6283369c2267c049bec25448f06a",
                "sha256": "32e3dc720c84765224d29ed7e9d6972a369d41d756e6f26ddb5b7aa01241331d"
            },
            "downloads": -1,
            "filename": "mo-imports-3.149.20327.tar.gz",
            "has_sig": false,
            "md5_digest": "145b6283369c2267c049bec25448f06a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 5415,
            "upload_time": "2020-11-22T04:16:26",
            "upload_time_iso_8601": "2020-11-22T04:16:26.545655Z",
            "url": "https://files.pythonhosted.org/packages/e2/8a/52ec0e84bc8837d19da57ea9c1644c75b513d4f7aab7b3e24a437a4a047b/mo-imports-3.149.20327.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2020-11-22 04:16:26",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": null,
    "github_project": "klahnakoski",
    "error": "Could not fetch GitHub repository",
    "lcname": "mo-imports"
}
        
Elapsed time: 0.21706s