Skip to content
Projeler
Gruplar
Parçacıklar
Yardım
Yükleniyor...
Oturum aç / Kaydol
Gezinmeyi değiştir
C
cpython
Proje
Proje
Ayrıntılar
Etkinlik
Cycle Analytics
Depo (repository)
Depo (repository)
Dosyalar
Kayıtlar (commit)
Dallar (branch)
Etiketler
Katkıda bulunanlar
Grafik
Karşılaştır
Grafikler
Konular (issue)
0
Konular (issue)
0
Liste
Pano
Etiketler
Kilometre Taşları
Birleştirme (merge) Talepleri
0
Birleştirme (merge) Talepleri
0
CI / CD
CI / CD
İş akışları (pipeline)
İşler
Zamanlamalar
Grafikler
Paketler
Paketler
Wiki
Wiki
Parçacıklar
Parçacıklar
Üyeler
Üyeler
Collapse sidebar
Close sidebar
Etkinlik
Grafik
Grafikler
Yeni bir konu (issue) oluştur
İşler
Kayıtlar (commit)
Konu (issue) Panoları
Kenar çubuğunu aç
Batuhan Osman TASKAYA
cpython
Commits
42da874c
Kaydet (Commit)
42da874c
authored
Ara 14, 2007
tarafından
Raymond Hettinger
Dosyalara gözat
Seçenekler
Dosyalara Gözat
İndir
Eposta Yamaları
Sade Fark
Cleaner method naming convention
üst
90e10e79
Hide whitespace changes
Inline
Side-by-side
Showing
3 changed files
with
30 additions
and
30 deletions
+30
-30
collections.rst
Doc/library/collections.rst
+15
-15
collections.py
Lib/collections.py
+7
-7
test_collections.py
Lib/test/test_collections.py
+8
-8
No files found.
Doc/library/collections.rst
Dosyayı görüntüle @
42da874c
...
...
@@ -368,8 +368,8 @@ they add the ability to access fields by name instead of position index.
can be specified as a list of strings (such as ['x', 'y']).
Any valid Python identifier may be used for a fieldname except for names
starting
and ending with double underscores. Valid identifiers consist of
letters, digits, and underscores but do not start with a digit
and cannot be
starting
with an underscore. Valid identifiers consist of letters, digits,
and underscores but do not start with a digit or underscore
and cannot be
a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, *print*,
or *raise*.
...
...
@@ -386,15 +386,15 @@ Example::
class Point(tuple):
'Point(x, y)'
__slots__ = ()
_
_fields__
= ('x', 'y')
_
fields
= ('x', 'y')
def __new__(cls, x, y):
return tuple.__new__(cls, (x, y))
def __repr__(self):
return 'Point(x=%r, y=%r)' % self
def _
_asdict__
(self):
def _
asdict
(self):
'Return a new dict mapping field names to their values'
return dict(zip(('x', 'y'), self))
def _
_replace__
(self, **kwds):
def _
replace
(self, **kwds):
'Return a new Point object replacing specified fields with new values'
return Point(**dict(zip(('x', 'y'), self), **kwds))
x = property(itemgetter(0))
...
...
@@ -444,40 +444,40 @@ When casting a dictionary to a named tuple, use the double-star-operator::
In addition to the methods inherited from tuples, named tuples support
two additonal methods and a read-only attribute.
.. method:: somenamedtuple._
_asdict__
()
.. method:: somenamedtuple._
asdict
()
Return a new dict which maps field names to their corresponding values:
::
>>> p._
_asdict__
()
>>> p._
asdict
()
{'x': 11, 'y': 22}
.. method:: somenamedtuple._
_replace__
(kwargs)
.. method:: somenamedtuple._
replace
(kwargs)
Return a new instance of the named tuple replacing specified fields with new values:
::
>>> p = Point(x=11, y=22)
>>> p._
_replace__
(x=33)
>>> p._
replace
(x=33)
Point(x=33, y=22)
>>> for partnum, record in inventory.items():
... inventory[partnum] = record._
_replace__
(price=newprices[partnum], updated=time.now())
... inventory[partnum] = record._
replace
(price=newprices[partnum], updated=time.now())
.. attribute:: somenamedtuple._
_fields__
.. attribute:: somenamedtuple._
fields
Return a tuple of strings listing the field names. This is useful for introspection
and for creating new named tuple types from existing named tuples.
::
>>> p._
_fields__
# view the field names
>>> p._
fields
# view the field names
('x', 'y')
>>> Color = namedtuple('Color', 'red green blue')
>>> Pixel = namedtuple('Pixel', Point._
_fields__ + Color.__fields__
)
>>> Pixel = namedtuple('Pixel', Point._
fields + Color._fields
)
>>> Pixel(11, 22, 128, 255, 0)
Pixel(x=11, y=22, red=128, green=255, blue=0)'
...
...
@@ -493,13 +493,13 @@ the :meth:`__repr__` method:
Point(10.000, 20.000)
Default values can be implemented by starting with a prototype instance
and customizing it with :meth:`_
_replace__
`:
and customizing it with :meth:`_
replace
`:
::
>>> Account = namedtuple('Account', 'owner balance transaction_count')
>>> model_account = Account('<owner name>', 0.0, 0)
>>> johns_account = model_account._
_replace__
(owner='John')
>>> johns_account = model_account._
replace
(owner='John')
.. rubric:: Footnotes
...
...
Lib/collections.py
Dosyayı görüntüle @
42da874c
...
...
@@ -26,12 +26,12 @@ def namedtuple(typename, field_names, verbose=False):
(11, 22)
>>> p.x + p.y # fields also accessable by name
33
>>> d = p._
_asdict__()
# convert to a dictionary
>>> d = p._
asdict()
# convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._
_replace__(x=100) # __replace__
() is like str.replace() but targets named fields
>>> p._
replace(x=100) # _replace
() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
...
...
@@ -49,8 +49,8 @@ def namedtuple(typename, field_names, verbose=False):
raise
ValueError
(
'Type names and field names cannot start with a number:
%
r'
%
name
)
seen_names
=
set
()
for
name
in
field_names
:
if
name
.
startswith
(
'_
_'
)
and
name
.
endswith
(
'__'
)
and
len
(
name
)
>
3
:
raise
ValueError
(
'Field names cannot start
and end with double underscores
:
%
r'
%
name
)
if
name
.
startswith
(
'_
'
)
:
raise
ValueError
(
'Field names cannot start
with an underscore
:
%
r'
%
name
)
if
name
in
seen_names
:
raise
ValueError
(
'Encountered duplicate field name:
%
r'
%
name
)
seen_names
.
add
(
name
)
...
...
@@ -61,15 +61,15 @@ def namedtuple(typename, field_names, verbose=False):
template
=
'''class
%(typename)
s(tuple):
'
%(typename)
s(
%(argtxt)
s)'
__slots__ = ()
_
_fields__
= property(lambda self:
%(field_names)
r)
_
fields
= property(lambda self:
%(field_names)
r)
def __new__(cls,
%(argtxt)
s):
return tuple.__new__(cls, (
%(argtxt)
s))
def __repr__(self):
return '
%(typename)
s(
%(reprtxt)
s)'
%%
self
def _
_asdict__
(self, dict=dict, zip=zip):
def _
asdict
(self, dict=dict, zip=zip):
'Return a new dict mapping field names to their values'
return dict(zip(
%(field_names)
r, self))
def _
_replace__
(self, **kwds):
def _
replace
(self, **kwds):
'Return a new
%(typename)
s object replacing specified fields with new values'
return
%(typename)
s(**dict(zip(
%(field_names)
r, self), **kwds))
\n
'''
%
locals
()
for
i
,
name
in
enumerate
(
field_names
):
...
...
Lib/test/test_collections.py
Dosyayı görüntüle @
42da874c
...
...
@@ -25,11 +25,11 @@ class TestNamedTuple(unittest.TestCase):
self
.
assertRaises
(
ValueError
,
namedtuple
,
'abc'
,
'efg g
%
hi'
)
# field with non-alpha char
self
.
assertRaises
(
ValueError
,
namedtuple
,
'abc'
,
'abc class'
)
# field has keyword
self
.
assertRaises
(
ValueError
,
namedtuple
,
'abc'
,
'8efg 9ghi'
)
# field starts with digit
self
.
assertRaises
(
ValueError
,
namedtuple
,
'abc'
,
'_
_efg__ ghi'
)
# field with double underscores
self
.
assertRaises
(
ValueError
,
namedtuple
,
'abc'
,
'_
efg ghi'
)
# field with leading underscore
self
.
assertRaises
(
ValueError
,
namedtuple
,
'abc'
,
'efg efg ghi'
)
# duplicate field
namedtuple
(
'Point0'
,
'x1 y2'
)
# Verify that numbers are allowed in names
namedtuple
(
'_'
,
'
_ __ ___'
)
# Verify that underscores are allowed
namedtuple
(
'_'
,
'
a b c'
)
# Test leading underscores in a typename
def
test_instance
(
self
):
Point
=
namedtuple
(
'Point'
,
'x y'
)
...
...
@@ -46,17 +46,17 @@ class TestNamedTuple(unittest.TestCase):
self
.
assertEqual
(
repr
(
p
),
'Point(x=11, y=22)'
)
self
.
assert_
(
'__dict__'
not
in
dir
(
p
))
# verify instance has no dict
self
.
assert_
(
'__weakref__'
not
in
dir
(
p
))
self
.
assertEqual
(
p
.
_
_fields__
,
(
'x'
,
'y'
))
# test __fields__
attribute
self
.
assertEqual
(
p
.
_
_replace__
(
x
=
1
),
(
1
,
22
))
# test __replace__
method
self
.
assertEqual
(
p
.
_
_asdict__
(),
dict
(
x
=
11
,
y
=
22
))
# test __dict__
method
self
.
assertEqual
(
p
.
_
fields
,
(
'x'
,
'y'
))
# test _fields
attribute
self
.
assertEqual
(
p
.
_
replace
(
x
=
1
),
(
1
,
22
))
# test _replace
method
self
.
assertEqual
(
p
.
_
asdict
(),
dict
(
x
=
11
,
y
=
22
))
# test _asdict
method
# Verify that _
_fields__
is read-only
# Verify that _
fields
is read-only
try
:
p
.
_
_fields__
=
(
'F1'
,
'F2'
)
p
.
_
fields
=
(
'F1'
,
'F2'
)
except
AttributeError
:
pass
else
:
self
.
fail
(
'The _
_fields__
attribute needs to be read-only'
)
self
.
fail
(
'The _
fields
attribute needs to be read-only'
)
# verify that field string can have commas
Point
=
namedtuple
(
'Point'
,
'x, y'
)
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment