Read-only attribute in module

Ben Finney ben+python at benfinney.id.au
Thu Feb 9 13:32:59 CET 2012


Mateusz Loskot <mateusz at loskot.net> writes:

> I'm wondering, is there any mean to implement attribute in module
> scope which is read-only?

Python is designed by and for consenting adults. Rather than
restricting, instead use conventions to make your intent clear to the
user of your library.

> So, the following
>
> import xyz
> print(xyz.flag)  # OK
> xyz.flag = 0    # error due to no write access

PEP 8 <URL:http://www.python.org/dev/peps/pep-0008/> gives the style
guide for Python code (strictly for the standard library, but it is
recommended for all Python code).

If you want a module attribute that is intended to remain bound to the
same value, use PEP 8's recommendation and name the attribute in
‘ALL_UPPER_CASE’.

If you want an attribute that is intended only for internal use (an
implementation detail that should not be relied upon outside the
library), use PEP 8's recommendation and name the attribute with a
‘_single_leading_underscore’.

-- 
 \       “We jealously reserve the right to be mistaken in our view of |
  `\      what exists, given that theories often change under pressure |
_o__)              from further investigation.” —Thomas W. Clark, 2009 |
Ben Finney



More information about the Python-list mailing list