[issue35527] Make fields selectively immutable in dataclasses

2019-01-01 Thread Rémi Lapeyre

Rémi Lapeyre  added the comment:

Hi @rhettinger, this is similar to #33474.

I started working on an implementation of this.

With the implementation you propose, if a field has both init=True and 
frozen=True, it may be set after the creation of the instance:

@dataclass
class Person:
ssn: int = field(init=False, frozen=True)
name: str

p = Person(name='foo')
p.name = 'bar'
p.ssn = 1234

Wouldn't this conflict with the purpose of safe hashing?

I think it would need __setattr__ to be:

  def __setattr__(self, attr, value):
if attr in {'ssn', 'birth_city'}:
 raise TypeError(
 f'{attr!r} is not settable after initialization')
return super(cls, self).__setattr__(self, name, attr)

wouldn't it?

--
nosy: +remi.lapeyre

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue35527] Make fields selectively immutable in dataclasses

2018-12-18 Thread Yury Selivanov


Yury Selivanov  added the comment:

+1.  I've tried to use `field(frozen=True)` today and was surprised it's not 
supported.

--
nosy: +yselivanov

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue35527] Make fields selectively immutable in dataclasses

2018-12-18 Thread Raymond Hettinger


New submission from Raymond Hettinger :

The unsafe_hash option is unsafe only because it doesn't afford mutability 
protections.  This can be mitigated with selective immutability.

@dataclass
class Person:
ssn: int = field(immutable=True)
birth_city: int = field(immutable=True)
name: str  # A person can change their name
address: str   # A person can move  
age: int   # An age can change

This would generate something like this:

   def __setattr__(self, attr, value):
  if attr in {'ssn', 'birth_city'} and hasattr(self, attr):
   raise TypeError(
   f'{attr!r} is not settable after initialization')
  return object.__setattr__(self, name, attr)

A number of APIs are possible -- the important thing to be able to selectively 
block updates to particular fields (particularly those used in hashing and 
ordering).

--
assignee: eric.smith
components: Library (Lib)
messages: 332080
nosy: eric.smith, rhettinger
priority: normal
severity: normal
status: open
title: Make fields selectively immutable in dataclasses
type: enhancement
versions: Python 3.8

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com