Skip to content

Commit

Permalink
Merge pull request #309 from int3l/main
Browse files Browse the repository at this point in the history
Code examples for episode 456
  • Loading branch information
asottile authored Jul 27, 2022
2 parents 8ffef51 + 45e5b5d commit 9f08714
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 0 deletions.
18 changes: 18 additions & 0 deletions sample_code/ep456/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# [python regex dynamic replacements (intermediate)](https://youtu.be/o_PD7AAbs4U)

Today I show a cool technique for regex replacement in python!

## Interactive examples

### Bash

```bash
python t.py
python t.py | flake8 -

virtualenv venv
. venv/bin/activate

pip install yesqa
yesqa src.py
```
5 changes: 5 additions & 0 deletions sample_code/ep456/rev01/src.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import os # noqa: F401

print('hello demo') # some comment

# another comment here
5 changes: 5 additions & 0 deletions sample_code/ep456/rev02/src.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import os # noqa: F401

print('hello demo') # noqa

# another comment here
8 changes: 8 additions & 0 deletions sample_code/ep456/rev02/t.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import re

with open('src.py') as f:
contents = f.read()

comment = re.compile('#[^\n]+')

print(comment.sub('', contents))
5 changes: 5 additions & 0 deletions sample_code/ep456/rev03/src.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import os # noqa: F401

print('hello demo') # noqa

# another comment here
16 changes: 16 additions & 0 deletions sample_code/ep456/rev03/t.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from __future__ import annotations
from typing import Match

import re

with open('src.py') as f:
contents = f.read()

comment = re.compile('#([^\n]+)')


def cb(match: Match[str]) -> str:
return f'#{len(match[1]) * "."}'


print(comment.sub(cb, contents), end='')
5 changes: 5 additions & 0 deletions sample_code/ep456/rev04/src.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import os # noqa: F401

print('hello demo') # noqa

# another comment here
16 changes: 16 additions & 0 deletions sample_code/ep456/rev04/t.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from __future__ import annotations
from typing import Match

import re

with open('src.py') as f:
contents = f.read()

comment = re.compile('(# ?)([^\n]+)')


def cb(match: Match[str]) -> str:
return f'{match[1]}{len(match[2]) * "."}'


print(comment.sub(cb, contents), end='')

0 comments on commit 9f08714

Please sign in to comment.