Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Book recommendation: Fluent Python
-
@Phuket2 You mean you didn't COMPREHEND List Comprehensions? :-)
This joke might even help you grok them. :-)
-
@MartinPacker , yeah yeah :) I thought about the irony also. Like one of Robbie Williams songs, Same same but different ;) But in the lyrics, he is contemplating about thinking :) another song, he does not want to die, but he does not want to live either.
Being old, I can take criticism and laugh at myself. The only good things about being old :) well the good news is I am still here, the bad news is I am still here :) -
if attr[:len(self.attr_prefix)] == self.attr_prefix # could be simplified to --> if attr.startswith(self.attr_prefix)
On comprehensions, the best advise that I can give you is practice, practice, practice. They take time to wrap your mind around but they allow you to express yourself in tighter ways that actually execute faster. str.join() often plays a key role when using comprehensions to create strings.
-
@ccc, thanks again. We don't pay you enough :) really, I envy the young guys today, growing up in a sharing culture. I know I have said it before. But I am sure they really think this sharing culture is normal. Grow up in a world when your web browser is mosaic and no one wanted to share any ideas. It was difficult to learn. Well mosaic might be a bit of an exaggeration, however I did use it. I think next evolution was Netscape. Oh well, I get nostalgic after some drinks :) well, we could also mention the bbs on 1200 baud modem :)
Anyway, I made some mods. I could be going in the opposite direction from the goal posts. Hard to know sometimes. But it's ok, you still learn that way.class FontSizeRatios(object): def __init__(self, base_font = ('<System>' , 44) ): self.base_font = base_font self.attr_prefix = 'x_' self.x_header = 1 self.x_subheader = .8 self.x_subtext = .6 self.x_note = .4 self.x_footer = .2 def _attr_list(self): return [attr for attr in dir(self) if attr[:len(self.attr_prefix)] == self.attr_prefix] # if the attr does not contain the prefix, append # it the the beginging. def _clean_attr(self, attr): return attr if attr.startswith(self.attr_prefix) else ''.join([self.attr_prefix, attr]) def get_font_style(self, style, font_name = None): # if the attr.prefix is not passed, append # it to the front of style. need to do this # because of __getitem__ # hmmmm, tricks for young players, when you # do a for in.... attr = self._clean_attr(style) if attr in self._attr_list(): return ((font_name or (self.base_font[0]), self.base_font[1] * getattr(self, attr))) else: return (self.base_font) def __len__(self): return len(self._attr_list()) def __getitem__(self, pos): return self._attr_list()[pos] def __repr__(self): return '\n'.join(attr for attr in self._attr_list()) def style_ratio(self, style, new_value): attr = self._clean_attr(style) if attr in self._attr_list(): setattr(self, attr, new_value) if __name__ == '__main__': f_base = ('American Typewriter', 44) fsr = FontSizeRatios(f_base) print 'attr count', len(fsr) fsr.x_forgotton = 2 print 'attr count', len(fsr) fsr.style_ratio('forgotton', .8) for style in fsr: f = fsr.get_font_style(style) console.set_font(f[0], f[1]) print style console.set_font() print fsr.get_font_style('footer' , 'Apple Color Emoji') print 'slice..', fsr[3:] print fsr.get_font_style('footer')
-
I am be stupid at times. I should be cleaning the getitem result.
-
def __repr__(self): return '\n'.join(attr for attr in self._attr_list()) # --> return '\n'.join(self._attr_list())
-
@ccc , thanks. I guess because the list is an iterable. Takes some getting used to.
-
@ccc, I know I should not be asking this here. But even after reading I can't figure it out. Would be great if you know the pattern @ccc.
I am trying to create a function that returns a list of tuples with the attribute name and its value. I get an error that I am trying to use attr before its defined, which I sort of get. Yes, I can do it in loops, just trying to stick with the listcomps at the moment.
def create_attr_list(self): return [(attr, value) for attr in self._attr_list, for value in getattr(self, attr )]
-
@ccc , it's ok I got.....yeah...streamers falling in the bar :)
def create_attr_list(self): return [(attr, getattr(self, attr)) for attr in self._attr_list()]
Happy with myself now :)
-
Why not return a dict instead?
def create_attr_dict(self): return {attr : getattr(self, attr) for attr in self._attr_list()} # dict comprehension # or even... return self.__dict__
In general, the more you focus on your Puthon code, the simpler it becomes. Fewer, cleaner lines to express the same thing and it usually executes faster.
The next episode of the podcast above is an interview with the author of Effective Python which adds even more insights.
-
@ccc , yes. Just still trying to crawl at the moment. Lol, I don't really work at a fast pace. Read a little, code a little, Facebook a little, drink a little etc... ;)
But @omz posted some code previously when I was asking about fonts and families. He didn't write as a listcomp so inexperienced guys like me could understand it. But have been trying to refactor to listcomp.
I have done nothing with the ctypes as yet. I need to be able to coerce them to python types.
But, I am giving it a go....# coding: utf-8 from objc_util import * def get_all_fonts(): # from forum , @omz's code UIFont = ObjCClass('UIFont') ''' all_fonts = [] families = UIFont.familyNames() for family in families: names = UIFont.fontNamesForFamilyName_(family) all_fonts += names return all_fonts ''' return [{family: str(family) , 'styles': list(UIFont.fontNamesForFamilyName_(family))} for family in UIFont.familyNames()] print get_all_fonts()
-
I think you want something like this:
[{'family': str(family) , 'styles': [str(s) for s in UIFont.fontNamesForFamilyName_(family)]} for family in UIFont.familyNames()]
(Pretty much the same as your code, I only converted the Objective-C strings to Python strings.)
-
@omz , yes thanks, that was it :) when printing the values from the dict it was fine (both versions appear the same at least), just when printing the dict item, I could see all the objective-c types. Maybe not a problem, but when not use to it, unsettling :)