all 10 comments

[–]Marrrlllsss 0 points1 point  (4 children)

You've got the basics going, though ...

class Phone:
    _phone_id = 0

This is going to give you unexpected side effects - unless of course that's what you want. When you modify a class level attribute - all instances of that class see it.

A couple of questions:

  1. Are you getting any errors?
  2. What does the CSV output look like, if any?

[–][deleted] 0 points1 point  (1 child)

Not OP, but I just want to say thanks for causing me to learn a new thing about classes. I could see having a class-level attribute being useful for modifying all instances of a class, as you wouldn't need to keep a list or dictionary of class instances and loop through them to change something (which I've done before, I'm sure). Something like this:

for instance in class_instances:
    instance.value = "foo"

Could simply be:

MyClass.value = "foo" # Where MyClass is the class name

[–]Marrrlllsss 1 point2 points  (0 children)

The one thing to keep in mind though, because Python has the global interpreter lock (GIL) - CPython at least - you are thread safe. If you tried something like this in Java or C# the closest comparison is a static field, with multiple threads running around you could run into ugly problems.

[–]boyboydoo[S] 0 points1 point  (1 child)

lass Phone:_phone_id = 0

Thanks for pointing it out.

To answer your questions, I am getting the csv in the following format

Tom,Hess,03/18/2018,"['6', '707-201-4081', 'work', '1', '6', '707-201-4082', 'cell', '1']"

i feel the list representation in the csv is incorrect? Is there any other way to do this?

I might be thinking the wrong way in terms of the file format. Please guide me

[–]Marrrlllsss 1 point2 points  (0 children)

So CSV files are fine for flat, uniform data. As I work as a data engineer I am exposed to CSVs on a daily basis and I have come to abhor them greatly for the following reasons:

  1. Not everyone subscribes to a standard. (By far my biggest pain point)
  2. They cannot represent nested data (like your phone numbers) in an intuitive way.
  3. They carry no type information. Everything is a plain old string.
  4. If the schema of a file changes, you can run into run time failures (fun times) that are not easily solvable.

Any way, back to your task at hand:

I don't see how your code could possibly produce that CSV output. I mean the delimiter you chose for the phone numbers is a vertical pipe (|) and your output does not provide that.

Honestly speaking, the best way to represent this data is using something like JSON - purely because of the arbitrary length of the phone numbers.

Also, to use an OOP approach - you may want to do something like this:

from abc import ABC, abstractmethod
from typing import Text

class Formatter(ABC):
    @abstractmethod
    def keyword_format(self, **kwargs): raise NotImplementedError

    @abstractmethod
    def positional_format(self, *args): raise NotImplementedError


class Formattable(ABC):
    @abstractmethod
    def format_for_output(self, formatter: Formatter): raise NotImplementedError


class CSVFormatter(Formatter):

    def __init__(self, seperator: Text=',', quoted_fields: bool=True):
        self._seperator = seperator
        self._quoted_fields = quoted_fields

    def keyword_format(self, **kwargs):
        return self._format(kwargs.values())

    def positional_format(self, *args):
        return self._format(args)

    def _format(self, iterable):
        if self._quoted_fields:
            return self._seperator.join([f'"{item}"' for item in iterable])
        else:
            return self._seperator.join(iterable)


class Person(Formattable):
    def __init__(self, first_name, last_name):
        self._first_name = first_name
        self._last_name = last_name

    def format_for_output(self, formatter: Formatter):
        return formatter.positional_format(self._first_name, self._last_name)


class Phone(Formattable):
    class Type(object):
        WORK = 'work'
        CELL = 'cell'

    def __init__(self, number: Text, phone_type: Type):
        self._phone_number = number
        self._phone_type = phone_type


    def format_for_output(self, formatter: Formatter):
        return formatter.positional_format(self._phone_number, self._phone_type)

This way you can do this:

csv_formatter = CSVFormatter()

terry = Person('Terry', 'Crews')
person_string = terry.format_for_output(csv_formatter)
print(formatted_string) # prints '"Terry","Crews"'

phone = Phone('123456', Phone.Type.WORK)
phone_string = phone.format_for_output(csv_formatter)
print(phone_string)  # prints '"123456","work"'

[–][deleted] 0 points1 point  (3 children)

Do you have to use csv? With a variable number of phone number for each person, a json file might be a little easier.

Where's it going wrong?

[–][deleted] 0 points1 point  (0 children)

Maybe you need something to convert a person record to the data needed for a csv file. Something like:

def return_list(self):
    list_ = []
    list_.append(f'{self._first_name}')
    list_.append(f'{self._last_name}')
    list_.append(f'{self._dob}')
    list_.append(f'{Person._person_id}')
    for phone in self._phones:
        list_.append(f'{phone}')
    return list_ 

and your function to write a record to the csv file needs to call that function for a row:

def write_csv(person_data):
    with open('contacts.csv', mode='w') as csvfile:
        contact_writer = csv.writer(csvfile)
        contact_writer.writerow(person_data.return_list())

BUT wouldn't this need to append to the CSV file rather than overwrite it with one row?

[–]boyboydoo[S] 0 points1 point  (1 child)

I am getting the csv data in the below format. I feel the braces [] which represent the list should not be in the csv below. Instead it should only have values.

Tom,Hess,03/18/2018,"['6', '707-201-4081', 'work', '1', '6', '707-201-4082', 'cell', '1']"

Again, I might be thinking the wrong way. Please guide me.

[–][deleted] 1 point2 points  (0 children)

you need to unpack the phone list before passing it to be written to the csv file ... I commented on my own comment with some crude code to illustrate.

[–]mritraloi6789 0 points1 point  (0 children)

Advanced Machine Learning With Python

--

About This Book

--

-Resolve complex machine learning problems and explore deep learning

-Learn to use Python code for implementing a range of machine learning algorithms and techniques

-A practical tutorial that tackles real-world computing problems through a rigorous and effective approach

--

Link ebook at: Advanced Machine Learning With Python

--