Create an Atom from a NumPy dtype. An optional default value may be specified as the dflt argument. Information in the dtype not represented in an Atom is ignored:: >>> import numpy as np >>> Atom.from_dtype(np.dtype((np.int16, (2, 2))))
(cls, dtype: np.dtype, dflt: Any = None)
| 340 | |
| 341 | @classmethod |
| 342 | def from_dtype(cls, dtype: np.dtype, dflt: Any = None) -> Atom: |
| 343 | """Create an Atom from a NumPy dtype. |
| 344 | |
| 345 | An optional default value may be specified as the dflt |
| 346 | argument. Information in the dtype not represented in an Atom is |
| 347 | ignored:: |
| 348 | |
| 349 | >>> import numpy as np |
| 350 | >>> Atom.from_dtype(np.dtype((np.int16, (2, 2)))) |
| 351 | Int16Atom(shape=(2, 2), dflt=0) |
| 352 | >>> Atom.from_dtype(np.dtype('float64')) |
| 353 | Float64Atom(shape=(), dflt=0.0) |
| 354 | |
| 355 | Note: for easier use in Python 3, where all strings lead to the |
| 356 | Unicode dtype, this dtype will also generate a StringAtom. Since |
| 357 | this is only viable for strings that are castable as ascii, a |
| 358 | warning is issued. |
| 359 | |
| 360 | >>> Atom.from_dtype(np.dtype('U20')) # doctest: +SKIP |
| 361 | Atom.py:392: FlavorWarning: support for unicode type is very |
| 362 | limited, and only works for strings that can be cast as ascii |
| 363 | StringAtom(itemsize=20, shape=(), dflt=b'') |
| 364 | |
| 365 | """ |
| 366 | basedtype = dtype.base |
| 367 | shape = tuple(SizeType(i) for i in dtype.shape) |
| 368 | if basedtype.names: |
| 369 | raise ValueError( |
| 370 | "compound data types are not supported: %r" % dtype |
| 371 | ) |
| 372 | if basedtype.shape != (): |
| 373 | raise ValueError("nested data types are not supported: %r" % dtype) |
| 374 | if basedtype.kind == "S": # can not reuse something like 'string80' |
| 375 | itemsize = basedtype.itemsize |
| 376 | return cls.from_kind("string", itemsize, shape, dflt) |
| 377 | elif basedtype.kind == "U": |
| 378 | # workaround for unicode type (standard string type in Python 3) |
| 379 | warnings.warn( |
| 380 | "support for unicode type is very limited, and " |
| 381 | "only works for strings that can be cast as ascii", |
| 382 | FlavorWarning, |
| 383 | ) |
| 384 | itemsize = basedtype.itemsize // 4 |
| 385 | assert ( |
| 386 | str(itemsize) in basedtype.str |
| 387 | ), "something went wrong in handling unicode." |
| 388 | return cls.from_kind("string", itemsize, shape, dflt) |
| 389 | # Most NumPy types have direct correspondence with PyTables types. |
| 390 | return cls.from_type(basedtype.name, shape, dflt) |
| 391 | |
| 392 | @classmethod |
| 393 | def from_type( |