Search Results

Search found 200 results on 8 pages for 'pythonic'.

Page 6/8 | < Previous Page | 2 3 4 5 6 7 8  | Next Page >

  • What is the cleanest way to do a sort plus uniq on a Python list?

    - by knorv
    Consider a Python list my_list containing ['foo', 'foo', 'bar']. What is the most Pythonic way to uniqify:ing and sorting and the list (think cat my_list | sort | uniq)? This is how I currently do it and while it works I'm sure there are better ways to do it. my_list = [] ... my_list.append("foo") my_list.append("foo") my_list.append("bar") ... my_list = set(my_list) my_list = list(my_list) my_list.sort()

    Read the article

  • What is the preferred syntax for initializing a dict?

    - by daotoad
    I'm putting in some effort to learn Python, and I am paying close attention to common coding standards. This may seem like a pointlessly nit-picky question, but I am trying to focus on best-practices as I learn, so I don't have to unlearn any 'bad' habits. I see two common methods for initializing a dict: a = { 'a': 'value', 'another': 'value', } b = dict( a='value', another='value', ) Which is considered to be "more pythonic"? Which do you use? Why?

    Read the article

  • Downloading files from an http server in python

    - by cellular
    Using urllib2, we can get the http response from a web server. If that server simply holds a list of files, we could parse through the files and download each individually. However, I'm not sure what the easiest, most pythonic way to parse through the files would be. When you get a whole http response of the generic file server list, through urllib2's urlopen() method, how can we neatly download each file?

    Read the article

  • Does this syntax for specifying Django conditional form display align with python/django convention?

    - by andy
    I asked a similar question on Stackoverflow and was told it was better asked here. So I'll ask it slightly rephrased. I am working on a Django project, part of which will become a distributable plugin that allows the python/django developer to specify conditional form field display logic in the form class or model class. I am trying to decide how the developer must specify that logic. Here's an example: class MyModel(models.Model): #these are some django model fields which will be used in a form yes_or_no = models.SomeField...choices are yes or no... why = models.SomeField...text, but only relevant if yes_or_no == yes... elaborate_even_more = models.SomeField...more text, just here so we can have multiple conditions #here i am inventing some syntax...i am looking for suggestions!! #this is one possibility why.show_if = ('yes_or_no','==','yes') elaborate_even_more.show_if = (('yes_or_no','==','yes'),('why','is not','None')) #help me choose a syntax that is *easy*...and Pythonic and...Djangonic...and that makes your fingers happy to type! #another alternative... conditions = {'why': ('yes_or_no','==','yes'), 'elaborate_even_more': (('yes_or_no','==','yes'),('why','is not','None')) } #or another alternative... """Showe the field whiche hath the name *why* only under that circumstance in whiche the field whiche hath the name *yes_or_no* hath the value *yes*, in strictest equality.""" etc... Those conditions will be eventually passed via django templates to some javascript that will show or hide form fields accordingly. Which of those options (or please propose a better option) aligns better with conventions such that it will be easiest for the python/django developer to use? Also are there other considerations that should impact what syntax I choose?

    Read the article

  • Splitting Pygame functionality between classes or modules?

    - by sec_goat
    I am attempting to make my pygame application more modular so that different functionalities are split up into different classes and modules. I am having some trouble getting pygame to allow me to draw or load images in secondary classes when the display has been set and pygame.init() has been done in my main class. I have typically used C# and XNA to accomplish this sort of behavior, but this time I need to use python. How do I init pygame in class1, then create an instance of class2 which loads and converts() images. I have tried pygame.init() in class 2 but then it tells me no display mode has been set, when it has been set in class1. I am under the impression i do not wnat to create multiple pygame.displays as that gets problematic I am probably missing something pythonic and simple but I am not sure what. How do I create a Display class, init python and then have other modules do my work like loading images, fonts etc.? here is the simplest version of what I am doing: class1: def __init__(self): self.screen = pygame.display.set_mode((600,400)) self.imageLoader = class2() class2: def __init__(self): self.images = ['list of images'] def load_images(): self.images = os.listdir('./images/') #get all images in the images directory for img in self.images: #read all images in the directory and load them into pygame new_img = pygame.image.load(os.path.join('images', img)).convert() scale_img = pygame.transform.scale(new_img, (pygame.display.Info().current_w, pygame.display.Info().current_h)) self.images.append(scale_img) if __name__ == "__main__": c1 = class1() c1.imageLoader.load_images() Of course when it tries to load an convert the images it tells me pygame has not been initialized, so i throw in a pygame.init() in class2 ( i have heard it is safe to init multiple times) and then the error goes to pygame.error: No video mode has been set

    Read the article

  • @staticmethod vs module-level function

    - by darkfeline
    This is not about @staticmethod and @classmethod! I know how staticmethod works. What I want to know is the proper use cases for @staticmethod vs. a module-level function. I've googled this question, and it seems there's some general agreement that module-level functions are preferred over static methods because it's more pythonic. Static methods have the advantage of being bound to its class, which may make sense if only that class uses it. However, in Python functionality is usually organized by module not class, so usually making it a module function makes sense too. Static methods can also be overridden by subclasses, which is an advantage or disadvantage depending on how you look at it. Although, static methods are usually "functionally pure" so overriding it may not be smart, but it may be convenient sometimes (though this may be one of those "convenient, but NEVER DO IT" kind of things only experience can teach you). Are there any general rule-of-thumbs for using either staticmethod or module-level functions? What concrete advantages or disadvantages do they have (e.g. future extension, external extension, readability)? If possible, also provide a case example.

    Read the article

  • Python XLWT attempt to overwrite cell workaround

    - by PPTim
    Hi, Using the python module xlwt, writing to the same cell twice throws an error: Message File Name Line Position Traceback <module> S:\******** write C:\Python26\lib\site-packages\xlwt\Worksheet.py 1003 write C:\Python26\lib\site-packages\xlwt\Row.py 231 insert_cell C:\Python26\lib\site-packages\xlwt\Row.py 150 Exception: Attempt to overwrite cell: sheetname=u'Sheet 1' rowx=1 colx=12 with the code snippet def insert_cell(self, col_index, cell_obj): if col_index in self.__cells: if not self.__parent._cell_overwrite_ok: msg = "Attempt to overwrite cell: sheetname=%r rowx=%d colx=%d" \ % (self.__parent.name, self.__idx, col_index) raise Exception(msg) #row 150 prev_cell_obj = self.__cells[col_index] sst_idx = getattr(prev_cell_obj, 'sst_idx', None) if sst_idx is not None: self.__parent_wb.del_str(sst_idx) self.__cells[col_index] = cell_obj Looks like the code 'raise'es an exception which halts the entire process. Is removing the 'raise' term enough to allow for overwriting cells? I appreciate xlwt's warning, but i thought the pythonic way is to assume "we know what we're doing". I don't want to break anything else in touching the module.

    Read the article

  • Why is IoC / DI not common in Python?

    - by tux21b
    In Java IoC / DI is a very common practice which is extensively used in web applications, nearly all available frameworks and Java EE. On the other hand, there are also lots of big Python web applications, but beside of Zope (which I've heard should be really horrible to code) IoC doesn't seem to be very common in the Python world. (Please name some examples if you think that I'm wrong). There are of course several clones of popular Java IoC frameworks available for Python, springpython for example. But none of them seems to get used practically. At least, I've never stumpled upon a Django or sqlalchemy+<insert your favorite wsgi toolkit here> based web application which uses something like that. In my opinion IoC has reasonable advantages and would make it easy to replace the django-default-user-model for example, but extensive usage of interface classes and IoC in Python looks a bit odd and not »pythonic«. But maybe someone has a better explanation, why IoC isn't widely used in Python.

    Read the article

  • Perl for a Python programmer

    - by fortran
    I know Python (and a bunch of other languages) and I think it might be nice to learn Perl, even if it seems that most of the people is doing it the other way around... My main concern is not about the language itself (I think that part is always easy), but about learning the Perlish (as contrasted with Pythonic) way of doing things; because I don't think it'll be worth the effort if I end up programming Python in Perl. So my questions are basically two: Are there many problems/application areas where it's actually more convenient to solve them in Perl rather than in Python? If the first question is positive, where can I found a good place to get started and learn best practices that is not oriented to beginners?

    Read the article

  • Python class design - Splitting up big classes into multiple ones to group functionality

    - by Ivo Wetzel
    OK I've got 2 really big classes 1k lines each that I currently have split up into multiple ones. They then get recombined using multiple inheritance. Now I'm wondering, if there is any cleaner/better more pythonic way of doing this. Completely factoring them out would result in endless amounts of self.otherself.do_something calls, which I don't think is the way it should be done. To make things clear here's what it currently looks like: from gui_events import GUIEvents # event handlers from gui_helpers import GUIHelpers # helper methods that don't directly modify the GUI # GUI.py class GUI(gtk.Window, GUIEvents, GUIHelpers): # general stuff here stuff here One problem that is result of this is Pylint complaining giving me trillions of "init not called" / "undefined attribute" / "attribute accessed before definition" warnings.

    Read the article

  • Help me finish this Python 3.x self-challenge.

    - by Hamish Grubijan
    This is not a homework. I saw this article praising Linq library and how great it is for doing combinatorics stuff, and I thought to myself: Python can do it in a more readable fashion. After half hour of dabbing with Python I failed. Please finish where I left off. Also, do it in the most Pythonic and efficient way possible please. from itertools import permutations from operator import mul from functools import reduce glob_lst = [] def divisible(n): return (sum(j*10^i for i,j in enumerate(reversed(glob_lst))) % n == 0) oneToNine = list(range(1, 10)) twoToNine = oneToNine[1:] for perm in permutations(oneToNine, 9): for n in twoToNine: glob_lst = perm[1:n] #print(glob_lst) if not divisible(n): continue else: # Is invoked if the loop succeeds # So, we found the number print(perm) Thanks!

    Read the article

  • Python "Every Other Element" Idiom

    - by Matt Luongo
    Hey guys, I feel like I spend a lot of time writing code in Python, but not enough time creating Pythonic code. Recently I ran into a funny little problem that I thought might have an easy, idiomatic solution. Paraphrasing the original, I needed to collect every sequential pair in a list. For example, given the list [1,2,3,4,5,6], I wanted to compute [(1,2),(3,4),(5,6)]. I came up with a quick solution at the time that looked like translated Java. Revisiting the question, the best I could do was l = [1,2,3,4,5,6] [(l[2*x],l[2*x+1]) for x in range(len(l)/2)] which has the side effect of tossing out the last number in the case that the length isn't even. Is there a more idiomatic approach that I'm missing, or is this the best I'm going to get?

    Read the article

  • Python 3: unpack inner lists in list comprehension

    - by Beau Martínez
    I'm running the following code on a list of strings to return a list of its words: words = [re.split('\\s+', line) for line in lines] However, I end up getting something like: [['import', 're', ''], ['', ''], ['def', 'word_count(filename):', ''], ...] As opposed to the desired: ['import', 're', '', '', '', 'def', 'word_count(filename):', '', ...] How can I unpack the lists re.split('\\s+', line) produces in the above list comprehension? Naïvely, I tried using * but that doesn't work. (I'm looking for a simple and Pythonic way of doing; I was tempted to write a function but I'm sure the language accommodates for this issue.)

    Read the article

  • Help me finish this Python self-challenge.

    - by Hamish Grubijan
    This is not a homework. I saw this article praising Linq library and how great it is for doing combinatorics stuff, and I thought to myself: Python can do it in a more readable fashion. After half hour of dabbing with Python I failed. Please finish where I left off. Also, do it in the most Pythonic and efficient way possible please. from itertools import permutations from operator import mul from functools import reduce glob_lst = [] def divisible(n): return (sum(j*10^i for i,j in enumerate(reversed(glob_lst))) % n == 0) oneToNine = list(range(1, 10)) twoToNine = oneToNine[1:] for perm in permutations(oneToNine, 9): for n in twoToNine: glob_lst = perm[1:n] #print(glob_lst) if not divisible(n): continue else: # Is invoked if the loop succeeds # So, we found the number print(perm) Thanks!

    Read the article

  • Python: Slicing a list into n nearly-equal-length partitions

    - by Drew
    I'm looking for a fast, clean, pythonic way to divide a list into exactly n nearly-equal partitions. partition([1,2,3,4,5],5)->[[1],[2],[3],[4],[5]] partition([1,2,3,4,5],2)->[[1,2],[3,4,5]] (or [[1,2,3],[4,5]]) partition([1,2,3,4,5],3)->[[1,2],[3,4],[5]] (there are other ways to slice this one too) There are several answers in here http://stackoverflow.com/questions/1335392/iteration-over-list-slices that run very close to what I want, except they are focused on the size of the list, and I care about the number of the lists (some of them also pad with None). These are trivially converted, obviously, but I'm looking for a best practice. Similarly, people have pointed out great solutions here http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python for a very similar problem, but I'm more interested in the number of partitions than the specific size, as long as it's within 1. Again, this is trivially convertible, but I'm looking for a best practice.

    Read the article

  • Python: slicing a very large binary file

    - by Duncan Tait
    Say I have a binary file of 12GB and I want to slice 8GB out of the middle of it. I know the position indices I want to cut between. How do I do this? Obviously 12GB won't fit into memory, that's fine, but 8GB won't either... Which I thought was fine, but it appears binary doesn't seem to like it if you do it in chunks! I was appending 10MB at a time to a new binary file and there are discontinuities on the edges of each 10MB chunk in the new file. Is there a Pythonic way of doing this easily?

    Read the article

  • Best practise when using httplib2.Http() object

    - by tomaz
    I'm writing a pythonic web API wrapper with a class like this import httplib2 import urllib class apiWrapper: def __init__(self): self.http = httplib2.Http() def _http(self, url, method, dict): ''' Im using this wrapper arround the http object all the time inside the class ''' params = urllib.urlencode(dict) response, content = self.http.request(url,params,method) as you can see I'm using the _http() method to simplify the interaction with the httplib2.Http() object. This method is called quite often inside the class and I'm wondering what's the best way to interact with this object: create the object in the __init__ and then reuse it when the _http() method is called (as shown in the code above) or create the httplib2.Http() object inside the method for every call of the _http() method (as shown in the code sample below) import httplib2 import urllib class apiWrapper: def __init__(self): def _http(self, url, method, dict): '''Im using this wrapper arround the http object all the time inside the class''' http = httplib2.Http() params = urllib.urlencode(dict) response, content = http.request(url,params,method)

    Read the article

  • Python: Split by 1 or more occurrences of a delimiter

    - by Adam Matan
    Hi, I have a formatted string from a log file, which looks like: >>> a="test result" That is, the test and the result are split by some spaces - it was probably created using formatted string which gave test some constant spacing. Simple splitting won't do the trick: >>> a.split(" ") ['test', '', '', '', ... '', '', '', '', '', '', '', '', '', '', '', 'result'] split(DELIMITER, COUNT) cleared some unnecessary values: >>> a.split(" ",1) ['test', ' result'] This helped - but of course, I really need: ['test', 'result'] I can use split() followed by map + strip(), but I wondered if there is a more Pythonic way to do it. Thanks, Adam

    Read the article

  • removing pairs of elements from numpy arrays that are NaN (or another value) in Python

    - by user248237
    I have an array with two columns in numpy. For example: a = array([[1, 5, nan, 6], [10, 6, 6, nan]]) a = transpose(a) I want to efficiently iterate through the two columns, a[:, 0] and a[:, 1] and remove any pairs that meet a certain condition, in this case if they are NaN. The obvious way I can think of is: new_a = [] for val1, val2 in a: if val2 == nan or val2 == nan: new_a.append([val1, val2]) But that seems clunky. What's the pythonic numpy way of doing this? thanks.

    Read the article

  • Python equivalent of Java's compareTo()

    - by astay13
    I'm doing a project in Python (3.2) for which I need to compare user defined objects. I'm used to OOP in Java, where one would define a compareTo() method in the class that specifies the natural ordering of that class, as in the example below: public class Foo { int a, b; public Foo(int aa, int bb) { a = aa; b = bb; } public int compareTo(Foo that) { // return a negative number if this < that // return 0 if this == that // return a positive number if this > that if (this.a == that.a) return this.b - that.b; else return this.a - that.a; } } I'm fairly new to classes/objects in Python, so I'd like to know what is the "pythonic" way to define the natural ordering of a class?

    Read the article

  • How to make a Django model fields calculated at runtime?

    - by Anatoly Rr
    I have a model: class Person (models.Model): name = models.CharField () birthday = models.DateField () age = models.IntegerField () I want to make age field to behave like a property: def get_age (self): return (datetime.datetime.now() - self.birthday).days // 365 age = property (get_age) but at the same time I need age to be a true field, so I can find it in Person._meta.fields, and assign attributes to it: age.help_text = "Age of the person", etc. Obviously I cannot just override Person.save() method to calculate and store age in the database, because it inevitably will become wrong later (in fact, it shouldn't be stored in the database at all). Actually, I don't need to have setters now, but a nice solution must have setting feature. Is it possible in Django, or probably there is a more pythonic and djangoic approach to my problem?

    Read the article

  • Passing a non-iterable to list.extend ()

    - by JS
    Hello, I am creating a public method to allow callers to write values to a device, call it write_vals() for example. Since these values will by typed live, I would like to simplify the user's life by allowing them type in either a list or a single value, depending on how many values they need to write. For example: write_to_device([1,2,3]) or write_to_device(1) My function would like to work with a flat list, so I tried to be clever and code something like this: input_list = [] input_list.extend( input_val ) This works swimmingly when the user inputs a list, but fails miserably when the user inputs a single integer: TypeError: 'int' object is not iterable Using list.append() would create a nested list when a list was passed in, which would be an additional hassle to flatten. Checking the type of the object passed in seems clumsy and non-pythonic and wishing that list.extend() would accept non-iterables has gotten me nowhere. So has trying a variety of other coding methods. Suggestions (coding-related only, please) would be greatly appreciated.

    Read the article

  • Complex Django filter question

    - by HWM-Rocker
    Lets say I have this class (simplified): class Tag (...): children = models.ManyToManyField(null=True, symmetrical=False) Now I already implemented the functions get_parents, get_all_ancestors. Is there a nice pythonic way to just the top level tags? If I had designed my Tags differently (to point to the parents instead) I would just make get_all_parents().filter(children=null). My first thought is to create a new function that will go recursively through all parents and save those that has none. But is there a possibility with filters or Query-objects to do the same (with fewer lines of code)? Thanks for your help. [edit] When it is finished, it should be a hierarchical tagging system. Each tag can have children, parents, but only the children are saved. I want to get all the top level tags, that point through many children / childrens children to my tag.

    Read the article

  • How to read a file with variable multi-row data in Python

    - by dr.bunsen
    I have a file that is about 100Mb that looks like this: #meta data 1 skadjflaskdjfasljdfalskdjfl sdkfjhasdlkgjhsdlkjghlaskdj asdhfk #meta data 2 jflaksdjflaksjdflkjasdlfjas ldaksjflkdsajlkdfj #meta data 3 alsdkjflasdjkfglalaskdjf This file contains one row of meta data that corresponds to several, variable length data containing only alpha-numeric characters. What is the best way to read this data into a simple list like this: data = [[#meta data 1, skadjflaskdjfasljdfalskdjflsdkfjhasdlkgjhsdlkjghlaskdjasdhfk], [#meta data 2, jflaksdjflaksjdflkjasdlfjasldaksjflkdsajlkdfj], [#meta data 3, alsdkjflasdjkfglalaskdjf]] My initial idea was to use the read() method to read the whole file into memory and then use regular expressions to parse the data into the desired format. Is there a better more pythonic way? All metadata lines start with an octothorpe and all data lines are all alpha-numeric. Thanks!

    Read the article

  • Java hashcode based on identity

    - by hjfreyer
    The default behavior of Object.hashCode() is to return essentially the "address" of the object so that a.hashCode() == b.hashCode() if and only if a == b. How can I get this behavior in a user-defined class if a superclass already defines hashCode()? For instance: class A { public int hashCode() { return 0; } } class B extends A { public int hashCode() { // Now I want to return a unique hashcode for each object. // In pythonic terms, it'd look something like: return Object.hashCode(this); } } Ideas?

    Read the article

< Previous Page | 2 3 4 5 6 7 8  | Next Page >