Skip to main content
# str-macros

A minimalistic python package allowing to define macros on string based class attributes

## Installation

This package does not have any dependencies and works just fine with
Python 2.7 and Python 3.5+.

To install it via **pip** just run the following command:

```
pip install str-macros
```

## Slow start

The basic idea of this project is to provide a tool for simple macros execution.

For better understanding, let's start with an example.

Let's imagine that you are a developer who creates a tool for
a convenient work with Google AdWords.

Let's define two classes AdBanner and AdCampaign:

```python

class AdCampaign(object):
def __init__(self, campaign_id, name):
self.campaign_id = campaign_id
self.name = name

class AdBanner(object):
def __init__(self, ad_id, name, url, campaign):
self.ad_id = ad_id
self.name = name
self.url = url
self.campaign = campaign
```

But one important condition is that we want to have some analytics
about user clicks on our banners. To achieve this, we use utm labels and we want banner
urls to be in the following format:

```http://test.com/?utm_ad_name=test_ad&utm_campaign=test_campaign```

So, when we create an ad we specify not real url, but an url with some
macros like this:


```python
campaign = AdCampaign(1, 'test campaign')
banner = AdBanner(
id=1,
name='banner [banner_id] for campaign [campaign_name] [random]',
url='http://test.ru/?utm_name=[banner_name]',
campaign=campaign
)
```
So, we have four macros here:
```[banner_id], [campaign_name], [banner_name], [random]``` and we
want to enable them when we create it and send info to Google.

## Usage

Let's see how to deal with it:

```python
import random

from str_macros import MacrosMixin


class AdBanner(MacrosMixin):
MACRO_FIELDS = (
'name', 'url'
)

MACRO_MAP = {
'banner_id': lambda self: str(self.ad_id),
'campaign_name': lambda self: self.campaign.name,
'banner_name': lambda self: self.name,
'random': lambda self: str(random.randint(1, 100)),
}

def __init__(self, ad_id, name, url, campaign):
self.ad_id = ad_id
self.name = name
self.url = url
self.campaign = campaign
```

OK, now we have for variables which can be used in fields (attributes) which
are defined in MACRO_FIELDS and MACRO_MAP: macros that should be executed
for each of the variables.

#### Important params:
- MACRO_FIELDS: tuple or list of attributes in which to look
for patterns
- MACRO_MAP: dict {'pattern': func}: what function to run when a pattern found.
Should take only one argument - current object (self).
In this dictionary, keys are patterns, but without [].

When you assign some initial values to str fields - pattern shoud
be inside of **[]**.


Attention: if in MACRO_MAP you specify a function which uses a
field which is specified in MACRO_FIELDS you are going to end up
in an infinite recursion, so - don't make such mistakes. Example of such mistage:

```python
MACRO_FIELDS = (
'name', 'url'
)
MACRO_MAP = {
'banner_name': lambda self: self.name
# Danger!
# if you have pattern [banner_name] in name - infinite recursion
}
```

### Basic usage

By default, macros are disables. So:

```python
campaign = AdCampaign(1, 'test campaign')
banner = AdBanner(
id=1,
name='banner [banner_id] for campaign [campaign_name] [random]',
url='http://test.ru/?utm_name=[banner_name]',
campaign=campaign
)

print(banner.name)
# Macros disabled now
# banner [banner_id] for campaign [campaign_name] [random]'
AdBanner.start_macros()

# Macros enabled now
print(AdBanner.is_macros_enabled()) # True
print(banner.name)
# banner 1 for campaign test campaign 5

AdBanner.stop_macros()
print(banner.name)
# And disabled again
# banner [banner_id] for campaign [campaign_name] [random]'
print(AdBanner.is_macros_enabled()) # False
```

### Using context manager
```python
from str_macros import enabled_macros
AdBanner.is_macros_enabled() # False
with enabled_macros(AdBanner):
# macros are enabled here
AdBanner.is_macros_enabled() # True
# and here they are already disabled
```

### Using decorator
```python
from str_macros import enable_macros

@enable_macros(AdBanner)
def send_data():
# macros are enabled here
pass

```

## Django

This package works just fine with Django models CharFields and has been
developed mostly for it.

## Author

Dmitry Abramov ©

Metadata

Release files for str-macros 0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distribution (wheel)

Table of built distributions (wheels) for str-macros 0.1
File Interpreter ABI Platform Actions
str_macros-0.1-py2.py3-none-any.whl Python 2, Python 3 none any Details for str_macros-0.1-py2.py3-none-any.whl

Release files / str_macros-0.1-py2.py3-none-any.whl

Download URL str_macros-0.1-py2.py3-none-any.whl
Size 8.5 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
5876f4a1df6e673ca64679a6cfa911c1938611ccfaa9caece7158602b2ceab6b
BLAKE2b-256 checksum
How to use checksums
b358abf7e9bfc5269f92debe5d40d3022f1ce5b007821fbcdb6ffdd7072d2a17
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Security for str-macros 0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1 This release

1 release file No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page