• Stars
    star
    137
  • Rank 257,434 (Top 6 %)
  • Language
    Python
  • License
    BSD 2-Clause "Sim...
  • Created almost 10 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A totally different take on container boilerplate.

Overview

docs Documentation Status
tests
Travis-CI Build Status AppVeyor Build Status Requirements Status
Coverage Status Coverage Status
package

Container class boilerplate killer.

  • Free software: BSD 2-Clause License

Installation

pip install fields

Usage & examples

A class that has 2 attributes, name and size:

>>> from fields import Fields
>>> class Pizza(Fields.name.size):
...     pass
...
>>> p = Pizza("Pepperoni", "large")
>>> p
Pizza(name='Pepperoni', size='large')
>>> p.size
'large'
>>> p.name
'Pepperoni'

You can also use keyword arguments:

>>> Pizza(size="large", name="Pepperoni")
Pizza(name='Pepperoni', size='large')

You can have as many attributes as you want:

>>> class Pizza(Fields.name.ingredients.crust.size):
...     pass
...
>>> Pizza("Funghi", ["mushrooms", "mozarella"], "thin", "large")
Pizza(name='Funghi', ingredients=['mushrooms', 'mozarella'], crust='thin', size='large')

A class that has one required attribute value and two attributes (left and right) with default value None:

>>> class Node(Fields.value.left[None].right[None]):
...     pass
...
>>> Node(1, Node(2), Node(3, Node(4)))
Node(value=1, left=Node(value=2, left=None, right=None), right=Node(value=3, left=Node(value=4, left=None, right=None), right=None))
>>> Node(1, right=Node(2))
Node(value=1, left=None, right=Node(value=2, left=None, right=None))

You can also use it inline:

>>> Fields.name.size("Pepperoni", "large")
FieldsBase(name='Pepperoni', size='large')

Want tuples?

An alternative to namedtuple:

>>> from fields import Tuple
>>> class Pair(Tuple.a.b):
...     pass
...
>>> issubclass(Pair, tuple)
True
>>> p = Pair(1, 2)
>>> p.a
1
>>> p.b
2
>>> tuple(p)
(1, 2)
>>> a, b = p
>>> a
1
>>> b
2

Tuples are fast!

benchmark: 9 tests, min 5 rounds (of min 25.00us), 1.00s max time, timer: time.perf_counter

Name (time in us)                 Min        Max     Mean   StdDev  Rounds  Iterations
--------------------------------------------------------------------------------------
test_characteristic            6.0100  1218.4800  11.7102  34.3158   15899          10
test_fields                    6.8000  1850.5250   9.8448  33.8487    5535           4
test_slots_fields              6.3500   721.0300   8.6120  14.8090   15198          10
test_super_dumb                7.0111  1289.6667  11.6881  31.6012   15244           9
test_dumb                      3.7556   673.8444   5.8010  15.0514   14246          18
test_tuple                     3.1750   478.7750   5.1974   9.1878   14642          12
test_namedtuple                3.2778   538.1111   5.0403   9.9177   14105           9
test_attrs_decorated_class     4.2062   540.5125   5.3618  11.6708   14266          16
test_attrs_class               3.7889   316.1056   4.7731   6.0656   14026          18
--------------------------------------------------------------------------------------

Documentation

https://python-fields.readthedocs.org/

Development

To run all the tests run tox in your shell (pip install tox if you don't have it):

tox

FAQ

Why should I use this?

It's less to type, why have quotes around when the names need to be valid symbols anyway. In fact, this is one of the shortest forms possible to specify a container with fields.

But you're abusing a very well known syntax. You're using attribute access instead of a list of strings. Why?

Symbols should be symbols. Why validate strings so they are valid symbols when you can avoid that? Just use symbols. Save on both typing and validation code.

The use of language constructs is not that surprising or confusing in the sense that semantics precede conventional syntax use. For example, if we have class Person(Fields.first_name.last_name.height.weight): pass then it's going to be clear we're talking about a Person object with first_name, last_name, height and width fields: the words have clear meaning.

Again, you should not name your variables as f1, f2 or any other non-semantic symbols anyway.

Semantics precede syntax: it's like looking at a cake resembling a dog, you won't expect the cake to bark and run around.

Is this stable? Is it tested?

Yes. Mercilessly tested on Travis and AppVeyor.

Is the API stable?

Yes, ofcourse.

Why not namedtuple?

It's ugly, repetitive and inflexible. Compare this:

>>> from collections import namedtuple
>>> class MyContainer(namedtuple("MyContainer", ["field1", "field2"])):
...     pass
>>> MyContainer(1, 2)
MyContainer(field1=1, field2=2)

To this:

>>> class MyContainer(Tuple.field1.field2):
...     pass
>>> MyContainer(1, 2)
MyContainer(field1=1, field2=2)

Why not characteristic?

Ugly, inconsistent - you don't own the class:

Lets try this:

>>> import characteristic
>>> @characteristic.attributes(["field1", "field2"])
... class MyContainer(object):
...     def __init__(self, a, b):
...         if a > b:
...             raise ValueError("Expected %s < %s" % (a, b))
>>> MyContainer(1, 2)
Traceback (most recent call last):
    ...
ValueError: Missing keyword value for 'field1'.

WHAT !? Ok, lets write some more code:

>>> MyContainer(field1=1, field2=2)
Traceback (most recent call last):
    ...
TypeError: __init__() ... arguments...

This is bananas. You have to write your class around these quirks.

Lets try this:

>>> class MyContainer(Fields.field1.field2):
...     def __init__(self, a, b):
...         if a > b:
...             raise ValueError("Expected %s < %s" % (a, b))
...         super(MyContainer, self).__init__(a, b)

Just like a normal class, works as expected:

>>> MyContainer(1, 2)
MyContainer(field1=1, field2=2)

Why not attrs?

Now this is a very difficult question.

Consider this typical use-case:

>>> import attr
>>> @attr.s
... class Point(object):
...     x = attr.ib()
...     y = attr.ib()

Worth noting:

  • attrs is faster because it doesn't allow your class to be used as a mixin (it doesn't do any super(cls, self).__init__(...) for you).

  • The typical use-case doesn't allow you to have a custom __init__. You can use @attr.s(init=False) that will allow you to implement your own __init__. However, you can't have your own __init__ that calls attrs provided __init__ (like in a subclassing scenario).

  • It works better with IDEs and source code analysis tools because of the attributes defined on the class.

  • It's more composable if you only use @attr.s decorated hierarchies. Example:

    >>> @attr.s
    ... class A(object):
    ...     a = attr.ib()
    ...     def get_a(self):
    ...         return self.a
    >>> @attr.s
    ... class B(object):
    ...     b = attr.ib()
    >>> @attr.s
    ... class C(B, A):
    ...     c = attr.ib()
    >>> C(1, 2, 3)
    C(a=1, b=2, c=3)

All in all, attrs is a fast and minimal container library that does support subclasses, but quite differently than fields. Definitely worth considering.

Also, nowadays it has more features than fields. See #6.

Won't this confuse pylint?

Normaly it would, but there's a plugin that makes pylint understand it, just like any other class: pylint-fields.

Testimonials

Diabolical. Can't be unseen.

David Beazley

I think that's the saddest a single line of python has ever made me.

—Someone on IRC (#python)

Don't speak around saying that I like it.

—A PyPy contributor

Fields is completely bat-shit insane, but kind of cool.

—Someone on IRC (#python)

WHAT?!?!

—Unsuspecting victim at EuroPython 2015

I don't think it should work ...

—Unsuspecting victim at EuroPython 2015

Is it some Ruby thing?

—Unsuspecting victim at EuroPython 2015

Are Python programmers that lazy?

—Some Java developer

I'm going to use this in my next project. You're a terrible person.

—Isaac Dickinson

It's so bad you had to write a pylint plugin :)

—Colin Dunklau on IRC (#python)

Apologies

I tried my best at EuroPython ...

More Repositories

1

cookiecutter-pylibrary

Enhanced cookiecutter template for Python libraries.
Python
1,225
star
2

pytest-benchmark

py.test fixture for benchmarking code
Python
1,159
star
3

python-hunter

Hunter is a flexible code tracing toolkit.
Python
769
star
4

python-redis-lock

Lock context manager implemented via redis SET NX EX and BLPOP.
Python
514
star
5

python-manhole

Debugging manhole for python applications.
Python
356
star
6

django-redisboard

Redis monitoring and inspection tool in django admin.
Python
265
star
7

python-remote-pdb

Remote vanilla PDB (over TCP sockets).
Python
252
star
8

python-lazy-object-proxy

A fast and thorough lazy object proxy.
Python
234
star
9

django-prefetch

Generic model related data prefetch framework for Django.
Python
153
star
10

python-tblib

Serialization library for Exceptions and Tracebacks.
Python
149
star
11

python-nameless

Sample project. Use https://github.com/ionelmc/cookiecutter-pylibrary to make your own project. The purpose of this repo is to test the CI configuration.
Python
145
star
12

jquery-gp-gallery

jQuery gallery plugin (ala google plus photo galeries)
CSS
126
star
13

python-aspectlib

An aspect-oriented programming, monkey-patch and decorators library. It is useful when changing behavior in existing code is desired. It includes tools for debugging and testing: simple mock/record and a complete capture/replay framework.
Python
108
star
14

django-monkey-team

Django middleware and userscript that displays debug tracebacks on production sites (where you would have DEBUG = False) only to developers.
Python
57
star
15

django-uwsgi-cache

uWSGI Django cache backend.
Python
38
star
16

django-admin-customizer

Django admin customizing interface
Python
36
star
17

python-holdup

A tool to wait for services and execute command. Useful in Docker containers.
Python
33
star
18

projectskel

Project skeleton for python 2.7 projects with fabric and virtualenv. It's intended for django projects but can be customized for other types of projects.
Python
28
star
19

sphinx-py3doc-enhanced-theme

A theme based on the theme of https://docs.python.org/3/ with some responsive enhancements.
JavaScript
25
star
20

django-admin-utils

Utility code for easier django admin development
Python
25
star
21

tox-wheel

A Tox plugin that builds and installs wheels instead of sdist. Note that this plugin is obsolte as tox 4.0 already has wheel support.
Python
23
star
22

docker-webdav

NGINX WebDAV container
Shell
23
star
23

python-cookiepatcher

Just a small shim around cookiecutter that alters a bit the CLI to work better when reapplying templates to existing projects.
Python
18
star
24

nose-htmloutput

Python
14
star
25

nose-timelimit

Nose plugin that allows you automatically skip tests that are too slow.
Python
13
star
26

cookiecutter-pylibrary-minimal

This has been merged into https://github.com/ionelmc/cookiecutter-pylibrary - use that instead!
Python
12
star
27

pypi-alias

A small utility to make alias distributions on PyPI.
Python
11
star
28

python-su

Python
9
star
29

python-process-tests

Testcase classes and assertions for testing processes.
Python
9
star
30

python-packaging-blunders

Python
8
star
31

polymer-select-box

Tagging widget implemented as a Polymer webcomponent
HTML
7
star
32

django-badbrowser

Browser detection (including browser upgrade notices) for Django
Python
7
star
33

python-mongoql-conv

Library to convert those MongoDB queries to something else, like a python expresion, a function or a django query (Q) object tree
Python
7
star
34

python-cogen

Automatically exported from https://code.google.com/p/cogen
Python
6
star
35

python-signalfd

CFFI bindings for signalfd.
Python
6
star
36

python-appengine-sdk

Un-official `pip install`-able AppEngine SDK.
Python
6
star
37

python-redis-throttled-queue

WIP
Python
6
star
38

python-unlzw

Python
6
star
39

python-stampede

Event-loop based, miniature job queue and worker that runs the task in a subprocess (via fork).
Python
6
star
40

django-easyfilters

Fork of https://bitbucket.org/evildmp/django-easyfilters/
Python
5
star
41

pytest-cover

Merged into https://github.com/schlamar/pytest-cov - use that instead!
Python
5
star
42

javascript-userscripts

Automatically exported from code.google.com/p/webmonkey-userscripts
JavaScript
4
star
43

python-mongosizeof

Python
4
star
44

pylint-fields

Pylint plugin for python-fields
Python
4
star
45

python-pygaljs

Python package providing assets from https://github.com/Kozea/pygal.js
Python
4
star
46

python-tax

2021 update: use tox-direct instead. This was a variant of Tox that didn't use virtualenvs at all - just installed everything in the current environment.
Python
4
star
47

django-secdownload-storage

Django storage backend that can be used to serve files via lighttpd's mod_secdownload module.
Python
4
star
48

docker-in-docker

An actually usable DIND. Includes a bunch of debug tools and docker-compose.
3
star
49

django-customfields

Couple of custom model fields for django: CachedManyToManyField and InheritedField
Python
3
star
50

python-pth

Simple and brief path traversal and filesystem access library.
Python
3
star
51

python-nameless-minimal

Python
3
star
52

python-ftpd-example

Python
2
star
53

dotfiles

My zsh setup
Shell
2
star
54

docker-manylinux

https://hub.docker.com/r/ionelmc/manylinux
Shell
2
star
55

python-matrix

Python
2
star
56

docker-buildpack-deps

Just buildpack-deps with some extras
Dockerfile
2
star
57

polymer-query-box

Query editor widget implemented as a Polymer webcomponent
JavaScript
2
star
58

polymer-json-box

Simple json edit widget implemented as a Polymer webcomponent
JavaScript
2
star
59

docker-fakebuntu

Ubuntu Xenial image running minimal services: systemd, journald, sshd, dind (docker in docker)
C
2
star
60

python-css-sprite

Python
1
star
61

django-image-editor

Allows to edit images in the browser
JavaScript
1
star
62

ppa-socat

Shell
1
star
63

pytest-benchmark-elasticsearch

Elasticseach storage backend for pytest-benchmark.
Python
1
star
64

t.ionelmc.ro

Google analytics to __utm.gif redirector.
Python
1
star
65

dockerskel

Abandoned. Check out https://github.com/evozon/django-docker
Shell
1
star