How to provide periodic table information to Python module

12k views Asked by At

I'm writing a Python module, and I want many of the functions to have access to information on the periodic table; namely, atomic numbers and their corresponding atomic symbols. The information should never change. I'm struggling with how to implement this.

Hash vs. tuple: A hash would provide very convenient lookup, but could easily be changed. A tuple at least is immutable.

Variable vs. class: I've been trying to keep everything in my module in classes when possible, but I'm not sure that makes sense here, since there should only ever be one periodic table. One source of truth.

Maybe I'm missing something entirely. I've just never seen someone hardcode that much information in the Python projects I've looked at. Guidance would be very appreciated.

2

There are 2 answers

1
Matt Ellen On

Lots of people have already encoded the periodic table in textual form. Ask them for their data. For example if your software is compatible with Wikipedia's licence, then grab the data from them programmatically and put it in a database of some sort, or just grab it on demand.

5
Steve Barnes On

You could always start by installing periodictable it seems very complete - even if you have to do this yourself you can take a look at the code. I used:

sudo pip install periodictable

and then was able to do:

>>> import periodictable as pt
>>> g = pt.Au
>>> g.isotopes
[171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205]
>>> g.density
19.3
>>> g.mass
196.96655
>>> g.name
'gold'
>>> 

Personally I would make a class for element and then encode the members appropriate in instances of the class. e.g.:

class Element(object):
    """ This class represents a single element in the periodic table """
    def __init__(self, Symbol, Name, Number, Group, Period, etc):
       """ 
       Initialises a single element instance all the above prarmeters are required 
       """
       self.Symbol = Symbol
       #etc

You can then have either a definition of each element in your periodic table file, or organise them into named blocks or a single class, etc.