Re: [Tutor] Only appending one object to list, when I am expecting more than 1

2019-02-27 Thread Alex Kleider

On 2019-02-27 05:25, AdamC wrote:
That's great - bug found. Thanks. However the next question is, how do 
I
create an instance of a class with variable parameters (i.e. with 
dateAdded
already computed and stored, or with dateAdded created for the first 
time)?


Might this work?

class myClass(object):
  __init__(self, added_date=None):
if added_date:
self.date_attribute = added_date
else:
self.date_attribute = my_way_of_calculating_added_date()

You can then instantiate in either of these ways:

my_instance = myClass()

or

my_instance = myClass(my_way_of_calculating_added_date())
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Only appending one object to list, when I am expecting more than 1

2019-02-27 Thread Alan Gauld via Tutor
On 27/02/2019 13:25, AdamC wrote:
> That's great - bug found. Thanks. However the next question is, how do I
> create an instance of a class with variable parameters (i.e. with dateAdded
> already computed and stored, or with dateAdded created for the first time)?
> 
> I hope that makes sense.

Not really.
There are several possible interpretations of your question.

When asking concept things it often helps to include some
hypothetical examples of what you would like to happen.
For example in this case you might say you want:

c = myClass()  # default
c2 = myClass(anInt,aString)  # two args
c3 = myClass(aDate,aFloat)   # two different args
etc.

Or you maybe wanted something else? If so show
us how you think it would work and we can then
show you how to get something close.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Only appending one object to list, when I am expecting more than 1

2019-02-27 Thread Mats Wichmann
Without spending a lot of time on an answer, you can use default arguments in 
the cases where only the number of arts differs in your instance creation. If 
there's larger differences, look into @classmethod.

On February 27, 2019 5:25:02 AM PST, AdamC  wrote:
>That's great - bug found. Thanks. However the next question is, how do
>I
>create an instance of a class with variable parameters (i.e. with
>dateAdded
>already computed and stored, or with dateAdded created for the first
>time)?
>
>I hope that makes sense.
>
>Adam
>
>On Tue, 26 Feb 2019 at 18:24, Tobiah  wrote:
>
>>
>>
>> On 2/26/19 6:39 AM, AdamC wrote:
>> > Sorry folks - my code didn't work due to my debug var count to
>ensure
>> that
>> > I was looping properly.
>> >
>> > It should be:
>>
>> As was pointed out, the problem is not in your code.  It's in your
>> data.  You only have one record with a proper 'tpe' value, so that's
>> all you get in your media list.
>>
>>
>> Toby
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
>-- 
>--
>You back your data up on the same planet?
>http://www.monkeez.org
>PGP key: 0x7111B833
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Only appending one object to list, when I am expecting more than 1

2019-02-27 Thread Tobiah

Without fully understanding what you're getting at, I'll offer this:

class Car(object):

def __init__(self, **kwargs):

self.features = {
'make': 'Hyundai',
'color': 'purple'
}

self.features.update(kwargs)


c = Car(color='yellow', year=2017)


print c.features

output:

{'color': 'yellow', 'make': 'Hyundai', 'year': 2017}





On 2/27/19 5:25 AM, AdamC wrote:

That's great - bug found. Thanks. However the next question is, how do I
create an instance of a class with variable parameters (i.e. with dateAdded
already computed and stored, or with dateAdded created for the first time)?

I hope that makes sense.

Adam

On Tue, 26 Feb 2019 at 18:24, Tobiah  wrote:




On 2/26/19 6:39 AM, AdamC wrote:

Sorry folks - my code didn't work due to my debug var count to ensure

that

I was looping properly.

It should be:


As was pointed out, the problem is not in your code.  It's in your
data.  You only have one record with a proper 'tpe' value, so that's
all you get in your media list.


Toby
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor





___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Only appending one object to list, when I am expecting more than 1

2019-02-27 Thread AdamC
That's great - bug found. Thanks. However the next question is, how do I
create an instance of a class with variable parameters (i.e. with dateAdded
already computed and stored, or with dateAdded created for the first time)?

I hope that makes sense.

Adam

On Tue, 26 Feb 2019 at 18:24, Tobiah  wrote:

>
>
> On 2/26/19 6:39 AM, AdamC wrote:
> > Sorry folks - my code didn't work due to my debug var count to ensure
> that
> > I was looping properly.
> >
> > It should be:
>
> As was pointed out, the problem is not in your code.  It's in your
> data.  You only have one record with a proper 'tpe' value, so that's
> all you get in your media list.
>
>
> Toby
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


-- 
--
You back your data up on the same planet?
http://www.monkeez.org
PGP key: 0x7111B833
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Only appending one object to list, when I am expecting more than 1

2019-02-26 Thread Tobiah




On 2/26/19 6:39 AM, AdamC wrote:

Sorry folks - my code didn't work due to my debug var count to ensure that
I was looping properly.

It should be:


As was pointed out, the problem is not in your code.  It's in your
data.  You only have one record with a proper 'tpe' value, so that's
all you get in your media list.


Toby
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Only appending one object to list, when I am expecting more than 1

2019-02-26 Thread AdamC
Sorry folks - my code didn't work due to my debug var count to ensure that
I was looping properly.

It should be:
media = []

def loadFile():
filename = input('Filename? ')
f = open(filename, 'r')
createObjects(f)

def createObjects(f):
'''Takes a file object and iterates through entries, passing them to
create
object, depending on what object it is.'''
for line in f:
data = json.loads(line)
print(type(data['tpe']))
name = data['name']
platform = data['platform']
dateAdded = data['dateAdded']
tpe = data['tpe']
if data['tpe'] == 'Game':
a = createGame(name, platform, dateAdded,tpe)
game = {a: tpe}
media.append(game)
if data['tpe'] == 'Film':
a = createFilm(name, platform, dateAdded,tpe)
film = {a: tpe}
media.append(film)
# For some reason I'm only getting one object at a time now when
appending to media
print(len(media))

def createGame(name, platform, dateAdded, tpe):
return Game(name, platform, dateAdded)

def createFilm(name, platform, dateAdded, tpe):
return Film(name, platform, dateAdded)

Also, there is a bug that places an instance variable of dateAdded to tpe,
which is causing an error. This might be why I'm not getting more objects
than I expect.

My class is:

import datetime
class Media:
def __init__(self, name, platform, tpe):
self.name = name
self.platform = platform
date = datetime.datetime.now()
datestring = date.strftime("%Y:%m:%d:%H:%M:%s")
self.dateAdded = datestring
self.tpe = tpe
#self.dateAdded = datetime.datetime.now()

and

from . import media
#import media
class Game(media.Media):
#tpe = 'game'
# def __init__(self):
#self.type = 'game'

Thanks.
Adam


On Tue, 26 Feb 2019 at 10:02, Cameron Simpson  wrote:

> Thank you for a well formed problem description.
>
> However, as Steven has remarked the code you've included doesn't run.
> Can you follow up/reply with your actual working script, and also
> include some of the output you get.
>
> That said, I've a few small remarks about the code you have posted:
>
> On 26Feb2019 09:09, AdamC  wrote:
> >I'm creating lots of objects from json in a file. Part of reading the json
> >back means that it iterates over the file and loads a json object and then
> >creates the object from the dictionary.
> >
> >This is my  file:
> >
> >{"name": "Dwarf Fortress", "platform": "steam", "dateAdded":
> >"2019:02:25:16:56:1551113768", "tpe": "2019:02:21:13:49:1550756942"}
> >{"name": "Jaws", "platform": "Netflix", "dateAdded":
> >"2019:02:25:16:56:1551113768", "tpe": "2019:02:21:13:49:1550756960"}
> >{"name": "Wargames", "platform": "CLI", "dateAdded":
> >"2019:02:25:16:59:1551113984", "tpe": "Game"}
>
> BTW, I notice that only one of these rows has the "tpe" field set to
> "Game" or "Film", specificly the last one. So based on your code below,
> only one of these rows gets appended to the media array. Remarks below
> on writing code which is less prone to hiding this kind of problem.
>
> >and these are the functions that help load that file:
> >
> >media = []
> >
> >def loadFile():
> >filename = input('Filename? ')
> >f = open(filename, 'r')
> >createObjects(f)
>
> This f=open code would normally be written like this:
>
> with open(filename, 'r') as f:
> createObjects(f)
>
> That construction ensures that the file gets closed after running
> "createObjects()". As it is in your code the file is not explicitly
> closed; the CPython interpreter will, as it happens, close the file
> pretty promptly when "f" goes out of scope, but the language definition
> doesn't require such immediacy.
>
> >def createObjects(f):
> >'''Takes a file object and iterates through entries, passing them to
> >create
> >object, depending on what object it is.'''
> >for line in f:
> >count = count + 1
> >data = json.loads(line)
> >print(type(data['tpe']))
> >name = data['name']
> >platform = data['platform']
> >dateAdded = data['dateAdded']
> >tpe = data['tpe']
> >if data['tpe'] == 'Game':
> >a = createGame(name, platform, dateAdded,tpe)
> >game = {a: tpe}
> >media.append(game)
> >if data['tpe'] == 'Film':
> >a = createFilm(name, platform, dateAdded,tpe)
> >film = {a: tpe}
> >media.append(film)
>
> These if statements don't cover the case when "tpe" isn't "Game" or
> "Film", and (in other circumstances) could conceivably add two objects.
> If you construct it like this instead:
>
> if data['tpe'] == 'Game':
> a = createGame(name, platform, dateAdded,tpe)
> game = {a: tpe}
> media.append(game)
> elif data['tpe'] == 'Film':
> a = createFilm(name, platform, dateAdded,tpe)
> film = {a: tpe}
>

Re: [Tutor] Only appending one object to list, when I am expecting more than 1

2019-02-26 Thread Cameron Simpson

Thank you for a well formed problem description.

However, as Steven has remarked the code you've included doesn't run.  
Can you follow up/reply with your actual working script, and also 
include some of the output you get.


That said, I've a few small remarks about the code you have posted:

On 26Feb2019 09:09, AdamC  wrote:

I'm creating lots of objects from json in a file. Part of reading the json
back means that it iterates over the file and loads a json object and then
creates the object from the dictionary.

This is my  file:

{"name": "Dwarf Fortress", "platform": "steam", "dateAdded":
"2019:02:25:16:56:1551113768", "tpe": "2019:02:21:13:49:1550756942"}
{"name": "Jaws", "platform": "Netflix", "dateAdded":
"2019:02:25:16:56:1551113768", "tpe": "2019:02:21:13:49:1550756960"}
{"name": "Wargames", "platform": "CLI", "dateAdded":
"2019:02:25:16:59:1551113984", "tpe": "Game"}


BTW, I notice that only one of these rows has the "tpe" field set to 
"Game" or "Film", specificly the last one. So based on your code below, 
only one of these rows gets appended to the media array. Remarks below 
on writing code which is less prone to hiding this kind of problem.



and these are the functions that help load that file:

media = []

def loadFile():
   filename = input('Filename? ')
   f = open(filename, 'r')
   createObjects(f)


This f=open code would normally be written like this:

   with open(filename, 'r') as f:
   createObjects(f)

That construction ensures that the file gets closed after running 
"createObjects()". As it is in your code the file is not explicitly 
closed; the CPython interpreter will, as it happens, close the file 
pretty promptly when "f" goes out of scope, but the language definition 
doesn't require such immediacy.



def createObjects(f):
   '''Takes a file object and iterates through entries, passing them to
create
   object, depending on what object it is.'''
   for line in f:
   count = count + 1
   data = json.loads(line)
   print(type(data['tpe']))
   name = data['name']
   platform = data['platform']
   dateAdded = data['dateAdded']
   tpe = data['tpe']
   if data['tpe'] == 'Game':
   a = createGame(name, platform, dateAdded,tpe)
   game = {a: tpe}
   media.append(game)
   if data['tpe'] == 'Film':
   a = createFilm(name, platform, dateAdded,tpe)
   film = {a: tpe}
   media.append(film)


These if statements don't cover the case when "tpe" isn't "Game" or 
"Film", and (in other circumstances) could conceivably add two objects.  
If you construct it like this instead:


   if data['tpe'] == 'Game':
   a = createGame(name, platform, dateAdded,tpe)
   game = {a: tpe}
   media.append(game)
   elif data['tpe'] == 'Film':
   a = createFilm(name, platform, dateAdded,tpe)
   film = {a: tpe}
   media.append(film)
   else:
   print("Unhandled tpe value:", repr(tpe))

then (a) only 1 branch can ever apply and (b) reports any unexpected 
values which would otherwise _silently_ get ignored. By always having a 
final "else" in an if/elif//else chain you can catch/observe these 
unhandled situations.



def createGame(name, platform, dateAdded, tpe):
   return Game(name, platform, dateAdded)

def createFilm(name, platform, dateAdded, tpe):
   return Film(name, platform, dateAdded)


Unless there's more stuff happening in these functions which you've 
stripped out for clarity you could just call the object constructors 
directly from the if statements:


   if data['tpe'] == 'Game':
   a = Game(name, platform, dateAdded)
   game = {a: tpe}
   media.append(game)

Why would I only get one object in media, even though all three are 
created?


As you may gather, all three input lines are processed, but only one 
gets turned into an object to add to media. Change the if/if into an 
if/elif/else and see if things become more obvious.


Cheers,
Cameron Simpson 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Only appending one object to list, when I am expecting more than 1

2019-02-26 Thread Peter Otten
AdamC wrote:

> I'm creating lots of objects from json in a file. Part of reading the json
> back means that it iterates over the file and loads a json object and then
> creates the object from the dictionary.
> 
> This is my  file:
> 
> {"name": "Dwarf Fortress", "platform": "steam", "dateAdded":
> "2019:02:25:16:56:1551113768", "tpe": "2019:02:21:13:49:1550756942"}
> {"name": "Jaws", "platform": "Netflix", "dateAdded":
> "2019:02:25:16:56:1551113768", "tpe": "2019:02:21:13:49:1550756960"}
> {"name": "Wargames", "platform": "CLI", "dateAdded":
> "2019:02:25:16:59:1551113984", "tpe": "Game"}
> 
> and these are the functions that help load that file:
> 
> media = []
> 
> def loadFile():
> filename = input('Filename? ')
> f = open(filename, 'r')
> createObjects(f)
> 
> def createObjects(f):
> '''Takes a file object and iterates through entries, passing them to
> create
> object, depending on what object it is.'''
> for line in f:
> count = count + 1
> data = json.loads(line)
> print(type(data['tpe']))
> name = data['name']
> platform = data['platform']
> dateAdded = data['dateAdded']
> tpe = data['tpe']
> if data['tpe'] == 'Game':
> a = createGame(name, platform, dateAdded,tpe)
> game = {a: tpe}
> media.append(game)
> if data['tpe'] == 'Film':
> a = createFilm(name, platform, dateAdded,tpe)
> film = {a: tpe}
> media.append(film)
> # For some reason I'm only getting one object at a time now when
> appending to media
> print(len(media))
> 
> def createGame(name, platform, dateAdded, tpe):
> return Game(name, platform, dateAdded)
> 
> def createFilm(name, platform, dateAdded, tpe):
> return Film(name, platform, dateAdded)
> 
> (This isn't the order that the functions are held in the module).
> Why would I only get one object in media, even though all three are
> created?

Only one record in your jsonl sample has a 'tpe' handled by createObjects(). 
To make it easier to catch this problem (invalid or unsuspected data) I 
suggest that you rewrite the

> if data['tpe'] == 'Game':
> a = createGame(name, platform, dateAdded,tpe)
> game = {a: tpe}
> media.append(game)
> if data['tpe'] == 'Film':
> a = createFilm(name, platform, dateAdded,tpe)
> film = {a: tpe}
> media.append(film)

part of your code as

if data['tpe'] == 'Game':
a = createGame(name, platform, dateAdded,tpe)
game = {a: tpe}
media.append(game)
elif data['tpe'] == 'Film':
a = createFilm(name, platform, dateAdded,tpe)
film = {a: tpe}
media.append(film)
else:
# Instead of the error message you may also raise an exception.
print(
"Warning: unknown tpe={!r}".format(data["tpe"]),
file=sys.stderr
)

The unconditional else allows you to ensure that every line will be handled.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Only appending one object to list, when I am expecting more than 1

2019-02-26 Thread Steven D'Aprano
On Tue, Feb 26, 2019 at 09:09:56AM +, AdamC wrote:

> def createObjects(f):
> '''Takes a file object and iterates through entries, passing them to
> create
> object, depending on what object it is.'''
> for line in f:
> count = count + 1

This cannot be the code you are actually using, because that raises 
UnboundLocalError. count is never initialised, so that function you give 
cannot possibly run as shown.


py> def test():
... count = count + 1
...
py> test()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in test
UnboundLocalError: local variable 'count' referenced before assignment


There's no point us trying to debug code you aren't actually running. 
Try again with the actual working code. It might help if you read this:

http://www.sscce.org/



-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Only appending one object to list, when I am expecting more than 1

2019-02-26 Thread AdamC
I'm creating lots of objects from json in a file. Part of reading the json
back means that it iterates over the file and loads a json object and then
creates the object from the dictionary.

This is my  file:

{"name": "Dwarf Fortress", "platform": "steam", "dateAdded":
"2019:02:25:16:56:1551113768", "tpe": "2019:02:21:13:49:1550756942"}
{"name": "Jaws", "platform": "Netflix", "dateAdded":
"2019:02:25:16:56:1551113768", "tpe": "2019:02:21:13:49:1550756960"}
{"name": "Wargames", "platform": "CLI", "dateAdded":
"2019:02:25:16:59:1551113984", "tpe": "Game"}

and these are the functions that help load that file:

media = []

def loadFile():
filename = input('Filename? ')
f = open(filename, 'r')
createObjects(f)

def createObjects(f):
'''Takes a file object and iterates through entries, passing them to
create
object, depending on what object it is.'''
for line in f:
count = count + 1
data = json.loads(line)
print(type(data['tpe']))
name = data['name']
platform = data['platform']
dateAdded = data['dateAdded']
tpe = data['tpe']
if data['tpe'] == 'Game':
a = createGame(name, platform, dateAdded,tpe)
game = {a: tpe}
media.append(game)
if data['tpe'] == 'Film':
a = createFilm(name, platform, dateAdded,tpe)
film = {a: tpe}
media.append(film)
# For some reason I'm only getting one object at a time now when
appending to media
print(len(media))

def createGame(name, platform, dateAdded, tpe):
return Game(name, platform, dateAdded)

def createFilm(name, platform, dateAdded, tpe):
return Film(name, platform, dateAdded)

(This isn't the order that the functions are held in the module).
Why would I only get one object in media, even though all three are created?

Adam

--
You back your data up on the same planet?
http://kabads.monkeez.org 
PGP key: 0x7111B833
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor