New answers tagged

0

I have a function that will take some part of an object's deep data hierarchy as an argument. It would be cumbersome to instead pass in the several arguments needed to get to that part of the data hierarchy. So have no reason to reference self or cls. But the functionality will only be used on parts of objects of a particular class. So it seems a class ...


0

This is cleaner for the example you give: def sizeC(self, arg=None): if arg: self._size = arg return self._size However, Robert Harvey's right in that this is not the way to do fluent interfaces.


1

If you're writing code that needs a library, the import for the library is necessarily less code than the code which uses said library. When you put the two together in the same file, it is more likely that changes in one will result in remembering to do the other. Particularly if your editor uses pyflakes to enforce PEP compliance and therefore notices ...


2

No. Your function does not give consistent answers on how to sort numbers, because greater(x, y) != not greater(y, x) for some values of x and y. For example (3 % 4) % 2 == 1, and (4 % 3) % 2 == 1 also! This means that 3 > 4 AND 3 < 4, which is nonsense. If you convert it to a cmp-style function like @SystemDown suggests, you will get inconsistent ...


0

Right now the function you memoize simply returns the score the best solution. Change is so that it returns a tuple of the first step of the best solution and the score. Something like: @memoize def score(...) _, zero_score = score(...) _, one_score = score(...) if zero_score < one_score: return 0, zero_score else: return 1, ...


0

If your program depends on an LGPL licensed module/library, then the basic requirement on you is that you must ensure that the users of your program or derived versions of it have the possibility to replace the LGPL licensed code with a different, compatible, version. One way to ensure this is by putting your code under the (L)GPL license, which ensures ...


0

You need to find a way to determine how well each curve fits the data, but wouldn't the higher order polynomial always result in a better (or worst-case equal) fit than a lower order one? The degree 5 should be a better fit than the degree 4, and 4 better than 3, and so forth. Are you using numpy.polyfit? ...


1

If the next-level function has a __doc__, then you can just copy the __doc__ to your new function. For example: def a(x): """This function takes one parameter, x, and does nothing with it!""" pass def b(**kwargs): a(**kwargs) b.__doc__=a.__doc__ This could apply recursively, and could be applied by a decorator (which might be useful if you ...


0

Can you expand on what you mean by dynamically add properties? I take it that you need to do this while code is running, rather than simply edit the source files? If so maybe check out named tuples as part of the Python collections module https://docs.python.org/2/library/collections.html You can create a class dynamically like this EmployeeRecord = ...


5

Estimating password strength isn't a simple problem. You need to recognize common patterns humans like to use in passwords (words, keyboard-patterns, etc.). For example dropbox's estimator zxcvbn is pretty advanced. You should consider using an existing estimator library. As a super simple approximation I'd recommend: ...


2

What you need to do depends on the license of the packages. The license of both products that you specifically mention have this clause: Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. You can ...


1

Error codes are basically what you use when you really don't have any other choice. Like when using a really low level language where creating new data structures or throwing exceptions is either a bother or taxing on resources. The same old, same old regarding "program for people, not computers" holds here too. Be as helpful as possible to the developer ...


0

It sounds like the thing you want to do is this: Pick an array from the weighted list of non-empty arrays Pop a value from that array and add it to the output array Repeat some number of times You seem to be having some trouble doing step 1 in a fair way. My suggestion is to flatten the weighted list into a list containing each array <array-weight> ...


2

Yes, they will be able to log your public IP address. If you are trying to prevent someone from logging your IP address, you can't without going through a proxy. The public IP of the proxy would get logged by the service to which you are connecting.


0

What I did was use self.__dict__.update(json) which copies items in the JSON dict into the object's dict and so they appear as properties of the object. The client can then use dot notation to access or mutate them.


1

The concept underlying your question is so important I feel it needs another answer rather than just a comment (as I had started to do). The other 3 answers thus far provide some useful points of consideration on whether a given situation merits using what you call "nested function calls". But perhaps a more important point is hidden in the comments under ...


8

This really depends on how much nesting you use. After all, you are allowed to use function results directly in expressions to improve readability. Both, code that does not use nested expressions (like assembler code), and code that uses too much nested expressions is hard to read. Good code tries to strike a balance in between the extremes. So lets look at ...


1

It is absolutely not a bad practice in general. Functions call accept values and one way of producing a value is by calling another function. When I see a variable being defined, like: parsed_value = cashParser(input) ... I have to consider that parsed_value might be used more than once and I'll probably have to check if this is true or not (what if my ...


4

I think whether it's good or bad depends a lot on context. The main reason it might be considered bad is that it (arguably) makes the code harder to read and debug. This is especially true when you are first learning to program. As your coding skills (and code) gets more advanced, there are times when this is acceptable. For example, consider an error ...


0

First of all splitting a monolith into microservices is always going to be hard. See Decentralized Data Management - encapsulating databases into microservices for an idea of why. That said, there are several recipes for how to do it relatively sanely. One of them is http://12factor.net/. That one would say that you should maintain each library and ...


2

Not a Python guy but the PyPi server seems the best option. A quick googling gives the appearance that it's analogous to having a Nexus repo for the team's Java jars. Really as long as it's being deployed to some sort of central repository (to the office/team) that your dependency management tool of choice can work with (read from and deploy to) then it is ...


3

Your second option is definitely the way to go. Break out common libraries and install them onto your local PyPi server. Option 1 is horrendous because improvements to the libraries will be difficult to propagate to others who could use it. Option 3 is similar to option 1. The common pattern is to setup Jenkins so that when you push to master of a ...


1

We're using the code from http://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/3259271#3259271 whenever we run into problems on cmd.exe and windows. Linux seems to be utf-8, and the only problem we've seen there is when windows users' putty settings have been off. I don't know about OS X. Can you implement unicode ...


0

I'd like to start by rejecting the statement you make But try ... except will always be considered more Pythonic / idiomatic and thus "better" If you only need to know whether an object has an attribute, then use hasattr. This is justified by the Zen of Python's "There should be one-- and preferably only one --obvious way to do it.". It doesn't really ...


0

In the namedtuple documentation, it says: Any valid Python identifier may be used for a fieldname except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a keyword such as class, for, return, global, pass, print, or raise. Because namedtuples ...


1

namedtuple is a bit unusual thing in python. It is not a base class, it is a class generator. Invoking it creates a new class that uses a tuple for its storage and can be manipulated as either tuple or normal class with named fields. The generated class is intended to be used as a base for your own types that will add methods, and constraints. Including ...


3

Today, python offers a wide spectrum of tests than can be done for testing duck-type coding. Type Annotations Implementations For starters, static, compile time type-checking ability was added to Python 3 in 2015. Now, there are multiple third-party libraries that provide an implementations for the new type-checking hooks. MyPy — data type-checking ...


3

You only need two if statements (or for your specific case one if and one elif) like the following: if var1 > 100: print("Wrong.") elif var2 < 1: print("Wrong.") In above code, if var1 is greater than 100, the first "Wrong" string is printed and the second if statement is not executed (due to the 'else if' statement elif). If var1 is smaller ...


0

Programming languages almost universally do not let you do so. Actually the concept of a variable "triggering" the if statement is an abstraction that isn't actually supported by the language at all. The if statement is not triggered by var1 nor var2. It is "triggered" by the expression var1 > 100 or var2 < 1. You could get away with: ...


0

What you are suggesting is quite right . It should be asynchronous. You can post a request and the request gives you a unique Id. It posts a Done on this unique id in some store where you can poll. If you need to cancel a request , a cancel request using same Id should be posted Also on the back end where this computations are running , eg in a run ...


0

I suggest you look into wsgi and use multithreading. You can manage each request in a thread, and implement timeouts in the thread. You should also be able to manage the threads and cancel requests more easily.


0

Just a few thoughts: $20/month seems excessive for a site with a handful of visits a day. If you've not used Amazon's EC2 before, take a look at the "micro" instances. You can get a year's "free tier" use for virtually nothing, and then if things are working out, paying for three years upfront (for a "reserved instance") works out more like around ...


-2

... maybe because it's not that difficult to write one yourself def flatten(l): return flatten(l[0]) + (flatten(l[1:]) if len(l) > 1 else []) if type(l) is list else [l] ... and then flatten all you want :) >>> flatten([1,[2,3],4]) [1, 2, 3, 4] >>> flatten([1, [2, 3], 4, [5, [6, {'name': 'some_name', 'age':30}, 7]], [8, 9, [10, [11, ...


4

Is it pythonic to use properties to limit the mutability of class attributes (variables and methods)? For attributes/properties/variables at either the class or instance level: yes, absolutely! The decorator @property is built in specifically to give control over read, write, and delete. Common use cases include: enforcing read-only or write-only ...


3

I would definitely go for the return None option. Raising an exception may increase readability (although I doubt it) on the function itself, but handling it is messier. If you return None, from the caller function you can do the following: citation = check_case_citation("Case 145/80") if citation: # Do something else: # Do something else while, if ...


9

This is not a Python vs Other Languages distinction - it's actually Value Types vs Reference Types distinction. Python uses reference types, and while many modern languages also tend to use reference types, it's common to compare Python(or any language, actually) to C/C++, which use value types. (I'm simplifying things a lot here - there are languages that ...


0

I think your server API should have as many entries as required requests. Thus, any developer will be able to read the API easily (see lask routing as example). To avoid duplication in code, you can use internal methods


1

Your pdf creating class should not log, in fact, it should not have any knowledge about your log. It should create that pdf and report any issues to its creator/caller. The creator/caller should then decide what to do with it (write to the console, write to a log file, try again, ignore, whatever). Your pdf creator is a problem domain class and it should ...



Top 50 recent answers are included