Comments (7)
i think i know what it is. i should probably add a footnote in the book. but you need to change the @dataclass(frozen=True)
to @dataclass(unsafe_hash=True)
. because sqlalchemy reasons.
from code.
Sorry Harry, my bad. It was failing in a copy of the model file with the frozen=True
that I generated before by following the chapter. Sorry again for the extra work and thanks, diving in the hashes topics of dataclasses gave me a nice insight of what is happening.
from code.
Hi,
I hit the very same issue.
More to that, even with InstrumentationManager, dataclass is changed by SA: after mapping is performed, SA has added some of its internal attributes (_sa_instance_state and _sa_class_manager) to dataclass, so we can not speak about decoupling and this beats the purpose of Registry in the first place since dataclass only looks like its decoupled.
I am not sure if there is a clean way to do this with SA, and posted question here. Additionaly, turns out that InstrumentationManager is very old, untested and almost never used.
If anyone have some ideas, please share.
Thank you kindly
from code.
as always it's a tradeoff. Yes, in order to work, SQLAlchemy has to get its claws pretty deep into your objects, so they are not "truly" decoupled. On the other hand, an ORM does a lot of the heavy lifting for getting objects in and out of database columns.
The alternative is not to use an ORM at all, which I've enjoyed doing on the last few projects. You have to write a lot of your own SQL tho! Check out the exercise for the reader here, so you can get a feel for the tradeoff http://www.cosmicpython.com/book/chapter_02_repository.html#api_endpoint_with_repo
from code.
Not sure about it. I'm taking the code from the repo and it is already defined as:
@dataclass(unsafe_hash=True)`
class OrderLine:
orderid: str
sku: str
qty: int
from code.
it's weird that you'd get a dataclasses.FrozenInstanceError
then?
do you have a repo you can share?
from code.
After fighting SqlAlchemy and solving this before finding this issue I'd just like to say that you can use frozen dataclasses.
However, you will have to provide a custom instrumentation manager.
Example:
For a frozen OrderLine
dataclass
@dataclass(unsafe_hash=True)
class OrderLine:
orderid: str
sku: str
qty: int
We can use a custom FrozenDataclassInstrumentationManager
.
from sqlalchemy import Column, Integer, MetaData String, Table
from sqlalchemy.ext.instrumentation import InstrumentationManager
from sqlalchemy.orm import mapper
metadata = MetaData()
DEL_ATTR = object()
class FrozenDataclassInstrumentationManager(InstrumentationManager):
def install_member(self, class_, key, implementation):
self.originals.setdefault(key, class_.__dict__.get(key, DEL_ATTR))
setattr(class_, key, implementation)
def uninstall_member(self, class_, key):
original = self.originals.pop(key, None)
if original is not DEL_ATTR:
setattr(class_, key, original)
else:
delattr(class_, key)
def dispose(self, class_):
del self.originals
delattr(class_, "_sa_class_manager")
def manager_getter(self, class_):
def get(cls):
return cls.__dict__["_sa_class_manager"]
return get
def manage(self, class_, manager):
self.originals = {}
setattr(class_, "_sa_class_manager", manager)
def get_instance_dict(self, class_, instance):
return instance.__dict__
def install_state(self, class_, instance, state):
instance.__dict__["state"] = state
def remove_state(self, class_, instance, state):
del instance.__dict__["state"]
def state_getter(self, class_):
def find(instance):
return instance.__dict__["state"]
return find
OrderLine.__sa_instrumentation_manager__ = FrozenDataclassInstrumentationManager
orderline_table = Table(
"order_lines",
metadata,
Column("id", Integer, primary_key=True, autoincrement=True),
Column("sku", String(128), nullable=False),
Column("quantity", Integer, nullable=False),
)
mapper(
OrderLine,
orderline_table,
)
https://stackoverflow.com/a/66941711/2398354
from code.
Related Issues (20)
- mapper is deprecated on SQLAlchemy 1.4+ HOT 1
- Shouldn't `seen` be emptied at some point? HOT 3
- Chapter 6 Excercise for the Reader: Separate UoW and Context Manager HOT 2
- chapter 4, service layer exercise, "decrement" should be "increment" in test names HOT 6
- [Question] How do you return values (like created ids) in Commands/from the message bus? HOT 2
- Error in the tests HOT 3
- A better optimistic concurrency solution HOT 1
- ConnectionError: Need to add both User-Agent header and timeout to requests HOT 5
- Multiply Money NamedTuple in Chapter 1 is no longer a valid operation HOT 1
- django appendix - allocation_set question
- Question: Why there is using a specific model with an abstract repository but not some abstract or base model? HOT 1
- [Question] How would you implement Flask event Listeners? HOT 1
- Using Async Await? HOT 18
- Postgre/API never came up HOT 2
- Listing or returning items with UoW raises sqlalchemy.orm.exc.DetachedInstanceError HOT 2
- Psycopg2 error: Symbol not found _PQbackendPID HOT 1
- Chapter 4: we do `session.commit()` but do we have any changes to commit? HOT 2
- Is there a reason why we don't use sql alchemy orm to create database models? HOT 1
- FastAPI, asynchronous ORM HOT 3
- Chapter 13. Dependency Injection use same uow concurrently in entrypoint? HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from code.