3

I have come to python from C++ (I also know a little Java). I am writing code to exercise a server so I basically use http methods to send a load of requests to the server. As part of my code I created a class and called it testdata. This contains basically test input data (to send in requests) and output data to check against.

With my C++ hat on I created a load of getter and setter methods which were one lines. I even had an __init__ method to set eg self.<some_attribute_name> = "" or some safe default.

I realise now that you can freely add attributes to a python object and there is no need to pre-initialise simple variables in init.

So I have some questions.

  1. For my testdata class, should I even be using a class?

  2. I just add data items like this:

    import testing
    
    td = testing.testdata()
    td.sessionid = "123"
    
  3. But what about access eg to td.sessionid before I have previously assigned a value. I know I can use hasattr but that is an extra burden. Do I have to make sure I always assign first? What if I do td.sessionid before it is even assigned anything? I will get an AttributeError at runtime. How to handle this?

  4. Due to problem 3. above. Should I always use __init__ to initialise member data to safe default values? eg "" for strings.

What are recommended approaches in Python?

2 Answers 2

5

Generally, you use class attributes to provide defaults:

class TestData(object):
    sessionid = None

You only need to define a __init__ if you need to provide a new instance with attributes that have to be uniquely set for that new instance.

However, don't define a class just to hold state. Use classes when you are going to provide both state and behaviour. Python's standard types and library is otherwise more than rich enough to cover the just-data needs.

3
  • I don't agree with not using classes for just data sets. The member access syntax is more convenient than dictionary access and defining defaults is also more convenient. So depending on how the data is used a class may or may not be better.
    – Jan Hudec
    Commented Jul 26, 2013 at 12:20
  • 3
    @JanHudec: That's what we have collections.namedtuple for, for example. Commented Jul 26, 2013 at 12:20
  • One learns all the time. Never seen that one used yet.
    – Jan Hudec
    Commented Jul 26, 2013 at 12:26
3

In answer to your questions:

1. In my experience a collection of related config data has always been contained in a dictionary (http://docs.python.org/2/tutorial/datastructures.html#dictionaries). This allows easy manipulation of the data without the worries of instantiation required by classes. Behind the scenes a dictionary is just a hash table.

2. I don't see the question here but for a dictionary you have a number of options, see the link above but as an example:

data = {
    "foo": "123"
}
data["bar"] = 42

This example shows both creating a dictionary with a known key value pair but also how to add a new one.

3. Firstly I don't see why you would want to access it without it being assigned, what would be the point? However you could simply use the get function to get around this issue. So following on from the previous example:

data.get("foo")

would give you "123" while:

data.get("woops")

would give you None. Also you can pass in a second argument as the default e.g.

data.get("woops", "backup")

would give you backup

Just for completeness if you were to use the standard [] access notation attempting to access a key that does not exist would throw (called raise in python) a KeyError but you could deal with this using standard try/catch mechanisms (called try/except in python)

4. This point is kind of moot if you were to go down the dictionary root but put quite simply yes. Realistically this is what the constructor is for to 'construct' the instance of the object. Just because python lets you dynamically allocate new instance variables doesn't mean its the right thing to do. If you were to pass a lint checker over that code it would certainly moan

1
  • I didn't know about the .get syntax. Yes if I didn't need the power of member functions I would go with a dictionary for this type of requirement.
    – user619818
    Commented Jul 30, 2013 at 10:06

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.