الأنواع المدمجة¶
Generated Thu 18 Jun 2026 05:00:56 UTC
استثناء¶
جميع الاستثناءات لديها سمات value و errno قابلة للقراءة، وليس فقط StopIteration و OSError.¶
السبب: تم تحسين MicroPython لتقليل حجم الكود.
الحل البديل: استخدم value فقط مع استثناءات StopIteration، و``errno`` مع استثناءات OSError. لا تستخدم هذه السمات أو تعتمد عليها في الاستثناءات الأخرى.
مثال على الكود:
e = Exception(1)
print(e.value)
print(e.errno)
CPython output: |
MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
AttributeError: 'Exception' object has no attribute 'value'
|
1
1
|
تسلسل الاستثناءات غير مُنفَّذ¶
مثال على الكود:
try:
raise TypeError
except TypeError:
raise ValueError
CPython output: |
MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
TypeError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 11, in <module>
ValueError
|
Traceback (most recent call last):
File "<stdin>", line 11, in <module>
ValueError:
|
السمات المعرَّفة من قِبَل المستخدم لاستثناءات مدمجة غير مدعومة¶
السبب: تم تحسين MicroPython بشكل كبير لاستخدام الذاكرة.
الحل البديل: استخدم فئات فرعية للاستثناءات معرَّفة من قِبَل المستخدم.
مثال على الكود:
e = Exception()
e.x = 0
print(e.x)
CPython output: |
MicroPython output: |
0
|
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
AttributeError: 'Exception' object has no attribute 'x'
|
الاستثناء في شرط حلقة while قد يحمل رقم سطر غير متوقع¶
السبب: تم تحسين فحوصات الشرط لتحدث في نهاية جسم الحلقة، ويُبلَّغ عن رقم ذلك السطر.
مثال على الكود:
l = ["-foo", "-bar"]
i = 0
while l[i][0] == "-":
print("iter")
i += 1
CPython output: |
MicroPython output: |
iter
iter
Traceback (most recent call last):
File "<stdin>", line 11, in <module>
IndexError: list index out of range
|
iter
iter
Traceback (most recent call last):
File "<stdin>", line 13, in <module>
IndexError: list index out of range
|
الأسلوب Exception.__init__ غير موجود.¶
السبب: إنشاء فئات فرعية من الفئات الأصلية غير مدعوم بالكامل في MicroPython.
الحل البديل: استخدم super() بدلاً من ذلك:
class A(Exception):
def __init__(self):
super().__init__()
مثال على الكود:
class A(Exception):
def __init__(self):
Exception.__init__(self)
a = A()
CPython output: |
MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 18, in <module>
File "<stdin>", line 15, in __init__
AttributeError: type object 'Exception' has no attribute '__init__'
|
OSError¶
OSError constructor returns a plain OSError for all errno values, rather than a relevant subtype.¶
Cause: MicroPython does not include the CPython-standard OSError subclasses.
Workaround: Catch OSError and use its errno attribute to discriminate the cause.
مثال على الكود:
import errno
errno_list = [ # i.e. the set implemented by micropython
errno.EPERM,
errno.ENOENT,
errno.EIO,
errno.EBADF,
errno.EAGAIN,
errno.ENOMEM,
errno.EACCES,
errno.EEXIST,
errno.ENODEV,
errno.EISDIR,
errno.EINVAL,
errno.EOPNOTSUPP,
errno.EADDRINUSE,
errno.ECONNABORTED,
errno.ECONNRESET,
errno.ENOBUFS,
errno.ENOTCONN,
errno.ETIMEDOUT,
errno.ECONNREFUSED,
errno.EHOSTUNREACH,
errno.EALREADY,
errno.EINPROGRESS,
]
def errno_output_type(n):
try:
raise OSError(n, "")
except OSError as e:
return f"{type(e).__name__}"
except Exception as e:
return f"non-OSError {type(e).__name__}"
else:
return "no error"
for n in errno_list:
print(errno.errorcode[n], "=", errno_output_type(n))
CPython output: |
MicroPython output: |
EPERM = PermissionError
ENOENT = FileNotFoundError
EIO = OSError
EBADF = OSError
EAGAIN = BlockingIOError
ENOMEM = OSError
EACCES = PermissionError
EEXIST = FileExistsError
ENODEV = OSError
EISDIR = IsADirectoryError
EINVAL = OSError
ENOTSUP = OSError
EADDRINUSE = OSError
ECONNABORTED = ConnectionAbortedError
ECONNRESET = ConnectionResetError
ENOBUFS = OSError
ENOTCONN = OSError
ETIMEDOUT = TimeoutError
ECONNREFUSED = ConnectionRefusedError
EHOSTUNREACH = OSError
EALREADY = BlockingIOError
EINPROGRESS = BlockingIOError
|
EPERM = OSError
ENOENT = OSError
EIO = OSError
EBADF = OSError
EAGAIN = OSError
ENOMEM = OSError
EACCES = OSError
EEXIST = OSError
ENODEV = OSError
EISDIR = OSError
EINVAL = OSError
EOPNOTSUPP = OSError
EADDRINUSE = OSError
ECONNABORTED = OSError
ECONNRESET = OSError
ENOBUFS = OSError
ENOTCONN = OSError
ETIMEDOUT = OSError
ECONNREFUSED = OSError
EHOSTUNREACH = OSError
EALREADY = OSError
EINPROGRESS = OSError
|
bytearray¶
تعيين شريحة مصفوفة مع الجانب الأيمن غير المدعوم¶
مثال على الكود:
b = bytearray(4)
b[0:1] = [1, 2]
print(b)
CPython output: |
MicroPython output: |
bytearray(b'\x01\x02\x00\x00\x00')
|
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
NotImplementedError: array/bytes required on right side
|
bytes¶
كائنات bytes تدعم أسلوب .format()¶
السبب: يسعى MicroPython إلى أن يكون تطبيقاً أكثر انتظاماً، لذا إذا كان كلٌّ من str و`bytes` يدعمان __mod__() (عامل %)، فمن المنطقي دعم format() لكليهما أيضاً. يمكن أيضاً استبعاد دعم __mod__ عند الترجمة، مما يُبقي format() فقط لتنسيق bytes.
الحل البديل: إذا كنت مهتماً بالتوافق مع CPython، فلا تستخدم .format() على كائنات bytes.
مثال على الكود:
print(b"{}".format(1))
CPython output: |
MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
AttributeError: 'bytes' object has no attribute 'format'
|
b'1'
|
bytes() مع الوسيطات المُسمَّاة غير مُنفَّذ¶
الحل البديل: مرِّر الترميز كوسيطة موضعية، مثلاً print(bytes('abc', 'utf-8'))
مثال على الكود:
print(bytes("abc", encoding="utf8"))
CPython output: |
MicroPython output: |
b'abc'
|
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: keyword argument(s) not implemented - use normal args instead
|
الفهرسة المتقطعة لـ bytes بخطوة != 1 غير مُنفَّذة¶
السبب: تم تحسين MicroPython بشكل كبير لاستخدام الذاكرة.
الحل البديل: استخدم حلقة صريحة لهذه العملية النادرة جداً.
مثال على الكود:
print(b"123"[0:3:2])
CPython output: |
MicroPython output: |
b'13'
|
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: only slices with step=1 (aka None) are supported
|
complex¶
MicroPython's complex() accepts certain incorrect values that CPython rejects¶
السبب: تم تحسين MicroPython بشكل كبير لاستخدام الذاكرة.
Workaround: Do not use non-standard complex literals as argument to complex()
MicroPython's complex() function accepts literals that contain a space and
no sign between the real and imaginary parts, and interprets it as a plus.
مثال على الكود:
try:
print(complex("1 1j"))
except ValueError:
print("ValueError")
CPython output: |
MicroPython output: |
ValueError
|
(1+1j)
|
dict¶
طريقة عرض مفاتيح القاموس لا تتصرف كمجموعة.¶
السبب: غير مُنفَّذ.
الحل البديل: حوِّل المفاتيح صراحةً إلى مجموعة قبل استخدام عمليات المجموعة.
مثال على الكود:
print({1: 2, 3: 4}.keys() & {1})
CPython output: |
MicroPython output: |
{1}
|
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
TypeError: unsupported types for __and__: 'dict_view', 'set'
|
float¶
MicroPython allows implicit conversion of objects in maths operations while CPython does not.¶
الحل البديل: يجب تغليف الكائنات في float(obj) للتوافق مع CPython.
مثال على الكود:
class Test:
def __float__(self):
return 0.5
print(2.0 * Test())
CPython output: |
MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 14, in <module>
TypeError: unsupported operand type(s) for *: 'float' and 'Test'
|
1.0
|
int¶
أسلوب bit_length غير موجود.¶
السبب: أسلوب bit_length غير مُنفَّذ.
الحل البديل: تجنب استخدام هذا الأسلوب في MicroPython.
مثال على الكود:
x = 255
print("{} is {} bits long.".format(x, x.bit_length()))
CPython output: |
MicroPython output: |
255 is 8 bits long.
|
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
AttributeError: 'int' object has no attribute 'bit_length'
|
لا يوجد تحويل int للأنواع المشتقة من int¶
الحل البديل: تجنب إنشاء فئات فرعية من الأنواع المدمجة ما لم يكن ذلك ضرورياً حقاً. يُفضَّل https://en.wikipedia.org/wiki/Composition_over_inheritance .
مثال على الكود:
class A(int):
__add__ = lambda self, other: A(int(self) + other)
a = A(42)
print(a + a)
CPython output: |
MicroPython output: |
84
|
Traceback (most recent call last):
File "<stdin>", line 14, in <module>
File "<stdin>", line 10, in <lambda>
TypeError: unsupported types for __radd__: 'int', 'int'
|
أسلوب to_bytes لا يُنفِّذ المعامل signed.¶
السبب: معامل الكلمة المفتاحية signed غير مُنفَّذ لـ int.to_bytes().
عندما يكون العدد الصحيح سالباً، يتصرف MicroPython بنفس طريقة CPython int.to_bytes(..., signed=True)
عندما يكون العدد الصحيح غير سالب، يتصرف MicroPython بنفس طريقة CPython int.to_bytes(..., signed=False).
(الفرق دقيق، لكن في CPython قد يتطلب عدد صحيح موجب مُحوَّل بـ signed=True بايتاً إضافياً في طول المخرجات، لاستيعاب بت الإشارة 0.)
الحل البديل: كن حذراً عند استدعاء to_bytes() على قيمة عدد صحيح قد تكون سالبة.
مثال على الكود:
x = -1
print(x.to_bytes(1, "big"))
CPython output: |
MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 16, in <module>
OverflowError: can't convert negative int to unsigned
|
b'\xff'
|
list¶
حذف عنصر من القائمة بخطوة != 1 غير مُنفَّذ¶
الحل البديل: استخدم حلقة صريحة لهذه العملية النادرة.
مثال على الكود:
l = [1, 2, 3, 4]
del l[0:4:2]
print(l)
CPython output: |
MicroPython output: |
[2, 4]
|
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
NotImplementedError:
|
تخزين شريحة قائمة مع كائن غير قابل للتكرار على الجانب الأيمن غير مُنفَّذ¶
السبب: الجانب الأيمن مقيَّد ليكون tuple أو list
الحل البديل: استخدم list(<iter>) على الجانب الأيمن لتحويل الكائن القابل للتكرار إلى list
مثال على الكود:
l = [10, 20]
l[0:1] = range(4)
print(l)
CPython output: |
MicroPython output: |
[0, 1, 2, 3, 20]
|
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
TypeError: object 'range' isn't a tuple or list
|
تخزين شريحة قائمة بخطوة != 1 غير مُنفَّذ¶
الحل البديل: استخدم حلقة صريحة لهذه العملية النادرة.
مثال على الكود:
l = [1, 2, 3, 4]
l[0:4:2] = [5, 6]
print(l)
CPython output: |
MicroPython output: |
[5, 2, 6, 4]
|
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
NotImplementedError:
|
memoryview¶
قد يصبح memoryview غير صالح إذا تغيّر حجم هدفه¶
السبب: يمنع CPython تغيير حجم كائن bytearray أو io.bytesIO بينما يوجد كائن memoryview يشير إليه. يتطلب MicroPython من المبرمج التأكد يدوياً من عدم تغيير حجم الكائن بينما يشير إليه أي memoryview.
في أسوأ الحالات، قد يتسبب تغيير حجم كائن هو هدف memoryview في جعل memoryview(s) يشير إلى ذاكرة محررة غير صالحة (خطأ الاستخدام بعد التحرير) وإتلاف بيئة تشغيل MicroPython.
الحل البديل: لا تغيّر حجم أي كائن bytearray أو io.bytesIO تم تعيين memoryview له.
مثال على الكود:
b = bytearray(b"abcdefg")
m = memoryview(b)
b.extend(b"hijklmnop")
print(b, bytes(m))
CPython output: |
MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 12, in <module>
BufferError: Existing exports of data: object cannot be re-sized
|
bytearray(b'abcdefghijklmnop') b'abcdefg'
|
range¶
Range objects with large start or stop arguments misbehave.¶
Cause: Intermediate calculations overflow the C mp_int_t type
Workaround: Avoid using such ranges
مثال على الكود:
from sys import maxsize
# A range including `maxsize-1` cannot be created
try:
print(range(-maxsize - 1, 0))
except OverflowError:
print("OverflowError")
# A range with `stop-start` exceeding sys.maxsize has incorrect len(), while CPython cannot calculate len().
try:
print(len(range(-maxsize, maxsize)))
except OverflowError:
print("OverflowError")
# A range with `stop-start` exceeding sys.maxsize has incorrect len()
try:
print(len(range(-maxsize, maxsize, maxsize)))
except OverflowError:
print("OverflowError")
CPython output: |
MicroPython output: |
range(-9223372036854775808, 0)
OverflowError
2
|
OverflowError
0
0
|
str¶
MicroPython accepts the "," grouping option with any radix, unlike CPython¶
Cause: To reduce code size, MicroPython does not issue an error for this combination
Workaround: Do not use a format string like {:,b} if CPython compatibility is required.
مثال على الكود:
try:
print("{:,b}".format(99))
except ValueError:
print("ValueError")
try:
print("{:,x}".format(99))
except ValueError:
print("ValueError")
try:
print("{:,o}".format(99))
except ValueError:
print("ValueError")
CPython output: |
MicroPython output: |
ValueError
ValueError
ValueError
|
110,0011
63
143
|
MicroPython accepts but does not properly implement the "," or "_" grouping character for float values¶
Cause: To reduce code size, MicroPython does not implement this combination. Grouping characters will not appear in the number's significant digits and will appear at incorrect locations in leading zeros.
Workaround: Do not use a format string like {:,f} if exact CPython compatibility is required.
مثال على الكود:
print("{:,f}".format(3141.159))
print("{:_f}".format(3141.159))
print("{:011,.2f}".format(3141.159))
print("{:011_.2f}".format(3141.159))
CPython output: |
MicroPython output: |
3,141.159000
3_141.159000
0,003,141.16
0_003_141.16
|
3141.159000
3141.159000
000,3141.16
0_003141.16
|
السمات/الفهرسة غير مُنفَّذة¶
مثال على الكود:
print("{a[0]}".format(a=[1, 2]))
CPython output: |
MicroPython output: |
1
|
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: attributes not supported
|
str(...) مع الوسيطات المُسمَّاة غير مُنفَّذ¶
الحل البديل: أدخل تنسيق الترميز مباشرةً. مثلاً print(bytes('abc', 'utf-8'))
مثال على الكود:
print(str(b"abc", encoding="utf8"))
CPython output: |
MicroPython output: |
abc
|
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: keyword argument(s) not implemented - use normal args instead
|
str.ljust() و str.rjust() غير مُنفَّذتَين¶
السبب: تم تحسين MicroPython بشكل كبير لاستخدام الذاكرة. تتوفر حلول بديلة سهلة.
الحل البديل: بدلاً من s.ljust(10) استخدم "%-10s" % s، وبدلاً من s.rjust(10) استخدم "% 10s" % s. أو بدلاً من ذلك، "{:<10}".format(s) أو "{:>10}".format(s).
مثال على الكود:
print("abc".ljust(10))
CPython output: |
MicroPython output: |
abc
|
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
AttributeError: 'str' object has no attribute 'ljust'
|
None كأول وسيطة لـ rsplit مثل str.rsplit(None, n) غير مُنفَّذ¶
مثال على الكود:
print("a a a".rsplit(None, 1))
CPython output: |
MicroPython output: |
['a a', 'a']
|
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: rsplit(None,n)
|
الفهرسة بخطوة != 1 لم تُنفَّذ بعد¶
مثال على الكود:
print("abcdefghi"[0:9:2])
CPython output: |
MicroPython output: |
acegi
|
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: only slices with step=1 (aka None) are supported
|
tuple¶
قراءة عناصر tuple بخطوة != 1 غير مُنفَّذة¶
مثال على الكود:
print((1, 2, 3, 4)[0:4:2])
CPython output: |
MicroPython output: |
(1, 3)
|
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: only slices with step=1 (aka None) are supported
|