website/content/blog/exportpydecorator.md

35 lines
753 B
Markdown
Raw Normal View History

2020-06-26 22:34:39 -04:00
---
title: "Quick Python: Export Decorator"
date: 2020-06-14T22:15:38-04:00
draft: false
2022-01-02 14:24:29 -05:00
tags: ["Python"]
2023-01-05 14:04:45 -05:00
medium_enabled: true
2020-06-26 22:34:39 -04:00
---
A great [StackOverflow post](https://stackoverflow.com/a/35710527) by [Aaron Hall](https://stackoverflow.com/users/541136/aaron-hall) that shows how you can create an `export` decorator in order to not have to specify all the names you want to expose via [`__all__`](/blog/pythonall/).
2020-06-26 22:34:39 -04:00
The Decorator:
```python
import sys
def export(fn):
mod = sys.modules[fn.__module__]
if hasattr(mod, '__all__'):
mod.__all__.append(fn.__name__)
else:
mod.__all__ = [fn.__name__]
return fn
```
Usage:
```python
__all__ = []
@export # otherwise __all__ = ['test']
def test():
print("test")
```