Skip to content

Hultner/Python-Data-Classes-Talk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

56 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Hultnér Technologies

Hultnér Technologies AB | Blog | Slides, PyCon SE 18 | Nordisk Python Community | @ahultner


♜ Python Data Classes

Data Classes, in Python 3.6 and beyond.

PyCon Sweden, December 12, 2018 (Stockholm)

Data Classes, in Python 3.6 and beyond (youtube video)
Python 3.7 is here and the @dataclass-decorator is a major new feature simplifying class-creation. In this talk, we will learn to use the power of data classes to make our codebases cleaner and leaner in a pythonic way.

We will also learn how to use the backport in Python 3.6 codebases before upgrading.

GothPy, May 17, 2018

By Alexander Hultnér at GothPy 17th of May 2018.
A talk about data classes and how you can use them today. The code we experimented with in the demo is available in demo.py.

♜ Dataclasses FAQ

What's the requirements for using data classes?
Python 3.6+ (ordered dicts, type annotations) via pip install dataclasses  

When can I use data classes without installing the package?
Dataclasses are native in 3.7

What similar patterns are used in older Python versions?
Attrs was a large inspiration for data classes
NamedTuples, based on tuples, regretted design choices have been improved in dataclasses. Got a Dataclasses-style syntax recently.
ORMs, SQLAlchemy, Djangon ORM, PeeWee, etc.

♜ Quick Reference

@dataclass
class A:
	# Required, need to be first; just like in function signatures
	a: str
	
	# Optional value, “nullable”
	b: Optional[str] = None
	
	# Optional with default value
	c: str = "default"
	
	# Executed at startup
	d: str = str(datetime.now())
	
	# Executed when creating class instance
	e: str = field(default_factory=lambda: f"Created: {datetime.now()}") 
	
>>> A("Required value")
A(a='Required value', b=None, c='default', d='2018-05-24 20:39:19.930841', e='Created: 2018-05-24 20:40:05.762934')

♜ Links

About

Notes for my Python Dataclasses presentation

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published