Tag Info

New answers tagged

1

In Python, switching between an attribute and a property isn't a breaking change, it doesn't alter the interface at all, so there's not much point to an auto-property system. You can start with a public attribute, then later on switch to a property without needing to alter the code that interfaces with your class at all. This is also why defining get_ and ...


0

In Python, we have packages and modules. A module is "just" a .py file, and a package is "just" a directory with an __init__.py file (which is often empty). You can import any package or module which is in a directory listed in sys.path, modules within such a package, subpackages within such a package, modules within such subpackages, and so on. While you ...


0

I made a slightly different algorithm: def share(available, members): # find across how many members we must distribute and what the total sum of those values is total = available for idx, member in enumerate(members): total += member count = idx+1 if (idx >= len(members)-1): break if (total / ...


0

I am not sure what is your end goal in term of cleaning. Anyway, Python can really help you here. You can use the csv module in the standard library, or an external package like PETL. Both will automatically quote field values that need to be quoted. So for example, if the 3rd column value is Items,, it will be quoted (as it contains the separator ...


0

The diamond problem shouldn't ever happen as a result because you would never have two classes that inherit from the same class up the tree both applied to the same entity. Never say never. I bet you within all those 90 behaviors, you will have a diamond problem. Even worse if you don't notice it. From the small example, it seems you actually want ...


0

It's a bit of a code smell, and your gut feeling is right about this not being a good solution. But instead of passing the arguments, extract the method and the three parameters into a separate class. This class takes the arguments in the constructor and exposes the one method. Something tells me that this one method is actually doing something that can be ...


1

Multiple inheritance is sometimes the right thing to do. You probably shouldn't inherit both from Car and OilRig, but inheriting from both Walker and Talker can make a lot of sense, particularly if using delegation would introduce a lot of trivial delegating methods that are a pain to maintain. It is particularly benign if it verges on emulating traits or ...


4

My most common use of lambda is for key functions: list_of_foos.sort(key = lambda foo: foo.bar) max(list_of_foos, key = lambda foo: foo.bar) min(list_of_foos, key = lambda foo: foo.bar)


2

You can use a lambda expression anywhere you need to have a piece of executable code passed along like data (ie, as a parameter). In Python, there's little difference between using a lambda expression and a one-line function, except that the lambda doesn't clutter up the namespace, and you don't have to go hunting for where it is defined in the code. In ...


-1

(Its more a comment, than a real anwser, but I can't post here it as a comment yet) One of the terms you are searching for is "autocorrelation" (see Wikipedia). You can compare your first element to your second, and the 2nd to the 3rd and so on, in the next round you compare first with third, second with nr 4. basicly you shift the lines in each round one ...


2

I would suggest implementing command line parameters and command line help using argparse. The different functions could then be selected by command line options. If others without python installed need to use your program, then I would package it as an executable using pyinstaller. Pyinstaller can be used to build 3 possilbe executables: onefile, onedir ...


2

Have the 8 function calls wrapped in if __name__ == '__main__': Then you can call the script by running python NAME_OF_YOUR_SCRIPT.py If you need to pass any variables in when running it, use the argparse module


-1

I found the answer here. Python actually has this functionality built in. For example 'A' < 'F' # Returns true because A comes before F Thus one can use the function def is_in_range(range, letter): return range[:2] <= letter <=range[3:5] is_in_range('SA-SF','SM') False is_in_range('SG-SM','SM') True Note: Case will screw this up so ...


0

I may be misunderstanding some details of your question, but I'll try anyway. This is how I would do it: I would structure App1, App2, etc... as Python packages, and would version these packages to map to App1_v1, App1_v2, App2_v1, etc... I would then create another package for site.com, and version it to map to site.com/2012, site.com/2013, etc... All of ...


0

As Doc Brown says, joining properly indexed tables is efficient You make it easier on your application by defining appropriate views and dealing with the views rather than the underlying tables e.g. (Tested on SQL-SERVER, you didn't specify an RDBMS) See Fiddle CREATE VIEW URLsInPage AS SELECT Links.[Name], LinksInPage.[Page URL], ...


0

Would you not be able to handle this with classical object-oriented concepts? For example, each backend could be implemented as a class with a common interface, and InputPin and OutputPin classes would used them in a composed manner.


2

You are confused between generators and iterators. They are not the same concept at all. Iterators are great and ubiquitous in Python. You should use them a lot. Both my_func_gen and my_func_list use them. Generators are a lazy way to build iterables. They are useful when the fully realized list would not fit in memory, or when the cost to calculate each ...


1

Arguably the reverse is true; microservices are attractive because of limitations of the languages currently used. This is why you see two distinct camps in microservices: small ones written in dynamic languages that lack a built-in usable concept of a documented and statically checked interface. So they build one themselves out of HTTP and tests. Much ...


3

It seems that with this type of architecture developers no longer have to maintain large codebases, and the applications themselves are mostly thin wrappers around databases. You've fallen into the NoSQL mindset. "Hey, why should we learn this complex thing called SQL that the old-timers use? Why don't we just use a giant key/value store for ...


2

A common way is, to define one global logger at the beginning of the module with: import logging logger = logging.getLogger(__name__) so it's easier to assign different log-levels to different modules. If you don't have a distinguishing logger name, you can directly use the log-functions of logging; instead of logDebug simply write logging.debug.


0

In this case you can pretend that it is, but be careful. List comprehentions create or mutate variables in the surrounding scope. (in ipython console): In [1]: x NameError: name 'x' is not defined In [2]: [x for x in range(10)] Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [3]: x Out[3]: 9 So if you had something like x = "foo" [x for x ...] x will not ...


2

Yes it is, because there is no state being mutated. The line branch_counts = [count_leaves(b) for b in tree] can be interpreted as a simple binding (like a let statement in Haskell or Lisp), as there are no further reassignments or mutations. Additionally, you could reformat it like this to make it clearer: def count_leaves(tree): return 1 if ...


1

asyncio is a set of libraries. The PEP and implementation define event loop abstractions, protocols for tasks to interact with the event loop, and various I/O classes and concurrency primitives that can be used in asynchronous code. The way to write these tasks is/was to write a generator and the way to wait on the completion of another task is/was to yield ...


2

The OOP way is to combine together polymorphism and recursion. A binary tree is defined as either empty or a set of value, left and right where both left and right are binary trees. To represent it properly left and right must be binary tree themselves, even if they are empty. To represent that in object oriented way, we'll have a tree base class and node ...


0

The behavior and semantics of nested functions are much closer to anonymous functions than to non-nested functions. Most likely, they simply wanted the syntax to reflect that difference. However, it wouldn't surprise me to see nested functions in a future update, because I believe the reasons are more cultural than technical. Go was intended as a ...


6

Go's primary design goal is to be simple to learn and simple to use even for sub-mediocre programmers, so if you want to write idiomatic Go the anti-pattern you should avoid the most is the "Clever Code" anti-pattern. As for a good reason to not allow nested functions even though you allow anonymous functions - one of the differences between Python and Go ...


0

There are significant risks if you build your own package. You will need to track upstream changes and keep up to date. (Otherwise you will miss security, functionality, and optimization changes.) Rather than build on the production server, build on the the development server and package the software for installation on the production server. For many ...


3

There are several tradeoffs you've made that are not immediately obvious. By running your own builds, you're responsible for keeping track of upstream updates, particularly with regard to security. You're also suspectible to changes in your environment that would've been handled in distribution packages, but you again have to monitor and re-integrate such ...


1

I can understand the fact that Java needs both a compiler and an interpreter. It doesn't. There's nothing in the Java Language Specification that says that Java needs to have a compiler. There's also nothing in the Java Language Specification that says that Java needs to have an interpreter. Whether to use an interpreter, a compiler, or a combination ...


7

As far as I know, you cannot execute a Python program (compiled to bytecode) on every machine, such as on windows, or on linux without modification. You are incorrect. The python bytecode is cross platform. See Is python bytecode version-dependent? Is it platform-dependent? on Stack Overflow. However, it is not compatible across versions. Python 2.6 ...


2

It's true that the bytecode is not suitable as a distribution format, but that doesn't mean it's useless. Aside from improving startup time on a given machine, after the first run, interpreting bytecode is also far simpler than interpreting an AST or, god forbid, interpreting line-by-line. Bytecode is a more low-level, more regular, more compact (both ...


3

In general, in Python I favor using functions over subclassing internal classes. In the end, if you write your String -> dict method, you end up working with a dict, pure as the driven snow. Just put your functions in a sensible module and import them only where needed; this will also encourage you not to import the functions everywhere, which will help ...


1

The kind of iterative development you're speaking of is typically done via Unit Tests in C#. Add a Unit Test project to your solution. Add aUnit Test class to the test project. Define the public API you want to create. Write a test to exercise one of the class's members. Run the tests. It should fail. Implement the functionality. Run the tests. If ...


0

Whenever I have small code snippets that I'd like to test, I personally enjoy using .Net Fiddle. Don't forget you can always spin up small projects like a C# console app to do fairly straightforward things. This may be especially necessary if you need to use third party libraries.


3

Can I develop in an 'interactive mode' the same way in C# - that is, load in some sample data, write methods interactively to ensure they're working right, then push methods up to classes as they're completed? Not the same way. There isn't really such interactive tools for C# since the problems you're usually solving are large enough to make that ...


1

This: app.route('/', method='GET')(home) ... Is the same as this: func = app.route('/', method='GET') func(home) In other words, app.route(...) returns a function, which is then called.


1

You probably want to use something like the visitor pattern, or the strategy pattern. something like (assuming a few refactors): services = [a,b,c] # add more as needed accum_strat = lambda l,s: s.Find_Service(l).GetVal() accum_list = [[] for x in range(len(services))] for l in locations: for srv, lst in zip(services, accum_list): ...


2

What you are looking for is called a REPL, a quick search for "C++ REPL" gets you to Cling, but I have not used it. I'm not sure what is the real benefit from using a REPL over to use a debugger with an interface that you are comfortable with. Static typing should help you get the code right before ever running it, also IDE's suggestions become much better ...


0

A Node program is at its core a normal program, it isn't even a web-server unless you write code specifically to make it so (though that is pretty easy with the built-in HTTP library). Your program will get the HTTP requests, and your code can respond any way you like, using all the resources otherwise available to the program. If JavaScript was old-school ...


1

Serialization is a two part problem: Knowledge about how to instantiate a class aka structure. Knowledge about how to persist/transfer the information that is needed to instantiate a class aka mechanics. As far as possible, structure should be kept separate from the mechanics. This increases the modularity of your system. If you bury the information on ...


7

I generally avoid having the class know how to serialize itself, for a couple of reasons. First, if you want to (de)serialize to/from a different format, you now need to pollute the model with that extra logic. If the model is accessed via an interface, then you also pollute the contract. public class Image { public void toJPG(String filePath) { ... } ...


0

Unlike all other servers you have mentioned, Node is single threaded, but asynchronous - as some have mentioned here, it schedules callbacks instead of waiting for operation to execute and runs callbacks when the operation is complete, however a number of other operations might have been processed in between with the same thread. Caveats: Although it's a ...


0

You would probably be well-served looking through the numpy documentation, the library has a lot of optimised ways of doing simple and complex operations on ndarrays that avoid using multiple for-loops. You could just do this to achieve the same thing: import numpy as np total = np.sum(arraytransition) arraytransition_normalised = arraytransition / total ...


6

Let's immediately get the Turing-completeness disclaimer out of the way and say any language can probably approximate any runtime feature of any other language. Good? Good. The main difference between the Node.js approach and a Python threaded-server (or a typical Java HTTP server implementation) is that Node.js is single threaded while the latter two are ...


1

Generally speaking, you should not be modifying the source code files of third party code unless they're the type of changes for which it would make sense to contribute them back upstream (e.g. bug fixes). Obviously, there are exceptional situations where you may wish to go ahead and modify those files anyway, but you usually want to avoid forking the ...


1

You could create @property decorated functions. In the setter one, you make sure you have something that calls all the pre-defined callback for said property. This is a visitor pattern really. So, in untested and incomplete code, something akin to this: @ook.setter def ook(self, value): self._whatever = ook for func in self._ook_callbacks: ...


2

This is the job of the package manager. In the case of Python: pip. If you package the library you are building and specify its dependencies, your users (grandpa), will simply need to run: $ pip install --upgrade <name-of-package> to get the latest version you've released and all of its dependencies. If you don't want to publish your code online, ...


0

Every programming language is invented by different mind set, experience and objective, and there is no universal guideline setup for creating a language. So whenever a new language comes up it's their inventor choice to think about best naming/ syntax so this is all up to them what they think is best will add there. For example to add two numbers i will ...



Top 50 recent answers are included