Re: Python Madlibs.py code and error message
Stephen Hansen writes: > On Wed, Apr 27, 2016, at 10:32 PM, Ben Finney wrote: > > Better: when you have many semantically-different values, use named > > (not positional) parameters in the format string. […] > > > > https://docs.python.org/3/library/string.html#formatstrings> > > Except the poster is not using Python 3, so all of this is for naught. Everything I described above works fine in Python 2. Any still-supported version has ‘str.format’. -- \“The deepest sin against the human mind is to believe things | `\ without evidence.” —Thomas Henry Huxley, _Evolution and | _o__)Ethics_, 1893 | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Madlibs.py code and error message
On Wed, Apr 27, 2016, at 10:32 PM, Ben Finney wrote: > Stephen Hansen writes: > > > The error message means there's a mismatch between the number of > > formatting instructions (ie, %s) and arguments passed to formatting. I > > leave it to you to count and find what's missing or extra, because I'm > > seriously not going to do that :) > > Better: when you have many semantically-different values, use named (not > positional) parameters in the format string. > > Some simple format string examples: > > "First, thou shalt count to {0}" # References first positional > argument > "Bring me a {}" # Implicitly references the first > positional argument > "From {} to {}" # Same as "From {0} to {1}" > "My quest is {name}" # References keyword argument 'name' > […] > > https://docs.python.org/3/library/string.html#formatstrings> Except the poster is not using Python 3, so all of this is for naught. -- Stephen Hansen m e @ i x o k a i . i o -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On 04/27/2016 09:06 PM, Christopher Reimer wrote: On 4/27/2016 8:52 PM, Michael Torrie wrote: In fact if it were me I would save game state to some kind of ini file, which would mean manually going through each object and writing out the relevant data to the ini file using the right syntax. And then reverse the process when restoring from a file. XML could be another format used for your file, if you're into that kind of thing. Funny that you should mention the ini file. I wrote a ConfigParser class for my const['whatever'] variable. It wouldn't take much to use that in the meantime until I get a handle on pickle. If you are saving chess game state, you should look at the Portable Game Notation format: https://en.wikipedia.org/wiki/Portable_Game_Notation -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Pythonic style
On Thursday 28 April 2016 13:23, Ben Finney wrote: > Christopher Reimer writes: > >> In short, my original code before I turned it into a separate >> dictionary. *sigh* > > No, I think that misses the points that were being made. The discussion > you're talking about was *not* to say “attribute access is better than > dictionary access”, or vice versa. Each is good for its purpose. > > Rather, the discussion was to drive home the point that in Python those > are *two distinct concepts*, and you need to not conflate them. > > If you want items in a mapping, explicitly use a Python ‘dict’ instance. > If you want attributes that describe an object, explicitly use > attributes of that object. Deliberately choose which one makes more > sense. Think of it like this: attribute access is for accessing parts of a thing: dog.tail car.engine cup.handle or one of a small number of fixed fields from a record: employment_record.start_date employee.salary autopsy.cause_of_death person.title Mappings (dicts) are for recording a potentially unlimited number of distinct records with arbitrary keys, especially since the keys don't have to be valid identifiers: employees['Fred Smith'] students['Joanna McTavish'] prisoners[12345] catalog['Widgets']['GMH-12345'] dictionary['update'] While Python allows you to write code to use attribute syntax for item access, doing so is a category mistake and leads to semantic confusion and potential bugs: employees.Fred_Smith students.Joanna_McTavish prisoners.P12345 parts.widgets.GMH_12345 dictionary.update The last example shows how mixing up these two distinct concepts can lead to problems. Should dictionary.update refer to the update method, or the entry for the word "update"? -- Steve -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Madlibs.py code and error message
Stephen Hansen writes: > The error message means there's a mismatch between the number of > formatting instructions (ie, %s) and arguments passed to formatting. I > leave it to you to count and find what's missing or extra, because I'm > seriously not going to do that :) Better: when you have many semantically-different values, use named (not positional) parameters in the format string. Some simple format string examples: "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' […] https://docs.python.org/3/library/string.html#formatstrings> By using names, you will not need to count positional arguments; and when there's an error, the error will state the name, making it easier to debug. Also feasible with ‘%’ syntax. But, if you're writing new code, you may as well use the more powerful ‘str.format’ described at that URL. -- \ “To have the choice between proprietary software packages, is | `\ being able to choose your master. Freedom means not having a | _o__)master.” —Richard M. Stallman, 2007-05-16 | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Pythonic style
On Thursday, April 28, 2016 at 9:26:21 AM UTC+5:30, Chris Angelico wrote: > My rule of thumb is: Dunders are for defining, not for calling. It's > not a hard-and-fast rule, but it'll get you through 99%+ of > situations. Neat and clever. Should get in the docs somewhere -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Madlibs.py code and error message
On Wed, Apr 27, 2016, at 10:01 PM, Cai Gengyang wrote: > I changed it to all lowercase, this time I get a different error message > though (a TypeError message) The error message means there's a mismatch between the number of formatting instructions (ie, %s) and arguments passed to formatting. I leave it to you to count and find what's missing or extra, because I'm seriously not going to do that :) -- Stephen Hansen m e @ i x o k a i . i o -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Madlibs.py code and error message
I changed it to all lowercase, this time I get a different error message though (a TypeError message) # This program does the following ... writes a Mad Libs story # Author: Cai Gengyang print "Mad Libs is starting!" name = raw_input("Enter a name: ") adjective1 = raw_input("Enter an adjective: ") adjective2 = raw_input("Enter a second adjective: ") adjective3 = raw_input("Enter a third adjective: ") verb1 = raw_input("Enter a verb: ") verb2 = raw_input("Enter a second verb: ") verb3 = raw_input("Enter a third verb: ") noun1 = raw_input("Enter a noun: ") noun2 = raw_input("Enter a noun: ") noun3 = raw_input("Enter a noun: ") noun4 = raw_input("Enter a noun: ") animal = raw_input("Enter an animal: ") food = raw_input("Enter a food: ") fruit = raw_input("Enter a fruit: ") number = raw_input("Enter a number: ") superhero_name = raw_input("Enter a superhero_name: ") country = raw_input("Enter a country: ") dessert = raw_input("Enter a dessert: ") year = raw_input("Enter a year: ") #The template for the story STORY = "This morning I woke up and felt %s because _ was going to finally %s over the big _ %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to _ to the rythym of the %s, which made all of the %ss very _. %s tried to _ into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping _ into a puddle of %s. %s then fell asleep and woke up in the year _, in a world where %ss ruled the world." print STORY % (adjective1, name, verb1, adjective2, noun1, noun2, animal, food, verb2, noun3, fruit, adjective3, name, verb3, number, name , superhero_name, superhero_name, name, country, name, dessert, name, year, noun4) Terminal Output : $ python Madlibs.py Mad Libs is starting! Enter a name: andrew Enter an adjective: beautiful Enter a second adjective: honest Enter a third adjective: pretty Enter a verb: hit Enter a second verb: run Enter a third verb: fire Enter a noun: honesty Enter a noun: love Enter a noun: peace Enter a noun: wisdom Enter an animal: elephant Enter a food: burger Enter a fruit: watermelon Enter a number: 1985 Enter a superhero_name: batman Enter a country: america Enter a dessert: icekachang Enter a year: 1982 Traceback (most recent call last): File "Madlibs.py", line 34, in print STORY % (adjective1, name, verb1, adjective2, noun1, noun2, an imal, food, verb2, noun3, fruit, adj ective3, name, verb3, number, name , superhero_name, superhero_name, nam e, country, name, dessert, name, yea r, noun4) TypeError: not all arguments converted during string formatting On Thursday, April 28, 2016 at 12:50:28 PM UTC+8, Gregory Ewing wrote: > Cai Gengyang wrote: > > > adjective1 = raw_input("Enter an adjective: ") > > > > NameError: name 'Adjective1' is not defined > > Python is case-sensitive. You've spelled it "adjective1" in one > place and "Adjective1" in another. You need to be consistent. > > -- > Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Madlibs.py code and error message
On Wed, Apr 27, 2016, at 09:37 PM, Cai Gengyang wrote: > print STORY % (Adjective1, name, Verb1, Adjective2, Noun1, Noun2, animal, > food, Verb2, Noun3, fruit, Adjective3, name, Verb3, number, name , > superhero_name, superhero_name, name, country, name, dessert, name, year, > Noun4) Python is case-sensitive. "Adjective1" and "adjective1" are separate things. In your code you're reading into "adjective1". -- Stephen Hansen m e @ i x o k a i . i o -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Madlibs.py code and error message
Cai Gengyang wrote: adjective1 = raw_input("Enter an adjective: ") NameError: name 'Adjective1' is not defined Python is case-sensitive. You've spelled it "adjective1" in one place and "Adjective1" in another. You need to be consistent. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Python Madlibs.py code and error message
Python Madlibs.py code and error message --- Anyone can help? I keep getting stuck here ... # This program does the following ... writes a Mad Libs story # Author: Cai Gengyang print "Mad Libs is starting!" name = raw_input("Enter a name: ") adjective1 = raw_input("Enter an adjective: ") adjective2 = raw_input("Enter a second adjective: ") adjective3 = raw_input("Enter a third adjective: ") verb1 = raw_input("Enter a verb: ") verb2 = raw_input("Enter a second verb: ") verb3 = raw_input("Enter a third verb: ") noun1 = raw_input("Enter a noun: ") noun2 = raw_input("Enter a noun: ") noun3 = raw_input("Enter a noun: ") noun4 = raw_input("Enter a noun: ") animal = raw_input("Enter an animal: ") food = raw_input("Enter a food: ") fruit = raw_input("Enter a fruit: ") number = raw_input("Enter a number: ") superhero_name = raw_input("Enter a superhero_name: ") country = raw_input("Enter a country: ") dessert = raw_input("Enter a dessert: ") year = raw_input("Enter a year: ") #The template for the story STORY = "This morning I woke up and felt %s because _ was going to finally %s over the big _ %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to _ to the rythym of the %s, which made all of the %ss very _. %s tried to _ into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping _ into a puddle of %s. %s then fell asleep and woke up in the year _, in a world where %ss ruled the world." print STORY % (Adjective1, name, Verb1, Adjective2, Noun1, Noun2, animal, food, Verb2, Noun3, fruit, Adjective3, name, Verb3, number, name , superhero_name, superhero_name, name, country, name, dessert, name, year, Noun4) Terminal Output : $ python Madlibs.py Mad Libs is starting! Enter a name: Cai Gengyang Enter an adjective: beautiful Enter a second adjective: honest Enter a third adjective: huge Enter a verb: hit Enter a second verb: run Enter a third verb: jump Enter a noun: anger Enter a noun: belief Enter a noun: wealth Enter a noun: regret Enter an animal: elephant Enter a food: burger Enter a fruit: watermelon Enter a number: 6 Enter a superhero_name: batman Enter a country: America Enter a dessert: icekachang Enter a year: 1984 Traceback (most recent call last): File "Madlibs.py", line 34, in print STORY % (Adjective1, name, Verb1, Adjective2, Noun1, Noun2, an imal, food, Verb2, Noun3, fruit, Adj ective3, name, Verb3, number, name , superhero_name, superhero_name, nam e, country, name, dessert, name, yea r, Noun4) NameError: name 'Adjective1' is not defined -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On 04/27/2016 10:06 PM, Christopher Reimer wrote: > On 4/27/2016 8:52 PM, Michael Torrie wrote: >> In fact if it were me I would save game state to some kind of ini file, >> which would mean manually going through each object and writing out the >> relevant data to the ini file using the right syntax. And then reverse >> the process when restoring from a file. XML could be another format >> used for your file, if you're into that kind of thing. > > Funny that you should mention the ini file. I wrote a ConfigParser class > for my const['whatever'] variable. It wouldn't take much to use that in > the meantime until I get a handle on pickle. I'm not sure pickle is the way to go anyway. Especially for your purposes. Definitely you could make a ConfigParser that could read and write your object instances. -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On 4/27/2016 8:52 PM, Michael Torrie wrote: In fact if it were me I would save game state to some kind of ini file, which would mean manually going through each object and writing out the relevant data to the ini file using the right syntax. And then reverse the process when restoring from a file. XML could be another format used for your file, if you're into that kind of thing. Funny that you should mention the ini file. I wrote a ConfigParser class for my const['whatever'] variable. It wouldn't take much to use that in the meantime until I get a handle on pickle. Thank you, Chris R. -- https://mail.python.org/mailman/listinfo/python-list
Re: Pythonic style
On 4/27/2016 8:52 PM, Ethan Furman wrote: The point Ben was trying to make is this: you should never* call __dunder__ methods in normal code; there is no need to do so: - use len(), not __len__() - use next(), not __next__() - use some_instance.an_attribute, not some_instance.__dict__['an_attribute'] DOH! I need a doughnut. :) Thank you, Chris R. -- https://mail.python.org/mailman/listinfo/python-list
Re: Pythonic style
On 4/27/2016 8:23 PM, Ben Finney wrote: If you want items in a mapping, explicitly use a Python ‘dict’ instance. If you want attributes that describe an object, explicitly use attributes of that object. Deliberately choose which one makes more sense. Okay, that makes sense. Thank you, Chris R. -- https://mail.python.org/mailman/listinfo/python-list
Re: Pythonic style
On Thu, Apr 28, 2016 at 1:52 PM, Ethan Furman wrote: > > The point Ben was trying to make is this: you should never* call __dunder__ > methods in normal code; there is no need to do so: > > - use len(), not __len__() > - use next(), not __next__() > - use some_instance.an_attribute, not some_instance.__dict__['an_attribute'] > > -- > ~Ethan~ > > * Okay, maybe /almost/ never. About the only time you need to is when > giving your classes special methods, such as __add__ or __repr__. My rule of thumb is: Dunders are for defining, not for calling. It's not a hard-and-fast rule, but it'll get you through 99%+ of situations. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On 4/27/2016 8:05 PM, Ethan Furman wrote: I ripped out the fetch_state because that will take more work -- you can't pass a Pawn's saved state in to Piece and get the results you want. pickle is worth looking at for saving/restoring. The original idea was to pass a Pawn dictionary to the constructor of the Pawn object. The Piece object will throw a NotImplementedError if called directly. I guess I'll have to look at pickle sooner rather than later. Also, your code will give the same notation to Kings and Knights. Good catch. I knew I was forgetting something. I overrode variable in the Knight class to produce the correct notation. Thank you, Chris R. -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On 04/27/2016 08:49 PM, Christopher Reimer wrote: > On 4/27/2016 7:00 PM, Michael Torrie wrote: >> I am guessing that the reason you are storing state as it's own >> dictionary is so that you can pass the state itself to the constructor? > > Someone said it was bad to store the object itself to file (my original > plan) and that I should use a dictionary instead. This is my > implementation of that idea. However, saving and loading data is far > down my to do list. Pickle should be able to serialize an object that stores state as attributes, as that's what objects normally do. But you could also serialize and save the objects yourself manually too. In fact if it were me I would save game state to some kind of ini file, which would mean manually going through each object and writing out the relevant data to the ini file using the right syntax. And then reverse the process when restoring from a file. XML could be another format used for your file, if you're into that kind of thing. -- https://mail.python.org/mailman/listinfo/python-list
Re: Pythonic style
On 04/27/2016 08:07 PM, Christopher Reimer wrote: On 4/27/2016 7:07 PM, Ben Finney wrote: >> Ian Kelly wrote: self.__dict__ = {'key', 'value'} is essentially equivalent to: self.key = value >> I would say the latter is more Pythonic, because it: >> >> [snip] >> * Uses the built-in mechanisms of Python (don't invoke magic attributes, instead use the system that makes use of them behind the scenes). In short, my original code before I turned it into a separate dictionary. *sigh* No. The point Ben was trying to make is this: you should never* call __dunder__ methods in normal code; there is no need to do so: - use len(), not __len__() - use next(), not __next__() - use some_instance.an_attribute, not some_instance.__dict__['an_attribute'] -- ~Ethan~ * Okay, maybe /almost/ never. About the only time you need to is when giving your classes special methods, such as __add__ or __repr__. -- https://mail.python.org/mailman/listinfo/python-list
Re: Pythonic style
Christopher Reimer writes: > In short, my original code before I turned it into a separate > dictionary. *sigh* No, I think that misses the points that were being made. The discussion you're talking about was *not* to say “attribute access is better than dictionary access”, or vice versa. Each is good for its purpose. Rather, the discussion was to drive home the point that in Python those are *two distinct concepts*, and you need to not conflate them. If you want items in a mapping, explicitly use a Python ‘dict’ instance. If you want attributes that describe an object, explicitly use attributes of that object. Deliberately choose which one makes more sense. -- \ “The double standard that exempts religious activities from | `\ almost all standards of accountability should be dismantled | _o__) once and for all.” —Daniel Dennett, 2010-01-12 | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Pythonic style (was: Differences between Class(Object) and Class(Dict) for dictionary usage?)
On 4/27/2016 7:07 PM, Ben Finney wrote: I would say the latter is more Pythonic, because it: * Better conveys the intention (“set the value of the ‘self.key’ attribute”). * Uses the built-in mechanisms of Python (don't invoke magic attributes, instead use the system that makes use of them behind the scenes). * Expresses that intention more concisely (fewer terms). * Expresses that intention more clearly (less syntactic noise). In short, my original code before I turned it into a separate dictionary. *sigh* Thank you, Chris R. -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On 04/27/2016 06:12 PM, Christopher Reimer wrote: After considering the feedback I got for sanity checking my code, I've decided to simplify the base class for the chess pieces (see code below). All the variables are stored inside a dictionary with most values accessible through properties. A custom dictionary can be loaded through the constructor and or saved out through the fetch_state method. The subclasses only have to implement the is_move_valid method, which is different for each type of chess piece. Much better. Here's my take on it: class Piece(object): def __init__(self, color, position): self._color = color self._first_move = True self._initial_position = position self._move_count = 0 self._name = color.title() + ' ' + self.__class__.__name__ self._notation = color.title()[:1] + self.__class__.__name__[:1] self._position = position @property def color(self): return self._color def is_move_valid(self, new_position, board_state): raise NotImplementedError @property def move_count(self): return self._move_count @property def name(self): return self._name @property def notation(self): return self._notation @property def position(self): return self._position @position.setter def position(self, position): self._position = position if self._first_move: self._first_move = False self._move_count += 1 Now all the attributes are, well, attributes of the instance (that's what instances are for). I ripped out the fetch_state because that will take more work -- you can't pass a Pawn's saved state in to Piece and get the results you want. pickle is worth looking at for saving/restoring. Also, your code will give the same notation to Kings and Knights. -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On 4/27/2016 7:00 PM, Michael Torrie wrote: I am guessing that the reason you are storing state as it's own dictionary is so that you can pass the state itself to the constructor? Someone said it was bad to store the object itself to file (my original plan) and that I should use a dictionary instead. This is my implementation of that idea. However, saving and loading data is far down my to do list. I know you've stated reasons for doing things the way you have, but this self._state dict smells a bit funny, especially where you have self._state = state, which means that several instances could have the exact same state object at the same time and strikes me as mildly un-pythonic and very confusing. "State" is what instances themselves are supposed to track by design. I recommend you use this feature rather than duplicating it with your own error-prone dict handling. So far the code is working as designed for new chess pieces (see below). Thank you, Chris R. Rook('white', (1, 1)) @ 2106251742008 Knight('white', (1, 2)) @ 2106251755648 Bishop('white', (1, 3)) @ 2106251755760 Queen('white', (1, 4)) @ 2106251755872 King('white', (1, 5)) @ 2106251755984 Bishop('white', (1, 6)) @ 2106251756096 Knight('white', (1, 7)) @ 2106251756208 Rook('white', (1, 8)) @ 2106251756320 Pawn('white', (2, 1)) @ 2106251756432 Pawn('white', (2, 2)) @ 2106251756544 Pawn('white', (2, 3)) @ 2106251756656 Pawn('white', (2, 4)) @ 2106251756768 Pawn('white', (2, 5)) @ 2106251756880 Pawn('white', (2, 6)) @ 2106251756992 Pawn('white', (2, 7)) @ 2106251757104 Pawn('white', (2, 8)) @ 2106251757216 Pawn('black', (7, 1)) @ 2106251742288 Pawn('black', (7, 2)) @ 2106251742400 Pawn('black', (7, 3)) @ 2106251742512 Pawn('black', (7, 4)) @ 2106251742624 Pawn('black', (7, 5)) @ 2106251742736 Pawn('black', (7, 6)) @ 2106251742848 Pawn('black', (7, 7)) @ 2106251742960 Pawn('black', (7, 8)) @ 2106251743072 Rook('black', (8, 1)) @ 2106251743184 Knight('black', (8, 2)) @ 2106251742120 Bishop('black', (8, 3)) @ 2106251740608 Queen('black', (8, 4)) @ 2106251740496 King('black', (8, 5)) @ 2106251740832 Bishop('black', (8, 6)) @ 2106251741672 Knight('black', (8, 7)) @ 2106251741784 Rook('black', (8, 8)) @ 2106251741896 -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On 4/26/2016 8:56 PM, Random832 wrote: what exactly do you mean by property decorators? If you're just accessing them in a dictionary what's the benefit over having the values be simple attributes rather than properties? After considering the feedback I got for sanity checking my code, I've decided to simplify the base class for the chess pieces (see code below). All the variables are stored inside a dictionary with most values accessible through properties. A custom dictionary can be loaded through the constructor and or saved out through the fetch_state method. The subclasses only have to implement the is_move_valid method, which is different for each type of chess piece. Thank you, Chris R. class Piece(object): def __init__(self, color, position, state=None): if state is None: self._state = { 'class': self.__class__.__name__, 'color': color, 'first_move': True, 'initial_position': position, 'move_count': 0, 'name': color.title() + ' ' + self.__class__.__name__, 'notation': color.title()[:1] + self.__class__.__name__[:1], 'position': position } else: self._state = state @property def color(self): return self._state['color'] def fetch_state(self): return self._state def is_move_valid(self, new_position, board_state): raise NotImplementedError @property def move_count(self): return self._state['move_count'] @property def name(self): return self._state['name'] @property def notation(self): return self._state['notation'] @property def position(self): return self._state['position'] @position.setter def position(self, position): self._state['position'] = position if self._state['first_move']: self._state['first_move'] = False self._state['move_count'] += 1 -- https://mail.python.org/mailman/listinfo/python-list
Pythonic style (was: Differences between Class(Object) and Class(Dict) for dictionary usage?)
Christopher Reimer writes: > On 4/27/2016 7:33 AM, Ian Kelly wrote: > > > self.__dict__ = {'key', 'value'} > > > > self.key = value > > Which expression is Pythonic? (Note that assignment is not an expression in Python; assigment is a statement.) > I've seen both used in various examples on the Internet. I would say the latter is more Pythonic, because it: * Better conveys the intention (“set the value of the ‘self.key’ attribute”). * Uses the built-in mechanisms of Python (don't invoke magic attributes, instead use the system that makes use of them behind the scenes). * Expresses that intention more concisely (fewer terms). * Expresses that intention more clearly (less syntactic noise). -- \“Nothing so needs reforming as other people's habits.” —Mark | `\ Twain, _Pudd'n'head Wilson_ | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On 04/27/2016 07:12 PM, Christopher Reimer wrote: > class Piece(object): > def __init__(self, color, position, state=None): > if state is None: > self._state = { > 'class': self.__class__.__name__, > 'color': color, > 'first_move': True, > 'initial_position': position, > 'move_count': 0, > 'name': color.title() + ' ' + self.__class__.__name__, > 'notation': color.title()[:1] + > self.__class__.__name__[:1], > 'position': position > } I am guessing that the reason you are storing state as it's own dictionary is so that you can pass the state itself to the constructor? > else: > self._state = state I'm not sure why you are storing the class name in self._state above, but keep in mind that this part of the constructor will just reference whatever was in the passed-in state object, whether it's right or wrong. So the value of self._state.class and self._state.notation may or may not be right, compared to what is set in the previous section if None is passed in. Also self._state = state means that the state object passed will be the self._state object. Not a copy, but the exact same object. So multiple instances could have the exact object as self._state. Not sure if this is what you intended or not. Personally I would ditch the self._state dictionary entirely and store the state directly as instance attributes. self.color, self.first_move, etc. For the constructor if you want to duplicate another object's state, just pass the entire object as an argument and copy the attributes manually, rather than passing around the state dict. I know you've stated reasons for doing things the way you have, but this self._state dict smells a bit funny, especially where you have self._state = state, which means that several instances could have the exact same state object at the same time and strikes me as mildly un-pythonic and very confusing. "State" is what instances themselves are supposed to track by design. I recommend you use this feature rather than duplicating it with your own error-prone dict handling. -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On 4/27/2016 7:33 AM, Ian Kelly wrote: This class definition looks muddled. Because Test2 inherits from dict, the object referred to by "self" will be a dict, and self.__dict__ is actually a *different* dict, containing the attributes of self. The line: self.__dict__ = {'key', 'value'} is essentially equivalent to: self.key = value and will be regardless of whether you inherit from object or dict. If you find this distinction confusing, then I recommend not inheriting from dict. Which expression is Pythonic? I've seen both used in various examples on the Internet. Thank you, Chris R. -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On 4/27/2016 7:24 AM, Ian Kelly wrote: Some other great questions to ask yourself are "do I really want len(my_object) to return the number of items in this dict" and "do I really want list(my_object) to return all the keys in this dict"? If the answer to all those is yes, then it's probably fair to say that your object is-a dict and should be modeled as such. These questions are more useful for me to consider. For my chess piece base class, the answer is no. Thank you, Chris R. -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On 4/26/2016 8:56 PM, Random832 wrote: what exactly do you mean by property decorators? If you're just accessing them in a dictionary what's the benefit over having the values be simple attributes rather than properties? After considering the feedback I got for sanity checking my code, I've decided to simplify the base class for the chess pieces (see code below). All the variables are stored inside a dictionary with most values accessible through properties. A custom dictionary can be loaded through the constructor and or saved out through the fetch_state method. The subclasses only have to implement the is_move_valid method, which is different for each type of chess piece. Thank you, Chris R. class Piece(object): def __init__(self, color, position, state=None): if state is None: self._state = { 'class': self.__class__.__name__, 'color': color, 'first_move': True, 'initial_position': position, 'move_count': 0, 'name': color.title() + ' ' + self.__class__.__name__, 'notation': color.title()[:1] + self.__class__.__name__[:1], 'position': position } else: self._state = state @property def color(self): return self._state['color'] def fetch_state(self): return self._state def is_move_valid(self, new_position, board_state): raise NotImplementedError @property def move_count(self): return self._state['move_count'] @property def name(self): return self._state['name'] @property def notation(self): return self._state['notation'] @property def position(self): return self._state['position'] @position.setter def position(self, position): self._state['position'] = position if self._state['first_move']: self._state['first_move'] = False self._state['move_count'] += 1 -- https://mail.python.org/mailman/listinfo/python-list
Big World, Big Data, Big Mind : Spark | Scala | Python
Become proficient in both Scala and python to implement programming skills on Apache spark and have independent understanding of all three platforms Objectives: Understand the difference between Apache Spark and Hadoop Learn Scala and its programming implementation Implement Spark on a cluster Write Spark Applications using Python, Java and Scala Understand Module 4-RDD and its operation Learn common Spark Algorithms Define and explain Spark Streaming Execute Pattern Matching in Scala Understand Scala Java Interoperability Understand the purpose, importance and Installation of Python Get expertise in Python core Data types, Regular Expressions, Looping, and object Oriented Programming Master the concepts of File Operations, Functions, Special methods of defining a Class and SQLite in Python Take a quick overview on Panda Learn how to manage Hadoop File System Get an understanding on Server logs, Pig script and Work Flow Editor Work on a detailed Project on Web Logging in Python and Implement everything you learnt on a live Project Work on Minor and Major Projects applying programming techniques of Scala to run on Spark applications Start learning Spark | Scala | Python from basics to advance levels. https://goo.gl/4SEsJR -- https://mail.python.org/mailman/listinfo/python-list
Re: Python path and append
On Tue, Apr 26, 2016, at 07:56 PM, Seymore4Head wrote: > On Tue, 26 Apr 2016 11:53:57 +1000, Steven D'Aprano > wrote: > > >On Tue, 26 Apr 2016 08:04 am, Seymore4Head wrote: > > > >> BTW I was trying to use a line like yours that used an output file > >> that didn't exist and was getting an error. I assume that import os > >> fixes that. > > > > > >Why would you assume that? > > > > > >"Doctor, I have a problem with my arm, but I won't tell you what. I assume > >that if I take cough drops that will fix it." > > OK. Dumb question acknowledged. > > I got an error when I tried to write to a non existent file. I > "incorrectly" assumed wrong. That is going to be a common theme. Oh, he wasn't saying it was a dumb question. He was complaining you said you were "getting an error". That's not a dumb question, that's a useless report of a problem. If you don't say what exactly the error is, we can't help you. If you want help, the two best things to do are: 1) Show actual code. 2) Show actual, complete tracebacks. Having a nice description of what you expect to happen is often nice too, especially if its doing something "wrong" and not giving an obvious traceback. Seeing specifically what the wrong behavior is, and you explaining why you think its wrong, can be invaluable. -- Stephen Hansen m e @ i x o k a i . i o -- https://mail.python.org/mailman/listinfo/python-list
Re: Python(x,y) 64 bit
On Wed, Apr 27, 2016, at 04:25 PM, Pierre wrote: > I did check and it looks like the Python(x,y) 64 distribution I > downloaded uses a 32 bit Python. > The question is if there is ANY Python(x,y) 64 distribution that uses the > 64 bit python version. > I looked it up online and could not find anything related to this issue I don't know anything about Python(x,y), but from their website it looks like it doesn't offer 64-bit python. Note, Python(x,y) is not affiliated with Python itself. That said, perhaps you should check out https://www.continuum.io/downloads which is the Anaconda scientific distribution, which I know does offer 64-bit Python support. --- Stephen Hansen m e @ i x o k a i . i o -- https://mail.python.org/mailman/listinfo/python-list
Re: Python(x,y) 64 bit
On Wednesday, April 27, 2016 at 11:17:32 AM UTC-4, Zachary Ware wrote: > Hi Pierre, > > On Wed, Apr 27, 2016 at 6:23 AM, Pierre wrote: > > Hello, > > > > I installed Python(x,y) 64 bit version and ran it using a library that > > requires Python 64 bit. > > I got an error which indicated that I am using Python 32 bit. > > > > So, is the python used by Python(x,y) 64 bit, using Python 64 or 32 bit? > > You can check by doing `python -c "import sys;print(sys.maxsize == > 2**63-1)"`. You'll get True for 64-bit, False for 32-bit. There's a > possibility that you've gotten a misleading error message, though. > What version of Python(x,y) are you using, and what library? > > -- > Zach Zach, I did check and it looks like the Python(x,y) 64 distribution I downloaded uses a 32 bit Python. The question is if there is ANY Python(x,y) 64 distribution that uses the 64 bit python version. I looked it up online and could not find anything related to this issue -- https://mail.python.org/mailman/listinfo/python-list
Re: Importerror: cannot import name httpshandler linux
On Wed, 27 Apr 2016 10:13:45 -0700, bharadwajsrivatsa wrote: > I tried installing Python 2.7.11 on HP-UX which already has all > the build and run time dependencies installed on it such as > openssl, libffi, etc. But after installing python , I tried > installing some open source packages using pip. But pip thows the error: > Importerror: cannot import name httpshandler linux. > > PLease help me out to resolve this. Try installing the libssl-dev package. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Importerror: cannot import name httpshandler linux
I tried installing Python 2.7.11 on HP-UX which already has all the build and run time dependencies installed on it such as openssl, libffi, etc. But after installing python , I tried installing some open source packages using pip. But pip thows the error: Importerror: cannot import name httpshandler linux. PLease help me out to resolve this. -- https://mail.python.org/mailman/listinfo/python-list
Re: Howw to prevent the duplication of any value in a column within a CSV file (python)
potential_passengers = ['bob','john','sue','wendy','chris','bob','jen','wendy'] accepted_passengers = set() for name in potential_passengers: print('checking on {}...'.format(name)) if name not in accepted_passengers: accepted_passengers.add(name) print('welcome aboard, {}!'.format(name)) else: print('i am sorry, we have already accepted a {}.'.format(name)) print() HTH, Don -- https://mail.python.org/mailman/listinfo/python-list
Re: how to create a dictionary from csv file?
Am 27.04.2016 um 11:31 schrieb Peter Otten: Sibylle Koczian wrote: And if the csv module is used anyway, why not simply read into a DictReader? How would that help with looking up 3.5 by "apple" given the OP's sample data banana,4.0 apple,3.5 orange,3.0 Quite right, it wouldn't. Misread the problem, sorry. -- https://mail.python.org/mailman/listinfo/python-list
urgent requirement DB2 with AIX or LINUX@ Foster City,CA
This is Naveen from SAGE IT INC. Hope you are doing great. Please send me your updated resume if you're interested for this position Title: DB2 with AIX or LINUX Location: Foster City, CA Duration: 12+ Months Job Description Strong DB2 LUW V10 (AIX/LINUX) expertise combined with sharp conceptual and analytical thinking! Working knowledge of Hadoop is a big plus. The successful candidate should have a working experience with Large (multi-terabytes) systems on DB2. Working experience with hadoop and Oracle-based systems as it pertains to the Datawarehousing environment is big plus. Should have hands-on advanced trouble-shooting and performance tuning knowledge/experience; understand and be able to define different DB2 partitioning strategies; be able to provide 3rd and 4th level support. The responsibilities will include but they will not be limited to * Requirement gathering and performing capacity planning, database physical design, architecture and configuration of large infrastructures, developing complex shell scripts, preparing specifications and defining best practices and standards. * Provide database expertise to other Global Engineering and Application teams; represent DB Engineering in project planning, sizing, design and defining backup/recovery strategies. * The successful candidate should be adaptive to the Visa's agile environment! * Experience with IBM DB2 for LUW Database Editions 9.x and 10.x * Must have experience in administrating DB2 LUW in DPF (Partitioning) envrionment. * Experience in IBM DB2 applicances like ISAS is preferred. * Experience in shell scripting (.ksh,.bash) in AIX and Linux platforms. * Experience IBM DB2 for LUW backup and recovery processes * Experience in troubleshooting and supporting DB2 for LUW database instances. * Experience in multiple methods of data movement technologies like Import, Export, and Ingest. * Experience in DB2 LUW performance tuning methodologies. * Knowledge of DB2 for LUW high availability and DR solutions Thanks& Regards Durga Naveen SageIT IT Solutions INC cnav...@sageitinc.net 972-996-0650 Extn 349 www.sageitinc.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Python(x,y) 64 bit
Hi Pierre, On Wed, Apr 27, 2016 at 6:23 AM, Pierre wrote: > Hello, > > I installed Python(x,y) 64 bit version and ran it using a library that > requires Python 64 bit. > I got an error which indicated that I am using Python 32 bit. > > So, is the python used by Python(x,y) 64 bit, using Python 64 or 32 bit? You can check by doing `python -c "import sys;print(sys.maxsize == 2**63-1)"`. You'll get True for 64-bit, False for 32-bit. There's a possibility that you've gotten a misleading error message, though. What version of Python(x,y) are you using, and what library? -- Zach -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On Tue, Apr 26, 2016 at 9:43 PM, Christopher Reimer wrote: > class Test2(dict): > def __init__(self): > self.__dict__ = {'key', 'value'} This class definition looks muddled. Because Test2 inherits from dict, the object referred to by "self" will be a dict, and self.__dict__ is actually a *different* dict, containing the attributes of self. The line: self.__dict__ = {'key', 'value'} is essentially equivalent to: self.key = value and will be regardless of whether you inherit from object or dict. If you find this distinction confusing, then I recommend not inheriting from dict. -- https://mail.python.org/mailman/listinfo/python-list
Re: Differences between Class(Object) and Class(Dict) for dictionary usage?
On Tue, Apr 26, 2016 at 11:31 PM, Ethan Furman wrote: > On 04/26/2016 08:43 PM, Christopher Reimer wrote: > >> If I'm using a dictionary to store variables for an object, and >> accessing the variable values from dictionary via property decorators, >> would it be better to derive the class from object or dict? >> >> class Test1(object): >> def __init__(self): >> self.state = {'key': 'value'} >> >> Or: >> >> class Test2(dict): >> def __init__(self): >> self.__dict__ = {'key', 'value'} >> >> I haven't seen a good pro/con discussion on the Internet for using one >> over the other. I played with both in my code. Doesn't seem to make a >> great difference either way. Using object seems to be the most simplest >> approach. > > > Using a dict gets you a bunch of methods for free: keys(), values(), > items(), get(), etc., etc.. You get those for free either way; in the first case you just have use self.state.keys() instead of self.keys(). The question boils down to composition versus inheritance, and the prevailing wisdom is to prefer composition. For me the discerning test is "do the things that are in this dict make sense as items contained by my object?" If the answer is yes, then go ahead and subclass from dict. More often, the answer is no. Some other great questions to ask yourself are "do I really want len(my_object) to return the number of items in this dict" and "do I really want list(my_object) to return all the keys in this dict"? If the answer to all those is yes, then it's probably fair to say that your object is-a dict and should be modeled as such. -- https://mail.python.org/mailman/listinfo/python-list
Re: Howw to prevent the duplication of any value in a column within a CSV file (python)
On Apr 27, 2016 7:25 PM, "Adam Davis" wrote: > > On Wednesday, 27 April 2016 07:37:42 UTC+1, Chris Angelico wrote: > > On Wed, Apr 27, 2016 at 4:26 PM, Adam Davis wrote: > > > I understand what you're saying! But where you say: " the_set = set()", what would go within the set brackets? > > > > Nothing. The empty parentheses mean "call this with no arguments", and > > when you call the set constructor like that, you get back an empty > > set. > > > > ChrisA > > Thanks Chris. Where Ian says 'the_set.add(item)', what would be put within item in terms of my codes function/aim? item is name in your case. Since it's the one you care about existing or not. It would be like: Read from csv, For each row, the_set.add(name) Now that you have the_set in memory, whenever you want to check whether a particular name has taken the quiz, just do: if name in the_set: # forbid else: # allow Regards, Andrew -- https://mail.python.org/mailman/listinfo/python-list
Re: Howw to prevent the duplication of any value in a column within a CSV file (python)
On Wednesday, 27 April 2016 07:37:42 UTC+1, Chris Angelico wrote: > On Wed, Apr 27, 2016 at 4:26 PM, Adam Davis wrote: > > I understand what you're saying! But where you say: " the_set = set()", > > what would go within the set brackets? > > Nothing. The empty parentheses mean "call this with no arguments", and > when you call the set constructor like that, you get back an empty > set. > > ChrisA Thanks Chris. Where Ian says 'the_set.add(item)', what would be put within item in terms of my codes function/aim? -- https://mail.python.org/mailman/listinfo/python-list
Re: Basic Concepts
On Wed, 27 Apr 2016 07:29 pm, Smith wrote: > Fill in the blanks to declare a variable, add 5 to it and print its value: > > >>> x = 4 > >>> x_ = 5 > >>> print_ > > > Any suggestion ? Okay, you have a variable x with the value of 4: x = 4 How do you think you would print the value of x? Hint: here I print the value of z instead: print z -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Python(x,y) 64 bit
Hello, I installed Python(x,y) 64 bit version and ran it using a library that requires Python 64 bit. I got an error which indicated that I am using Python 32 bit. So, is the python used by Python(x,y) 64 bit, using Python 64 or 32 bit? Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Basic Concepts
On Wed, 27 Apr 2016 11:29:12 +0200, Smith wrote: > Fill in the blanks to declare a variable, add 5 to it and print its > value: > > >>> x = 4 x_ = 5 print_ > > > Any suggestion ? > > Thanks 2 suggestions:- 1) Stay awake during your class so that you can complete basic homework assignments. 2) Try reading the online python tutorial which covers this type of basic operation (& much more). assistance with homework can be obtained her but only if you have made some effort, posted your code and given some explanation of why you think it is not working. even then you will get suggestions to steer you in the right direction rather than working code. -- The more a man is imbued with the ordered regularity of all events, the firmer becomes his conviction that there is no room left by the side of this ordered regularity for causes of a different nature. For him neither the rule of human nor the rule of divine will exists as an independent cause of natural events. To be sure, the doctrine of a personal God interfering with natural events could never be refuted, in the real sense, by science, for this doctrine can always take refuge in those domains in which scientific knowledge has not yet been able to set foot. But I am persuaded that such behavior on the part of the representatives of religion would not only be unworthy but also fatal. For a doctrine which is able to maintain itself not in clear light, but only in the dark, will of necessity lose its effect on mankind, with incalculable harm to human progress. In their struggle for the ethical good, teachers of religion must have the stature to give up the doctrine of a personal God, that is, give up that source of fear and hope which in the past placed such vast powers in the hands of priests. In their labors they will have to avail themselves of those forces which are capable of cultivating the Good, the True, and the Beautiful in humanity itself. This is, to be sure, a more difficult but an incomparably more worthy task. - Albert Einstein -- https://mail.python.org/mailman/listinfo/python-list
newsreader pan could not find my post
Hello, I post a message in comp.lang python, but with caching new articles in the newsreader pan I don't see my article. How can I contact the administrater or this group. Thanks -- https://mail.python.org/mailman/listinfo/python-list
RE: Basic Concepts
>>> x = 4 >>> x + 5 9 -Original Message- From: Python-list [mailto:python-list-bounces+joaquin.alzola=lebara@python.org] On Behalf Of Smith Sent: 27 April 2016 10:29 To: python-list@python.org Subject: Basic Concepts Fill in the blanks to declare a variable, add 5 to it and print its value: >>> x = 4 >>> x_ = 5 >>> print_ Any suggestion ? Thanks -- https://mail.python.org/mailman/listinfo/python-list This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt. -- https://mail.python.org/mailman/listinfo/python-list
Re: how to create a dictionary from csv file?
Sibylle Koczian wrote: > Am 27.04.2016 um 04:42 schrieb jf...@ms4.hinet.net: >> Just curious:-) why everyone here open the csv file without using >> newline='' as suggested in Python 3.4.4 document section 14.1? Carelessness, lack of knowledge (I plead guilty), not on Windows and no embedded newline in sight? > And if the csv module is used anyway, why not simply read into a > DictReader? How would that help with looking up 3.5 by "apple" given the OP's sample data banana,4.0 apple,3.5 orange,3.0 ? Please give a code example. Finally, why would you think that asking rhetorical questions is a good way to communicate? -- https://mail.python.org/mailman/listinfo/python-list
Basic Concepts
Fill in the blanks to declare a variable, add 5 to it and print its value: >>> x = 4 >>> x_ = 5 >>> print_ Any suggestion ? Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: how to create a dictionary from csv file?
Am 27.04.2016 um 04:42 schrieb jf...@ms4.hinet.net: Just curious:-) why everyone here open the csv file without using newline='' as suggested in Python 3.4.4 document section 14.1? And if the csv module is used anyway, why not simply read into a DictReader? -- https://mail.python.org/mailman/listinfo/python-list
Re: Immediate Requirement: use the Python Job Board for recruitment (was:
On Wednesday 27 April 2016 16:36, Bob Martin wrote: > Recruiters post everywhere but seem not to read anywhere. > They have flooded the android developer lists to the point where > they are no longer worth reading. Wanted: Android developer. Must have five years experience with "Marshmellow" or ten years with any previous version. -- Steven -- https://mail.python.org/mailman/listinfo/python-list